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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.97! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.96 2018/09/02 23:22:47 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.15      www      2843:     my $ua=new LWP::UserAgent;
1.23      www      2844:     my $request;
1.711     albertel 2845: 
                   2846:     $form{'no_update_last_known'}=1;
1.895     albertel 2847:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2848:     if (%form) {
1.782     albertel 2849:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2850:       $request->content(join('&',map {
                   2851:             my $name = escape($_);
                   2852:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2853:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2854:             : &escape($form{$_}) );
                   2855:         } keys(%form)));
1.23      www      2856:     } else {
1.782     albertel 2857:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2858:     }
                   2859: 
1.15      www      2860:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2861:     my $response= $ua->request($request);
1.944     foxr     2862:     if (wantarray) {
1.1172.2.3  raeburn  2863: 	return ($response->content, $response);
1.944     foxr     2864:     } else {
1.1172.2.3  raeburn  2865: 	return $response->content;
1.942     foxr     2866:     }
1.324     www      2867: }
                   2868: 
                   2869: sub externalssi {
                   2870:     my ($url)=@_;
                   2871:     my $ua=new LWP::UserAgent;
                   2872:     my $request=new HTTP::Request('GET',$url);
                   2873:     my $response=$ua->request($request);
1.954     raeburn  2874:     if (wantarray) {
                   2875:         return ($response->content, $response);
                   2876:     } else {
                   2877:         return $response->content;
                   2878:     }
1.15      www      2879: }
1.254     www      2880: 
1.492     albertel 2881: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2882: 
                   2883: sub allowuploaded {
                   2884:     my ($srcurl,$url)=@_;
                   2885:     $url=&clutter(&declutter($url));
                   2886:     my $dir=$url;
                   2887:     $dir=~s/\/[^\/]+$//;
                   2888:     my %httpref=();
                   2889:     my $httpurl=&hreflocation('',$url);
                   2890:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2891:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2892: }
1.477     raeburn  2893: 
1.1172.2.13  raeburn  2894: #
                   2895: # Determine if the current user should be able to edit a particular resource,
                   2896: # when viewing in course context.
                   2897: # (a) When viewing resource used to determine if "Edit" item is included in
                   2898: #     Functions.
                   2899: # (b) When displaying folder contents in course editor, used to determine if
                   2900: #     "Edit" link will be displayed alongside resource.
                   2901: #
                   2902: #  input: six args -- filename (decluttered), course number, course domain,
                   2903: #                   url, symb (if registered) and group (if this is a group
                   2904: #                   item -- e.g., bulletin board, group page etc.).
                   2905: #  output: array of five scalars --
                   2906: #          $cfile -- url for file editing if editable on current server
                   2907: #          $home -- homeserver of resource (i.e., for author if published,
                   2908: #                                           or course if uploaded.).
                   2909: #          $switchserver --  1 if server switch will be needed.
                   2910: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2911: #          $forceview -- 1 if icon/link should be to go to view mode
                   2912: #
                   2913: 
                   2914: sub can_edit_resource {
                   2915:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2916:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2917: #
                   2918: # For aboutme pages user can only edit his/her own.
                   2919: #
                   2920:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2921:         my ($sdom,$sname) = ($1,$2);
                   2922:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2923:             $home = $env{'user.home'};
                   2924:             $cfile = $resurl;
                   2925:             if ($env{'form.forceedit'}) {
                   2926:                 $forceview = 1;
                   2927:             } else {
                   2928:                 $forceedit = 1;
                   2929:             }
                   2930:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2931:         } else {
                   2932:             return;
                   2933:         }
                   2934:     }
                   2935: 
                   2936:     if ($env{'request.course.id'}) {
                   2937:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2938:         if ($group ne '') {
                   2939: # if this is a group homepage or group bulletin board, check group privs
                   2940:             my $allowed = 0;
                   2941:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2942:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2943:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2944:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2945:                     $allowed = 1;
                   2946:                 }
                   2947:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2948:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2949:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2950:                     $allowed = 1;
                   2951:                 }
                   2952:             }
                   2953:             if ($allowed) {
                   2954:                 $home=&homeserver($cnum,$cdom);
                   2955:                 if ($env{'form.forceedit'}) {
                   2956:                     $forceview = 1;
                   2957:                 } else {
                   2958:                     $forceedit = 1;
                   2959:                 }
                   2960:                 $cfile = $resurl;
                   2961:             } else {
                   2962:                 return;
                   2963:             }
                   2964:         } else {
1.1172.2.15  raeburn  2965:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2966:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2967:                     return;
                   2968:                 }
                   2969:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2970: #
                   2971: # No edit allowed where CC has switched to student role.
                   2972: #
                   2973:                 return;
                   2974:             }
                   2975:         }
                   2976:     }
                   2977: 
                   2978:     if ($file ne '') {
                   2979:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2980:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2981:                 $uploaded = 1;
                   2982:                 $incourse = 1;
                   2983:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2984:                     $cfile = &hreflocation('',$file);
                   2985:                     if ($env{'form.forceedit'}) {
                   2986:                         $forceview = 1;
                   2987:                     } else {
                   2988:                         $forceedit = 1;
                   2989:                     }
                   2990:                 }
                   2991:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2992:                 $incourse = 1;
                   2993:                 if ($env{'form.forceedit'}) {
                   2994:                     $forceview = 1;
                   2995:                 } else {
                   2996:                     $forceedit = 1;
                   2997:                 }
                   2998:                 $cfile = $resurl;
                   2999:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3000:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3001:                     $incourse = 1;
                   3002:                     if ($env{'form.forceedit'}) {
                   3003:                         $forceview = 1;
                   3004:                     } else {
                   3005:                         $forceedit = 1;
                   3006:                     }
                   3007:                     $cfile = $resurl;
                   3008:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3009:                     $incourse = 1;
                   3010:                     $cfile = $resurl.'/smpedit';
                   3011:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3012:                     $incourse = 1;
                   3013:                     if ($env{'form.forceedit'}) {
                   3014:                         $forceview = 1;
                   3015:                     } else {
                   3016:                         $forceedit = 1;
                   3017:                     }
                   3018:                     $cfile = $resurl;
1.1172.2.15  raeburn  3019:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3020:                     $incourse = 1;
                   3021:                     if ($env{'form.forceedit'}) {
                   3022:                         $forceview = 1;
                   3023:                     } else {
                   3024:                         $forceedit = 1;
                   3025:                     }
                   3026:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3027:                 }
                   3028:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3029:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3030:                 if (&is_on_map($template)) {
                   3031:                     $incourse = 1;
                   3032:                     $forceview = 1;
                   3033:                     $cfile = $template;
                   3034:                 }
                   3035:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3036:                     $incourse = 1;
                   3037:                     if ($env{'form.forceedit'}) {
                   3038:                         $forceview = 1;
                   3039:                     } else {
                   3040:                         $forceedit = 1;
                   3041:                     }
                   3042:                     $cfile = $resurl;
                   3043:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3044:                 $incourse = 1;
                   3045:                 $forceview = 1;
                   3046:                 if ($symb) {
                   3047:                     my ($map,$id,$res)=&decode_symb($symb);
                   3048:                     $env{'request.symb'} = $symb;
                   3049:                     $cfile = &clutter($res);
                   3050:                 } else {
                   3051:                     $cfile = $env{'form.suppurl'};
                   3052:                     $cfile =~ s{^http://}{};
                   3053:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3054:                 }
1.1172.2.31  raeburn  3055:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3056:                 if ($env{'form.forceedit'}) {
                   3057:                     $forceview = 1;
                   3058:                 } else {
                   3059:                     $forceedit = 1;
                   3060:                 }
                   3061:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3062:             }
                   3063:         }
                   3064:         if ($uploaded || $incourse) {
                   3065:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3066:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3067:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3068:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3069:             # Check that the user has permission to edit this resource
                   3070:             my $setpriv = 1;
                   3071:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3072:             if (defined($cfudom)) {
                   3073:                 $home=&homeserver($cfuname,$cfudom);
                   3074:                 $cfile=$file;
                   3075:             }
                   3076:         }
                   3077:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3078:             (($home ne '') && ($home ne 'no_host'))) {
                   3079:             my @ids=&current_machine_ids();
                   3080:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3081:                 $switchserver=1;
                   3082:             }
                   3083:         }
                   3084:     }
                   3085:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3086: }
                   3087: 
                   3088: sub is_course_upload {
                   3089:     my ($file,$cnum,$cdom) = @_;
                   3090:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3091:     $uploadpath =~ s{^\/}{};
                   3092:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3093:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3094:         return 1;
                   3095:     }
                   3096:     return;
                   3097: }
                   3098: 
                   3099: sub in_course {
                   3100:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3101:     if ($hideprivileged) {
                   3102:         my $skipuser;
1.1172.2.23  raeburn  3103:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3104:         my @possdoms = ($cdom);
                   3105:         if ($coursehash{'checkforpriv'}) {
                   3106:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3107:         }
                   3108:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3109:             $skipuser = 1;
                   3110:             if ($coursehash{'nothideprivileged'}) {
                   3111:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3112:                     my $user;
                   3113:                     if ($item =~ /:/) {
                   3114:                         $user = $item;
                   3115:                     } else {
                   3116:                         $user = join(':',split(/[\@]/,$item));
                   3117:                     }
                   3118:                     if ($user eq $uname.':'.$udom) {
                   3119:                         undef($skipuser);
                   3120:                         last;
                   3121:                     }
                   3122:                 }
                   3123:             }
                   3124:             if ($skipuser) {
                   3125:                 return 0;
                   3126:             }
                   3127:         }
                   3128:     }
                   3129:     $type ||= 'any';
                   3130:     if (!defined($cdom) || !defined($cnum)) {
                   3131:         my $cid  = $env{'request.course.id'};
                   3132:         $cdom = $env{'course.'.$cid.'.domain'};
                   3133:         $cnum = $env{'course.'.$cid.'.num'};
                   3134:     }
                   3135:     my $typesref;
                   3136:     if (($type eq 'any') || ($type eq 'all')) {
                   3137:         $typesref = ['active','previous','future'];
                   3138:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3139:         $typesref = [$type];
                   3140:     }
                   3141:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3142:                               $typesref,undef,[$cdom]);
                   3143:     my ($tmp) = keys(%roles);
                   3144:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3145:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3146:     if (@course_roles > 0) {
                   3147:         return 1;
                   3148:     }
                   3149:     return 0;
                   3150: }
                   3151: 
1.478     albertel 3152: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3153: # input: action, courseID, current domain, intended
1.637     raeburn  3154: #        path to file, source of file, instruction to parse file for objects,
                   3155: #        ref to hash for embedded objects,
                   3156: #        ref to hash for codebase of java objects.
1.1095    raeburn  3157: #        reference to scalar to accommodate mime type determined
                   3158: #          from File::MMagic if $parser = parse.
1.637     raeburn  3159: #
1.485     raeburn  3160: # output: url to file (if action was uploaddoc), 
                   3161: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3162: #
1.478     albertel 3163: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3164: # course.
1.477     raeburn  3165: #
1.478     albertel 3166: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3167: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3168: #          course's home server.
1.477     raeburn  3169: #
1.478     albertel 3170: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3171: #          be copied from $source (current location) to 
                   3172: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3173: #         and will then be copied to
                   3174: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3175: #         course's home server.
1.485     raeburn  3176: #
1.481     raeburn  3177: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3178: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3179: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3180: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3181: #         in course's home server.
1.637     raeburn  3182: #
1.477     raeburn  3183: 
                   3184: sub process_coursefile {
1.1095    raeburn  3185:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3186:         $mimetype)=@_;
1.477     raeburn  3187:     my $fetchresult;
1.638     albertel 3188:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3189:     if ($action eq 'propagate') {
1.638     albertel 3190:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3191: 			     $home);
1.481     raeburn  3192:     } else {
1.477     raeburn  3193:         my $fpath = '';
                   3194:         my $fname = $file;
1.478     albertel 3195:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3196:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3197:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3198:         if ($action eq 'copy') {
                   3199:             if ($source eq '') {
                   3200:                 $fetchresult = 'no source file';
                   3201:                 return $fetchresult;
                   3202:             } else {
                   3203:                 my $destination = $filepath.'/'.$fname;
                   3204:                 rename($source,$destination);
                   3205:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3206:                                  $home);
1.481     raeburn  3207:             }
                   3208:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3209:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3210:             print $fh $env{'form.'.$source};
1.481     raeburn  3211:             close($fh);
1.637     raeburn  3212:             if ($parser eq 'parse') {
1.1024    raeburn  3213:                 my $mm = new File::MMagic;
1.1095    raeburn  3214:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3215:                 if ($type eq 'text/html') {
1.1024    raeburn  3216:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3217:                     unless ($parse_result eq 'ok') {
                   3218:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3219:                     }
1.637     raeburn  3220:                 }
1.1095    raeburn  3221:                 if (ref($mimetype)) {
                   3222:                     $$mimetype = $type;
                   3223:                 } 
1.637     raeburn  3224:             }
1.477     raeburn  3225:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3226:                                  $home);
1.481     raeburn  3227:             if ($fetchresult eq 'ok') {
                   3228:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3229:             } else {
                   3230:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3231:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3232:                 return '/adm/notfound.html';
                   3233:             }
1.477     raeburn  3234:         }
                   3235:     }
1.485     raeburn  3236:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3237:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3238:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3239:     }
                   3240:     return $fetchresult;
                   3241: }
                   3242: 
1.637     raeburn  3243: sub build_filepath {
                   3244:     my ($fpath) = @_;
                   3245:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3246:     unless ($fpath eq '') {
                   3247:         my @parts=split('/',$fpath);
                   3248:         foreach my $part (@parts) {
                   3249:             $filepath.= '/'.$part;
                   3250:             if ((-e $filepath)!=1) {
                   3251:                 mkdir($filepath,0777);
                   3252:             }
                   3253:         }
                   3254:     }
                   3255:     return $filepath;
                   3256: }
                   3257: 
                   3258: sub store_edited_file {
1.638     albertel 3259:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3260:     my $file = $primary_url;
                   3261:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3262:     my $fpath = '';
                   3263:     my $fname = $file;
                   3264:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3265:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3266:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3267:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3268:     print $fh $content;
                   3269:     close($fh);
1.638     albertel 3270:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3271:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3272: 			  $home);
1.637     raeburn  3273:     if ($$fetchresult eq 'ok') {
                   3274:         return '/uploaded/'.$fpath.'/'.$fname;
                   3275:     } else {
1.638     albertel 3276:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3277: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3278:         return '/adm/notfound.html';
                   3279:     }
                   3280: }
                   3281: 
1.531     albertel 3282: sub clean_filename {
1.831     albertel 3283:     my ($fname,$args)=@_;
1.315     www      3284: # Replace Windows backslashes by forward slashes
1.257     www      3285:     $fname=~s/\\/\//g;
1.831     albertel 3286:     if (!$args->{'keep_path'}) {
                   3287:         # Get rid of everything but the actual filename
                   3288: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3289:     }
1.315     www      3290: # Replace spaces by underscores
                   3291:     $fname=~s/\s+/\_/g;
                   3292: # Replace all other weird characters by nothing
1.831     albertel 3293:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3294: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3295: # numbers
                   3296:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3297:     return $fname;
                   3298: }
1.1051    raeburn  3299: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3300: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3301: # image with the same aspect ratio as the original, but with dimensions which do 
                   3302: # not exceed $resizewidth and $resizeheight.
                   3303:  
1.984     neumanie 3304: sub resizeImage {
1.1051    raeburn  3305:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3306:     my $ima = Image::Magick->new;
                   3307:     my $resized;
                   3308:     if (-e $img_path) {
                   3309:         $ima->Read($img_path);
                   3310:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3311:             my $width = $ima->Get('width');
                   3312:             my $height = $ima->Get('height');
                   3313:             if ($width > $resizewidth) {
                   3314: 	        my $factor = $width/$resizewidth;
                   3315:                 my $newheight = $height/$factor;
                   3316:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3317:                 $resized = 1;
                   3318:             }
                   3319:         }
                   3320:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3321:             my $width = $ima->Get('width');
                   3322:             my $height = $ima->Get('height');
                   3323:             if ($height > $resizeheight) {
                   3324:                 my $factor = $height/$resizeheight;
                   3325:                 my $newwidth = $width/$factor;
                   3326:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3327:                 $resized = 1;
                   3328:             }
                   3329:         }
                   3330:         if ($resized) {
                   3331:             $ima->Write($img_path);
                   3332:         }
                   3333:     }
                   3334:     return;
1.977     amueller 3335: }
                   3336: 
1.608     albertel 3337: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3338: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3339: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3340: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3341: #                                    canceloverwrite, or ''. 
                   3342: #                   if 'coursedoc': upload to the current course
                   3343: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3344: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3345: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3346: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3347: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3348: #        $allfiles - reference to hash for embedded objects
                   3349: #        $codebase - reference to hash for codebase of java objects
                   3350: #        $desuname - username for permanent storage of uploaded file
                   3351: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3352: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3353: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3354: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3355: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3356: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3357: #                    from File::MMagic.
1.858     raeburn  3358: # 
1.686     albertel 3359: # output: url of file in userspace, or error: <message> 
                   3360: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3361: 
1.531     albertel 3362: sub userfileupload {
1.1090    raeburn  3363:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3364:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3365:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3366:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3367:     $fname=&clean_filename($fname);
1.1090    raeburn  3368:     # See if there is anything left
1.257     www      3369:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3370:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3371:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3372:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3373:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3374:         my $now = time;
1.1090    raeburn  3375:         my $filepath;
1.1095    raeburn  3376:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3377:              $filepath = 'tmp/helprequests/'.$now;
                   3378:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3379:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3380:                          '_'.$env{'user.domain'}.'/pending';
                   3381:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3382:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3383:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3384:                 $docudom = $destudom;
                   3385:             } else {
                   3386:                 $docudom = $env{'user.domain'};
                   3387:             }
1.1172.2.96  raeburn  3388:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3389:                 $docuname = $destuname;
                   3390:             } else {
                   3391:                 $docuname = $env{'user.name'};
                   3392:             }
                   3393:             if (exists($env{'form.group'})) {
                   3394:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3395:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3396:             }
                   3397:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3398:             if ($context eq 'canceloverwrite') {
                   3399:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3400:                 if (-e  $tempfile) {
                   3401:                     my @info = stat($tempfile);
                   3402:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3403:                         unlink($tempfile);
                   3404:                     }
                   3405:                 }
                   3406:                 return;
1.523     raeburn  3407:             }
                   3408:         }
1.1090    raeburn  3409:         # Create the directory if not present
1.741     raeburn  3410:         my @parts=split(/\//,$filepath);
                   3411:         my $fullpath = $perlvar{'lonDaemons'};
                   3412:         for (my $i=0;$i<@parts;$i++) {
                   3413:             $fullpath .= '/'.$parts[$i];
                   3414:             if ((-e $fullpath)!=1) {
                   3415:                 mkdir($fullpath,0777);
                   3416:             }
                   3417:         }
1.1172.2.96  raeburn  3418:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3419:         print $fh $env{'form.'.$formname};
                   3420:         close($fh);
1.1090    raeburn  3421:         if ($context eq 'existingfile') {
                   3422:             my @info = stat($fullpath.'/'.$fname);
                   3423:             return ($fullpath.'/'.$fname,$info[9]);
                   3424:         } else {
                   3425:             return $fullpath.'/'.$fname;
                   3426:         }
1.523     raeburn  3427:     }
1.995     raeburn  3428:     if ($subdir eq 'scantron') {
                   3429:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3430:     } else {
1.995     raeburn  3431:         $fname="$subdir/$fname";
                   3432:     }
1.1090    raeburn  3433:     if ($context eq 'coursedoc') {
1.638     albertel 3434: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3435: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3436:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3437:             return &finishuserfileupload($docuname,$docudom,
                   3438: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3439: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3440:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3441:         } else {
1.1172.2.21  raeburn  3442:             if ($env{'form.folder'}) {
                   3443:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3444:             }
1.638     albertel 3445:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3446: 				       $fname,$formname,$parser,
1.1095    raeburn  3447: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3448:         }
1.719     banghart 3449:     } elsif (defined($destuname)) {
                   3450:         my $docuname=$destuname;
                   3451:         my $docudom=$destudom;
1.860     raeburn  3452: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3453: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3454:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3455:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3456:     } else {
1.638     albertel 3457:         my $docuname=$env{'user.name'};
                   3458:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3459:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3460:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3461:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3462:         }
1.860     raeburn  3463: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3464: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3465:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3466:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3467:     }
1.271     www      3468: }
                   3469: 
                   3470: sub finishuserfileupload {
1.860     raeburn  3471:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3472:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3473:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3474:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3475:   
1.860     raeburn  3476:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3477:     $file=$fname;
                   3478:     if ($fname=~m|/|) {
                   3479:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3480: 	$path.=$fnamepath.'/';
                   3481:     }
1.259     www      3482:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3483:     my $count;
                   3484:     for ($count=4;$count<=$#parts;$count++) {
                   3485:         $filepath.="/$parts[$count]";
                   3486:         if ((-e $filepath)!=1) {
                   3487: 	    mkdir($filepath,0777);
                   3488:         }
                   3489:     }
1.984     neumanie 3490: 
1.258     www      3491: # Save the file
                   3492:     {
1.1172.2.96  raeburn  3493: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3494: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3495: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3496: 	    return '/adm/notfound.html';
                   3497: 	}
1.1090    raeburn  3498:         if ($context eq 'overwrite') {
1.1117    foxr     3499:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3500:             my $target = $filepath.'/'.$file;
                   3501:             if (-e $source) {
                   3502:                 my @info = stat($source);
                   3503:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3504:                     unless (&File::Copy::move($source,$target)) {
                   3505:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3506:                         return "Moving from $source failed";
                   3507:                     }
                   3508:                 } else {
                   3509:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3510:                 }
                   3511:             } else {
                   3512:                 return "Temporary file: $source missing";
                   3513:             }
                   3514:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3515: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3516: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3517: 	    return '/adm/notfound.html';
                   3518: 	}
1.570     albertel 3519: 	close(FH);
1.1051    raeburn  3520:         if ($resizewidth && $resizeheight) {
                   3521:             my $mm = new File::MMagic;
                   3522:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3523:             if ($mime_type =~ m{^image/}) {
                   3524: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3525:             }  
1.977     amueller 3526: 	}
1.258     www      3527:     }
1.1152    raeburn  3528:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3529:         if (ref($mimetype)) {
                   3530:             if ($$mimetype eq '') {
                   3531:                 my $mm = new File::MMagic;
                   3532:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3533:                 $$mimetype = $type;
                   3534:             }
                   3535:         }
                   3536:     }
1.637     raeburn  3537:     if ($parser eq 'parse') {
1.1152    raeburn  3538:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3539:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3540:                                                        $allfiles,$codebase);
                   3541:             unless ($parse_result eq 'ok') {
                   3542:                 &logthis('Failed to parse '.$filepath.$file.
                   3543: 	   	         ' for embedded media: '.$parse_result); 
                   3544:             }
1.637     raeburn  3545:         }
                   3546:     }
1.860     raeburn  3547:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3548:         my $input = $filepath.'/'.$file;
                   3549:         my $output = $filepath.'/'.'tn-'.$file;
                   3550:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3551:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3552:         system({$args[0]} @args);
1.860     raeburn  3553:         if (-e $filepath.'/'.'tn-'.$file) {
                   3554:             $fetchthumb  = 1; 
                   3555:         }
                   3556:     }
1.858     raeburn  3557:  
1.259     www      3558: # Notify homeserver to grep it
                   3559: #
1.984     neumanie 3560:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3561:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3562:     if ($fetchresult eq 'ok') {
1.860     raeburn  3563:         if ($fetchthumb) {
                   3564:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3565:             if ($thumbresult ne 'ok') {
                   3566:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3567:                          $docuhome.': '.$thumbresult);
                   3568:             }
                   3569:         }
1.259     www      3570: #
1.258     www      3571: # Return the URL to it
1.494     albertel 3572:         return '/uploaded/'.$path.$file;
1.263     www      3573:     } else {
1.494     albertel 3574:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3575: 		 ': '.$fetchresult);
1.263     www      3576:         return '/adm/notfound.html';
1.858     raeburn  3577:     }
1.493     albertel 3578: }
                   3579: 
1.637     raeburn  3580: sub extract_embedded_items {
1.961     raeburn  3581:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3582:     my @state = ();
1.1164    raeburn  3583:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3584:     my %javafiles = (
                   3585:                       codebase => '',
                   3586:                       code => '',
                   3587:                       archive => ''
                   3588:                     );
                   3589:     my %mediafiles = (
                   3590:                       src => '',
                   3591:                       movie => '',
                   3592:                      );
1.648     raeburn  3593:     my $p;
                   3594:     if ($content) {
                   3595:         $p = HTML::LCParser->new($content);
                   3596:     } else {
1.961     raeburn  3597:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3598:     }
1.641     albertel 3599:     while (my $t=$p->get_token()) {
1.640     albertel 3600: 	if ($t->[0] eq 'S') {
                   3601: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3602: 	    push(@state, $tagname);
1.648     raeburn  3603:             if (lc($tagname) eq 'allow') {
                   3604:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3605:             }
1.640     albertel 3606: 	    if (lc($tagname) eq 'img') {
                   3607: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3608: 	    }
1.886     albertel 3609: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3610:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3611: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3612:                 }
1.886     albertel 3613: 	    }
1.645     raeburn  3614:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3615:                 my $src;
1.645     raeburn  3616:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3617:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3618:                 } else {
1.1164    raeburn  3619:                     if ($attr->{'src'} ne '') {
                   3620:                         $src = $attr->{'src'};
                   3621:                         &add_filetype($allfiles,$src,'src');
                   3622:                     }
                   3623:                 }
                   3624:                 my $text = $p->get_trimmed_text();
                   3625:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3626:                     my @swfargs = split(/,/,$1);
                   3627:                     foreach my $item (@swfargs) {
                   3628:                         $item =~ s/["']//g;
                   3629:                         $item =~ s/^\s+//;
                   3630:                         $item =~ s/\s+$//;
                   3631:                     }
                   3632:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3633:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3634:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3635:                         } else {
                   3636:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3637:                         }
                   3638:                     }
1.645     raeburn  3639:                 }
                   3640:             }
                   3641:             if (lc($tagname) eq 'link') {
                   3642:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3643:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3644:                 }
                   3645:             }
1.640     albertel 3646: 	    if (lc($tagname) eq 'object' ||
                   3647: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3648: 		foreach my $item (keys(%javafiles)) {
                   3649: 		    $javafiles{$item} = '';
                   3650: 		}
1.1164    raeburn  3651:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3652:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3653:                 }
1.640     albertel 3654: 	    }
                   3655: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3656: 		my $name = lc($attr->{'name'});
                   3657: 		foreach my $item (keys(%javafiles)) {
                   3658: 		    if ($name eq $item) {
                   3659: 			$javafiles{$item} = $attr->{'value'};
                   3660: 			last;
                   3661: 		    }
                   3662: 		}
1.1164    raeburn  3663:                 my $pathfrom;
1.640     albertel 3664: 		foreach my $item (keys(%mediafiles)) {
                   3665: 		    if ($name eq $item) {
1.1164    raeburn  3666:                         $pathfrom = $attr->{'value'};
                   3667:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3668: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3669: 			last;
                   3670: 		    }
                   3671: 		}
1.1164    raeburn  3672:                 if ($name eq 'flashvars') {
                   3673:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3674:                 }
                   3675:                 if ($pathfrom ne '') {
                   3676:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3677:                                          $pathfrom);
                   3678:                 }
1.640     albertel 3679: 	    }
                   3680: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3681: 		foreach my $item (keys(%javafiles)) {
                   3682: 		    if ($attr->{$item}) {
                   3683: 			$javafiles{$item} = $attr->{$item};
                   3684: 			last;
                   3685: 		    }
                   3686: 		}
                   3687: 		foreach my $item (keys(%mediafiles)) {
                   3688: 		    if ($attr->{$item}) {
                   3689: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3690: 			last;
                   3691: 		    }
                   3692: 		}
1.1164    raeburn  3693:                 if (lc($tagname) eq 'embed') {
                   3694:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3695:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3696:                                              $attr->{'src'});
                   3697:                     }
                   3698:                 }
1.640     albertel 3699: 	    }
1.1172.2.35  raeburn  3700:             if (lc($tagname) eq 'iframe') {
                   3701:                 my $src = $attr->{'src'} ;
                   3702:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3703:                     &add_filetype($allfiles,$src,'src');
                   3704:                 } elsif ($src =~ m{^/}) {
                   3705:                     if ($env{'request.course.id'}) {
                   3706:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3707:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3708:                         my $url = &hreflocation('',$fullpath);
                   3709:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3710:                             my $relpath = $1;
                   3711:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3712:                                 &add_filetype($allfiles,$1,'src');
                   3713:                             }
                   3714:                         }
                   3715:                     }
                   3716:                 }
                   3717:             }
1.1164    raeburn  3718:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3719:                 pop(@state);
1.1164    raeburn  3720:             }
1.640     albertel 3721: 	} elsif ($t->[0] eq 'E') {
                   3722: 	    my ($tagname) = ($t->[1]);
                   3723: 	    if ($javafiles{'codebase'} ne '') {
                   3724: 		$javafiles{'codebase'} .= '/';
                   3725: 	    }  
                   3726: 	    if (lc($tagname) eq 'applet' ||
                   3727: 		lc($tagname) eq 'object' ||
                   3728: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3729: 		) {
                   3730: 		foreach my $item (keys(%javafiles)) {
                   3731: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3732: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3733: 			&add_filetype($allfiles,$file,$item);
                   3734: 		    }
                   3735: 		}
                   3736: 	    } 
                   3737: 	    pop @state;
                   3738: 	}
                   3739:     }
1.1164    raeburn  3740:     foreach my $id (sort(keys(%flashvars))) {
                   3741:         if ($shockwave{$id} ne '') {
                   3742:             my @pairs = split(/\&/,$flashvars{$id});
                   3743:             foreach my $pair (@pairs) {
                   3744:                 my ($key,$value) = split(/\=/,$pair);
                   3745:                 if ($key eq 'thumb') {
                   3746:                     &add_filetype($allfiles,$value,$key);
                   3747:                 } elsif ($key eq 'content') {
                   3748:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3749:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3750:                     if ($ext ne '') {
                   3751:                         &add_filetype($allfiles,$path.$value,$ext);
                   3752:                     }
                   3753:                 }
                   3754:             }
                   3755:         }
                   3756:     }
1.637     raeburn  3757:     return 'ok';
                   3758: }
                   3759: 
1.639     albertel 3760: sub add_filetype {
                   3761:     my ($allfiles,$file,$type)=@_;
                   3762:     if (exists($allfiles->{$file})) {
                   3763: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3764: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3765: 	}
                   3766:     } else {
                   3767: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3768:     }
                   3769: }
                   3770: 
1.1164    raeburn  3771: sub embedded_dependency {
                   3772:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3773:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3774:         if (($identifier ne '') &&
                   3775:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3776:             ($pathfrom ne '')) {
                   3777:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3778:             foreach my $dep (@{$related->{$identifier}}) {
                   3779:                 &add_filetype($allfiles,$path.$dep,'object');
                   3780:             }
                   3781:         }
                   3782:     }
                   3783:     return;
                   3784: }
                   3785: 
1.493     albertel 3786: sub removeuploadedurl {
1.984     neumanie 3787:     my ($url)=@_;	
                   3788:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3789:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3790: }
                   3791: 
                   3792: sub removeuserfile {
                   3793:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3794:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3795:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3796:     if ($result eq 'ok') {	
1.798     raeburn  3797:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3798:             my $metafile = $fname.'.meta';
                   3799:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3800: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3801:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3802:             my $sqlresult = 
1.823     albertel 3803:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3804:                                         'portfolio_metadata',$group,
                   3805:                                         'delete');
1.798     raeburn  3806:         }
                   3807:     }
                   3808:     return $result;
1.257     www      3809: }
1.15      www      3810: 
1.530     albertel 3811: sub mkdiruserfile {
                   3812:     my ($docuname,$docudom,$dir)=@_;
                   3813:     my $home=&homeserver($docuname,$docudom);
                   3814:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3815: }
                   3816: 
1.531     albertel 3817: sub renameuserfile {
                   3818:     my ($docuname,$docudom,$old,$new)=@_;
                   3819:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3820:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3821:                         &escape("$old").':'.&escape("$new"),$home);
                   3822:     if ($result eq 'ok') {
                   3823:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3824:             my $oldmeta = $old.'.meta';
                   3825:             my $newmeta = $new.'.meta';
                   3826:             my $metaresult = 
                   3827:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3828: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3829:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3830:             my $sqlresult = 
1.823     albertel 3831:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3832:                                         'portfolio_metadata',$group,
                   3833:                                         'delete');
1.798     raeburn  3834:         }
                   3835:     }
                   3836:     return $result;
1.531     albertel 3837: }
                   3838: 
1.14      www      3839: # ------------------------------------------------------------------------- Log
                   3840: 
                   3841: sub log {
                   3842:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3843:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3844: }
                   3845: 
                   3846: # ------------------------------------------------------------------ Course Log
1.352     www      3847: #
                   3848: # This routine flushes several buffers of non-mission-critical nature
                   3849: #
1.157     www      3850: 
                   3851: sub flushcourselogs {
1.352     www      3852:     &logthis('Flushing log buffers');
                   3853: #
                   3854: # course logs
                   3855: # This is a log of all transactions in a course, which can be used
                   3856: # for data mining purposes
                   3857: #
                   3858: # It also collects the courseid database, which lists last transaction
                   3859: # times and course titles for all courseids
                   3860: #
                   3861:     my %courseidbuffer=();
1.921     raeburn  3862:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3863:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3864: 		          &escape($courselogs{$crsid}),
                   3865: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3866: 	    delete $courselogs{$crsid};
                   3867:         } else {
                   3868:             &logthis('Failed to flush log buffer for '.$crsid);
                   3869:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3870:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3871:                         " exceeded maximum size, deleting.</font>");
                   3872:                delete $courselogs{$crsid};
                   3873:             }
1.352     www      3874:         }
1.920     raeburn  3875:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3876:             'description' => $coursedescrbuf{$crsid},
                   3877:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3878:             'type'        => $coursetypebuf{$crsid},
                   3879:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3880:         };
1.191     harris41 3881:     }
1.352     www      3882: #
                   3883: # Write course id database (reverse lookup) to homeserver of courses 
                   3884: # Is used in pickcourse
                   3885: #
1.840     albertel 3886:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3887:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3888:                                     $courseidbuffer{$crs_home},
                   3889:                                     $crs_home,'timeonly');
1.352     www      3890:     }
                   3891: #
                   3892: # File accesses
                   3893: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3894: #
1.449     matthew  3895:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3896:         if ($entry =~ /___count$/) {
                   3897:             my ($dom,$name);
1.807     albertel 3898:             ($dom,$name,undef)=
1.811     albertel 3899: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3900:             if (! defined($dom) || $dom eq '' || 
                   3901:                 ! defined($name) || $name eq '') {
1.620     albertel 3902:                 my $cid = $env{'request.course.id'};
                   3903:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3904:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3905:             }
1.450     matthew  3906:             my $value = $accesshash{$entry};
                   3907:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3908:             my %temphash=($url => $value);
1.449     matthew  3909:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3910:             if ($result eq 'ok') {
                   3911:                 delete $accesshash{$entry};
                   3912:             }
                   3913:         } else {
1.811     albertel 3914:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3915:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3916:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3917:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3918:                 delete $accesshash{$entry};
                   3919:             }
1.185     www      3920:         }
1.191     harris41 3921:     }
1.352     www      3922: #
                   3923: # Roles
                   3924: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3925: #
1.800     albertel 3926:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3927:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3928: 	    split(/\:/,$entry);
                   3929:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3930:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3931:                 $rudom,$runame) eq 'ok') {
                   3932: 	    delete $userrolehash{$entry};
                   3933:         }
                   3934:     }
1.662     raeburn  3935: #
1.1172.2.90  raeburn  3936: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  3937: #
                   3938:     my %domrolebuffer = ();
1.1000    raeburn  3939:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3940:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3941:         if ($domrolebuffer{$rudom}) {
                   3942:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3943:                       '='.&escape($domainrolehash{$entry});
                   3944:         } else {
                   3945:             $domrolebuffer{$rudom}.=&escape($entry).
                   3946:                       '='.&escape($domainrolehash{$entry});
                   3947:         }
                   3948:         delete $domainrolehash{$entry};
                   3949:     }
                   3950:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  3951:         my %servers;
                   3952:         if (defined(&domain($dom,'primary'))) {
                   3953:             my $primary=&domain($dom,'primary');
                   3954:             my $hostname=&hostname($primary);
                   3955:             $servers{$primary} = $hostname;
                   3956:         } else {
                   3957:             %servers = &get_servers($dom,'library');
                   3958:         }
1.841     albertel 3959: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  3960: 	    if (&reply('domroleput:'.$dom.':'.
                   3961: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3962: 	        last;
                   3963: 	    } else {
1.841     albertel 3964: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3965: 	    }
1.662     raeburn  3966:         }
                   3967:     }
1.186     www      3968:     $dumpcount++;
1.157     www      3969: }
                   3970: 
                   3971: sub courselog {
                   3972:     my $what=shift;
1.158     www      3973:     $what=time.':'.$what;
1.620     albertel 3974:     unless ($env{'request.course.id'}) { return ''; }
                   3975:     $coursedombuf{$env{'request.course.id'}}=
                   3976:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3977:     $coursenumbuf{$env{'request.course.id'}}=
                   3978:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3979:     $coursehombuf{$env{'request.course.id'}}=
                   3980:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3981:     $coursedescrbuf{$env{'request.course.id'}}=
                   3982:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3983:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3984:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3985:     $courseownerbuf{$env{'request.course.id'}}=
                   3986:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3987:     $coursetypebuf{$env{'request.course.id'}}=
                   3988:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3989:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3990: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3991:     } else {
1.620     albertel 3992: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3993:     }
1.620     albertel 3994:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3995: 	&flushcourselogs();
                   3996:     }
1.158     www      3997: }
                   3998: 
                   3999: sub courseacclog {
                   4000:     my $fnsymb=shift;
1.620     albertel 4001:     unless ($env{'request.course.id'}) { return ''; }
                   4002:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4003:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4004:         $what.=':POST';
1.583     matthew  4005:         # FIXME: Probably ought to escape things....
1.800     albertel 4006: 	foreach my $key (keys(%env)) {
                   4007:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4008:                 my $formitem = $1;
                   4009:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4010:                     $what.=':'.$formitem.'='.$env{$key};
                   4011:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4012:                     $what.=':'.$formitem.'='.$env{$key};
                   4013:                 }
1.158     www      4014:             }
1.191     harris41 4015:         }
1.583     matthew  4016:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4017:         # FIXME: We should not be depending on a form parameter that someone
                   4018:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4019:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4020:             $what.= ':POST';
                   4021:             # FIXME: Probably ought to escape things....
                   4022:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4023:                                  'crsdiscuss') {
1.620     albertel 4024:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4025:             }
                   4026:         }
1.158     www      4027:     }
                   4028:     &courselog($what);
1.149     www      4029: }
                   4030: 
1.185     www      4031: sub countacc {
                   4032:     my $url=&declutter(shift);
1.458     matthew  4033:     return if (! defined($url) || $url eq '');
1.620     albertel 4034:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4035: #
                   4036: # Mark that this url was used in this course
                   4037: #
1.620     albertel 4038:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4039: #
                   4040: # Increase the access count for this resource in this child process
                   4041: #
1.281     www      4042:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4043:     $accesshash{$key}++;
1.185     www      4044: }
1.349     www      4045: 
1.361     www      4046: sub linklog {
                   4047:     my ($from,$to)=@_;
                   4048:     $from=&declutter($from);
                   4049:     $to=&declutter($to);
                   4050:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4051:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4052: }
1.1160    www      4053: 
                   4054: sub statslog {
                   4055:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4056:     if ($users<2) { return; }
                   4057:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4058:             'course'       => $env{'request.course.id'},
                   4059:             'sections'     => '"all"',
                   4060:             'num_students' => $users,
                   4061:             'part'         => $part,
                   4062:             'symb'         => $symb,
                   4063:             'mean_tries'   => $av_attempts,
                   4064:             'deg_of_diff'  => $degdiff});
                   4065:     foreach my $key (keys(%dynstore)) {
                   4066:         $accesshash{$key}=$dynstore{$key};
                   4067:     }
                   4068: }
1.361     www      4069:   
1.349     www      4070: sub userrolelog {
                   4071:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4072:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4073:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4074:        $userrolehash
                   4075:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4076:                     =$tend.':'.$tstart;
1.662     raeburn  4077:     }
1.1169    droeschl 4078:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4079:        $userrolehash
                   4080:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4081:                     =$tend.':'.$tstart;
                   4082:     }
1.1172.2.90  raeburn  4083:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4084:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4085:        $domainrolehash
                   4086:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4087:                     = $tend.':'.$tstart;
                   4088:     }
1.351     www      4089: }
                   4090: 
1.957     raeburn  4091: sub courserolelog {
                   4092:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4093:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4094:         my $cdom = $1;
                   4095:         my $cnum = $2;
                   4096:         my $sec = $3;
                   4097:         my $namespace = 'rolelog';
                   4098:         my %storehash = (
                   4099:                            role    => $trole,
                   4100:                            start   => $tstart,
                   4101:                            end     => $tend,
                   4102:                            selfenroll => $selfenroll,
                   4103:                            context    => $context,
                   4104:                         );
                   4105:         if ($trole eq 'gr') {
                   4106:             $namespace = 'groupslog';
                   4107:             $storehash{'group'} = $sec;
                   4108:         } else {
                   4109:             $storehash{'section'} = $sec;
                   4110:         }
                   4111:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4112:                    $domain,$cnum,$cdom);
                   4113:         if (($trole ne 'st') || ($sec ne '')) {
                   4114:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4115:         }
                   4116:     }
                   4117:     return;
                   4118: }
                   4119: 
1.1172.2.9  raeburn  4120: sub domainrolelog {
                   4121:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4122:     if ($area =~ m{^/($match_domain)/$}) {
                   4123:         my $cdom = $1;
                   4124:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4125:         my $namespace = 'rolelog';
                   4126:         my %storehash = (
                   4127:                            role    => $trole,
                   4128:                            start   => $tstart,
                   4129:                            end     => $tend,
                   4130:                            context => $context,
                   4131:                         );
                   4132:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4133:                    $domain,$domconfiguser,$cdom);
                   4134:     }
                   4135:     return;
                   4136: 
                   4137: }
                   4138: 
                   4139: sub coauthorrolelog {
                   4140:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4141:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4142:         my $audom = $1;
                   4143:         my $auname = $2;
                   4144:         my $namespace = 'rolelog';
                   4145:         my %storehash = (
                   4146:                            role    => $trole,
                   4147:                            start   => $tstart,
                   4148:                            end     => $tend,
                   4149:                            context => $context,
                   4150:                         );
                   4151:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4152:                    $domain,$auname,$audom);
                   4153:     }
                   4154:     return;
                   4155: }
                   4156: 
1.351     www      4157: sub get_course_adv_roles {
1.948     raeburn  4158:     my ($cid,$codes) = @_;
1.620     albertel 4159:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4160:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4161:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4162:     my %nothide=();
1.800     albertel 4163:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4164:         if ($user !~ /:/) {
                   4165: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4166:         } else {
                   4167:             $nothide{$user}=1;
                   4168:         }
1.470     www      4169:     }
1.1172.2.23  raeburn  4170:     my @possdoms = ($coursehash{'domain'});
                   4171:     if ($coursehash{'checkforpriv'}) {
                   4172:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4173:     }
1.351     www      4174:     my %returnhash=();
                   4175:     my %dumphash=
                   4176:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4177:     my $now=time;
1.997     raeburn  4178:     my %privileged;
1.1000    raeburn  4179:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4180: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4181:         if (($tstart) && ($tstart<0)) { next; }
                   4182:         if (($tend) && ($tend<$now)) { next; }
                   4183:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4184:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4185: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4186:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4187:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4188: 	if ($role eq 'cr') { next; }
1.948     raeburn  4189:         if ($codes) {
                   4190:             if ($section) { $role .= ':'.$section; }
                   4191:             if ($returnhash{$role}) {
                   4192:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4193:             } else {
                   4194:                 $returnhash{$role}=$username.':'.$domain;
                   4195:             }
1.351     www      4196:         } else {
1.988     raeburn  4197:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4198:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4199:             if ($returnhash{$key}) {
                   4200: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4201:             } else {
                   4202:                 $returnhash{$key}=$username.':'.$domain;
                   4203:             }
1.351     www      4204:         }
1.948     raeburn  4205:     }
1.400     www      4206:     return %returnhash;
                   4207: }
                   4208: 
                   4209: sub get_my_roles {
1.937     raeburn  4210:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4211:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4212:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4213:     my (%dumphash,%nothide);
1.1086    raeburn  4214:     if ($context eq 'userroles') {
1.1166    raeburn  4215:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4216:     } else {
1.1172.2.23  raeburn  4217:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4218:         if ($hidepriv) {
                   4219:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4220:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4221:                 if ($user !~ /:/) {
                   4222:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4223:                 } else {
                   4224:                     $nothide{$user} = 1;
                   4225:                 }
                   4226:             }
                   4227:         }
1.858     raeburn  4228:     }
1.400     www      4229:     my %returnhash=();
                   4230:     my $now=time;
1.999     raeburn  4231:     my %privileged;
1.800     albertel 4232:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4233:         my ($role,$tend,$tstart);
                   4234:         if ($context eq 'userroles') {
1.1149    raeburn  4235:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4236: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4237:         } else {
                   4238:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4239:         }
1.400     www      4240:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4241:         my $status = 'active';
1.939     raeburn  4242:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4243:             $status = 'previous';
                   4244:         } 
                   4245:         if (($tstart) && ($now<$tstart)) {
                   4246:             $status = 'future';
                   4247:         }
                   4248:         if (ref($types) eq 'ARRAY') {
                   4249:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4250:                 next;
                   4251:             } 
                   4252:         } else {
                   4253:             if ($status ne 'active') {
                   4254:                 next;
                   4255:             }
                   4256:         }
1.867     raeburn  4257:         my ($rolecode,$username,$domain,$section,$area);
                   4258:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4259:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4260:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4261:         } else {
                   4262:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4263:         }
1.832     raeburn  4264:         if (ref($roledoms) eq 'ARRAY') {
                   4265:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4266:                 next;
                   4267:             }
                   4268:         }
                   4269:         if (ref($roles) eq 'ARRAY') {
                   4270:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4271:                 if ($role =~ /^cr\//) {
                   4272:                     if (!grep(/^cr$/,@{$roles})) {
                   4273:                         next;
                   4274:                     }
1.1104    raeburn  4275:                 } elsif ($role =~ /^gr\//) {
                   4276:                     if (!grep(/^gr$/,@{$roles})) {
                   4277:                         next;
                   4278:                     }
1.922     raeburn  4279:                 } else {
                   4280:                     next;
                   4281:                 }
1.832     raeburn  4282:             }
1.867     raeburn  4283:         }
1.937     raeburn  4284:         if ($hidepriv) {
1.1172.2.23  raeburn  4285:             my @privroles = ('dc','su');
1.999     raeburn  4286:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4287:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4288:             } else {
1.1172.2.23  raeburn  4289:                 my $possdoms = [$domain];
                   4290:                 if (ref($roledoms) eq 'ARRAY') {
                   4291:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4292:                 }
1.1172.2.23  raeburn  4293:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4294:                     if (!$nothide{$username.':'.$domain}) {
                   4295:                         next;
                   4296:                     }
                   4297:                 }
1.937     raeburn  4298:             }
                   4299:         }
1.933     raeburn  4300:         if ($withsec) {
                   4301:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4302:                 $tstart.':'.$tend;
                   4303:         } else {
                   4304:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4305:         }
1.832     raeburn  4306:     }
1.373     www      4307:     return %returnhash;
1.399     www      4308: }
                   4309: 
1.1172.2.89  raeburn  4310: sub get_all_adhocroles {
                   4311:     my ($dom) = @_;
                   4312:     my @roles_by_num = ();
                   4313:     my %domdefaults = &get_domain_defaults($dom);
                   4314:     my (%description,%access_in_dom,%access_info);
                   4315:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4316:         my $count = 0;
                   4317:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4318:         my %ordered;
                   4319:         foreach my $role (sort(keys(%domcurrent))) {
                   4320:             my ($order,$desc,$access_in_dom);
                   4321:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4322:                 $order = $domcurrent{$role}{'order'};
                   4323:                 $desc = $domcurrent{$role}{'desc'};
                   4324:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4325:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4326:             }
                   4327:             if ($order eq '') {
                   4328:                 $order = $count;
                   4329:             }
                   4330:             $ordered{$order} = $role;
                   4331:             if ($desc ne '') {
                   4332:                 $description{$role} = $desc;
                   4333:             } else {
                   4334:                 $description{$role}= $role;
                   4335:             }
                   4336:             $count++;
                   4337:         }
                   4338:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4339:             push(@roles_by_num,$ordered{$item});
                   4340:         }
                   4341:     }
                   4342:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4343: }
                   4344: 
                   4345: sub get_my_adhocroles {
                   4346:     my ($cid,$checkreg) = @_;
                   4347:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4348:     if ($env{'request.course.id'} eq $cid) {
                   4349:         $cdom = $env{'course.'.$cid.'.domain'};
                   4350:         $cnum = $env{'course.'.$cid.'.num'};
                   4351:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4352:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4353:         $cdom = $1;
                   4354:         $cnum = $2;
                   4355:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4356:                                      $cdom,$cnum);
                   4357:     }
                   4358:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4359:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4360:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4361:         if ($rosterhash{$user} ne '') {
                   4362:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4363:             return ([],{}) if ($type eq 'auto');
                   4364:         }
                   4365:     }
                   4366:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4367:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4368:             my $then=$env{'user.login.time'};
                   4369:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4370:             if (!$update) {
                   4371:                 $update = $then;
                   4372:             }
                   4373:             my @liveroles;
                   4374:             foreach my $role ('dh','da') {
                   4375:                 if ($env{"user.role.$role./$cdom/"}) {
                   4376:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4377:                     my $limit = $update;
                   4378:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4379:                         $limit = $then;
                   4380:                     }
                   4381:                     my $activerole = 1;
                   4382:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4383:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4384:                     if ($activerole) {
                   4385:                         push(@liveroles,$role);
                   4386:                     }
                   4387:                 }
                   4388:             }
                   4389:             if (@liveroles) {
1.1172.2.89  raeburn  4390:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4391:                     my ($accessref,$accessinfo,%access_in_dom);
                   4392:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4393:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4394:                         if (@{$roles_by_num}) {
                   4395:                             my %settings;
                   4396:                             if ($env{'request.course.id'} eq $cid) {
                   4397:                                 foreach my $envkey (keys(%env)) {
                   4398:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4399:                                         $settings{$1} = $env{$envkey};
                   4400:                                     }
                   4401:                                 }
                   4402:                             } else {
                   4403:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4404:                             }
                   4405:                             my %setincrs;
                   4406:                             if ($settings{'internal.adhocaccess'}) {
                   4407:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4408:                             }
                   4409:                             my @statuses;
                   4410:                             if ($env{'environment.inststatus'}) {
                   4411:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4412:                             }
                   4413:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4414:                             if (ref($accessref) eq 'HASH') {
                   4415:                                 %access_in_dom = %{$accessref};
                   4416:                             }
                   4417:                             foreach my $role (@{$roles_by_num}) {
                   4418:                                 my ($curraccess,@okstatus,@personnel);
                   4419:                                 if ($setincrs{$role}) {
                   4420:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4421:                                     if ($curraccess eq 'status') {
                   4422:                                         @okstatus = split(/\&/,$rest);
                   4423:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4424:                                         @personnel = split(/\&/,$rest);
                   4425:                                     }
                   4426:                                 } else {
                   4427:                                     $curraccess = $access_in_dom{$role};
                   4428:                                     if (ref($accessinfo) eq 'HASH') {
                   4429:                                         if ($curraccess eq 'status') {
                   4430:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4431:                                                 @okstatus = @{$accessinfo->{$role}};
                   4432:                                             }
                   4433:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4434:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4435:                                                 @personnel = @{$accessinfo->{$role}};
                   4436:                                             }
                   4437:                                         }
                   4438:                                     }
                   4439:                                 }
                   4440:                                 if ($curraccess eq 'none') {
                   4441:                                     next;
                   4442:                                 } elsif ($curraccess eq 'all') {
                   4443:                                     push(@possroles,$role);
1.1172.2.90  raeburn  4444:                                 } elsif ($curraccess eq 'dh') {
                   4445:                                     if (grep(/^dh$/,@liveroles)) {
                   4446:                                         push(@possroles,$role);
                   4447:                                     } else {
                   4448:                                         next;
                   4449:                                     }
                   4450:                                 } elsif ($curraccess eq 'da') {
                   4451:                                     if (grep(/^da$/,@liveroles)) {
                   4452:                                         push(@possroles,$role);
                   4453:                                     } else {
                   4454:                                         next;
                   4455:                                     }
1.1172.2.89  raeburn  4456:                                 } elsif ($curraccess eq 'status') {
                   4457:                                     if (@okstatus) {
                   4458:                                         if (!@statuses) {
                   4459:                                             if (grep(/^default$/,@okstatus)) {
                   4460:                                                 push(@possroles,$role);
                   4461:                                             }
                   4462:                                         } else {
                   4463:                                             foreach my $status (@okstatus) {
                   4464:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4465:                                                     push(@possroles,$role);
                   4466:                                                     last;
                   4467:                                                 }
                   4468:                                             }
                   4469:                                         }
                   4470:                                     }
                   4471:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4472:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4473:                                         if ($curraccess eq 'exc') {
                   4474:                                             push(@possroles,$role);
                   4475:                                         }
                   4476:                                     } elsif ($curraccess eq 'inc') {
                   4477:                                         push(@possroles,$role);
                   4478:                                     }
                   4479:                                 }
                   4480:                             }
                   4481:                         }
                   4482:                     }
                   4483:                 }
                   4484:             }
                   4485:         }
                   4486:     }
                   4487:     unless (ref($description) eq 'HASH') {
                   4488:         if (ref($roles_by_num) eq 'ARRAY') {
                   4489:             my %desc;
                   4490:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4491:             $description = \%desc;
                   4492:         } else {
                   4493:             $description = {};
                   4494:         }
                   4495:     }
                   4496:     return (\@possroles,$description);
                   4497: }
                   4498: 
1.399     www      4499: # ----------------------------------------------------- Frontpage Announcements
                   4500: #
                   4501: #
                   4502: 
                   4503: sub postannounce {
                   4504:     my ($server,$text)=@_;
1.844     albertel 4505:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4506:     unless ($text=~/\w/) { $text=''; }
                   4507:     return &reply('setannounce:'.&escape($text),$server);
                   4508: }
                   4509: 
                   4510: sub getannounce {
1.448     albertel 4511: 
1.1172.2.96  raeburn  4512:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4513: 	my $announcement='';
1.800     albertel 4514: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4515: 	close($fh);
1.399     www      4516: 	if ($announcement=~/\w/) { 
                   4517: 	    return 
                   4518:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4519:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4520: 	} else {
                   4521: 	    return '';
                   4522: 	}
                   4523:     } else {
                   4524: 	return '';
                   4525:     }
1.351     www      4526: }
1.353     www      4527: 
                   4528: # ---------------------------------------------------------- Course ID routines
                   4529: # Deal with domain's nohist_courseid.db files
                   4530: #
                   4531: 
                   4532: sub courseidput {
1.921     raeburn  4533:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4534:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4535:     my $outcome;
                   4536:     if ($caller eq 'timeonly') {
                   4537:         my $cids = '';
                   4538:         foreach my $item (keys(%$storehash)) {
                   4539:             $cids.=&escape($item).'&';
                   4540:         }
                   4541:         $cids=~s/\&$//;
                   4542:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4543:                           $coursehome);       
                   4544:     } else {
                   4545:         my $items = '';
                   4546:         foreach my $item (keys(%$storehash)) {
                   4547:             $items.= &escape($item).'='.
                   4548:                      &freeze_escape($$storehash{$item}).'&';
                   4549:         }
                   4550:         $items=~s/\&$//;
                   4551:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4552:                           $coursehome);
1.918     raeburn  4553:     }
                   4554:     if ($outcome eq 'unknown_cmd') {
                   4555:         my $what;
                   4556:         foreach my $cid (keys(%$storehash)) {
                   4557:             $what .= &escape($cid).'=';
1.921     raeburn  4558:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4559:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4560:             }
                   4561:             $what =~ s/\:$/&/;
                   4562:         }
                   4563:         $what =~ s/\&$//;  
                   4564:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4565:     } else {
                   4566:         return $outcome;
                   4567:     }
1.353     www      4568: }
                   4569: 
                   4570: sub courseiddump {
1.921     raeburn  4571:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4572:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4573:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4574:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4575:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4576:     my $as_hash = 1;
                   4577:     my %returnhash;
                   4578:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4579:     my %libserv = &all_library();
                   4580:     foreach my $tryserver (keys(%libserv)) {
                   4581:         if ( (  $hostidflag == 1 
                   4582: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4583: 	     || (!defined($hostidflag)) ) {
                   4584: 
1.918     raeburn  4585: 	    if (($domfilter eq '') ||
                   4586: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4587:                 my $rep;
                   4588:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4589:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4590:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4591:                                 &escape($descfilter), &escape($instcodefilter),
                   4592:                                 &escape($ownerfilter), &escape($coursefilter),
                   4593:                                 &escape($typefilter), &escape($regexp_ok),
                   4594:                                 $as_hash, &escape($selfenrollonly),
                   4595:                                 &escape($catfilter), $showhidden, $caller,
                   4596:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4597:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4598:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4599:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4600:                 } else {
                   4601:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4602:                              $sincefilter.':'.&escape($descfilter).':'.
                   4603:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4604:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4605:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4606:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4607:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4608:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4609:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4610:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4611:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4612:                 }
                   4613: 
1.918     raeburn  4614:                 my @pairs=split(/\&/,$rep);
                   4615:                 foreach my $item (@pairs) {
                   4616:                     my ($key,$value)=split(/\=/,$item,2);
                   4617:                     $key = &unescape($key);
                   4618:                     next if ($key =~ /^error: 2 /);
                   4619:                     my $result = &thaw_unescape($value);
                   4620:                     if (ref($result) eq 'HASH') {
                   4621:                         $returnhash{$key}=$result;
                   4622:                     } else {
1.921     raeburn  4623:                         my @responses = split(/:/,$value);
                   4624:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4625:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4626:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4627:                         }
1.1008    raeburn  4628:                     }
1.353     www      4629:                 }
                   4630:             }
                   4631:         }
                   4632:     }
                   4633:     return %returnhash;
                   4634: }
                   4635: 
1.1055    raeburn  4636: sub courselastaccess {
                   4637:     my ($cdom,$cnum,$hostidref) = @_;
                   4638:     my %returnhash;
                   4639:     if ($cdom && $cnum) {
                   4640:         my $chome = &homeserver($cnum,$cdom);
                   4641:         if ($chome ne 'no_host') {
                   4642:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4643:             &extract_lastaccess(\%returnhash,$rep);
                   4644:         }
                   4645:     } else {
                   4646:         if (!$cdom) { $cdom=''; }
                   4647:         my %libserv = &all_library();
                   4648:         foreach my $tryserver (keys(%libserv)) {
                   4649:             if (ref($hostidref) eq 'ARRAY') {
                   4650:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4651:             } 
                   4652:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4653:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4654:                 &extract_lastaccess(\%returnhash,$rep);
                   4655:             }
                   4656:         }
                   4657:     }
                   4658:     return %returnhash;
                   4659: }
                   4660: 
                   4661: sub extract_lastaccess {
                   4662:     my ($returnhash,$rep) = @_;
                   4663:     if (ref($returnhash) eq 'HASH') {
                   4664:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4665:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4666:                  $rep eq '') {
                   4667:             my @pairs=split(/\&/,$rep);
                   4668:             foreach my $item (@pairs) {
                   4669:                 my ($key,$value)=split(/\=/,$item,2);
                   4670:                 $key = &unescape($key);
                   4671:                 next if ($key =~ /^error: 2 /);
                   4672:                 $returnhash->{$key} = &thaw_unescape($value);
                   4673:             }
                   4674:         }
                   4675:     }
                   4676:     return;
                   4677: }
                   4678: 
1.658     raeburn  4679: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4680: 
                   4681: sub dcmailput {
1.685     raeburn  4682:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4683:     my $status = &Apache::lonnet::critical(
1.740     www      4684:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4685:        &escape($message),$server);
1.662     raeburn  4686:     return $status;
                   4687: }
                   4688: 
1.658     raeburn  4689: sub dcmaildump {
                   4690:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4691:     my %returnhash=();
1.846     albertel 4692: 
                   4693:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4694:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4695:                                                          &escape($enddate).':';
                   4696: 	my @esc_senders=map { &escape($_)} @$senders;
                   4697: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4698: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4699:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4700:             if (($key) && ($value)) {
                   4701:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4702:             }
                   4703:         }
                   4704:     }
                   4705:     return %returnhash;
                   4706: }
1.662     raeburn  4707: # ---------------------------------------------------------- Domain roles
                   4708: 
                   4709: sub get_domain_roles {
                   4710:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4711:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4712:         $startdate = '.';
                   4713:     }
1.1018    raeburn  4714:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4715:         $enddate = '.';
                   4716:     }
1.922     raeburn  4717:     my $rolelist;
                   4718:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4719:         $rolelist = join('&',@{$roles});
1.922     raeburn  4720:     }
1.662     raeburn  4721:     my %personnel = ();
1.841     albertel 4722: 
                   4723:     my %servers = &get_servers($dom,'library');
                   4724:     foreach my $tryserver (keys(%servers)) {
                   4725: 	%{$personnel{$tryserver}}=();
                   4726: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4727: 					    &escape($startdate).':'.
                   4728: 					    &escape($enddate).':'.
                   4729: 					    &escape($rolelist), $tryserver))) {
                   4730: 	    my ($key,$value) = split(/\=/,$line,2);
                   4731: 	    if (($key) && ($value)) {
                   4732: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4733: 	    }
                   4734: 	}
1.662     raeburn  4735:     }
                   4736:     return %personnel;
                   4737: }
1.658     raeburn  4738: 
1.1172.2.89  raeburn  4739: sub get_active_domroles {
                   4740:     my ($dom,$roles) = @_;
                   4741:     return () unless (ref($roles) eq 'ARRAY');
                   4742:     my $now = time;
                   4743:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   4744:     my %domroles;
                   4745:     foreach my $server (keys(%dompersonnel)) {
                   4746:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   4747:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   4748:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   4749:         }
                   4750:     }
                   4751:     return %domroles;
                   4752: }
                   4753: 
1.1057    www      4754: # ----------------------------------------------------------- Interval timing 
1.149     www      4755: 
1.1153    www      4756: {
                   4757: # Caches needed for speedup of navmaps
                   4758: # We don't want to cache this for very long at all (5 seconds at most)
                   4759: # 
                   4760: # The user for whom we cache
                   4761: my $cachedkey='';
                   4762: # The cached times for this user
                   4763: my %cachedtimes=();
                   4764: # When this was last done
1.1172.2.66  raeburn  4765: my $cachedtime='';
1.1153    www      4766: 
                   4767: sub load_all_first_access {
1.1154    raeburn  4768:     my ($uname,$udom)=@_;
1.1156    www      4769:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4770:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4771:         return;
                   4772:     }
                   4773:     $cachedtime=time;
                   4774:     $cachedkey=$uname.':'.$udom;
                   4775:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4776: }
                   4777: 
1.504     albertel 4778: sub get_first_access {
1.1162    raeburn  4779:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4780:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4781:     if ($argsymb) { $symb=$argsymb; }
                   4782:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4783:     if ($argmap) { $map = $argmap; }
1.926     albertel 4784:     if ($type eq 'course') {
                   4785: 	$res='course';
                   4786:     } elsif ($type eq 'map') {
1.588     albertel 4787: 	$res=&symbread($map);
                   4788:     } else {
                   4789: 	$res=$symb;
                   4790:     }
1.1153    www      4791:     &load_all_first_access($uname,$udom);
                   4792:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4793: }
                   4794: 
                   4795: sub set_first_access {
1.1162    raeburn  4796:     my ($type,$interval)=@_;
1.790     albertel 4797:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4798:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4799:     if ($type eq 'course') {
                   4800: 	$res='course';
                   4801:     } elsif ($type eq 'map') {
1.588     albertel 4802: 	$res=&symbread($map);
                   4803:     } else {
                   4804: 	$res=$symb;
                   4805:     }
1.1153    www      4806:     $cachedkey='';
1.1162    raeburn  4807:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4808:     if (!$firstaccess) {
1.1162    raeburn  4809:         my $start = time;
                   4810: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4811:                           $udom,$uname);
                   4812:         if ($putres eq 'ok') {
                   4813:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4814:                  $udom,$uname); 
                   4815:             &appenv(
                   4816:                      {
                   4817:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4818:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4819:                      }
                   4820:                   );
1.1172.2.97! raeburn  4821:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
        !          4822:                 $cachedtimes{"$courseid\0$res"} = $start;
        !          4823:             }
1.1162    raeburn  4824:         }
                   4825:         return $putres;
1.505     albertel 4826:     }
                   4827:     return 'already_set';
1.504     albertel 4828: }
1.1153    www      4829: }
1.1172.2.32  raeburn  4830: 
                   4831: sub checkout {
                   4832:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4833:     my $now=time;
                   4834:     my $lonhost=$perlvar{'lonHostID'};
                   4835:     my $infostr=&escape(
                   4836:                  'CHECKOUTTOKEN&'.
                   4837:                  $tuname.'&'.
                   4838:                  $tudom.'&'.
                   4839:                  $tcrsid.'&'.
                   4840:                  $symb.'&'.
                   4841:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4842:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4843:     if ($token=~/^error\:/) {
                   4844:         &logthis("<font color=\"blue\">WARNING: ".
                   4845:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4846:                  "</font>");
                   4847:         return '';
                   4848:     }
                   4849: 
                   4850:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4851:     $token=~tr/a-z/A-Z/;
                   4852: 
                   4853:     my %infohash=('resource.0.outtoken' => $token,
                   4854:                   'resource.0.checkouttime' => $now,
                   4855:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4856: 
                   4857:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4858:        return '';
                   4859:     } else {
                   4860:         &logthis("<font color=\"blue\">WARNING: ".
                   4861:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4862:                  "</font>");
                   4863:     }
                   4864: 
                   4865:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4866:                          &escape('Checkout '.$infostr.' - '.
                   4867:                                                  $token)) ne 'ok') {
                   4868:         return '';
                   4869:     } else {
                   4870:         &logthis("<font color=\"blue\">WARNING: ".
                   4871:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4872:                  "</font>");
                   4873:     }
                   4874:     return $token;
                   4875: }
                   4876: 
                   4877: # ------------------------------------------------------------ Check in an item
                   4878: 
                   4879: sub checkin {
                   4880:     my $token=shift;
                   4881:     my $now=time;
                   4882:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4883:     $lonhost=~tr/A-Z/a-z/;
                   4884:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4885:     $dtoken=~s/\W/\_/g;
                   4886:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4887:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4888: 
                   4889:     unless (($tuname) && ($tudom)) {
                   4890:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4891:         return '';
                   4892:     }
                   4893: 
                   4894:     unless (&allowed('mgr',$tcrsid)) {
                   4895:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4896:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4897:         return '';
                   4898:     }
                   4899: 
                   4900:     my %infohash=('resource.0.intoken' => $token,
                   4901:                   'resource.0.checkintime' => $now,
                   4902:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4903: 
                   4904:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4905:        return '';
                   4906:     }
                   4907: 
                   4908:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4909:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4910:         return '';
                   4911:     }
                   4912: 
                   4913:     return ($symb,$tuname,$tudom,$tcrsid);
                   4914: }
                   4915: 
1.110     www      4916: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4917: 
                   4918: sub expirespread {
                   4919:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4920:     my $cid=$env{'request.course.id'}; 
1.110     www      4921:     if ($cid) {
                   4922:        my $now=time;
                   4923:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4924:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4925:                             $env{'course.'.$cid.'.num'}.
1.110     www      4926: 	        	    ':nohist_expirationdates:'.
                   4927:                             &escape($key).'='.$now,
1.620     albertel 4928:                             $env{'course.'.$cid.'.home'})
1.110     www      4929:     }
                   4930:     return 'ok';
1.14      www      4931: }
                   4932: 
1.109     www      4933: # ----------------------------------------------------- Devalidate Spreadsheets
                   4934: 
                   4935: sub devalidate {
1.325     www      4936:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4937:     my $cid=$env{'request.course.id'}; 
1.109     www      4938:     if ($cid) {
1.391     matthew  4939:         # delete the stored spreadsheets for
                   4940:         # - the student level sheet of this user in course's homespace
                   4941:         # - the assessment level sheet for this resource 
                   4942:         #   for this user in user's homespace
1.553     albertel 4943: 	# - current conditional state info
1.325     www      4944: 	my $key=$uname.':'.$udom.':';
1.109     www      4945:         my $status=
1.299     matthew  4946: 	    &del('nohist_calculatedsheets',
1.391     matthew  4947: 		 [$key.'studentcalc:'],
1.620     albertel 4948: 		 $env{'course.'.$cid.'.domain'},
                   4949: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4950: 		.' '.
                   4951: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4952: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4953:         unless ($status eq 'ok ok') {
                   4954:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4955:                     $uname.' at '.$udom.' for '.
1.109     www      4956: 		    $symb.': '.$status);
1.133     albertel 4957:         }
1.553     albertel 4958: 	&delenv('user.state.'.$cid);
1.109     www      4959:     }
                   4960: }
                   4961: 
1.265     albertel 4962: sub get_scalar {
                   4963:     my ($string,$end) = @_;
                   4964:     my $value;
                   4965:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4966: 	$value = $1;
                   4967:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4968: 	$value = $1;
                   4969:     }
                   4970:     return &unescape($value);
                   4971: }
                   4972: 
                   4973: sub array2str {
                   4974:   my (@array) = @_;
                   4975:   my $result=&arrayref2str(\@array);
                   4976:   $result=~s/^__ARRAY_REF__//;
                   4977:   $result=~s/__END_ARRAY_REF__$//;
                   4978:   return $result;
                   4979: }
                   4980: 
1.204     albertel 4981: sub arrayref2str {
                   4982:   my ($arrayref) = @_;
1.265     albertel 4983:   my $result='__ARRAY_REF__';
1.204     albertel 4984:   foreach my $elem (@$arrayref) {
1.265     albertel 4985:     if(ref($elem) eq 'ARRAY') {
                   4986:       $result.=&arrayref2str($elem).'&';
                   4987:     } elsif(ref($elem) eq 'HASH') {
                   4988:       $result.=&hashref2str($elem).'&';
                   4989:     } elsif(ref($elem)) {
                   4990:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4991:     } else {
                   4992:       $result.=&escape($elem).'&';
                   4993:     }
                   4994:   }
                   4995:   $result=~s/\&$//;
1.265     albertel 4996:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4997:   return $result;
                   4998: }
                   4999: 
1.168     albertel 5000: sub hash2str {
1.204     albertel 5001:   my (%hash) = @_;
                   5002:   my $result=&hashref2str(\%hash);
1.265     albertel 5003:   $result=~s/^__HASH_REF__//;
                   5004:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5005:   return $result;
                   5006: }
                   5007: 
                   5008: sub hashref2str {
                   5009:   my ($hashref)=@_;
1.265     albertel 5010:   my $result='__HASH_REF__';
1.800     albertel 5011:   foreach my $key (sort(keys(%$hashref))) {
                   5012:     if (ref($key) eq 'ARRAY') {
                   5013:       $result.=&arrayref2str($key).'=';
                   5014:     } elsif (ref($key) eq 'HASH') {
                   5015:       $result.=&hashref2str($key).'=';
                   5016:     } elsif (ref($key)) {
1.265     albertel 5017:       $result.='=';
1.800     albertel 5018:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5019:     } else {
1.1132    raeburn  5020: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5021:     }
                   5022: 
1.800     albertel 5023:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5024:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5025:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5026:       $result.=&hashref2str($hashref->{$key}).'&';
                   5027:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5028:        $result.='&';
1.800     albertel 5029:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5030:     } else {
1.800     albertel 5031:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5032:     }
                   5033:   }
1.168     albertel 5034:   $result=~s/\&$//;
1.265     albertel 5035:   $result .= '__END_HASH_REF__';
1.168     albertel 5036:   return $result;
                   5037: }
                   5038: 
                   5039: sub str2hash {
1.265     albertel 5040:     my ($string)=@_;
                   5041:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5042:     return %$hash;
                   5043: }
                   5044: 
                   5045: sub str2hashref {
1.168     albertel 5046:   my ($string) = @_;
1.265     albertel 5047: 
                   5048:   my %hash;
                   5049: 
                   5050:   if($string !~ /^__HASH_REF__/) {
                   5051:       if (! ($string eq '' || !defined($string))) {
                   5052: 	  $hash{'error'}='Not hash reference';
                   5053:       }
                   5054:       return (\%hash, $string);
                   5055:   }
                   5056: 
                   5057:   $string =~ s/^__HASH_REF__//;
                   5058: 
                   5059:   while($string !~ /^__END_HASH_REF__/) {
                   5060:       #key
                   5061:       my $key='';
                   5062:       if($string =~ /^__HASH_REF__/) {
                   5063:           ($key, $string)=&str2hashref($string);
                   5064:           if(defined($key->{'error'})) {
                   5065:               $hash{'error'}='Bad data';
                   5066:               return (\%hash, $string);
                   5067:           }
                   5068:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5069:           ($key, $string)=&str2arrayref($string);
                   5070:           if($key->[0] eq 'Array reference error') {
                   5071:               $hash{'error'}='Bad data';
                   5072:               return (\%hash, $string);
                   5073:           }
                   5074:       } else {
                   5075:           $string =~ s/^(.*?)=//;
1.267     albertel 5076: 	  $key=&unescape($1);
1.265     albertel 5077:       }
                   5078:       $string =~ s/^=//;
                   5079: 
                   5080:       #value
                   5081:       my $value='';
                   5082:       if($string =~ /^__HASH_REF__/) {
                   5083:           ($value, $string)=&str2hashref($string);
                   5084:           if(defined($value->{'error'})) {
                   5085:               $hash{'error'}='Bad data';
                   5086:               return (\%hash, $string);
                   5087:           }
                   5088:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5089:           ($value, $string)=&str2arrayref($string);
                   5090:           if($value->[0] eq 'Array reference error') {
                   5091:               $hash{'error'}='Bad data';
                   5092:               return (\%hash, $string);
                   5093:           }
                   5094:       } else {
                   5095: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5096:       }
                   5097:       $string =~ s/^&//;
                   5098: 
                   5099:       $hash{$key}=$value;
1.204     albertel 5100:   }
1.265     albertel 5101: 
                   5102:   $string =~ s/^__END_HASH_REF__//;
                   5103: 
                   5104:   return (\%hash, $string);
1.204     albertel 5105: }
                   5106: 
                   5107: sub str2array {
1.265     albertel 5108:     my ($string)=@_;
                   5109:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5110:     return @$array;
                   5111: }
                   5112: 
                   5113: sub str2arrayref {
1.204     albertel 5114:   my ($string) = @_;
1.265     albertel 5115:   my @array;
                   5116: 
                   5117:   if($string !~ /^__ARRAY_REF__/) {
                   5118:       if (! ($string eq '' || !defined($string))) {
                   5119: 	  $array[0]='Array reference error';
                   5120:       }
                   5121:       return (\@array, $string);
                   5122:   }
                   5123: 
                   5124:   $string =~ s/^__ARRAY_REF__//;
                   5125: 
                   5126:   while($string !~ /^__END_ARRAY_REF__/) {
                   5127:       my $value='';
                   5128:       if($string =~ /^__HASH_REF__/) {
                   5129:           ($value, $string)=&str2hashref($string);
                   5130:           if(defined($value->{'error'})) {
                   5131:               $array[0] ='Array reference error';
                   5132:               return (\@array, $string);
                   5133:           }
                   5134:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5135:           ($value, $string)=&str2arrayref($string);
                   5136:           if($value->[0] eq 'Array reference error') {
                   5137:               $array[0] ='Array reference error';
                   5138:               return (\@array, $string);
                   5139:           }
                   5140:       } else {
                   5141: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5142:       }
                   5143:       $string =~ s/^&//;
                   5144: 
                   5145:       push(@array, $value);
1.191     harris41 5146:   }
1.265     albertel 5147: 
                   5148:   $string =~ s/^__END_ARRAY_REF__//;
                   5149: 
                   5150:   return (\@array, $string);
1.168     albertel 5151: }
                   5152: 
1.167     albertel 5153: # -------------------------------------------------------------------Temp Store
                   5154: 
1.168     albertel 5155: sub tmpreset {
                   5156:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5157:   if (!$symb) {
                   5158:     $symb=&symbread();
1.620     albertel 5159:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5160:   }
                   5161:   $symb=escape($symb);
                   5162: 
1.620     albertel 5163:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5164:   $namespace=~s/\//\_/g;
                   5165:   $namespace=~s/\W//g;
                   5166: 
1.620     albertel 5167:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5168:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5169:   if ($domain eq 'public' && $stuname eq 'public') {
                   5170:       $stuname=$ENV{'REMOTE_ADDR'};
                   5171:   }
1.1117    foxr     5172:   my $path=LONCAPA::tempdir();
1.168     albertel 5173:   my %hash;
                   5174:   if (tie(%hash,'GDBM_File',
                   5175: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5176: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5177:     foreach my $key (keys(%hash)) {
1.180     albertel 5178:       if ($key=~ /:$symb/) {
1.168     albertel 5179: 	delete($hash{$key});
                   5180:       }
                   5181:     }
                   5182:   }
                   5183: }
                   5184: 
1.167     albertel 5185: sub tmpstore {
1.168     albertel 5186:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5187: 
                   5188:   if (!$symb) {
                   5189:     $symb=&symbread();
1.620     albertel 5190:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5191:   }
                   5192:   $symb=escape($symb);
                   5193: 
                   5194:   if (!$namespace) {
                   5195:     # I don't think we would ever want to store this for a course.
                   5196:     # it seems this will only be used if we don't have a course.
1.620     albertel 5197:     #$namespace=$env{'request.course.id'};
1.168     albertel 5198:     #if (!$namespace) {
1.620     albertel 5199:       $namespace=$env{'request.state'};
1.168     albertel 5200:     #}
                   5201:   }
                   5202:   $namespace=~s/\//\_/g;
                   5203:   $namespace=~s/\W//g;
1.620     albertel 5204:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5205:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5206:   if ($domain eq 'public' && $stuname eq 'public') {
                   5207:       $stuname=$ENV{'REMOTE_ADDR'};
                   5208:   }
1.168     albertel 5209:   my $now=time;
                   5210:   my %hash;
1.1117    foxr     5211:   my $path=LONCAPA::tempdir();
1.168     albertel 5212:   if (tie(%hash,'GDBM_File',
                   5213: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5214: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5215:     $hash{"version:$symb"}++;
                   5216:     my $version=$hash{"version:$symb"};
                   5217:     my $allkeys=''; 
                   5218:     foreach my $key (keys(%$storehash)) {
                   5219:       $allkeys.=$key.':';
1.591     albertel 5220:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5221:     }
                   5222:     $hash{"$version:$symb:timestamp"}=$now;
                   5223:     $allkeys.='timestamp';
                   5224:     $hash{"$version:keys:$symb"}=$allkeys;
                   5225:     if (untie(%hash)) {
                   5226:       return 'ok';
                   5227:     } else {
                   5228:       return "error:$!";
                   5229:     }
                   5230:   } else {
                   5231:     return "error:$!";
                   5232:   }
                   5233: }
1.167     albertel 5234: 
1.168     albertel 5235: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5236: 
1.168     albertel 5237: sub tmprestore {
                   5238:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5239: 
1.168     albertel 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.591     albertel 5247: 
1.620     albertel 5248:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5249:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5250:   if ($domain eq 'public' && $stuname eq 'public') {
                   5251:       $stuname=$ENV{'REMOTE_ADDR'};
                   5252:   }
1.168     albertel 5253:   my %returnhash;
                   5254:   $namespace=~s/\//\_/g;
                   5255:   $namespace=~s/\W//g;
                   5256:   my %hash;
1.1117    foxr     5257:   my $path=LONCAPA::tempdir();
1.168     albertel 5258:   if (tie(%hash,'GDBM_File',
                   5259: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5260: 	  &GDBM_READER(),0640)) {
1.168     albertel 5261:     my $version=$hash{"version:$symb"};
                   5262:     $returnhash{'version'}=$version;
                   5263:     my $scope;
                   5264:     for ($scope=1;$scope<=$version;$scope++) {
                   5265:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5266:       my @keys=split(/:/,$vkeys);
                   5267:       my $key;
                   5268:       $returnhash{"$scope:keys"}=$vkeys;
                   5269:       foreach $key (@keys) {
1.591     albertel 5270: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5271: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5272:       }
                   5273:     }
1.168     albertel 5274:     if (!(untie(%hash))) {
                   5275:       return "error:$!";
                   5276:     }
                   5277:   } else {
                   5278:     return "error:$!";
                   5279:   }
                   5280:   return %returnhash;
1.167     albertel 5281: }
                   5282: 
1.9       www      5283: # ----------------------------------------------------------------------- Store
                   5284: 
                   5285: sub store {
1.1172.2.64  raeburn  5286:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5287:     my $home='';
                   5288: 
1.168     albertel 5289:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5290: 
1.213     www      5291:     $symb=&symbclean($symb);
1.122     albertel 5292:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5293: 
1.620     albertel 5294:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5295:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5296: 
                   5297:     &devalidate($symb,$stuname,$domain);
1.109     www      5298: 
                   5299:     $symb=escape($symb);
1.187     www      5300:     if (!$namespace) { 
1.620     albertel 5301:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5302:           return ''; 
                   5303:        } 
                   5304:     }
1.620     albertel 5305:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5306: 
                   5307:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5308:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5309: 
1.12      www      5310:     my $namevalue='';
1.800     albertel 5311:     foreach my $key (keys(%$storehash)) {
                   5312:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5313:     }
1.12      www      5314:     $namevalue=~s/\&$//;
1.187     www      5315:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5316:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5317: }
                   5318: 
1.47      www      5319: # -------------------------------------------------------------- Critical Store
                   5320: 
                   5321: sub cstore {
1.1172.2.64  raeburn  5322:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5323:     my $home='';
                   5324: 
1.168     albertel 5325:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5326: 
1.213     www      5327:     $symb=&symbclean($symb);
1.122     albertel 5328:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5329: 
1.620     albertel 5330:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5331:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5332: 
                   5333:     &devalidate($symb,$stuname,$domain);
1.109     www      5334: 
                   5335:     $symb=escape($symb);
1.187     www      5336:     if (!$namespace) { 
1.620     albertel 5337:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5338:           return ''; 
                   5339:        } 
                   5340:     }
1.620     albertel 5341:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5342: 
                   5343:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5344:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5345: 
1.47      www      5346:     my $namevalue='';
1.800     albertel 5347:     foreach my $key (keys(%$storehash)) {
                   5348:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5349:     }
1.47      www      5350:     $namevalue=~s/\&$//;
1.187     www      5351:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5352:     return critical
1.1172.2.64  raeburn  5353:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5354: }
                   5355: 
1.9       www      5356: # --------------------------------------------------------------------- Restore
                   5357: 
                   5358: sub restore {
1.124     www      5359:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5360:     my $home='';
                   5361: 
1.168     albertel 5362:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5363: 
1.122     albertel 5364:     if (!$symb) {
1.1172.2.26  raeburn  5365:         return if ($namespace eq 'courserequests');
                   5366:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5367:     } else {
1.1172.2.26  raeburn  5368:         unless ($namespace eq 'courserequests') {
                   5369:             $symb=&escape(&symbclean($symb));
                   5370:         }
1.122     albertel 5371:     }
1.188     www      5372:     if (!$namespace) { 
1.620     albertel 5373:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5374:           return ''; 
                   5375:        } 
                   5376:     }
1.620     albertel 5377:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5378:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5379:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5380:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5381: 
1.12      www      5382:     my %returnhash=();
1.800     albertel 5383:     foreach my $line (split(/\&/,$answer)) {
                   5384: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5385:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5386:     }
1.75      www      5387:     my $version;
                   5388:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5389:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5390:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5391:        }
1.75      www      5392:     }
1.13      www      5393:     return %returnhash;
1.34      www      5394: }
                   5395: 
                   5396: # ---------------------------------------------------------- Course Description
1.1118    foxr     5397: #
                   5398: #  
1.34      www      5399: 
                   5400: sub coursedescription {
1.731     albertel 5401:     my ($courseid,$args)=@_;
1.34      www      5402:     $courseid=~s/^\///;
1.49      www      5403:     $courseid=~s/\_/\//g;
1.34      www      5404:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5405:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5406:     my $normalid=$cdomain.'_'.$cnum;
                   5407:     # need to always cache even if we get errors otherwise we keep 
                   5408:     # trying and trying and trying to get the course description.
                   5409:     my %envhash=();
                   5410:     my %returnhash=();
1.731     albertel 5411:     
                   5412:     my $expiretime=600;
                   5413:     if ($env{'request.course.id'} eq $normalid) {
                   5414: 	$expiretime=120;
                   5415:     }
                   5416: 
                   5417:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5418:     if (!$args->{'freshen_cache'}
                   5419: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5420: 	foreach my $key (keys(%env)) {
                   5421: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5422: 	    my ($setting) = $1;
                   5423: 	    $returnhash{$setting} = $env{$key};
                   5424: 	}
                   5425: 	return %returnhash;
                   5426:     }
                   5427: 
1.1118    foxr     5428:     # get the data again
                   5429: 
1.731     albertel 5430:     if (!$args->{'one_time'}) {
                   5431: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5432:     }
1.811     albertel 5433: 
1.34      www      5434:     if ($chome ne 'no_host') {
1.302     albertel 5435:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5436:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5437: 	   my $username = $env{'user.name'}; # Defult username
                   5438: 	   if(defined $args->{'user'}) {
                   5439: 	       $username = $args->{'user'};
                   5440: 	   }
1.129     albertel 5441:            $returnhash{'home'}= $chome;
                   5442: 	   $returnhash{'domain'} = $cdomain;
                   5443: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5444:            if (!defined($returnhash{'type'})) {
                   5445:                $returnhash{'type'} = 'Course';
                   5446:            }
1.130     albertel 5447:            while (my ($name,$value) = each %returnhash) {
1.53      www      5448:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5449:            }
1.270     www      5450:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5451:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5452: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5453:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5454:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5455:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5456:        }
                   5457:     }
1.731     albertel 5458:     if (!$args->{'one_time'}) {
1.949     raeburn  5459: 	&appenv(\%envhash);
1.731     albertel 5460:     }
1.302     albertel 5461:     return %returnhash;
1.461     www      5462: }
                   5463: 
1.1080    raeburn  5464: sub update_released_required {
                   5465:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5466:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5467:         $cid = $env{'request.course.id'};
                   5468:         $cdom = $env{'course.'.$cid.'.domain'};
                   5469:         $cnum = $env{'course.'.$cid.'.num'};
                   5470:         $chome = $env{'course.'.$cid.'.home'};
                   5471:     }
                   5472:     if ($needsrelease) {
                   5473:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5474:         my $needsupdate;
                   5475:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5476:             $needsupdate = 1;
                   5477:         } else {
                   5478:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5479:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5480:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5481:                 $needsupdate = 1;
                   5482:             }
                   5483:         }
                   5484:         if ($needsupdate) {
                   5485:             my %needshash = (
                   5486:                              'internal.releaserequired' => $needsrelease,
                   5487:                             );
                   5488:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5489:             if ($putresult eq 'ok') {
                   5490:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5491:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5492:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5493:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5494:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5495:                 }
                   5496:             }
                   5497:         }
                   5498:     }
                   5499:     return;
                   5500: }
                   5501: 
1.461     www      5502: # -------------------------------------------------See if a user is privileged
                   5503: 
                   5504: sub privileged {
1.1172.2.23  raeburn  5505:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5506:     my $now = time;
1.1172.2.23  raeburn  5507:     my $roles;
                   5508:     if (ref($possroles) eq 'ARRAY') {
                   5509:         $roles = $possroles;
                   5510:     } else {
                   5511:         $roles = ['dc','su'];
                   5512:     }
                   5513:     if (ref($possdomains) eq 'ARRAY') {
                   5514:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5515:         foreach my $dom (@{$possdomains}) {
                   5516:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5517:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5518:                 foreach my $role (@{$roles}) {
                   5519:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5520:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5521:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5522:                             return 1 unless (($end && $end < $now) ||
                   5523:                                              ($start && $start > $now));
                   5524:                         }
                   5525:                     }
                   5526:                 }
                   5527:             }
                   5528:         }
                   5529:     } else {
                   5530:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5531:         my $now = time;
1.1170    droeschl 5532: 
1.1172.2.58  raeburn  5533:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5534:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5535:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5536:                 return 1 unless ($tend && $tend < $now)
                   5537:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5538:             }
1.1172.2.23  raeburn  5539:         }
                   5540:     }
1.461     www      5541:     return 0;
1.9       www      5542: }
1.1       albertel 5543: 
1.1172.2.23  raeburn  5544: sub privileged_by_domain {
                   5545:     my ($domains,$roles) = @_;
                   5546:     my %privileged = ();
                   5547:     my $cachetime = 60*60*24;
                   5548:     my $now = time;
                   5549:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5550:         return %privileged;
                   5551:     }
                   5552:     foreach my $dom (@{$domains}) {
                   5553:         next if (ref($privileged{$dom}) eq 'HASH');
                   5554:         my $needroles;
                   5555:         foreach my $role (@{$roles}) {
                   5556:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5557:             if (defined($cached)) {
                   5558:                 if (ref($result) eq 'HASH') {
                   5559:                     $privileged{$dom}{$role} = $result;
                   5560:                 }
                   5561:             } else {
                   5562:                 $needroles = 1;
                   5563:             }
                   5564:         }
                   5565:         if ($needroles) {
                   5566:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5567:             $privileged{$dom} = {};
                   5568:             foreach my $server (keys(%dompersonnel)) {
                   5569:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5570:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5571:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5572:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5573:                         next if ($end && $end < $now);
                   5574:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5575:                             $dompersonnel{$server}{$item};
                   5576:                     }
                   5577:                 }
                   5578:             }
                   5579:             if (ref($privileged{$dom}) eq 'HASH') {
                   5580:                 foreach my $role (@{$roles}) {
                   5581:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5582:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5583:                     } else {
                   5584:                         my %hash = ();
                   5585:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5586:                     }
                   5587:                 }
                   5588:             }
                   5589:         }
                   5590:     }
                   5591:     return %privileged;
                   5592: }
                   5593: 
1.103     harris41 5594: # -------------------------------------------------------- Get user privileges
1.11      www      5595: 
                   5596: sub rolesinit {
1.1169    droeschl 5597:     my ($domain, $username) = @_;
                   5598:     my %userroles = ('user.login.time' => time);
                   5599:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5600: 
                   5601:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5602:     # also, blocking can be triggered by an activating timer
                   5603:     # it's saved in the user's %env.
                   5604:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5605:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5606:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5607:         %timerintchk, %timerintenv);
                   5608: 
1.1162    raeburn  5609:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5610:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5611:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5612:     }
1.1169    droeschl 5613: 
1.1162    raeburn  5614:     foreach my $key (keys(%timerinterval)) {
                   5615:         my ($cid,$rest) = split(/\0/,$key);
                   5616:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5617:     }
1.1169    droeschl 5618: 
1.11      www      5619:     my %allroles=();
1.1162    raeburn  5620:     my %allgroups=();
1.11      www      5621: 
1.1172.2.58  raeburn  5622:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5623:         my $role = $rolesdump{$area};
                   5624:         $area =~ s/\_\w\w$//;
                   5625: 
                   5626:         my ($trole, $tend, $tstart, $group_privs);
                   5627: 
                   5628:         if ($role =~ /^cr/) {
                   5629:         # Custom role, defined by a user 
                   5630:         # e.g., user.role.cr/msu/smith/mynewrole
                   5631:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5632:                 $trole = $1;
                   5633:                 ($tend, $tstart) = split('_', $2);
                   5634:             } else {
                   5635:                 $trole = $role;
                   5636:             }
                   5637:         } elsif ($role =~ m|^gr/|) {
                   5638:         # Role of member in a group, defined within a course/community
                   5639:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5640:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5641:             next if $tstart eq '-1';
                   5642:             ($trole, $group_privs) = split(/\//, $trole);
                   5643:             $group_privs = &unescape($group_privs);
                   5644:         } else {
                   5645:         # Just a normal role, defined in roles.tab
                   5646:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5647:         }
                   5648: 
                   5649:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5650:                  $username);
                   5651:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5652: 
                   5653:         # role expired or not available yet?
                   5654:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5655:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5656: 
                   5657:         next if $area eq '' or $trole eq '';
                   5658: 
                   5659:         my $spec = "$trole.$area";
                   5660:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5661: 
                   5662:         if ($trole =~ /^cr\//) {
                   5663:         # Custom role, defined by a user
                   5664:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5665:         } elsif ($trole eq 'gr') {
                   5666:         # Role of a member in a group, defined within a course/community
                   5667:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5668:             next;
                   5669:         } else {
                   5670:         # Normal role, defined in roles.tab
                   5671:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5672:         }
                   5673: 
                   5674:         my $cid = $tdomain.'_'.$trest;
                   5675:         unless ($firstaccchk{$cid}) {
                   5676:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5677:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5678:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5679:                         $coursetimerstarts{$cid}{$item}; 
                   5680:                 }
                   5681:             }
                   5682:             $firstaccchk{$cid} = 1;
                   5683:         }
                   5684:         unless ($timerintchk{$cid}) {
                   5685:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5686:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5687:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5688:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5689:                 }
1.12      www      5690:             }
1.1169    droeschl 5691:             $timerintchk{$cid} = 1;
1.191     harris41 5692:         }
1.11      www      5693:     }
1.1169    droeschl 5694: 
1.1172.2.91  raeburn  5695:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   5696:                                                           \%allroles, \%allgroups);
1.1169    droeschl 5697:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  5698:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 5699: 
1.1162    raeburn  5700:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5701: }
                   5702: 
1.567     raeburn  5703: sub set_arearole {
1.1172.2.19  raeburn  5704:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5705:     unless ($nolog) {
1.567     raeburn  5706: # log the associated role with the area
1.1172.2.19  raeburn  5707:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5708:     }
1.743     albertel 5709:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5710: }
                   5711: 
                   5712: sub custom_roleprivs {
                   5713:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5714:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5715:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5716:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5717:         my ($rdummy,$roledef)=
                   5718:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5719:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5720:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5721:             if (defined($syspriv)) {
1.1043    raeburn  5722:                 if ($trest =~ /^$match_community$/) {
                   5723:                     $syspriv =~ s/bre\&S//; 
                   5724:                 }
1.567     raeburn  5725:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5726:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5727:             }
                   5728:             if ($tdomain ne '') {
                   5729:                 if (defined($dompriv)) {
                   5730:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5731:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5732:                 }
                   5733:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  5734:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5735:                         my $rolename = $1;
                   5736:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   5737:                     }
1.567     raeburn  5738:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5739:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5740:                 }
                   5741:             }
                   5742:         }
                   5743:     }
                   5744: }
                   5745: 
1.1172.2.89  raeburn  5746: sub course_adhocrole_privs {
                   5747:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   5748:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   5749:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   5750:         my (%currprivs,%storeprivs);
                   5751:         foreach my $item (split(/:/,$coursepriv)) {
                   5752:             my ($priv,$restrict) = split(/\&/,$item);
                   5753:             $currprivs{$priv} = $restrict;
                   5754:         }
                   5755:         my (%possadd,%possremove,%full);
                   5756:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   5757:             my ($priv,$restrict)=split(/\&/,$item);
                   5758:             $full{$priv} = $restrict;
                   5759:         }
                   5760:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   5761:              next if ($item eq '');
                   5762:              my ($rule,$rest) = split(/=/,$item);
                   5763:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   5764:              foreach my $priv (split(/:/,$rest)) {
                   5765:                  if ($priv ne '') {
                   5766:                      if ($rule eq 'off') {
                   5767:                          $possremove{$priv} = 1;
                   5768:                      } else {
                   5769:                          $possadd{$priv} = 1;
                   5770:                      }
                   5771:                  }
                   5772:              }
                   5773:          }
                   5774:          foreach my $priv (sort(keys(%full))) {
                   5775:              if (exists($currprivs{$priv})) {
                   5776:                  unless (exists($possremove{$priv})) {
                   5777:                      $storeprivs{$priv} = $currprivs{$priv};
                   5778:                  }
                   5779:              } elsif (exists($possadd{$priv})) {
                   5780:                  $storeprivs{$priv} = $full{$priv};
                   5781:              }
                   5782:          }
                   5783:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   5784:      }
                   5785:      return $coursepriv;
                   5786: }
                   5787: 
1.678     raeburn  5788: sub group_roleprivs {
                   5789:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5790:     my $access = 1;
                   5791:     my $now = time;
                   5792:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5793:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5794:     if ($access) {
1.811     albertel 5795:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5796:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5797:     }
                   5798: }
1.567     raeburn  5799: 
                   5800: sub standard_roleprivs {
                   5801:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5802:     if (defined($pr{$trole.':s'})) {
                   5803:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5804:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5805:     }
                   5806:     if ($tdomain ne '') {
                   5807:         if (defined($pr{$trole.':d'})) {
                   5808:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5809:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5810:         }
                   5811:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5812:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5813:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5814:         }
                   5815:     }
                   5816: }
                   5817: 
                   5818: sub set_userprivs {
1.1064    raeburn  5819:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5820:     my $author=0;
                   5821:     my $adv=0;
1.1172.2.91  raeburn  5822:     my $rar=0;
1.678     raeburn  5823:     my %grouproles = ();
                   5824:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5825:         my @groupkeys; 
1.1000    raeburn  5826:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5827:             push(@groupkeys,$role);
                   5828:         }
                   5829:         if (ref($groups_roles) eq 'HASH') {
                   5830:             foreach my $key (keys(%{$groups_roles})) {
                   5831:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5832:                     push(@groupkeys,$key);
                   5833:                 }
                   5834:             }
                   5835:         }
                   5836:         if (@groupkeys > 0) {
                   5837:             foreach my $role (@groupkeys) {
                   5838:                 my ($trole,$area,$sec,$extendedarea);
                   5839:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5840:                     $trole = $1;
                   5841:                     $area = $2;
                   5842:                     $sec = $3;
                   5843:                     $extendedarea = $area.$sec;
                   5844:                     if (exists($$allgroups{$area})) {
                   5845:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5846:                             my $spec = $trole.'.'.$extendedarea;
                   5847:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5848:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5849:                         }
1.678     raeburn  5850:                     }
                   5851:                 }
                   5852:             }
                   5853:         }
                   5854:     }
1.800     albertel 5855:     foreach my $group (keys(%grouproles)) {
                   5856:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5857:     }
1.800     albertel 5858:     foreach my $role (keys(%{$allroles})) {
                   5859:         my %thesepriv;
1.941     raeburn  5860:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5861:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5862:             if ($item ne '') {
                   5863:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5864:                 if ($restrictions eq '') {
                   5865:                     $thesepriv{$privilege}='F';
                   5866:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5867:                     $thesepriv{$privilege}.=$restrictions;
                   5868:                 }
                   5869:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  5870:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  5871:             }
                   5872:         }
                   5873:         my $thesestr='';
1.1104    raeburn  5874:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5875: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5876: 	}
                   5877:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5878:     }
1.1172.2.91  raeburn  5879:     return ($author,$adv,$rar);
1.567     raeburn  5880: }
                   5881: 
1.994     raeburn  5882: sub role_status {
1.1104    raeburn  5883:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5884:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5885:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5886:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5887:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5888:             $$where = '/'.$two;
1.994     raeburn  5889:             $$trolecode=$$role.'.'.$$where;
                   5890:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5891:             $$tstatus='is';
1.1104    raeburn  5892:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5893:                 $$tstatus='future';
1.1034    raeburn  5894:                 if ($$tstart<$now) {
                   5895:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5896:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5897:                             my (%allroles,%allgroups,$group_privs,
                   5898:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5899:                             my %userroles = (
                   5900:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5901:                             );
1.1064    raeburn  5902:                             @rolecodes = ('cm'); 
1.1002    raeburn  5903:                             my $spec=$$role.'.'.$$where;
                   5904:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5905:                             if ($$role =~ /^cr\//) {
                   5906:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5907:                                 push(@rolecodes,'cr');
1.1002    raeburn  5908:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5909:                                 push(@rolecodes,$$role);
1.1002    raeburn  5910:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5911:                                                     $env{'user.name'});
1.1064    raeburn  5912:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5913:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5914:                                 $group_privs = &unescape($group_privs);
                   5915:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5916:                                 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  5917:                                 &get_groups_roles($tdomain,$trest,
                   5918:                                                   \%course_roles,\@rolecodes,
                   5919:                                                   \%groups_roles);
1.1002    raeburn  5920:                             } else {
1.1064    raeburn  5921:                                 push(@rolecodes,$$role);
1.1002    raeburn  5922:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5923:                             }
1.1172.2.91  raeburn  5924:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   5925:                                                                    \%groups_roles);
1.1064    raeburn  5926:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  5927:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  5928:                         }
                   5929:                     }
1.1034    raeburn  5930:                     $$tstatus = 'is';
1.1002    raeburn  5931:                 }
1.994     raeburn  5932:             }
                   5933:             if ($$tend) {
1.1104    raeburn  5934:                 if ($$tend<$update) {
1.994     raeburn  5935:                     $$tstatus='expired';
                   5936:                 } elsif ($$tend<$now) {
                   5937:                     $$tstatus='will_not';
                   5938:                 }
                   5939:             }
                   5940:         }
                   5941:     }
                   5942: }
                   5943: 
1.1104    raeburn  5944: sub get_groups_roles {
                   5945:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5946:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5947:                   (ref($rolecodes) eq 'ARRAY') && 
                   5948:                   (ref($groups_roles) eq 'HASH')); 
                   5949:     if (keys(%{$cdom_courseroles}) > 0) {
                   5950:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5951:         if ($cdom ne '' && $cnum ne '') {
                   5952:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5953:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5954:                     my $crsrole = $1;
                   5955:                     my $crssec = $2;
                   5956:                     if ($crsrole =~ /^cr/) {
                   5957:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5958:                             push(@{$rolecodes},'cr');
                   5959:                         }
                   5960:                     } else {
                   5961:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5962:                             push(@{$rolecodes},$crsrole);
                   5963:                         }
                   5964:                     }
                   5965:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5966:                     if ($crssec ne '') {
                   5967:                         $rolekey .= "/$crssec";
                   5968:                     }
                   5969:                     $rolekey .= './';
                   5970:                     $groups_roles->{$rolekey} = $rolecodes;
                   5971:                 }
                   5972:             }
                   5973:         }
                   5974:     }
                   5975:     return;
                   5976: }
                   5977: 
                   5978: sub delete_env_groupprivs {
                   5979:     my ($where,$courseroles,$possroles) = @_;
                   5980:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5981:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5982:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5983:         %{$courseroles->{$udom}} =
                   5984:             &get_my_roles('','','userroles',['active'],
                   5985:                           $possroles,[$udom],1);
                   5986:     }
                   5987:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5988:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5989:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5990:             my $area = '/'.$cdom.'/'.$cnum;
                   5991:             my $privkey = "user.priv.$crsrole.$area";
                   5992:             if ($crssec ne '') {
                   5993:                 $privkey .= '/'.$crssec;
                   5994:             }
                   5995:             $privkey .= ".$area/$group";
                   5996:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5997:         }
                   5998:     }
                   5999:     return;
                   6000: }
                   6001: 
1.994     raeburn  6002: sub check_adhoc_privs {
1.1172.2.86  raeburn  6003:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6004:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6005:     if ($sec) {
                   6006:         $cckey .= '/'.$sec;
                   6007:     }
1.1172.2.9  raeburn  6008:     my $setprivs;
1.994     raeburn  6009:     if ($env{$cckey}) {
                   6010:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6011:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6012:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6013:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6014:             $setprivs = 1;
1.994     raeburn  6015:         }
                   6016:     } else {
1.1172.2.87  raeburn  6017:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6018:         $setprivs = 1;
1.994     raeburn  6019:     }
1.1172.2.9  raeburn  6020:     return $setprivs;
1.994     raeburn  6021: }
                   6022: 
                   6023: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6024: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6025:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6026:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6027:     if ($sec ne '') {
                   6028:         $area .= '/'.$sec;
                   6029:     }
1.994     raeburn  6030:     my $spec = $role.'.'.$area;
                   6031:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6032:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6033:     my %rolehash = ();
1.1172.2.89  raeburn  6034:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6035:         my $rolename = $1;
1.1172.2.84  raeburn  6036:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6037:         my %domdef = &get_domain_defaults($dcdom);
                   6038:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6039:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6040:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6041:             }
                   6042:         }
1.1172.2.84  raeburn  6043:     } else {
                   6044:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6045:     }
1.1172.2.91  raeburn  6046:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6047:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6048:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6049:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6050:         &appenv( {'request.role'        => $spec,
                   6051:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6052:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6053:                  }
                   6054:                );
                   6055:         my $tadv=0;
                   6056:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6057:         &appenv({'request.role.adv'    => $tadv});
                   6058:     }
1.994     raeburn  6059: }
                   6060: 
1.12      www      6061: # --------------------------------------------------------------- get interface
                   6062: 
                   6063: sub get {
1.131     albertel 6064:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6065:    my $items='';
1.800     albertel 6066:    foreach my $item (@$storearr) {
                   6067:        $items.=&escape($item).'&';
1.191     harris41 6068:    }
1.12      www      6069:    $items=~s/\&$//;
1.620     albertel 6070:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6071:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6072:    my $uhome=&homeserver($uname,$udomain);
                   6073: 
1.133     albertel 6074:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6075:    my @pairs=split(/\&/,$rep);
1.273     albertel 6076:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6077:      return @pairs;
                   6078:    }
1.15      www      6079:    my %returnhash=();
1.42      www      6080:    my $i=0;
1.800     albertel 6081:    foreach my $item (@$storearr) {
                   6082:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6083:       $i++;
1.191     harris41 6084:    }
1.15      www      6085:    return %returnhash;
1.27      www      6086: }
                   6087: 
                   6088: # --------------------------------------------------------------- del interface
                   6089: 
                   6090: sub del {
1.133     albertel 6091:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6092:    my $items='';
1.800     albertel 6093:    foreach my $item (@$storearr) {
                   6094:        $items.=&escape($item).'&';
1.191     harris41 6095:    }
1.984     neumanie 6096: 
1.27      www      6097:    $items=~s/\&$//;
1.620     albertel 6098:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6099:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6100:    my $uhome=&homeserver($uname,$udomain);
                   6101:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6102: }
                   6103: 
                   6104: # -------------------------------------------------------------- dump interface
                   6105: 
1.1172.2.22  raeburn  6106: sub unserialize {
                   6107:     my ($rep, $escapedkeys) = @_;
                   6108: 
                   6109:     return {} if $rep =~ /^error/;
                   6110: 
                   6111:     my %returnhash=();
                   6112:     foreach my $item (split(/\&/,$rep)) {
                   6113:         my ($key, $value) = split(/=/, $item, 2);
                   6114:         $key = unescape($key) unless $escapedkeys;
                   6115:         next if $key =~ /^error: 2 /;
                   6116:         $returnhash{$key} = &thaw_unescape($value);
                   6117:     }
                   6118:     return \%returnhash;
                   6119: }
                   6120: 
                   6121: # see Lond::dump_with_regexp
                   6122: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6123: sub dump {
1.1172.2.22  raeburn  6124:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6125:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6126:     if (!$uname) { $uname=$env{'user.name'}; }
                   6127:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6128: 
1.1172.2.55  raeburn  6129:     if ($regexp) {
                   6130:         $regexp=&escape($regexp);
                   6131:     } else {
                   6132:         $regexp='.';
                   6133:     }
1.1172.2.22  raeburn  6134:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6135:         # user is hosted on this machine
1.1172.2.55  raeburn  6136:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6137:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6138:         return %{&unserialize($reply, $escapedkeys)};
                   6139:     }
1.1166    raeburn  6140:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6141:     my @pairs=split(/\&/,$rep);
                   6142:     my %returnhash=();
1.1098    foxr     6143:     if (!($rep =~ /^error/ )) {
                   6144: 	foreach my $item (@pairs) {
                   6145: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6146:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6147: 	    next if ($key =~ /^error: 2 /);
                   6148: 	    $returnhash{$key}=&thaw_unescape($value);
                   6149: 	}
1.755     albertel 6150:     }
                   6151:     return %returnhash;
1.407     www      6152: }
                   6153: 
1.1098    foxr     6154: 
1.717     albertel 6155: # --------------------------------------------------------- dumpstore interface
                   6156: 
                   6157: sub dumpstore {
                   6158:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6159:    # same as dump but keys must be escaped. They may contain colon separated
                   6160:    # lists of values that may themself contain colons (e.g. symbs).
                   6161:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6162: }
                   6163: 
1.407     www      6164: # -------------------------------------------------------------- keys interface
                   6165: 
                   6166: sub getkeys {
                   6167:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6168:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6169:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6170:    my $uhome=&homeserver($uname,$udomain);
                   6171:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6172:    my @keyarray=();
1.800     albertel 6173:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6174:       next if ($key =~ /^error: 2 /);
1.800     albertel 6175:       push(@keyarray,&unescape($key));
1.407     www      6176:    }
                   6177:    return @keyarray;
1.318     matthew  6178: }
                   6179: 
1.319     matthew  6180: # --------------------------------------------------------------- currentdump
                   6181: sub currentdump {
1.328     matthew  6182:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6183:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6184:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6185:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6186:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6187:    my $rep;
                   6188: 
                   6189:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6190:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6191:                    $courseid)));
                   6192:    } else {
                   6193:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6194:    }
                   6195: 
1.318     matthew  6196:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6197:    #
1.318     matthew  6198:    my %returnhash=();
1.319     matthew  6199:    #
                   6200:    if ($rep eq "unknown_cmd") { 
                   6201:        # an old lond will not know currentdump
                   6202:        # Do a dump and make it look like a currentdump
1.822     albertel 6203:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6204:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6205:        my %hash = @tmp;
                   6206:        @tmp=();
1.424     matthew  6207:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6208:    } else {
                   6209:        my @pairs=split(/\&/,$rep);
1.800     albertel 6210:        foreach my $pair (@pairs) {
                   6211:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6212:            my ($symb,$param) = split(/:/,$key);
                   6213:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6214:                                                         &thaw_unescape($value);
1.319     matthew  6215:        }
1.191     harris41 6216:    }
1.12      www      6217:    return %returnhash;
1.424     matthew  6218: }
                   6219: 
                   6220: sub convert_dump_to_currentdump{
                   6221:     my %hash = %{shift()};
                   6222:     my %returnhash;
                   6223:     # Code ripped from lond, essentially.  The only difference
                   6224:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6225:     # we might run in to problems with parameter names =~ /^v\./
                   6226:     while (my ($key,$value) = each(%hash)) {
                   6227:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6228: 	$symb  = &unescape($symb);
                   6229: 	$param = &unescape($param);
1.424     matthew  6230:         next if ($v eq 'version' || $symb eq 'keys');
                   6231:         next if (exists($returnhash{$symb}) &&
                   6232:                  exists($returnhash{$symb}->{$param}) &&
                   6233:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6234:         $returnhash{$symb}->{$param}=$value;
                   6235:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6236:     }
                   6237:     #
                   6238:     # Remove all of the keys in the hashes which keep track of
                   6239:     # the version of the parameter.
                   6240:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6241:         # use a foreach because we are going to delete from the hash.
                   6242:         foreach my $key (keys(%$param_hash)) {
                   6243:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6244:         }
                   6245:     }
                   6246:     return \%returnhash;
1.12      www      6247: }
                   6248: 
1.627     albertel 6249: # ------------------------------------------------------ critical inc interface
                   6250: 
                   6251: sub cinc {
                   6252:     return &inc(@_,'critical');
                   6253: }
                   6254: 
1.449     matthew  6255: # --------------------------------------------------------------- inc interface
                   6256: 
                   6257: sub inc {
1.627     albertel 6258:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6259:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6260:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6261:     my $uhome=&homeserver($uname,$udomain);
                   6262:     my $items='';
                   6263:     if (! ref($store)) {
                   6264:         # got a single value, so use that instead
                   6265:         $items = &escape($store).'=&';
                   6266:     } elsif (ref($store) eq 'SCALAR') {
                   6267:         $items = &escape($$store).'=&';        
                   6268:     } elsif (ref($store) eq 'ARRAY') {
                   6269:         $items = join('=&',map {&escape($_);} @{$store});
                   6270:     } elsif (ref($store) eq 'HASH') {
                   6271:         while (my($key,$value) = each(%{$store})) {
                   6272:             $items.= &escape($key).'='.&escape($value).'&';
                   6273:         }
                   6274:     }
                   6275:     $items=~s/\&$//;
1.627     albertel 6276:     if ($critical) {
                   6277: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6278:     } else {
                   6279: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6280:     }
1.449     matthew  6281: }
                   6282: 
1.12      www      6283: # --------------------------------------------------------------- put interface
                   6284: 
                   6285: sub put {
1.134     albertel 6286:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6287:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6288:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6289:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6290:    my $items='';
1.800     albertel 6291:    foreach my $item (keys(%$storehash)) {
                   6292:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6293:    }
1.12      www      6294:    $items=~s/\&$//;
1.134     albertel 6295:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6296: }
                   6297: 
1.631     albertel 6298: # ------------------------------------------------------------ newput interface
                   6299: 
                   6300: sub newput {
                   6301:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6302:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6303:    if (!$uname) { $uname=$env{'user.name'}; }
                   6304:    my $uhome=&homeserver($uname,$udomain);
                   6305:    my $items='';
                   6306:    foreach my $key (keys(%$storehash)) {
                   6307:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6308:    }
                   6309:    $items=~s/\&$//;
                   6310:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6311: }
                   6312: 
                   6313: # ---------------------------------------------------------  putstore interface
                   6314: 
1.524     raeburn  6315: sub putstore {
1.1172.2.59  raeburn  6316:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6317:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6318:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6319:    my $uhome=&homeserver($uname,$udomain);
                   6320:    my $items='';
1.715     albertel 6321:    foreach my $key (keys(%$storehash)) {
                   6322:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6323:    }
1.715     albertel 6324:    $items=~s/\&$//;
1.716     albertel 6325:    my $esc_symb=&escape($symb);
                   6326:    my $esc_v=&escape($version);
1.715     albertel 6327:    my $reply =
1.716     albertel 6328:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6329: 	      $uhome);
1.1172.2.59  raeburn  6330:    if (($tolog) && ($reply eq 'ok')) {
                   6331:        my $namevalue='';
                   6332:        foreach my $key (keys(%{$storehash})) {
                   6333:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6334:        }
                   6335:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6336:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6337:                      '&version='.$esc_v.
                   6338:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6339:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6340:    }
1.715     albertel 6341:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6342:        # gfall back to way things use to be done
1.715     albertel 6343:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6344: 			    $uname);
1.524     raeburn  6345:    }
1.715     albertel 6346:    return $reply;
                   6347: }
                   6348: 
                   6349: sub old_putstore {
1.716     albertel 6350:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6351:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6352:     if (!$uname) { $uname=$env{'user.name'}; }
                   6353:     my $uhome=&homeserver($uname,$udomain);
                   6354:     my %newstorehash;
1.800     albertel 6355:     foreach my $item (keys(%$storehash)) {
                   6356: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6357: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6358:     }
                   6359:     my $items='';
                   6360:     my %allitems = ();
1.800     albertel 6361:     foreach my $item (keys(%newstorehash)) {
                   6362: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6363: 	    my $key = $1.':keys:'.$2;
                   6364: 	    $allitems{$key} .= $3.':';
                   6365: 	}
1.800     albertel 6366: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6367:     }
1.800     albertel 6368:     foreach my $item (keys(%allitems)) {
                   6369: 	$allitems{$item} =~ s/\:$//;
                   6370: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6371:     }
                   6372:     $items=~s/\&$//;
                   6373:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6374: }
                   6375: 
1.47      www      6376: # ------------------------------------------------------ critical put interface
                   6377: 
                   6378: sub cput {
1.134     albertel 6379:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6380:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6381:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6382:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6383:    my $items='';
1.800     albertel 6384:    foreach my $item (keys(%$storehash)) {
                   6385:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6386:    }
1.47      www      6387:    $items=~s/\&$//;
1.134     albertel 6388:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6389: }
                   6390: 
                   6391: # -------------------------------------------------------------- eget interface
                   6392: 
                   6393: sub eget {
1.133     albertel 6394:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6395:    my $items='';
1.800     albertel 6396:    foreach my $item (@$storearr) {
                   6397:        $items.=&escape($item).'&';
1.191     harris41 6398:    }
1.12      www      6399:    $items=~s/\&$//;
1.620     albertel 6400:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6401:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6402:    my $uhome=&homeserver($uname,$udomain);
                   6403:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6404:    my @pairs=split(/\&/,$rep);
                   6405:    my %returnhash=();
1.42      www      6406:    my $i=0;
1.800     albertel 6407:    foreach my $item (@$storearr) {
                   6408:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6409:       $i++;
1.191     harris41 6410:    }
1.12      www      6411:    return %returnhash;
                   6412: }
                   6413: 
1.667     albertel 6414: # ------------------------------------------------------------ tmpput interface
                   6415: sub tmpput {
1.802     raeburn  6416:     my ($storehash,$server,$context)=@_;
1.667     albertel 6417:     my $items='';
1.800     albertel 6418:     foreach my $item (keys(%$storehash)) {
                   6419: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6420:     }
                   6421:     $items=~s/\&$//;
1.802     raeburn  6422:     if (defined($context)) {
                   6423:         $items .= ':'.&escape($context);
                   6424:     }
1.667     albertel 6425:     return &reply("tmpput:$items",$server);
                   6426: }
                   6427: 
                   6428: # ------------------------------------------------------------ tmpget interface
                   6429: sub tmpget {
1.688     albertel 6430:     my ($token,$server)=@_;
                   6431:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6432:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6433:     my %returnhash;
1.1172.2.85  raeburn  6434:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6435:         return %returnhash;
                   6436:     }
1.667     albertel 6437:     foreach my $item (split(/\&/,$rep)) {
                   6438: 	my ($key,$value)=split(/=/,$item);
                   6439: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6440:     }
                   6441:     return %returnhash;
                   6442: }
                   6443: 
1.1113    raeburn  6444: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6445: sub tmpdel {
                   6446:     my ($token,$server)=@_;
                   6447:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6448:     return &reply("tmpdel:$token",$server);
                   6449: }
                   6450: 
1.1172.2.13  raeburn  6451: # ------------------------------------------------------------ get_timebased_id
                   6452: 
                   6453: sub get_timebased_id {
                   6454:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6455:         $maxtries) = @_;
                   6456:     my ($newid,$error,$dellock);
                   6457:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6458:         return ('','ok','invalid call to get suffix');
                   6459:     }
                   6460: 
                   6461: # set defaults for any optional args for which values were not supplied
                   6462:     if ($who eq '') {
                   6463:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6464:     }
                   6465:     if (!$locktries) {
                   6466:         $locktries = 3;
                   6467:     }
                   6468:     if (!$maxtries) {
                   6469:         $maxtries = 10;
                   6470:     }
                   6471: 
                   6472:     if (($cdom eq '') || ($cnum eq '')) {
                   6473:         if ($env{'request.course.id'}) {
                   6474:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6475:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6476:         }
                   6477:         if (($cdom eq '') || ($cnum eq '')) {
                   6478:             return ('','ok','call to get suffix not in course context');
                   6479:         }
                   6480:     }
                   6481: 
                   6482: # construct locking item
                   6483:     my $lockhash = {
                   6484:                       $prefix."\0".'locked_'.$keyid => $who,
                   6485:                    };
                   6486:     my $tries = 0;
                   6487: 
                   6488: # attempt to get lock on nohist_$namespace file
                   6489:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6490:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6491:         $tries ++;
                   6492:         sleep 1;
                   6493:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6494:     }
                   6495: 
                   6496: # attempt to get unique identifier, based on current timestamp
                   6497:     if ($gotlock eq 'ok') {
                   6498:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6499:         my $id = time;
                   6500:         $newid = $id;
1.1172.2.56  raeburn  6501:         if ($idtype eq 'addcode') {
                   6502:             $newid .= &sixnum_code();
                   6503:         }
1.1172.2.13  raeburn  6504:         my $idtries = 0;
                   6505:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6506:             if ($idtype eq 'concat') {
                   6507:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6508:             } elsif ($idtype eq 'addcode') {
                   6509:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6510:             } else {
                   6511:                 $newid ++;
                   6512:             }
                   6513:             $idtries ++;
                   6514:         }
                   6515:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6516:             my %new_item =  (
                   6517:                               $prefix."\0".$newid => $who,
                   6518:                             );
                   6519:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6520:                                                  $cdom,$cnum);
                   6521:             if ($putresult ne 'ok') {
                   6522:                 undef($newid);
                   6523:                 $error = 'error saving new item: '.$putresult;
                   6524:             }
                   6525:         } else {
1.1172.2.56  raeburn  6526:              undef($newid);
1.1172.2.13  raeburn  6527:              $error = ('error: no unique suffix available for the new item ');
                   6528:         }
                   6529: #  remove lock
                   6530:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6531:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6532:     } else {
                   6533:         $error = "error: could not obtain lockfile\n";
                   6534:         $dellock = 'ok';
1.1172.2.58  raeburn  6535:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6536:             $dellock = 'nolock';
                   6537:         }
1.1172.2.13  raeburn  6538:     }
                   6539:     return ($newid,$dellock,$error);
                   6540: }
                   6541: 
1.1172.2.56  raeburn  6542: sub sixnum_code {
                   6543:     my $code;
                   6544:     for (0..6) {
                   6545:         $code .= int( rand(9) );
                   6546:     }
                   6547:     return $code;
                   6548: }
                   6549: 
1.765     albertel 6550: # -------------------------------------------------- portfolio access checking
                   6551: 
                   6552: sub portfolio_access {
1.1172.2.77  raeburn  6553:     my ($requrl,$clientip) = @_;
1.765     albertel 6554:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6555:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6556:     if ($result) {
                   6557:         my %setters;
                   6558:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6559:             my ($startblock,$endblock) =
                   6560:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6561:             if ($startblock && $endblock) {
                   6562:                 return 'B';
                   6563:             }
                   6564:         } else {
                   6565:             my ($startblock,$endblock) =
                   6566:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6567:             if ($startblock && $endblock) {
                   6568:                 return 'B';
                   6569:             }
                   6570:         }
                   6571:     }
1.765     albertel 6572:     if ($result eq 'ok') {
1.766     albertel 6573:        return 'F';
1.765     albertel 6574:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6575:        return 'A';
1.765     albertel 6576:     }
1.766     albertel 6577:     return '';
1.765     albertel 6578: }
                   6579: 
                   6580: sub get_portfolio_access {
1.1172.2.77  raeburn  6581:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6582: 
                   6583:     if (!ref($access_hash)) {
                   6584: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6585: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6586: 						   $file_name);
                   6587: 	$access_hash = $access_controls{$file_name};
                   6588:     }
                   6589: 
1.1172.2.77  raeburn  6590:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6591:     my $now = time;
                   6592:     if (ref($access_hash) eq 'HASH') {
                   6593:         foreach my $key (keys(%{$access_hash})) {
                   6594:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6595:             if ($start > $now) {
                   6596:                 next;
                   6597:             }
                   6598:             if ($end && $end<$now) {
                   6599:                 next;
                   6600:             }
                   6601:             if ($scope eq 'public') {
                   6602:                 $public = $key;
                   6603:                 last;
                   6604:             } elsif ($scope eq 'guest') {
                   6605:                 $guest = $key;
                   6606:             } elsif ($scope eq 'domains') {
                   6607:                 push(@domains,$key);
                   6608:             } elsif ($scope eq 'users') {
                   6609:                 push(@users,$key);
                   6610:             } elsif ($scope eq 'course') {
                   6611:                 push(@courses,$key);
                   6612:             } elsif ($scope eq 'group') {
                   6613:                 push(@groups,$key);
1.1172.2.77  raeburn  6614:             } elsif ($scope eq 'ip') {
                   6615:                 push(@ips,$key);
1.765     albertel 6616:             }
                   6617:         }
                   6618:         if ($public) {
                   6619:             return 'ok';
1.1172.2.77  raeburn  6620:         } elsif (@ips > 0) {
                   6621:             my $allowed;
                   6622:             foreach my $ipkey (@ips) {
                   6623:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6624:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6625:                         $allowed = 1;
                   6626:                         last;
                   6627:                     }
                   6628:                 }
                   6629:             }
                   6630:             if ($allowed) {
                   6631:                 return 'ok';
                   6632:             }
1.765     albertel 6633:         }
                   6634:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6635:             if ($guest) {
                   6636:                 return $guest;
                   6637:             }
                   6638:         } else {
                   6639:             if (@domains > 0) {
                   6640:                 foreach my $domkey (@domains) {
                   6641:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6642:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6643:                             return 'ok';
                   6644:                         }
                   6645:                     }
                   6646:                 }
                   6647:             }
                   6648:             if (@users > 0) {
                   6649:                 foreach my $userkey (@users) {
1.865     raeburn  6650:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6651:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6652:                             if (ref($item) eq 'HASH') {
                   6653:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6654:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6655:                                     return 'ok';
                   6656:                                 }
                   6657:                             }
                   6658:                         }
                   6659:                     } 
1.765     albertel 6660:                 }
                   6661:             }
                   6662:             my %roleshash;
                   6663:             my @courses_and_groups = @courses;
                   6664:             push(@courses_and_groups,@groups); 
                   6665:             if (@courses_and_groups > 0) {
                   6666:                 my (%allgroups,%allroles); 
                   6667:                 my ($start,$end,$role,$sec,$group);
                   6668:                 foreach my $envkey (%env) {
1.1060    raeburn  6669:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6670:                         my $cid = $2.'_'.$3; 
                   6671:                         if ($1 eq 'gr') {
                   6672:                             $group = $4;
                   6673:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6674:                         } else {
                   6675:                             if ($4 eq '') {
                   6676:                                 $sec = 'none';
                   6677:                             } else {
                   6678:                                 $sec = $4;
                   6679:                             }
                   6680:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6681:                         }
1.811     albertel 6682:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6683:                         my $cid = $2.'_'.$3;
                   6684:                         if ($4 eq '') {
                   6685:                             $sec = 'none';
                   6686:                         } else {
                   6687:                             $sec = $4;
                   6688:                         }
                   6689:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6690:                     }
                   6691:                 }
                   6692:                 if (keys(%allroles) == 0) {
                   6693:                     return;
                   6694:                 }
                   6695:                 foreach my $key (@courses_and_groups) {
                   6696:                     my %content = %{$$access_hash{$key}};
                   6697:                     my $cnum = $content{'number'};
                   6698:                     my $cdom = $content{'domain'};
                   6699:                     my $cid = $cdom.'_'.$cnum;
                   6700:                     if (!exists($allroles{$cid})) {
                   6701:                         next;
                   6702:                     }    
                   6703:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6704:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6705:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6706:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6707:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6708:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6709:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6710:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6711:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6712:                                         if (grep/^all$/,@sections) {
                   6713:                                             return 'ok';
                   6714:                                         } else {
                   6715:                                             if (grep/^$sec$/,@sections) {
                   6716:                                                 return 'ok';
                   6717:                                             }
                   6718:                                         }
                   6719:                                     }
                   6720:                                 }
                   6721:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6722:                                     if (grep/^none$/,@groups) {
                   6723:                                         return 'ok';
                   6724:                                     }
                   6725:                                 } else {
                   6726:                                     if (grep/^all$/,@groups) {
                   6727:                                         return 'ok';
                   6728:                                     } 
                   6729:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6730:                                         if (grep/^$group$/,@groups) {
                   6731:                                             return 'ok';
                   6732:                                         }
                   6733:                                     }
                   6734:                                 } 
                   6735:                             }
                   6736:                         }
                   6737:                     }
                   6738:                 }
                   6739:             }
                   6740:             if ($guest) {
                   6741:                 return $guest;
                   6742:             }
                   6743:         }
                   6744:     }
                   6745:     return;
                   6746: }
                   6747: 
                   6748: sub course_group_datechecker {
                   6749:     my ($dates,$now,$status) = @_;
                   6750:     my ($start,$end) = split(/\./,$dates);
                   6751:     if (!$start && !$end) {
                   6752:         return 'ok';
                   6753:     }
                   6754:     if (grep/^active$/,@{$status}) {
                   6755:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6756:             return 'ok';
                   6757:         }
                   6758:     }
                   6759:     if (grep/^previous$/,@{$status}) {
                   6760:         if ($end > $now ) {
                   6761:             return 'ok';
                   6762:         }
                   6763:     }
                   6764:     if (grep/^future$/,@{$status}) {
                   6765:         if ($start > $now) {
                   6766:             return 'ok';
                   6767:         }
                   6768:     }
                   6769:     return; 
                   6770: }
                   6771: 
                   6772: sub parse_portfolio_url {
                   6773:     my ($url) = @_;
                   6774: 
                   6775:     my ($type,$udom,$unum,$group,$file_name);
                   6776:     
1.823     albertel 6777:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6778: 	$type = 1;
                   6779:         $udom = $1;
                   6780:         $unum = $2;
                   6781:         $file_name = $3;
1.823     albertel 6782:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6783: 	$type = 2;
                   6784:         $udom = $1;
                   6785:         $unum = $2;
                   6786:         $group = $3;
                   6787:         $file_name = $3.'/'.$4;
                   6788:     }
                   6789:     if (wantarray) {
                   6790: 	return ($type,$udom,$unum,$file_name,$group);
                   6791:     }
                   6792:     return $type;
                   6793: }
                   6794: 
                   6795: sub is_portfolio_url {
                   6796:     my ($url) = @_;
                   6797:     return scalar(&parse_portfolio_url($url));
                   6798: }
                   6799: 
1.798     raeburn  6800: sub is_portfolio_file {
                   6801:     my ($file) = @_;
1.820     raeburn  6802:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6803:         return 1;
                   6804:     }
                   6805:     return;
                   6806: }
                   6807: 
1.976     raeburn  6808: sub usertools_access {
1.1084    raeburn  6809:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6810:     my ($access,%tools);
                   6811:     if ($context eq '') {
                   6812:         $context = 'tools';
                   6813:     }
                   6814:     if ($context eq 'requestcourses') {
                   6815:         %tools = (
                   6816:                       official   => 1,
                   6817:                       unofficial => 1,
1.1006    raeburn  6818:                       community  => 1,
1.1172.2.37  raeburn  6819:                       textbook   => 1,
1.985     raeburn  6820:                  );
1.1172.2.9  raeburn  6821:     } elsif ($context eq 'requestauthor') {
                   6822:         %tools = (
                   6823:                       requestauthor => 1,
                   6824:                  );
1.985     raeburn  6825:     } else {
                   6826:         %tools = (
                   6827:                       aboutme   => 1,
                   6828:                       blog      => 1,
1.1172.2.6  raeburn  6829:                       webdav    => 1,
1.985     raeburn  6830:                       portfolio => 1,
                   6831:                  );
                   6832:     }
1.976     raeburn  6833:     return if (!defined($tools{$tool}));
                   6834: 
1.1172.2.35  raeburn  6835:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6836:         $udom = $env{'user.domain'};
                   6837:         $uname = $env{'user.name'};
                   6838:     }
                   6839: 
1.978     raeburn  6840:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6841:         if ($action ne 'reload') {
1.985     raeburn  6842:             if ($context eq 'requestcourses') {
                   6843:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6844:             } elsif ($context eq 'requestauthor') {
                   6845:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6846:             } else {
                   6847:                 return $env{'environment.availabletools.'.$tool};
                   6848:             }
                   6849:         }
1.976     raeburn  6850:     }
                   6851: 
1.1172.2.9  raeburn  6852:     my ($toolstatus,$inststatus,$envkey);
                   6853:     if ($context eq 'requestauthor') {
                   6854:         $envkey = $context;
                   6855:     } else {
                   6856:         $envkey = $context.'.'.$tool;
                   6857:     }
1.976     raeburn  6858: 
1.985     raeburn  6859:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6860:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6861:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6862:         $inststatus = $env{'environment.inststatus'};
                   6863:     } else {
1.1084    raeburn  6864:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6865:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6866:             $inststatus = $userenvref->{'inststatus'};
                   6867:         } else {
1.1172.2.9  raeburn  6868:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6869:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6870:             $inststatus = $userenv{'inststatus'};
                   6871:         }
1.976     raeburn  6872:     }
                   6873: 
                   6874:     if ($toolstatus ne '') {
                   6875:         if ($toolstatus) {
                   6876:             $access = 1;
                   6877:         } else {
                   6878:             $access = 0;
                   6879:         }
                   6880:         return $access;
                   6881:     }
                   6882: 
1.1084    raeburn  6883:     my ($is_adv,%domdef);
                   6884:     if (ref($is_advref) eq 'HASH') {
                   6885:         $is_adv = $is_advref->{'is_adv'};
                   6886:     } else {
                   6887:         $is_adv = &is_advanced_user($udom,$uname);
                   6888:     }
                   6889:     if (ref($domdefref) eq 'HASH') {
                   6890:         %domdef = %{$domdefref};
                   6891:     } else {
                   6892:         %domdef = &get_domain_defaults($udom);
                   6893:     }
1.976     raeburn  6894:     if (ref($domdef{$tool}) eq 'HASH') {
                   6895:         if ($is_adv) {
                   6896:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6897:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6898:                     $access = 1;
                   6899:                 } else {
                   6900:                     $access = 0;
                   6901:                 }
                   6902:                 return $access;
                   6903:             }
                   6904:         }
                   6905:         if ($inststatus ne '') {
                   6906:             my ($hasaccess,$hasnoaccess);
                   6907:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6908:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6909:                     if ($domdef{$tool}{$affiliation}) {
                   6910:                         $hasaccess = 1;
                   6911:                     } else {
                   6912:                         $hasnoaccess = 1;
                   6913:                     }
                   6914:                 }
                   6915:             }
                   6916:             if ($hasaccess || $hasnoaccess) {
                   6917:                 if ($hasaccess) {
                   6918:                     $access = 1;
                   6919:                 } elsif ($hasnoaccess) {
                   6920:                     $access = 0; 
                   6921:                 }
                   6922:                 return $access;
                   6923:             }
                   6924:         } else {
                   6925:             if ($domdef{$tool}{'default'} ne '') {
                   6926:                 if ($domdef{$tool}{'default'}) {
                   6927:                     $access = 1;
                   6928:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6929:                     $access = 0;
                   6930:                 }
                   6931:                 return $access;
                   6932:             }
                   6933:         }
                   6934:     } else {
1.1172.2.6  raeburn  6935:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6936:             $access = 1;
                   6937:         } else {
                   6938:             $access = 0;
                   6939:         }
1.976     raeburn  6940:         return $access;
                   6941:     }
                   6942: }
                   6943: 
1.1050    raeburn  6944: sub is_course_owner {
                   6945:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6946:     if (($udom eq '') || ($uname eq '')) {
                   6947:         $udom = $env{'user.domain'};
                   6948:         $uname = $env{'user.name'};
                   6949:     }
                   6950:     unless (($udom eq '') || ($uname eq '')) {
                   6951:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6952:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6953:                 return 1;
                   6954:             } else {
                   6955:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6956:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6957:                     return 1;
                   6958:                 }
                   6959:             }
                   6960:         }
                   6961:     }
                   6962:     return;
                   6963: }
                   6964: 
1.976     raeburn  6965: sub is_advanced_user {
                   6966:     my ($udom,$uname) = @_;
1.1085    raeburn  6967:     if ($udom ne '' && $uname ne '') {
                   6968:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6969:             if (wantarray) {
                   6970:                 return ($env{'user.adv'},$env{'user.author'});
                   6971:             } else {
                   6972:                 return $env{'user.adv'};
                   6973:             }
1.1085    raeburn  6974:         }
                   6975:     }
1.976     raeburn  6976:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6977:     my %allroles;
1.1128    raeburn  6978:     my ($is_adv,$is_author);
1.976     raeburn  6979:     foreach my $role (keys(%roleshash)) {
                   6980:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6981:         my $area = '/'.$tdomain.'/'.$trest;
                   6982:         if ($sec ne '') {
                   6983:             $area .= '/'.$sec;
                   6984:         }
                   6985:         if (($area ne '') && ($trole ne '')) {
                   6986:             my $spec=$trole.'.'.$area;
                   6987:             if ($trole =~ /^cr\//) {
                   6988:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6989:             } elsif ($trole ne 'gr') {
                   6990:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6991:             }
1.1128    raeburn  6992:             if ($trole eq 'au') {
                   6993:                 $is_author = 1;
                   6994:             }
1.976     raeburn  6995:         }
                   6996:     }
                   6997:     foreach my $role (keys(%allroles)) {
                   6998:         last if ($is_adv);
                   6999:         foreach my $item (split(/:/,$allroles{$role})) {
                   7000:             if ($item ne '') {
                   7001:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7002:                 if ($privilege eq 'adv') {
                   7003:                     $is_adv = 1;
                   7004:                     last;
                   7005:                 }
                   7006:             }
                   7007:         }
                   7008:     }
1.1128    raeburn  7009:     if (wantarray) {
                   7010:         return ($is_adv,$is_author);
                   7011:     }
1.976     raeburn  7012:     return $is_adv;
                   7013: }
1.798     raeburn  7014: 
1.1035    raeburn  7015: sub check_can_request {
1.1036    raeburn  7016:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7017:     my $canreq = 0;
                   7018:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7019:     my @options = ('approval','validate','autolimit');
                   7020:     my $optregex = join('|',@options);
                   7021:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7022:         foreach my $type (@{$types}) {
                   7023:             if (&usertools_access($env{'user.name'},
                   7024:                                   $env{'user.domain'},
                   7025:                                   $type,undef,'requestcourses')) {
                   7026:                 $canreq ++;
1.1036    raeburn  7027:                 if (ref($request_domains) eq 'HASH') {
                   7028:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7029:                 }
1.1035    raeburn  7030:                 if ($dom eq $env{'user.domain'}) {
                   7031:                     $can_request->{$type} = 1;
                   7032:                 }
                   7033:             }
                   7034:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7035:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7036:                 if (@curr > 0) {
1.1036    raeburn  7037:                     foreach my $item (@curr) {
                   7038:                         if (ref($request_domains) eq 'HASH') {
                   7039:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7040:                             if ($otherdom ne '') {
                   7041:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7042:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7043:                                         push(@{$request_domains->{$type}},$otherdom);
                   7044:                                     }
                   7045:                                 } else {
                   7046:                                     push(@{$request_domains->{$type}},$otherdom);
                   7047:                                 }
                   7048:                             }
                   7049:                         }
                   7050:                     }
                   7051:                     unless($dom eq $env{'user.domain'}) {
                   7052:                         $canreq ++;
1.1035    raeburn  7053:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7054:                             $can_request->{$type} = 1;
                   7055:                         }
                   7056:                     }
                   7057:                 }
                   7058:             }
                   7059:         }
                   7060:     }
                   7061:     return $canreq;
                   7062: }
                   7063: 
1.341     www      7064: # ---------------------------------------------- Custom access rule evaluation
                   7065: 
                   7066: sub customaccess {
                   7067:     my ($priv,$uri)=@_;
1.807     albertel 7068:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7069:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7070:     $udom = &LONCAPA::clean_domain($udom);
                   7071:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7072:     my $access=0;
1.800     albertel 7073:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7074: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7075: 	if ($type eq 'user') {
                   7076: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7077: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7078: 		if ($tdom) {
                   7079: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7080: 		}
1.896     albertel 7081: 		if ($tuname) {
                   7082: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7083: 		}
                   7084: 		$access=($effect eq 'allow');
                   7085: 		last;
                   7086: 	    }
                   7087: 	} else {
                   7088: 	    if ($role) {
                   7089: 		if ($role ne $urole) { next; }
                   7090: 	    }
                   7091: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7092: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7093: 		if ($tdom) {
                   7094: 		    if ($tdom ne $udom) { next; }
                   7095: 		}
                   7096: 		if ($tcrs) {
                   7097: 		    if ($tcrs ne $ucrs) { next; }
                   7098: 		}
                   7099: 		if ($tsec) {
                   7100: 		    if ($tsec ne $usec) { next; }
                   7101: 		}
                   7102: 		$access=($effect eq 'allow');
                   7103: 		last;
                   7104: 	    }
                   7105: 	    if ($realm eq '' && $role eq '') {
                   7106: 		$access=($effect eq 'allow');
                   7107: 	    }
1.402     bowersj2 7108: 	}
1.341     www      7109:     }
                   7110:     return $access;
                   7111: }
                   7112: 
1.103     harris41 7113: # ------------------------------------------------- Check for a user privilege
1.12      www      7114: 
                   7115: sub allowed {
1.1172.2.65  raeburn  7116:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7117:     my $ver_orguri=$uri;
1.439     www      7118:     $uri=&deversion($uri);
1.152     www      7119:     my $orguri=$uri;
1.52      www      7120:     $uri=&declutter($uri);
1.809     raeburn  7121: 
1.810     raeburn  7122:     if ($priv eq 'evb') {
                   7123: # Evade communication block restrictions for specified role in a course
                   7124:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7125:             return $1;
                   7126:         } else {
                   7127:             return;
                   7128:         }
                   7129:     }
                   7130: 
1.620     albertel 7131:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7132: # Free bre access to adm and meta resources
1.775     albertel 7133:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7134: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7135: 	&& ($priv eq 'bre')) {
1.14      www      7136: 	return 'F';
1.159     www      7137:     }
                   7138: 
1.545     banghart 7139: # Free bre access to user's own portfolio contents
1.714     raeburn  7140:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7141:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7142: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7143:         my %setters;
                   7144:         my ($startblock,$endblock) = 
                   7145:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7146:         if ($startblock && $endblock) {
                   7147:             return 'B';
                   7148:         } else {
                   7149:             return 'F';
                   7150:         }
1.545     banghart 7151:     }
                   7152: 
1.762     raeburn  7153: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7154:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7155:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7156:         if (exists($env{'request.course.id'})) {
                   7157:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7158:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7159:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7160:                 my $courseprivid=$env{'request.course.id'};
                   7161:                 $courseprivid=~s/\_/\//;
                   7162:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7163:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7164:                     return $1; 
1.762     raeburn  7165:                 } else {
                   7166:                     if ($env{'request.course.sec'}) {
                   7167:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7168:                     }
                   7169:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7170:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7171:                         return $2;
                   7172:                     }
1.714     raeburn  7173:                 }
                   7174:             }
                   7175:         }
                   7176:     }
                   7177: 
1.159     www      7178: # Free bre to public access
                   7179: 
                   7180:     if ($priv eq 'bre') {
1.238     www      7181:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7182: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7183:            return 'F'; 
                   7184:         }
1.238     www      7185:         if ($copyright eq 'priv') {
                   7186:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7187: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7188: 		return '';
                   7189:             }
                   7190:         }
                   7191:         if ($copyright eq 'domain') {
                   7192:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7193: 	    unless (($env{'user.domain'} eq $1) ||
                   7194:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7195: 		return '';
                   7196:             }
1.262     matthew  7197:         }
1.620     albertel 7198:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7199:             # Library role, so allow browsing of resources in this domain.
                   7200:             return 'F';
1.238     www      7201:         }
1.341     www      7202:         if ($copyright eq 'custom') {
                   7203: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7204:         }
1.14      www      7205:     }
1.264     matthew  7206:     # Domain coordinator is trying to create a course
1.620     albertel 7207:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7208:         # uri is the requested domain in this case.
                   7209:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7210:         # a role of dc for the domain in question.
1.620     albertel 7211:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7212:     }
1.29      www      7213: 
1.52      www      7214:     my $thisallowed='';
                   7215:     my $statecond=0;
                   7216:     my $courseprivid='';
                   7217: 
1.1039    raeburn  7218:     my $ownaccess;
1.1043    raeburn  7219:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7220:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7221:         if ($uri eq '') {
                   7222:             $ownaccess = 1;
                   7223:         } else {
                   7224:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7225:                 my $udom = $env{'user.domain'};
                   7226:                 my $uname = $env{'user.name'};
                   7227:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7228:                     $ownaccess = 1;
1.1040    raeburn  7229:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7230:                     unless ($uri =~ m{\.\./}) {
                   7231:                         $ownaccess = 1;
                   7232:                     }
                   7233:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7234:                     my $now = time;
                   7235:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7236:                         my $adom = $1;
                   7237:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7238:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7239:                                 my ($start,$end) = split('.',$env{$key});
                   7240:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7241:                                     $ownaccess = 1;
                   7242:                                     last;
                   7243:                                 }
                   7244:                             }
                   7245:                         }
                   7246:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7247:                         my $adom = $1;
                   7248:                         my $aname = $2;
1.1042    raeburn  7249:                         foreach my $role ('ca','aa') { 
                   7250:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7251:                                 my ($start,$end) =
                   7252:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7253:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7254:                                     $ownaccess = 1;
                   7255:                                     last;
                   7256:                                 }
1.1039    raeburn  7257:                             }
                   7258:                         }
                   7259:                     }
                   7260:                 }
                   7261:             }
                   7262:         }
                   7263:     }
                   7264: 
1.52      www      7265: # Course
                   7266: 
1.620     albertel 7267:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7268:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7269:             $thisallowed.=$1;
                   7270:         }
1.52      www      7271:     }
1.29      www      7272: 
1.52      www      7273: # Domain
                   7274: 
1.620     albertel 7275:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7276:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7277:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7278:             $thisallowed.=$1;
                   7279:         }
1.12      www      7280:     }
1.52      www      7281: 
1.1141    raeburn  7282: # User who is not author or co-author might still be able to edit
                   7283: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7284:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7285:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7286:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7287:             $thisallowed.=$1;
                   7288:         }
                   7289:     }
                   7290: 
1.52      www      7291: # Course: uri itself is a course
1.66      www      7292:     my $courseuri=$uri;
                   7293:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7294:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7295: 
1.620     albertel 7296:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7297:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7298:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7299:             $thisallowed.=$1;
                   7300:         }
1.12      www      7301:     }
1.29      www      7302: 
1.665     albertel 7303: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7304: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7305:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7306: 	$thisallowed='';
1.671     raeburn  7307:         my ($match)=&is_on_map($uri);
                   7308:         if ($match) {
                   7309:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7310:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7311:                 my $value = $1;
                   7312:                 if ($noblockcheck) {
                   7313:                     $thisallowed.=$value;
1.1162    raeburn  7314:                 } else {
1.1172.2.65  raeburn  7315:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7316:                     if (@blockers > 0) {
                   7317:                         $thisallowed = 'B';
                   7318:                     } else {
                   7319:                         $thisallowed.=$value;
                   7320:                     }
1.1162    raeburn  7321:                 }
1.671     raeburn  7322:             }
                   7323:         } else {
1.705     albertel 7324:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7325:             if ($refuri) {
                   7326:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7327:                     $thisallowed='F';
1.671     raeburn  7328:                 } else {
                   7329:                     $refuri=&declutter($refuri);
                   7330:                     my ($match) = &is_on_map($refuri);
                   7331:                     if ($match) {
1.1172.2.65  raeburn  7332:                         if ($noblockcheck) {
1.1162    raeburn  7333:                             $thisallowed='F';
1.1172.2.65  raeburn  7334:                         } else {
                   7335:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7336:                             if (@blockers > 0) {
                   7337:                                 $thisallowed = 'B';
                   7338:                             } else {
                   7339:                                 $thisallowed='F';
                   7340:                             }
1.1162    raeburn  7341:                         }
1.671     raeburn  7342:                     }
1.669     raeburn  7343:                 }
1.671     raeburn  7344:             }
                   7345:         }
1.314     www      7346:     }
1.492     albertel 7347: 
1.766     albertel 7348:     if ($priv eq 'bre'
                   7349: 	&& $thisallowed ne 'F' 
                   7350: 	&& $thisallowed ne '2'
                   7351: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7352: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7353:     }
                   7354:     
1.52      www      7355: # Full access at system, domain or course-wide level? Exit.
1.29      www      7356:     if ($thisallowed=~/F/) {
                   7357: 	return 'F';
                   7358:     }
                   7359: 
1.52      www      7360: # If this is generating or modifying users, exit with special codes
1.29      www      7361: 
1.643     www      7362:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7363: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7364: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7365: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7366: 	    unless ($auname) { return $thisallowed; }
                   7367: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7368: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7369: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7370: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7371: 	}
1.52      www      7372: 	return $thisallowed;
                   7373:     }
                   7374: #
1.103     harris41 7375: # Gathered so far: system, domain and course wide privileges
1.52      www      7376: #
                   7377: # Course: See if uri or referer is an individual resource that is part of 
                   7378: # the course
                   7379: 
1.620     albertel 7380:     if ($env{'request.course.id'}) {
1.232     www      7381: 
1.620     albertel 7382:        $courseprivid=$env{'request.course.id'};
                   7383:        if ($env{'request.course.sec'}) {
                   7384:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7385:        }
                   7386:        $courseprivid=~s/\_/\//;
                   7387:        my $checkreferer=1;
1.232     www      7388:        my ($match,$cond)=&is_on_map($uri);
                   7389:        if ($match) {
                   7390:            $statecond=$cond;
1.620     albertel 7391:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7392:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7393:                my $value = $1;
                   7394:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7395:                    if ($noblockcheck) {
1.1162    raeburn  7396:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7397:                    } else {
                   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:                    }
                   7405:                } else {
                   7406:                    $thisallowed.=$value;
                   7407:                }
1.52      www      7408:                $checkreferer=0;
                   7409:            }
1.29      www      7410:        }
1.83      www      7411:        
1.148     www      7412:        if ($checkreferer) {
1.620     albertel 7413: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7414:             unless ($refuri) {
1.800     albertel 7415:                 foreach my $key (keys(%env)) {
                   7416: 		    if ($key=~/^httpref\..*\*/) {
                   7417: 			my $pattern=$key;
1.156     www      7418:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7419:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7420:                         $pattern=~s/\//\\\//g;
1.152     www      7421:                         if ($orguri=~/$pattern/) {
1.800     albertel 7422: 			    $refuri=$env{$key};
1.148     www      7423:                         }
                   7424:                     }
1.191     harris41 7425:                 }
1.148     www      7426:             }
1.232     www      7427: 
1.148     www      7428:          if ($refuri) { 
1.152     www      7429: 	  $refuri=&declutter($refuri);
1.232     www      7430:           my ($match,$cond)=&is_on_map($refuri);
                   7431:             if ($match) {
                   7432:               my $refstatecond=$cond;
1.620     albertel 7433:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7434:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7435:                   my $value = $1;
                   7436:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7437:                       if ($noblockcheck) {
1.1162    raeburn  7438:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7439:                       } else {
                   7440:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7441:                           if (@blockers > 0) {
                   7442:                               $thisallowed = 'B';
                   7443:                           } else {
                   7444:                               $thisallowed.=$value;
                   7445:                           }
1.1162    raeburn  7446:                       }
                   7447:                   } else {
                   7448:                       $thisallowed.=$value;
                   7449:                   }
1.53      www      7450:                   $uri=$refuri;
                   7451:                   $statecond=$refstatecond;
1.52      www      7452:               }
                   7453:           }
1.148     www      7454:         }
1.29      www      7455:        }
1.52      www      7456:    }
1.29      www      7457: 
1.52      www      7458: #
1.103     harris41 7459: # Gathered now: all privileges that could apply, and condition number
1.52      www      7460: # 
                   7461: #
                   7462: # Full or no access?
                   7463: #
1.29      www      7464: 
1.52      www      7465:     if ($thisallowed=~/F/) {
                   7466: 	return 'F';
                   7467:     }
1.29      www      7468: 
1.52      www      7469:     unless ($thisallowed) {
                   7470:         return '';
                   7471:     }
1.29      www      7472: 
1.52      www      7473: # Restrictions exist, deal with them
                   7474: #
                   7475: #   C:according to course preferences
                   7476: #   R:according to resource settings
                   7477: #   L:unless locked
                   7478: #   X:according to user session state
                   7479: #
                   7480: 
                   7481: # Possibly locked functionality, check all courses
1.54      www      7482: # Locks might take effect only after 10 minutes cache expiration for other
                   7483: # courses, and 2 minutes for current course
1.52      www      7484: 
                   7485:     my $envkey;
                   7486:     if ($thisallowed=~/L/) {
1.1000    raeburn  7487:         foreach $envkey (keys(%env)) {
1.54      www      7488:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7489:                my $courseid=$2;
                   7490:                my $roleid=$1.'.'.$2;
1.92      www      7491:                $courseid=~s/^\///;
1.54      www      7492:                my $expiretime=600;
1.620     albertel 7493:                if ($env{'request.role'} eq $roleid) {
1.54      www      7494: 		  $expiretime=120;
                   7495:                }
                   7496: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7497:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7498:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7499: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7500:                }
1.620     albertel 7501:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7502:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7503: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7504:                        &log($env{'user.domain'},$env{'user.name'},
                   7505:                             $env{'user.home'},
1.57      www      7506:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7507:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7508:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7509: 		       return '';
                   7510:                    }
                   7511:                }
1.620     albertel 7512:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7513:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7514: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7515:                        &log($env{'user.domain'},$env{'user.name'},
                   7516:                             $env{'user.home'},
1.57      www      7517:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7518:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7519:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7520: 		       return '';
                   7521:                    }
                   7522:                }
                   7523: 	   }
1.29      www      7524:        }
1.52      www      7525:     }
                   7526:    
                   7527: #
                   7528: # Rest of the restrictions depend on selected course
                   7529: #
                   7530: 
1.620     albertel 7531:     unless ($env{'request.course.id'}) {
1.766     albertel 7532: 	if ($thisallowed eq 'A') {
                   7533: 	    return 'A';
1.814     raeburn  7534:         } elsif ($thisallowed eq 'B') {
                   7535:             return 'B';
1.766     albertel 7536: 	} else {
                   7537: 	    return '1';
                   7538: 	}
1.52      www      7539:     }
1.29      www      7540: 
1.52      www      7541: #
                   7542: # Now user is definitely in a course
                   7543: #
1.53      www      7544: 
                   7545: 
                   7546: # Course preferences
                   7547: 
                   7548:    if ($thisallowed=~/C/) {
1.620     albertel 7549:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7550:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7551:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7552: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7553: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7554: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7555: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7556: 			$env{'request.course.id'});
                   7557: 	   }
1.237     www      7558:            return '';
                   7559:        }
                   7560: 
1.620     albertel 7561:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7562: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7563: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7564: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7565: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7566: 			$env{'request.course.id'});
                   7567: 	   }
1.54      www      7568:            return '';
                   7569:        }
1.53      www      7570:    }
                   7571: 
                   7572: # Resource preferences
                   7573: 
                   7574:    if ($thisallowed=~/R/) {
1.620     albertel 7575:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7576:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7577: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7578: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7579: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7580: 	   }
                   7581: 	   return '';
1.54      www      7582:        }
1.53      www      7583:    }
1.30      www      7584: 
1.246     www      7585: # Restricted by state or randomout?
1.30      www      7586: 
1.52      www      7587:    if ($thisallowed=~/X/) {
1.620     albertel 7588:       if ($env{'acc.randomout'}) {
1.579     albertel 7589: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7590:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7591:             return ''; 
                   7592:          }
1.247     www      7593:       }
                   7594:       if (&condval($statecond)) {
1.52      www      7595: 	 return '2';
                   7596:       } else {
                   7597:          return '';
                   7598:       }
                   7599:    }
1.30      www      7600: 
1.766     albertel 7601:     if ($thisallowed eq 'A') {
                   7602: 	return 'A';
1.814     raeburn  7603:     } elsif ($thisallowed eq 'B') {
                   7604:         return 'B';
1.766     albertel 7605:     }
1.52      www      7606:    return 'F';
1.232     www      7607: }
1.1162    raeburn  7608: 
1.1172.2.13  raeburn  7609: # ------------------------------------------- Check construction space access
                   7610: 
                   7611: sub constructaccess {
                   7612:     my ($url,$setpriv)=@_;
                   7613: 
                   7614: # We do not allow editing of previous versions of files
                   7615:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7616: 
                   7617: # Get username and domain from URL
                   7618:     my ($ownername,$ownerdomain,$ownerhome);
                   7619: 
                   7620:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  7621:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  7622: 
                   7623: # The URL does not really point to any authorspace, forget it
                   7624:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7625: 
                   7626: # Now we need to see if the user has access to the authorspace of
                   7627: # $ownername at $ownerdomain
                   7628: 
                   7629:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7630: # Real author for this?
                   7631:        $ownerhome = $env{'user.home'};
                   7632:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7633:           return ($ownername,$ownerdomain,$ownerhome);
                   7634:        }
                   7635:     } else {
                   7636: # Co-author for this?
                   7637:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7638:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7639:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7640:             return ($ownername,$ownerdomain,$ownerhome);
                   7641:         }
                   7642:     }
                   7643: 
                   7644: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7645: # we might as well leave
                   7646:    unless ($setpriv) { return ''; }
                   7647: 
                   7648: # Backdoor access?
                   7649:     my $allowed=&allowed('eco',$ownerdomain);
                   7650: # Nope
                   7651:     unless ($allowed) { return ''; }
                   7652: # Looks like we may have access, but could be locked by the owner of the construction space
                   7653:     if ($allowed eq 'U') {
                   7654:         my %blocked=&get('environment',['domcoord.author'],
                   7655:                          $ownerdomain,$ownername);
                   7656: # Is blocked by owner
                   7657:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7658:     }
                   7659:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7660: # Grant temporary access
                   7661:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7662:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7663:         if (!$update) { $update = $then; }
                   7664:         my $refresh=$env{'user.refresh.time'};
                   7665:         if (!$refresh) { $refresh = $update; }
                   7666:         my $now = time;
                   7667:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7668:                            $now,'ca','constructaccess');
                   7669:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7670:         return($ownername,$ownerdomain,$ownerhome);
                   7671:     }
                   7672: # No business here
                   7673:     return '';
                   7674: }
                   7675: 
1.1172.2.66  raeburn  7676: # ----------------------------------------------------------- Content Blocking
                   7677: 
                   7678: {
                   7679: # Caches for faster Course Contents display where content blocking
                   7680: # is in operation (i.e., interval param set) for timed quiz.
                   7681: #
                   7682: # User for whom data are being temporarily cached.
                   7683: my $cacheduser='';
                   7684: # Cached blockers for this user (a hash of blocking items).
                   7685: my %cachedblockers=();
                   7686: # When the data were last cached.
                   7687: my $cachedlast='';
                   7688: 
                   7689: sub load_all_blockers {
                   7690:     my ($uname,$udom,$blocks)=@_;
                   7691:     if (($uname ne '') && ($udom ne '')) {
                   7692:         if (($cacheduser eq $uname.':'.$udom) &&
                   7693:             (abs($cachedlast-time)<5)) {
                   7694:             return;
                   7695:         }
                   7696:     }
                   7697:     $cachedlast=time;
                   7698:     $cacheduser=$uname.':'.$udom;
                   7699:     %cachedblockers = &get_commblock_resources($blocks);
                   7700: }
                   7701: 
1.1162    raeburn  7702: sub get_comm_blocks {
                   7703:     my ($cdom,$cnum) = @_;
                   7704:     if ($cdom eq '' || $cnum eq '') {
                   7705:         return unless ($env{'request.course.id'});
                   7706:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7707:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7708:     }
                   7709:     my %commblocks;
                   7710:     my $hashid=$cdom.'_'.$cnum;
                   7711:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7712:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7713:         %commblocks = %{$blocksref};
                   7714:     } else {
                   7715:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7716:         my $cachetime = 600;
                   7717:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7718:     }
                   7719:     return %commblocks;
                   7720: }
                   7721: 
1.1172.2.66  raeburn  7722: sub get_commblock_resources {
                   7723:     my ($blocks) = @_;
                   7724:     my %blockers = ();
                   7725:     return %blockers unless ($env{'request.course.id'});
                   7726:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7727:     my %commblocks;
                   7728:     if (ref($blocks) eq 'HASH') {
                   7729:         %commblocks = %{$blocks};
                   7730:     } else {
                   7731:         %commblocks = &get_comm_blocks();
                   7732:     }
1.1172.2.66  raeburn  7733:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7734:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7735:     return %blockers unless (ref($navmap));
                   7736:     my $now = time;
1.1162    raeburn  7737:     foreach my $block (keys(%commblocks)) {
                   7738:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7739:             my ($start,$end) = ($1,$2);
                   7740:             if ($start <= $now && $end >= $now) {
                   7741:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7742:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7743:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7744:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7745:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7746:                             }
                   7747:                         }
                   7748:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7749:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7750:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7751:                             }
                   7752:                         }
                   7753:                     }
                   7754:                 }
                   7755:             }
                   7756:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7757:             my $item = $1;
1.1163    raeburn  7758:             my @to_test;
1.1162    raeburn  7759:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7760:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7761:                     my @interval;
                   7762:                     my $type = 'map';
                   7763:                     if ($item eq 'course') {
                   7764:                         $type = 'course';
                   7765:                         @interval=&EXT("resource.0.interval");
                   7766:                     } else {
                   7767:                         if ($item =~ /___\d+___/) {
                   7768:                             $type = 'resource';
                   7769:                             @interval=&EXT("resource.0.interval",$item);
                   7770:                             if (ref($navmap)) {
                   7771:                                 my $res = $navmap->getBySymb($item);
                   7772:                                 push(@to_test,$res);
                   7773:                             }
1.1162    raeburn  7774:                         } else {
1.1172.2.66  raeburn  7775:                             my $mapsymb = &symbread($item,1);
                   7776:                             if ($mapsymb) {
                   7777:                                 if (ref($navmap)) {
                   7778:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7779:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7780:                                     foreach my $res (@to_test) {
                   7781:                                         my $symb = $res->symb();
                   7782:                                         next if ($symb eq $mapsymb);
                   7783:                                         if ($symb ne '') {
                   7784:                                             @interval=&EXT("resource.0.interval",$symb);
                   7785:                                             if ($interval[1] eq 'map') {
                   7786:                                                 last;
1.1162    raeburn  7787:                                             }
                   7788:                                         }
                   7789:                                     }
                   7790:                                 }
                   7791:                             }
                   7792:                         }
1.1172.2.66  raeburn  7793:                     }
                   7794:                     if ($interval[0] =~ /^\d+$/) {
                   7795:                         my $first_access;
                   7796:                         if ($type eq 'resource') {
                   7797:                             $first_access=&get_first_access($interval[1],$item);
                   7798:                         } elsif ($type eq 'map') {
                   7799:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7800:                         } else {
                   7801:                             $first_access=&get_first_access($interval[1]);
                   7802:                         }
                   7803:                         if ($first_access) {
                   7804:                             my $timesup = $first_access+$interval[0];
                   7805:                             if ($timesup > $now) {
                   7806:                                 my $activeblock;
                   7807:                                 foreach my $res (@to_test) {
                   7808:                                     if ($res->answerable()) {
                   7809:                                         $activeblock = 1;
                   7810:                                         last;
                   7811:                                     }
                   7812:                                 }
                   7813:                                 if ($activeblock) {
                   7814:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7815:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7816:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7817:                                          }
                   7818:                                     }
                   7819:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7820:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7821:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7822:                                         }
1.1162    raeburn  7823:                                     }
                   7824:                                 }
                   7825:                             }
                   7826:                         }
                   7827:                     }
                   7828:                 }
                   7829:             }
                   7830:         }
                   7831:     }
1.1172.2.66  raeburn  7832:     return %blockers;
1.1162    raeburn  7833: }
                   7834: 
1.1172.2.66  raeburn  7835: sub has_comm_blocking {
                   7836:     my ($priv,$symb,$uri,$blocks) = @_;
                   7837:     my @blockers;
                   7838:     return unless ($env{'request.course.id'});
                   7839:     return unless ($priv eq 'bre');
                   7840:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7841:     return if ($env{'request.state'} eq 'construct');
                   7842:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7843:     return unless (keys(%cachedblockers) > 0);
                   7844:     my (%possibles,@symbs);
                   7845:     if (!$symb) {
                   7846:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7847:     }
1.1172.2.66  raeburn  7848:     if ($symb) {
                   7849:         @symbs = ($symb);
                   7850:     } elsif (keys(%possibles)) {
                   7851:         @symbs = keys(%possibles);
                   7852:     }
                   7853:     my $noblock;
                   7854:     foreach my $symb (@symbs) {
                   7855:         last if ($noblock);
                   7856:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7857:         foreach my $block (keys(%cachedblockers)) {
                   7858:             if ($block =~ /^firstaccess____(.+)$/) {
                   7859:                 my $item = $1;
                   7860:                 if (($item eq $map) || ($item eq $symb)) {
                   7861:                     $noblock = 1;
                   7862:                     last;
                   7863:                 }
1.1162    raeburn  7864:             }
1.1172.2.66  raeburn  7865:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7866:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7867:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7868:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7869:                             push(@blockers,$block);
                   7870:                         }
                   7871:                     }
                   7872:                 }
                   7873:             }
                   7874:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7875:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7876:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7877:                         push(@blockers,$block);
                   7878:                     }
                   7879:                 }
1.1162    raeburn  7880:             }
                   7881:         }
                   7882:     }
1.1172.2.66  raeburn  7883:     return if ($noblock);
                   7884:     return @blockers;
                   7885: }
1.1162    raeburn  7886: }
                   7887: 
1.1172.2.66  raeburn  7888: # -------------------------------- Deversion and split uri into path an filename
                   7889: 
1.1133    foxr     7890: #
1.1172.2.66  raeburn  7891: #   Removes the version from a URI and
1.1133    foxr     7892: #   splits it in to its filename and path to the filename.
                   7893: #   Seems like File::Basename could have done this more clearly.
                   7894: #   Parameters:
                   7895: #      $uri   - input URI
                   7896: #   Returns:
                   7897: #     Two element list consisting of 
                   7898: #     $pathname  - the URI up to and excluding the trailing /
                   7899: #     $filename  - The part of the URI following the last /
                   7900: #  NOTE:
                   7901: #    Another realization of this is simply:
                   7902: #    use File::Basename;
                   7903: #    ...
                   7904: #    $uri = shift;
                   7905: #    $filename = basename($uri);
                   7906: #    $path     = dirname($uri);
                   7907: #    return ($filename, $path);
                   7908: #
                   7909: #     The implementation below is probably faster however.
                   7910: #
1.710     albertel 7911: sub split_uri_for_cond {
                   7912:     my $uri=&deversion(&declutter(shift));
                   7913:     my @uriparts=split(/\//,$uri);
                   7914:     my $filename=pop(@uriparts);
                   7915:     my $pathname=join('/',@uriparts);
                   7916:     return ($pathname,$filename);
                   7917: }
1.232     www      7918: # --------------------------------------------------- Is a resource on the map?
                   7919: 
                   7920: sub is_on_map {
1.710     albertel 7921:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7922:     #Trying to find the conditional for the file
1.620     albertel 7923:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7924: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7925:     if ($match) {
1.289     bowersj2 7926: 	return (1,$1);
                   7927:     } else {
1.434     www      7928: 	return (0,0);
1.289     bowersj2 7929:     }
1.12      www      7930: }
                   7931: 
1.427     www      7932: # --------------------------------------------------------- Get symb from alias
                   7933: 
                   7934: sub get_symb_from_alias {
                   7935:     my $symb=shift;
                   7936:     my ($map,$resid,$url)=&decode_symb($symb);
                   7937: # Already is a symb
                   7938:     if ($url) { return $symb; }
                   7939: # Must be an alias
                   7940:     my $aliassymb='';
                   7941:     my %bighash;
1.620     albertel 7942:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7943:                             &GDBM_READER(),0640)) {
                   7944:         my $rid=$bighash{'mapalias_'.$symb};
                   7945: 	if ($rid) {
                   7946: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7947: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7948: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7949: 	}
                   7950:         untie %bighash;
                   7951:     }
                   7952:     return $aliassymb;
                   7953: }
                   7954: 
1.12      www      7955: # ----------------------------------------------------------------- Define Role
                   7956: 
                   7957: sub definerole {
                   7958:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  7959:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 7960:     foreach my $role (split(':',$sysrole)) {
                   7961: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7962:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7963:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7964: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7965:                return "refused:s:$crole&$cqual"; 
                   7966:             }
                   7967:         }
1.191     harris41 7968:     }
1.800     albertel 7969:     foreach my $role (split(':',$domrole)) {
                   7970: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7971:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7972:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7973: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7974:                return "refused:d:$crole&$cqual"; 
                   7975:             }
                   7976:         }
1.191     harris41 7977:     }
1.800     albertel 7978:     foreach my $role (split(':',$courole)) {
                   7979: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7980:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7981:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7982: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7983:                return "refused:c:$crole&$cqual"; 
                   7984:             }
                   7985:         }
1.191     harris41 7986:     }
1.1172.2.84  raeburn  7987:     my $uhome;
                   7988:     if (($uname ne '') && ($udom ne '')) {
                   7989:         $uhome = &homeserver($uname,$udom);
                   7990:         return $uhome if ($uhome eq 'no_host');
                   7991:     } else {
                   7992:         $uname = $env{'user.name'};
                   7993:         $udom = $env{'user.domain'};
                   7994:         $uhome = $env{'user.home'};
                   7995:     }
1.620     albertel 7996:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  7997:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      7998:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  7999:     return reply($command,$uhome);
1.12      www      8000:   } else {
                   8001:     return 'refused';
                   8002:   }
1.105     harris41 8003: }
                   8004: 
                   8005: # ---------------- Make a metadata query against the network of library servers
                   8006: 
                   8007: sub metadata_query {
1.1172.2.33  raeburn  8008:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8009:     my %rhash;
1.845     albertel 8010:     my %libserv = &all_library();
1.244     matthew  8011:     my @server_list = (defined($server_array) ? @$server_array
                   8012:                                               : keys(%libserv) );
                   8013:     for my $server (@server_list) {
1.1172.2.33  raeburn  8014:         my $domains = '';
                   8015:         if (ref($domains_hash) eq 'HASH') {
                   8016:             $domains = $domains_hash->{$server};    
                   8017:         }
1.118     harris41 8018: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8019: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8020: 	    $rhash{$server}=$reply;
                   8021: 	}
                   8022: 	else {
                   8023: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8024: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8025: 			     $server);
                   8026: 	    $rhash{$server}=$reply;
                   8027: 	}
1.112     harris41 8028:     }
1.118     harris41 8029:     return \%rhash;
1.240     www      8030: }
                   8031: 
                   8032: # ----------------------------------------- Send log queries and wait for reply
                   8033: 
                   8034: sub log_query {
                   8035:     my ($uname,$udom,$query,%filters)=@_;
                   8036:     my $uhome=&homeserver($uname,$udom);
                   8037:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8038:     my $uhost=&hostname($uhome);
1.800     albertel 8039:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8040:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8041:                        $uhome);
1.479     albertel 8042:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8043:     return get_query_reply($queryid);
                   8044: }
                   8045: 
1.818     raeburn  8046: # -------------------------- Update MySQL table for portfolio file
                   8047: 
                   8048: sub update_portfolio_table {
1.821     raeburn  8049:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8050:     if ($group ne '') {
                   8051:         $file_name =~s /^\Q$group\E//;
                   8052:     }
1.818     raeburn  8053:     my $homeserver = &homeserver($uname,$udom);
                   8054:     my $queryid=
1.821     raeburn  8055:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8056:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8057:     my $reply = &get_query_reply($queryid);
                   8058:     return $reply;
                   8059: }
                   8060: 
1.899     raeburn  8061: # -------------------------- Update MySQL allusers table
                   8062: 
                   8063: sub update_allusers_table {
                   8064:     my ($uname,$udom,$names) = @_;
                   8065:     my $homeserver = &homeserver($uname,$udom);
                   8066:     my $queryid=
                   8067:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8068:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8069:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8070:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8071:                'generation='.&escape($names->{'generation'}).'%%'.
                   8072:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8073:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8074:     return;
1.899     raeburn  8075: }
                   8076: 
1.508     raeburn  8077: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8078: 
                   8079: sub fetch_enrollment_query {
1.511     raeburn  8080:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8081:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8082:     my $maxtries = 1;
1.508     raeburn  8083:     if ($context eq 'automated') {
                   8084:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8085:         $sleep = 2;
                   8086:         $loopmax = 100;
1.547     raeburn  8087:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8088:     } else {
                   8089:         $homeserver = &homeserver($cnum,$dom);
                   8090:     }
1.838     albertel 8091:     my $host=&hostname($homeserver);
1.506     raeburn  8092:     my $cmd = '';
1.1000    raeburn  8093:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8094:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8095:     }
                   8096:     $cmd =~ s/%%$//;
                   8097:     $cmd = &escape($cmd);
                   8098:     my $query = 'fetchenrollment';
1.620     albertel 8099:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8100:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8101:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8102:         return 'error: '.$queryid;
                   8103:     }
1.1172.2.93  raeburn  8104:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8105:     my $tries = 1;
                   8106:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8107:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8108:         $tries ++;
                   8109:     }
1.526     raeburn  8110:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8111:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8112:     } else {
1.901     albertel 8113:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8114:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8115:             foreach my $line (@responses) {
                   8116:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8117:                 $$replyref{$key} = $value;
                   8118:             }
                   8119:         } else {
1.1117    foxr     8120:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8121:             foreach my $line (@responses) {
                   8122:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8123:                 $$replyref{$key} = $value;
                   8124:                 if ($value > 0) {
1.800     albertel 8125:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8126:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8127:                         my $destname = $pathname.'/'.$filename;
                   8128:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8129:                         if ($xml_classlist =~ /^error/) {
                   8130:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8131:                         } else {
1.1172.2.96  raeburn  8132:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8133:                                 print FILE &unescape($xml_classlist);
                   8134:                                 close(FILE);
1.526     raeburn  8135:                             } else {
                   8136:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8137:                             }
                   8138:                         }
                   8139:                     }
                   8140:                 }
                   8141:             }
                   8142:         }
                   8143:         return 'ok';
                   8144:     }
                   8145:     return 'error';
                   8146: }
                   8147: 
1.242     www      8148: sub get_query_reply {
1.1172.2.79  raeburn  8149:     my ($queryid,$sleep,$loopmax) = @_;
                   8150:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8151:         $sleep = 0.2;
                   8152:     }
                   8153:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8154:         $loopmax = 100;
                   8155:     }
1.1117    foxr     8156:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8157:     my $reply='';
1.1172.2.79  raeburn  8158:     for (1..$loopmax) {
                   8159: 	sleep($sleep);
1.240     www      8160:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8161: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8162: 		$reply = join('',<$fh>);
                   8163: 		close($fh);
1.240     www      8164: 	   } else { return 'error: reply_file_error'; }
1.242     www      8165:            return &unescape($reply);
                   8166: 	}
1.240     www      8167:     }
1.242     www      8168:     return 'timeout:'.$queryid;
1.240     www      8169: }
                   8170: 
                   8171: sub courselog_query {
1.241     www      8172: #
                   8173: # possible filters:
                   8174: # url: url or symb
                   8175: # username
                   8176: # domain
                   8177: # action: view, submit, grade
                   8178: # start: timestamp
                   8179: # end: timestamp
                   8180: #
1.240     www      8181:     my (%filters)=@_;
1.620     albertel 8182:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8183:     if ($filters{'url'}) {
                   8184: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8185:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8186:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8187:     }
1.620     albertel 8188:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8189:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8190:     return &log_query($cname,$cdom,'courselog',%filters);
                   8191: }
                   8192: 
                   8193: sub userlog_query {
1.858     raeburn  8194: #
                   8195: # possible filters:
                   8196: # action: log check role
                   8197: # start: timestamp
                   8198: # end: timestamp
                   8199: #
1.240     www      8200:     my ($uname,$udom,%filters)=@_;
                   8201:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8202: }
                   8203: 
1.506     raeburn  8204: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8205: 
                   8206: sub auto_run {
1.508     raeburn  8207:     my ($cnum,$cdom) = @_;
1.876     raeburn  8208:     my $response = 0;
                   8209:     my $settings;
                   8210:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8211:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8212:         $settings = $domconfig{'autoenroll'};
                   8213:         if ($settings->{'run'} eq '1') {
                   8214:             $response = 1;
                   8215:         }
                   8216:     } else {
1.934     raeburn  8217:         my $homeserver;
                   8218:         if (&is_course($cdom,$cnum)) {
                   8219:             $homeserver = &homeserver($cnum,$cdom);
                   8220:         } else {
                   8221:             $homeserver = &domain($cdom,'primary');
                   8222:         }
                   8223:         if ($homeserver ne 'no_host') {
                   8224:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8225:         }
1.876     raeburn  8226:     }
1.506     raeburn  8227:     return $response;
                   8228: }
1.776     albertel 8229: 
1.506     raeburn  8230: sub auto_get_sections {
1.508     raeburn  8231:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8232:     my $homeserver;
                   8233:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8234:         $homeserver = &homeserver($cnum,$cdom);
                   8235:     }
                   8236:     if (!defined($homeserver)) { 
                   8237:         if ($cdom =~ /^$match_domain$/) {
                   8238:             $homeserver = &domain($cdom,'primary');
                   8239:         }
                   8240:     }
                   8241:     my @secs;
                   8242:     if (defined($homeserver)) {
                   8243:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8244:         unless ($response eq 'refused') {
                   8245:             @secs = split(/:/,$response);
                   8246:         }
1.506     raeburn  8247:     }
                   8248:     return @secs;
                   8249: }
1.776     albertel 8250: 
1.506     raeburn  8251: sub auto_new_course {
1.1099    raeburn  8252:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8253:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8254:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8255:     return $response;
                   8256: }
1.776     albertel 8257: 
1.506     raeburn  8258: sub auto_validate_courseID {
1.508     raeburn  8259:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8260:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8261:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8262:     return $response;
                   8263: }
1.776     albertel 8264: 
1.1007    raeburn  8265: sub auto_validate_instcode {
1.1020    raeburn  8266:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8267:     my ($homeserver,$response);
                   8268:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8269:         $homeserver = &homeserver($cnum,$cdom);
                   8270:     }
                   8271:     if (!defined($homeserver)) {
                   8272:         if ($cdom =~ /^$match_domain$/) {
                   8273:             $homeserver = &domain($cdom,'primary');
                   8274:         }
                   8275:     }
1.1065    raeburn  8276:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8277:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8278:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8279:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8280: }
                   8281: 
1.506     raeburn  8282: sub auto_create_password {
1.873     raeburn  8283:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8284:     my ($homeserver,$response);
1.506     raeburn  8285:     my $create_passwd = 0;
                   8286:     my $authchk = '';
1.873     raeburn  8287:     if ($udom =~ /^$match_domain$/) {
                   8288:         $homeserver = &domain($udom,'primary');
                   8289:     }
                   8290:     if ($homeserver eq '') {
                   8291:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8292:             $homeserver = &homeserver($cnum,$cdom);
                   8293:         }
                   8294:     }
                   8295:     if ($homeserver eq '') {
                   8296:         $authchk = 'nodomain';
1.506     raeburn  8297:     } else {
1.873     raeburn  8298:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8299:         if ($response eq 'refused') {
                   8300:             $authchk = 'refused';
                   8301:         } else {
1.901     albertel 8302:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8303:         }
1.506     raeburn  8304:     }
                   8305:     return ($authparam,$create_passwd,$authchk);
                   8306: }
                   8307: 
1.706     raeburn  8308: sub auto_photo_permission {
                   8309:     my ($cnum,$cdom,$students) = @_;
                   8310:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8311:     my ($outcome,$perm_reqd,$conditions) = 
                   8312: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8313:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8314: 	return (undef,undef);
                   8315:     }
1.706     raeburn  8316:     return ($outcome,$perm_reqd,$conditions);
                   8317: }
                   8318: 
                   8319: sub auto_checkphotos {
                   8320:     my ($uname,$udom,$pid) = @_;
                   8321:     my $homeserver = &homeserver($uname,$udom);
                   8322:     my ($result,$resulttype);
                   8323:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8324: 				   &escape($uname).':'.&escape($pid),
                   8325: 				   $homeserver));
1.709     albertel 8326:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8327: 	return (undef,undef);
                   8328:     }
1.706     raeburn  8329:     if ($outcome) {
                   8330:         ($result,$resulttype) = split(/:/,$outcome);
                   8331:     } 
                   8332:     return ($result,$resulttype);
                   8333: }
                   8334: 
                   8335: sub auto_photochoice {
                   8336:     my ($cnum,$cdom) = @_;
                   8337:     my $homeserver = &homeserver($cnum,$cdom);
                   8338:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8339: 						       &escape($cdom),
                   8340: 						       $homeserver)));
1.709     albertel 8341:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8342: 	return (undef,undef);
                   8343:     }
1.706     raeburn  8344:     return ($update,$comment);
                   8345: }
                   8346: 
                   8347: sub auto_photoupdate {
                   8348:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8349:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8350:     my $host=&hostname($homeserver);
1.706     raeburn  8351:     my $cmd = '';
                   8352:     my $maxtries = 1;
1.800     albertel 8353:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8354:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8355:     }
                   8356:     $cmd =~ s/%%$//;
                   8357:     $cmd = &escape($cmd);
                   8358:     my $query = 'institutionalphotos';
                   8359:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8360:     unless ($queryid=~/^\Q$host\E\_/) {
                   8361:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8362:         return 'error: '.$queryid;
                   8363:     }
                   8364:     my $reply = &get_query_reply($queryid);
                   8365:     my $tries = 1;
                   8366:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8367:         $reply = &get_query_reply($queryid);
                   8368:         $tries ++;
                   8369:     }
                   8370:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8371:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8372:     } else {
                   8373:         my @responses = split(/:/,$reply);
                   8374:         my $outcome = shift(@responses); 
                   8375:         foreach my $item (@responses) {
                   8376:             my ($key,$value) = split(/=/,$item);
                   8377:             $$photo{$key} = $value;
                   8378:         }
                   8379:         return $outcome;
                   8380:     }
                   8381:     return 'error';
                   8382: }
                   8383: 
1.521     raeburn  8384: sub auto_instcode_format {
1.793     albertel 8385:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8386: 	$cat_order) = @_;
1.521     raeburn  8387:     my $courses = '';
1.772     raeburn  8388:     my @homeservers;
1.521     raeburn  8389:     if ($caller eq 'global') {
1.841     albertel 8390: 	my %servers = &get_servers($codedom,'library');
                   8391: 	foreach my $tryserver (keys(%servers)) {
                   8392: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8393: 		push(@homeservers,$tryserver);
                   8394: 	    }
1.584     raeburn  8395:         }
1.1022    raeburn  8396:     } elsif ($caller eq 'requests') {
                   8397:         if ($codedom =~ /^$match_domain$/) {
                   8398:             my $chome = &domain($codedom,'primary');
                   8399:             unless ($chome eq 'no_host') {
                   8400:                 push(@homeservers,$chome);
                   8401:             }
                   8402:         }
1.521     raeburn  8403:     } else {
1.772     raeburn  8404:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8405:     }
1.793     albertel 8406:     foreach my $code (keys(%{$instcodes})) {
                   8407:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8408:     }
                   8409:     chop($courses);
1.772     raeburn  8410:     my $ok_response = 0;
                   8411:     my $response;
                   8412:     while (@homeservers > 0 && $ok_response == 0) {
                   8413:         my $server = shift(@homeservers); 
                   8414:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8415:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8416:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8417: 		split(/:/,$response);
1.772     raeburn  8418:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8419:             push(@{$codetitles},&str2array($codetitles_str));
                   8420:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8421:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8422:             $ok_response = 1;
                   8423:         }
                   8424:     }
                   8425:     if ($ok_response) {
1.521     raeburn  8426:         return 'ok';
1.772     raeburn  8427:     } else {
                   8428:         return $response;
1.521     raeburn  8429:     }
                   8430: }
                   8431: 
1.792     raeburn  8432: sub auto_instcode_defaults {
                   8433:     my ($domain,$returnhash,$code_order) = @_;
                   8434:     my @homeservers;
1.841     albertel 8435: 
                   8436:     my %servers = &get_servers($domain,'library');
                   8437:     foreach my $tryserver (keys(%servers)) {
                   8438: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8439: 	    push(@homeservers,$tryserver);
                   8440: 	}
1.792     raeburn  8441:     }
1.841     albertel 8442: 
1.792     raeburn  8443:     my $response;
1.841     albertel 8444:     foreach my $server (@homeservers) {
1.792     raeburn  8445:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8446:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8447: 	
                   8448: 	foreach my $pair (split(/\&/,$response)) {
                   8449: 	    my ($name,$value)=split(/\=/,$pair);
                   8450: 	    if ($name eq 'code_order') {
                   8451: 		@{$code_order} = split(/\&/,&unescape($value));
                   8452: 	    } else {
                   8453: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8454: 	    }
                   8455: 	}
                   8456: 	return 'ok';
1.792     raeburn  8457:     }
1.841     albertel 8458: 
                   8459:     return $response;
1.1003    raeburn  8460: }
                   8461: 
                   8462: sub auto_possible_instcodes {
1.1007    raeburn  8463:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8464:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8465:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8466:         return;
                   8467:     }
1.1003    raeburn  8468:     my (@homeservers,$uhome);
                   8469:     if (defined(&domain($domain,'primary'))) {
                   8470:         $uhome=&domain($domain,'primary');
                   8471:         push(@homeservers,&domain($domain,'primary'));
                   8472:     } else {
                   8473:         my %servers = &get_servers($domain,'library');
                   8474:         foreach my $tryserver (keys(%servers)) {
                   8475:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8476:                 push(@homeservers,$tryserver);
                   8477:             }
                   8478:         }
                   8479:     }
                   8480:     my $response;
                   8481:     foreach my $server (@homeservers) {
                   8482:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8483:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8484:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8485:             split(':',$response);
                   8486:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8487:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8488:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8489:             my ($name,$value)=split('=',$item);
                   8490:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8491:         }
                   8492:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8493:             my ($name,$value)=split('=',$item);
                   8494:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8495:         }
                   8496:         return 'ok';
                   8497:     }
                   8498:     return $response;
                   8499: }
1.792     raeburn  8500: 
1.1010    raeburn  8501: sub auto_courserequest_checks {
                   8502:     my ($dom) = @_;
1.1020    raeburn  8503:     my ($homeserver,%validations);
                   8504:     if ($dom =~ /^$match_domain$/) {
                   8505:         $homeserver = &domain($dom,'primary');
                   8506:     }
                   8507:     unless ($homeserver eq 'no_host') {
                   8508:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8509:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8510:             my @items = split(/&/,$response);
                   8511:             foreach my $item (@items) {
                   8512:                 my ($key,$value) = split('=',$item);
                   8513:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8514:             }
                   8515:         }
                   8516:     }
1.1010    raeburn  8517:     return %validations; 
                   8518: }
                   8519: 
1.1020    raeburn  8520: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8521:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8522:     my ($homeserver,$response);
                   8523:     if ($dom =~ /^$match_domain$/) {
                   8524:         $homeserver = &domain($dom,'primary');
                   8525:     }
1.1172.2.43  raeburn  8526:     unless ($homeserver eq 'no_host') {
                   8527:         my $customdata;
                   8528:         if (ref($custominfo) eq 'HASH') {
                   8529:             $customdata = &freeze_escape($custominfo);
                   8530:         }
1.1020    raeburn  8531:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8532:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8533:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8534:                                     $customdata,$homeserver));
1.1020    raeburn  8535:     }
                   8536:     return $response;
                   8537: }
                   8538: 
1.777     albertel 8539: sub auto_validate_class_sec {
1.918     raeburn  8540:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8541:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8542:     my $ownerlist;
                   8543:     if (ref($owners) eq 'ARRAY') {
                   8544:         $ownerlist = join(',',@{$owners});
                   8545:     } else {
                   8546:         $ownerlist = $owners;
                   8547:     }
1.773     raeburn  8548:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8549:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8550:     return $response;
                   8551: }
                   8552: 
1.1172.2.94  raeburn  8553: sub auto_validate_instclasses {
                   8554:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8555:     my ($homeserver,%validations);
                   8556:     $homeserver = &homeserver($cnum,$cdom);
                   8557:     unless ($homeserver eq 'no_host') {
                   8558:         my $ownerlist;
                   8559:         if (ref($owners) eq 'ARRAY') {
                   8560:             $ownerlist = join(',',@{$owners});
                   8561:         } else {
                   8562:             $ownerlist = $owners;
                   8563:         }
                   8564:         if (ref($classesref) eq 'HASH') {
                   8565:             my $classes = &freeze_escape($classesref);
                   8566:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8567:                                 ':'.$cdom.':'.$classes,$homeserver);
                   8568:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8569:                 my @items = split(/&/,$response);
                   8570:                 foreach my $item (@items) {
                   8571:                     my ($key,$value) = split('=',$item);
                   8572:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8573:                 }
                   8574:             }
                   8575:         }
                   8576:     }
                   8577:     return %validations;
                   8578: }
                   8579: 
1.1172.2.38  raeburn  8580: sub auto_crsreq_update {
                   8581:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8582:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8583:     my ($homeserver,%crsreqresponse);
                   8584:     if ($cdom =~ /^$match_domain$/) {
                   8585:         $homeserver = &domain($cdom,'primary');
                   8586:     }
                   8587:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8588:         my $info;
                   8589:         if (ref($inbound) eq 'HASH') {
                   8590:             $info = &freeze_escape($inbound);
                   8591:         }
                   8592:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8593:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8594:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8595:                             &escape($title).':'.&escape($code).':'.
                   8596:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8597:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8598:             my @items = split(/&/,$response);
                   8599:             foreach my $item (@items) {
                   8600:                 my ($key,$value) = split('=',$item);
                   8601:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8602:             }
                   8603:         }
                   8604:     }
                   8605:     return \%crsreqresponse;
                   8606: }
                   8607: 
1.1172.2.78  raeburn  8608: sub auto_export_grades {
                   8609:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8610:     my ($homeserver,%exportresponse);
                   8611:     if ($cdom =~ /^$match_domain$/) {
                   8612:         $homeserver = &domain($cdom,'primary');
                   8613:     }
                   8614:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8615:         my $info;
                   8616:         if (ref($inforef) eq 'HASH') {
                   8617:             $info = &freeze_escape($inforef);
                   8618:         }
                   8619:         if (ref($gradesref) eq 'HASH') {
                   8620:             my $grades = &freeze_escape($gradesref);
                   8621:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8622:                                 $info.':'.$grades,$homeserver);
                   8623:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8624:                 my @items = split(/&/,$response);
                   8625:                 foreach my $item (@items) {
                   8626:                     my ($key,$value) = split('=',$item);
                   8627:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8628:                 }
                   8629:             }
                   8630:         }
                   8631:     }
                   8632:     return \%exportresponse;
                   8633: }
                   8634: 
1.1172.2.68  raeburn  8635: sub check_instcode_cloning {
                   8636:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8637:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8638:         return;
                   8639:     }
                   8640:     my $canclone;
                   8641:     if (@{$code_order} > 0) {
                   8642:         my $instcoderegexp ='^';
                   8643:         my @clonecodes = split(/\&/,$cloner);
                   8644:         foreach my $item (@{$code_order}) {
                   8645:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8646:                 foreach my $pair (@clonecodes) {
                   8647:                     my ($key,$val) = split(/\=/,$pair,2);
                   8648:                     $val = &unescape($val);
                   8649:                     if ($key eq $item) {
                   8650:                         $instcoderegexp .= '('.$val.')';
                   8651:                         last;
                   8652:                     }
                   8653:                 }
                   8654:             } else {
                   8655:                 $instcoderegexp .= $codedefaults->{$item};
                   8656:             }
                   8657:         }
                   8658:         $instcoderegexp .= '$';
                   8659:         my (@from,@to);
                   8660:         eval {
                   8661:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8662:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8663:         };
                   8664:         if ((@from > 0) && (@to > 0)) {
                   8665:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8666:             if (!@diffs) {
                   8667:                 $canclone = 1;
                   8668:             }
                   8669:         }
                   8670:     }
                   8671:     return $canclone;
                   8672: }
                   8673: 
                   8674: sub default_instcode_cloning {
                   8675:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8676:     my (%codedefaults,@code_order,$canclone);
                   8677:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8678:         %codedefaults = %{$codedefaultsref};
                   8679:         @code_order = @{$codeorderref};
                   8680:     } elsif ($clonedom) {
                   8681:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8682:     }
                   8683:     if (($domdefclone) && (@code_order)) {
                   8684:         my @clonecodes = split(/\+/,$domdefclone);
                   8685:         my $instcoderegexp ='^';
                   8686:         foreach my $item (@code_order) {
                   8687:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8688:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8689:             } else {
                   8690:                 $instcoderegexp .= $codedefaults{$item};
                   8691:             }
                   8692:         }
                   8693:         $instcoderegexp .= '$';
                   8694:         my (@from,@to);
                   8695:         eval {
                   8696:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8697:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8698:         };
                   8699:         if ((@from > 0) && (@to > 0)) {
                   8700:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8701:             if (!@diffs) {
                   8702:                 $canclone = 1;
                   8703:             }
                   8704:         }
                   8705:     }
                   8706:     return $canclone;
                   8707: }
                   8708: 
1.679     raeburn  8709: # ------------------------------------------------------- Course Group routines
                   8710: 
                   8711: sub get_coursegroups {
1.809     raeburn  8712:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8713:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8714: }
                   8715: 
1.679     raeburn  8716: sub modify_coursegroup {
                   8717:     my ($cdom,$cnum,$groupsettings) = @_;
                   8718:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8719: }
                   8720: 
1.809     raeburn  8721: sub toggle_coursegroup_status {
                   8722:     my ($cdom,$cnum,$group,$action) = @_;
                   8723:     my ($from_namespace,$to_namespace);
                   8724:     if ($action eq 'delete') {
                   8725:         $from_namespace = 'coursegroups';
                   8726:         $to_namespace = 'deleted_groups';
                   8727:     } else {
                   8728:         $from_namespace = 'deleted_groups';
                   8729:         $to_namespace = 'coursegroups';
                   8730:     }
                   8731:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8732:     if (my $tmp = &error(%curr_group)) {
                   8733:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8734:         return ('read error',$tmp);
                   8735:     } else {
                   8736:         my %savedsettings = %curr_group; 
1.809     raeburn  8737:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8738:         my $deloutcome;
                   8739:         if ($result eq 'ok') {
1.809     raeburn  8740:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8741:         } else {
                   8742:             return ('write error',$result);
                   8743:         }
                   8744:         if ($deloutcome eq 'ok') {
                   8745:             return 'ok';
                   8746:         } else {
                   8747:             return ('delete error',$deloutcome);
                   8748:         }
                   8749:     }
                   8750: }
                   8751: 
1.679     raeburn  8752: sub modify_group_roles {
1.957     raeburn  8753:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8754:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8755:     my $role = 'gr/'.&escape($userprivs);
                   8756:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8757:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8758:     if ($result eq 'ok') {
                   8759:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8760:     }
1.679     raeburn  8761:     return $result;
                   8762: }
                   8763: 
                   8764: sub modify_coursegroup_membership {
                   8765:     my ($cdom,$cnum,$membership) = @_;
                   8766:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8767:     return $result;
                   8768: }
                   8769: 
1.682     raeburn  8770: sub get_active_groups {
                   8771:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8772:     my $now = time;
                   8773:     my %groups = ();
                   8774:     foreach my $key (keys(%env)) {
1.811     albertel 8775:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8776:             my ($start,$end) = split(/\./,$env{$key});
                   8777:             if (($end!=0) && ($end<$now)) { next; }
                   8778:             if (($start!=0) && ($start>$now)) { next; }
                   8779:             if ($1 eq $cdom && $2 eq $cnum) {
                   8780:                 $groups{$3} = $env{$key} ;
                   8781:             }
                   8782:         }
                   8783:     }
                   8784:     return %groups;
                   8785: }
                   8786: 
1.683     raeburn  8787: sub get_group_membership {
                   8788:     my ($cdom,$cnum,$group) = @_;
                   8789:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8790: }
                   8791: 
                   8792: sub get_users_groups {
                   8793:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8794:     my @usersgroups;
1.683     raeburn  8795:     my $cachetime=1800;
                   8796: 
                   8797:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8798:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8799:     if (defined($cached)) {
1.734     albertel 8800:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8801:     } else {  
                   8802:         $grouplist = '';
1.816     raeburn  8803:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8804:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8805:         my $access_end = $env{'course.'.$courseid.
                   8806:                               '.default_enrollment_end_date'};
                   8807:         my $now = time;
                   8808:         foreach my $key (keys(%roleshash)) {
                   8809:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8810:                 my $group = $1;
                   8811:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8812:                     my $start = $2;
                   8813:                     my $end = $1;
                   8814:                     if ($start == -1) { next; } # deleted from group
                   8815:                     if (($start!=0) && ($start>$now)) { next; }
                   8816:                     if (($end!=0) && ($end<$now)) {
                   8817:                         if ($access_end && $access_end < $now) {
                   8818:                             if ($access_end - $end < 86400) {
                   8819:                                 push(@usersgroups,$group);
1.733     raeburn  8820:                             }
                   8821:                         }
1.817     raeburn  8822:                         next;
1.733     raeburn  8823:                     }
1.817     raeburn  8824:                     push(@usersgroups,$group);
1.683     raeburn  8825:                 }
                   8826:             }
                   8827:         }
1.817     raeburn  8828:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8829:         $grouplist = join(':',@usersgroups);
                   8830:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8831:     }
1.733     raeburn  8832:     return @usersgroups;
1.683     raeburn  8833: }
                   8834: 
                   8835: sub devalidate_getgroups_cache {
                   8836:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8837:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8838: 
1.683     raeburn  8839:     my $hashid="$udom:$uname:$courseid";
                   8840:     &devalidate_cache_new('getgroups',$hashid);
                   8841: }
                   8842: 
1.12      www      8843: # ------------------------------------------------------------------ Plain Text
                   8844: 
                   8845: sub plaintext {
1.988     raeburn  8846:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8847:     if ($short =~ m{^cr/}) {
1.758     albertel 8848: 	return (split('/',$short))[-1];
                   8849:     }
1.742     raeburn  8850:     if (!defined($cid)) {
                   8851:         $cid = $env{'request.course.id'};
                   8852:     }
                   8853:     my %rolenames = (
1.1008    raeburn  8854:                       Course    => 'std',
                   8855:                       Community => 'alt1',
1.742     raeburn  8856:                     );
1.1037    raeburn  8857:     if ($cid ne '') {
                   8858:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8859:             unless ($forcedefault) {
                   8860:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8861:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8862:                 return &Apache::lonlocal::mt($roletext);
                   8863:             }
                   8864:         }
                   8865:     }
                   8866:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8867:         (defined($rolenames{$type})) && 
                   8868:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8869:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8870:     } elsif ($cid ne '') {
                   8871:         my $crstype = $env{'course.'.$cid.'.type'};
                   8872:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8873:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8874:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8875:         }
1.742     raeburn  8876:     }
1.1037    raeburn  8877:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8878: }
                   8879: 
                   8880: # ----------------------------------------------------------------- Assign Role
                   8881: 
                   8882: sub assignrole {
1.957     raeburn  8883:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8884:         $context)=@_;
1.21      www      8885:     my $mrole;
                   8886:     if ($role =~ /^cr\//) {
1.393     www      8887:         my $cwosec=$url;
1.811     albertel 8888:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8889: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8890:            my $refused = 1;
                   8891:            if ($context eq 'requestcourses') {
                   8892:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8893:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8894:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8895:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8896:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8897:                            if ($crsenv{'internal.courseowner'} eq
                   8898:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8899:                                $refused = '';
                   8900:                            }
                   8901:                        }
                   8902:                    }
                   8903:                }
                   8904:            }
                   8905:            if ($refused) {
                   8906:                &logthis('Refused custom assignrole: '.
                   8907:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8908:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8909:                return 'refused';
                   8910:            }
1.104     www      8911:         }
1.21      www      8912:         $mrole='cr';
1.678     raeburn  8913:     } elsif ($role =~ /^gr\//) {
                   8914:         my $cwogrp=$url;
1.811     albertel 8915:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8916:         unless (&allowed('mdg',$cwogrp)) {
                   8917:             &logthis('Refused group assignrole: '.
                   8918:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8919:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8920:             return 'refused';
                   8921:         }
                   8922:         $mrole='gr';
1.21      www      8923:     } else {
1.82      www      8924:         my $cwosec=$url;
1.811     albertel 8925:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8926:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8927:             my $refused;
                   8928:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8929:                 if (!(&allowed('c'.$role,$url))) {
                   8930:                     $refused = 1;
                   8931:                 }
                   8932:             } else {
                   8933:                 $refused = 1;
                   8934:             }
1.947     raeburn  8935:             if ($refused) {
1.1045    raeburn  8936:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8937:                 if (!$selfenroll && $context eq 'course') {
                   8938:                     my %crsenv;
                   8939:                     if ($role eq 'cc' || $role eq 'co') {
                   8940:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8941:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8942:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8943:                                 if ($crsenv{'internal.courseowner'} eq 
                   8944:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8945:                                     $refused = '';
                   8946:                                 }
                   8947:                             }
                   8948:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8949:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8950:                                 if ($crsenv{'internal.courseowner'} eq 
                   8951:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8952:                                     $refused = '';
                   8953:                                 }
                   8954:                             }
                   8955:                         }
                   8956:                     }
                   8957:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8958:                     $refused = '';
1.1017    raeburn  8959:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8960:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8961:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8962:                         my $wrongcc;
                   8963:                         if ($cnum =~ /^$match_community$/) {
                   8964:                             $wrongcc = 1 if ($role eq 'cc');
                   8965:                         } else {
                   8966:                             $wrongcc = 1 if ($role eq 'co');
                   8967:                         }
                   8968:                         unless ($wrongcc) {
                   8969:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8970:                             if ($crsenv{'internal.courseowner'} eq 
                   8971:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8972:                                 $refused = '';
                   8973:                             }
1.1017    raeburn  8974:                         }
                   8975:                     }
1.1172.2.9  raeburn  8976:                 } elsif ($context eq 'requestauthor') {
                   8977:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8978:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8979:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8980:                             $refused = '';
                   8981:                         } else {
                   8982:                             my %domdefaults = &get_domain_defaults($udom);
                   8983:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8984:                                 my $checkbystatus;
                   8985:                                 if ($env{'user.adv'}) {
                   8986:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8987:                                     if ($disposition eq 'automatic') {
                   8988:                                         $refused = '';
                   8989:                                     } elsif ($disposition eq '') {
                   8990:                                         $checkbystatus = 1;
                   8991:                                     }
                   8992:                                 } else {
                   8993:                                     $checkbystatus = 1;
                   8994:                                 }
                   8995:                                 if ($checkbystatus) {
                   8996:                                     if ($env{'environment.inststatus'}) {
                   8997:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8998:                                         foreach my $type (@inststatuses) {
                   8999:                                             if (($type ne '') &&
                   9000:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9001:                                                 $refused = '';
                   9002:                                             }
                   9003:                                         }
                   9004:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9005:                                         $refused = '';
                   9006:                                     }
                   9007:                                 }
                   9008:                             }
                   9009:                         }
                   9010:                     }
1.1017    raeburn  9011:                 }
                   9012:                 if ($refused) {
1.947     raeburn  9013:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9014:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9015: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9016:                     return 'refused';
                   9017:                 }
1.932     raeburn  9018:             }
1.1131    raeburn  9019:         } elsif ($role eq 'au') {
                   9020:             if ($url ne '/'.$udom.'/') {
                   9021:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9022:                          ' to assign author role for '.$uname.':'.$udom.
                   9023:                          ' in domain: '.$url.' refused (wrong domain).');
                   9024:                 return 'refused';
                   9025:             }
1.104     www      9026:         }
1.21      www      9027:         $mrole=$role;
                   9028:     }
1.620     albertel 9029:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9030:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9031:     if ($end) { $command.='_'.$end; }
1.21      www      9032:     if ($start) {
                   9033: 	if ($end) { 
1.81      www      9034:            $command.='_'.$start; 
1.21      www      9035:         } else {
1.81      www      9036:            $command.='_0_'.$start;
1.21      www      9037:         }
                   9038:     }
1.739     raeburn  9039:     my $origstart = $start;
                   9040:     my $origend = $end;
1.957     raeburn  9041:     my $delflag;
1.357     www      9042: # actually delete
                   9043:     if ($deleteflag) {
1.373     www      9044: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9045: # modify command to delete the role
1.620     albertel 9046:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9047:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9048: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9049: # set start and finish to negative values for userrolelog
                   9050:            $start=-1;
                   9051:            $end=-1;
1.957     raeburn  9052:            $delflag = 1;
1.357     www      9053:         }
                   9054:     }
                   9055: # send command
1.349     www      9056:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9057: # log new user role if status is ok
1.349     www      9058:     if ($answer eq 'ok') {
1.663     raeburn  9059: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9060:         if (($role eq 'cc') || ($role eq 'in') ||
                   9061:             ($role eq 'ep') || ($role eq 'ad') ||
                   9062:             ($role eq 'ta') || ($role eq 'st') ||
                   9063:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9064:             ($role eq 'co')) {
1.1172.2.13  raeburn  9065: # for course roles, perform group memberships changes triggered by role change.
                   9066:             unless ($role =~ /^gr/) {
                   9067:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9068:                                                  $origstart,$selfenroll,$context);
                   9069:             }
1.1172.2.9  raeburn  9070:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9071:                            $selfenroll,$context);
                   9072:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9073:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9074:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9075:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9076:                            $context);
                   9077:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9078:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9079:                              $context);
                   9080:         }
1.1053    raeburn  9081:         if ($role eq 'cc') {
                   9082:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9083:         }
1.349     www      9084:     }
                   9085:     return $answer;
1.169     harris41 9086: }
                   9087: 
1.1053    raeburn  9088: sub autoupdate_coowners {
                   9089:     my ($url,$end,$start,$uname,$udom) = @_;
                   9090:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9091:     if (($cdom ne '') && ($cnum ne '')) {
                   9092:         my $now = time;
                   9093:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9094:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9095:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9096:             my $instcode = $coursehash{'internal.coursecode'};
                   9097:             if ($instcode ne '') {
1.1056    raeburn  9098:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9099:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9100:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9101:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9102:                         if ($result eq 'valid') {
                   9103:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9104:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9105:                                     push(@newcoowners,$coowner);
                   9106:                                 }
                   9107:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9108:                                     push(@newcoowners,$uname.':'.$udom);
                   9109:                                 }
                   9110:                                 @newcoowners = sort(@newcoowners);
                   9111:                             } else {
                   9112:                                 push(@newcoowners,$uname.':'.$udom);
                   9113:                             }
                   9114:                         } else {
                   9115:                             if ($coursehash{'internal.co-owners'}) {
                   9116:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9117:                                     unless ($coowner eq $uname.':'.$udom) {
                   9118:                                         push(@newcoowners,$coowner);
                   9119:                                     }
                   9120:                                 }
                   9121:                                 unless (@newcoowners > 0) {
                   9122:                                     $delcoowners = 1;
                   9123:                                     $coowners = '';
                   9124:                                 }
                   9125:                             }
                   9126:                         }
                   9127:                         if (@newcoowners || $delcoowners) {
                   9128:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9129:                                             $delcoowners,@newcoowners);
                   9130:                         }
                   9131:                     }
                   9132:                 }
                   9133:             }
                   9134:         }
                   9135:     }
                   9136: }
                   9137: 
                   9138: sub store_coowners {
                   9139:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9140:     my $cid = $cdom.'_'.$cnum;
                   9141:     my ($coowners,$delresult,$putresult);
                   9142:     if (@newcoowners) {
                   9143:         $coowners = join(',',@newcoowners);
                   9144:         my %coownershash = (
                   9145:                             'internal.co-owners' => $coowners,
                   9146:                            );
                   9147:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9148:         if ($putresult eq 'ok') {
                   9149:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9150:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9151:             }
                   9152:         }
                   9153:     }
                   9154:     if ($delcoowners) {
                   9155:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9156:         if ($delresult eq 'ok') {
                   9157:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9158:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9159:             }
                   9160:         }
                   9161:     }
                   9162:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9163:         my %crsinfo =
                   9164:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9165:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9166:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9167:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9168:         }
                   9169:     }
                   9170: }
                   9171: 
1.169     harris41 9172: # -------------------------------------------------- Modify user authentication
1.197     www      9173: # Overrides without validation
                   9174: 
1.169     harris41 9175: sub modifyuserauth {
                   9176:     my ($udom,$uname,$umode,$upass)=@_;
                   9177:     my $uhome=&homeserver($uname,$udom);
1.197     www      9178:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9179:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9180:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9181:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9182:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9183: 		     &escape($upass),$uhome);
1.620     albertel 9184:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9185:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9186:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9187:     &log($udom,,$uname,$uhome,
1.620     albertel 9188:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9189:                                      $env{'user.name'}.', '.$umode.
1.197     www      9190:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9191:     unless ($reply eq 'ok') {
1.197     www      9192:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9193: 	return 'error: '.$reply;
                   9194:     }   
1.170     harris41 9195:     return 'ok';
1.80      www      9196: }
                   9197: 
1.81      www      9198: # --------------------------------------------------------------- Modify a user
1.80      www      9199: 
1.81      www      9200: sub modifyuser {
1.206     matthew  9201:     my ($udom,    $uname, $uid,
                   9202:         $umode,   $upass, $first,
                   9203:         $middle,  $last,  $gene,
1.1058    raeburn  9204:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9205:     $udom= &LONCAPA::clean_domain($udom);
                   9206:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9207:     my $showcandelete = 'none';
                   9208:     if (ref($candelete) eq 'ARRAY') {
                   9209:         if (@{$candelete} > 0) {
                   9210:             $showcandelete = join(', ',@{$candelete});
                   9211:         }
                   9212:     }
1.81      www      9213:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9214:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9215: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9216:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9217:                                      ' desiredhome not specified'). 
1.620     albertel 9218:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9219:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9220:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9221:     my $newuser;
                   9222:     if ($uhome eq 'no_host') {
                   9223:         $newuser = 1;
                   9224:     }
1.80      www      9225: # ----------------------------------------------------------------- Create User
1.406     albertel 9226:     if (($uhome eq 'no_host') && 
                   9227: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9228:         my $unhome='';
1.844     albertel 9229:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9230:             $unhome = $desiredhome;
1.620     albertel 9231: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9232: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9233:         } else { # load balancing routine for determining $unhome
1.81      www      9234:             my $loadm=10000000;
1.841     albertel 9235: 	    my %servers = &get_servers($udom,'library');
                   9236: 	    foreach my $tryserver (keys(%servers)) {
                   9237: 		my $answer=reply('load',$tryserver);
                   9238: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9239: 		    $loadm=$answer;
                   9240: 		    $unhome=$tryserver;
                   9241: 		}
1.80      www      9242: 	    }
                   9243:         }
                   9244:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9245: 	    return 'error: unable to find a home server for '.$uname.
                   9246:                    ' in domain '.$udom;
1.80      www      9247:         }
                   9248:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9249:                          &escape($upass),$unhome);
                   9250: 	unless ($reply eq 'ok') {
                   9251:             return 'error: '.$reply;
                   9252:         }   
1.230     stredwic 9253:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9254:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9255: 	    return 'error: unable verify users home machine.';
1.80      www      9256:         }
1.209     matthew  9257:     }   # End of creation of new user
1.80      www      9258: # ---------------------------------------------------------------------- Add ID
                   9259:     if ($uid) {
                   9260:        $uid=~tr/A-Z/a-z/;
                   9261:        my %uidhash=&idrget($udom,$uname);
1.196     www      9262:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9263:          && (!$forceid)) {
1.80      www      9264: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9265: 	      return 'error: user id "'.$uid.'" does not match '.
                   9266:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9267:           }
                   9268:        } else {
                   9269: 	  &idput($udom,($uname => $uid));
                   9270:        }
                   9271:     }
                   9272: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9273:     my @tmp=&get('environment',
1.899     raeburn  9274: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9275:                     'permanentemail','inststatus'],
1.134     albertel 9276: 		   $udom,$uname);
1.1075    raeburn  9277:     my (%names,%oldnames);
1.313     matthew  9278:     if ($tmp[0] =~ m/^error:.*/) { 
                   9279:         %names=(); 
                   9280:     } else {
                   9281:         %names = @tmp;
1.1075    raeburn  9282:         %oldnames = %names;
1.313     matthew  9283:     }
1.388     www      9284: #
1.1058    raeburn  9285: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9286: # of users did not contain them), do not overwrite existing values
                   9287: # unless field is in $candelete array ref.  
                   9288: #
                   9289: 
                   9290:     my @fields = ('firstname','middlename','lastname','generation',
                   9291:                   'permanentemail','id');
                   9292:     my %newvalues;
                   9293:     if (ref($candelete) eq 'ARRAY') {
                   9294:         foreach my $field (@fields) {
                   9295:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9296:                 if ($field eq 'firstname') {
                   9297:                     $names{$field} = $first;
                   9298:                 } elsif ($field eq 'middlename') {
                   9299:                     $names{$field} = $middle;
                   9300:                 } elsif ($field eq 'lastname') {
                   9301:                     $names{$field} = $last;
                   9302:                 } elsif ($field eq 'generation') { 
                   9303:                     $names{$field} = $gene;
                   9304:                 } elsif ($field eq 'permanentemail') {
                   9305:                     $names{$field} = $email;
                   9306:                 } elsif ($field eq 'id') {
                   9307:                     $names{$field}  = $uid;
                   9308:                 }
                   9309:             }
                   9310:         }
                   9311:     }
1.388     www      9312:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9313:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9314:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9315:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9316:     if ($email) {
                   9317:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9318:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9319:     }
1.899     raeburn  9320:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9321:     if (defined($inststatus)) {
                   9322:         $names{'inststatus'} = '';
                   9323:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9324:         if (ref($usertypes) eq 'HASH') {
                   9325:             my @okstatuses; 
                   9326:             foreach my $item (split(/:/,$inststatus)) {
                   9327:                 if (defined($usertypes->{$item})) {
                   9328:                     push(@okstatuses,$item);  
                   9329:                 }
                   9330:             }
                   9331:             if (@okstatuses) {
                   9332:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9333:             }
                   9334:         }
                   9335:     }
1.1075    raeburn  9336:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9337:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9338:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9339:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9340:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9341:     } else {
                   9342:         $logmsg .= ' during self creation';
                   9343:     }
1.1075    raeburn  9344:     my $changed;
                   9345:     if ($newuser) {
                   9346:         $changed = 1;
                   9347:     } else {
                   9348:         foreach my $field (@fields) {
                   9349:             if ($names{$field} ne $oldnames{$field}) {
                   9350:                 $changed = 1;
                   9351:                 last;
                   9352:             }
                   9353:         }
                   9354:     }
                   9355:     unless ($changed) {
                   9356:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9357:         &logthis($logmsg);
                   9358:         return 'ok';
                   9359:     }
                   9360:     my $reply = &put('environment', \%names, $udom,$uname);
                   9361:     if ($reply ne 'ok') { 
                   9362:         return 'error: '.$reply;
                   9363:     }
1.1087    raeburn  9364:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9365:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9366:     }
1.1075    raeburn  9367:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9368:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9369:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9370:     &logthis($logmsg);
1.134     albertel 9371:     return 'ok';
1.80      www      9372: }
                   9373: 
1.81      www      9374: # -------------------------------------------------------------- Modify student
1.80      www      9375: 
1.81      www      9376: sub modifystudent {
                   9377:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9378:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9379:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9380:     if (!$cid) {
1.620     albertel 9381: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9382: 	    return 'not_in_class';
                   9383: 	}
1.80      www      9384:     }
                   9385: # --------------------------------------------------------------- Make the user
1.81      www      9386:     my $reply=&modifyuser
1.209     matthew  9387: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9388:          $desiredhome,$email,$inststatus);
1.80      www      9389:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9390:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9391:     # student's environment
1.297     matthew  9392:     $uid = undef if (!$forceid);
1.455     albertel 9393:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9394: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9395:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9396:     return $reply;
                   9397: }
                   9398: 
                   9399: sub modify_student_enrollment {
1.1172.2.23  raeburn  9400:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9401:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9402:     my ($cdom,$cnum,$chome);
                   9403:     if (!$cid) {
1.620     albertel 9404: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9405: 	    return 'not_in_class';
                   9406: 	}
1.620     albertel 9407: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9408: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9409:     } else {
                   9410: 	($cdom,$cnum)=split(/_/,$cid);
                   9411:     }
1.620     albertel 9412:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9413:     if (!$chome) {
1.457     raeburn  9414: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9415:     }
1.455     albertel 9416:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9417:     # Make sure the user exists
1.81      www      9418:     my $uhome=&homeserver($uname,$udom);
                   9419:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9420: 	return 'error: no such user';
                   9421:     }
1.297     matthew  9422:     # Get student data if we were not given enough information
                   9423:     if (!defined($first)  || $first  eq '' || 
                   9424:         !defined($last)   || $last   eq '' || 
                   9425:         !defined($uid)    || $uid    eq '' || 
                   9426:         !defined($middle) || $middle eq '' || 
                   9427:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9428:         # They did not supply us with enough data to enroll the student, so
                   9429:         # we need to pick up more information.
1.297     matthew  9430:         my %tmp = &get('environment',
1.294     matthew  9431:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9432:                        ,$udom,$uname);
                   9433: 
1.800     albertel 9434:         #foreach my $key (keys(%tmp)) {
                   9435:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9436:         #}
1.294     matthew  9437:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9438:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9439:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9440:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9441:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9442:     }
1.556     albertel 9443:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9444:     my $user = "$uname:$udom";
                   9445:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9446:     my $reply=cput('classlist',
1.1148    raeburn  9447: 		   {$user => 
1.1172.2.76  raeburn  9448: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9449: 		   $cdom,$cnum);
1.1148    raeburn  9450:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9451:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9452:     } else { 
1.81      www      9453: 	return 'error: '.$reply;
                   9454:     }
1.297     matthew  9455:     # Add student role to user
1.83      www      9456:     my $uurl='/'.$cid;
1.81      www      9457:     $uurl=~s/\_/\//g;
                   9458:     if ($usec) {
                   9459: 	$uurl.='/'.$usec;
                   9460:     }
1.1148    raeburn  9461:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9462:                              $selfenroll,$context);
                   9463:     if ($result ne 'ok') {
                   9464:         if ($old_entry{$user} ne '') {
                   9465:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9466:         } else {
                   9467:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9468:         }
                   9469:     }
                   9470:     return $result; 
1.21      www      9471: }
                   9472: 
1.556     albertel 9473: sub format_name {
                   9474:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9475:     my $name;
                   9476:     if ($first ne 'lastname') {
                   9477: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9478:     } else {
                   9479: 	if ($lastname=~/\S/) {
                   9480: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9481: 	    $name=~s/\s+,/,/;
                   9482: 	} else {
                   9483: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9484: 	}
                   9485:     }
                   9486:     $name=~s/^\s+//;
                   9487:     $name=~s/\s+$//;
                   9488:     $name=~s/\s+/ /g;
                   9489:     return $name;
                   9490: }
                   9491: 
1.84      www      9492: # ------------------------------------------------- Write to course preferences
                   9493: 
                   9494: sub writecoursepref {
                   9495:     my ($courseid,%prefs)=@_;
                   9496:     $courseid=~s/^\///;
                   9497:     $courseid=~s/\_/\//g;
                   9498:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9499:     my $chome=homeserver($cnum,$cdomain);
                   9500:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9501: 	return 'error: no such course';
                   9502:     }
                   9503:     my $cstring='';
1.800     albertel 9504:     foreach my $pref (keys(%prefs)) {
                   9505: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9506:     }
1.84      www      9507:     $cstring=~s/\&$//;
                   9508:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9509: }
                   9510: 
                   9511: # ---------------------------------------------------------- Make/modify course
                   9512: 
                   9513: sub createcourse {
1.741     raeburn  9514:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9515:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9516:     $url=&declutter($url);
                   9517:     my $cid='';
1.1028    raeburn  9518:     if ($context eq 'requestcourses') {
                   9519:         my $can_create = 0;
                   9520:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9521:         if ($udom eq $ownerdom) {
                   9522:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9523:                                   $context)) {
                   9524:                 $can_create = 1;
                   9525:             }
                   9526:         } else {
                   9527:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9528:                                            $category);
                   9529:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9530:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9531:                 if (@curr > 0) {
                   9532:                     my @options = qw(approval validate autolimit);
                   9533:                     my $optregex = join('|',@options);
                   9534:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9535:                         $can_create = 1;
                   9536:                     }
                   9537:                 }
                   9538:             }
                   9539:         }
                   9540:         if ($can_create) {
                   9541:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9542:                 unless (&allowed('ccc',$udom)) {
                   9543:                     return 'refused'; 
                   9544:                 }
1.1017    raeburn  9545:             }
                   9546:         } else {
                   9547:             return 'refused';
                   9548:         }
1.1028    raeburn  9549:     } elsif (!&allowed('ccc',$udom)) {
                   9550:         return 'refused';
1.84      www      9551:     }
1.1011    raeburn  9552: # --------------------------------------------------------------- Get Unique ID
                   9553:     my $uname;
                   9554:     if ($cnum =~ /^$match_courseid$/) {
                   9555:         my $chome=&homeserver($cnum,$udom,'true');
                   9556:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9557:             $uname = $cnum;
                   9558:         } else {
1.1038    raeburn  9559:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9560:         }
                   9561:     } else {
1.1038    raeburn  9562:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9563:     }
                   9564:     return $uname if ($uname =~ /^error/);
                   9565: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9566:     if (!defined($course_server)) {
                   9567:         if (defined(&domain($udom,'primary'))) {
                   9568:             $course_server = &domain($udom,'primary');
                   9569:         } else {
                   9570:             $course_server = $env{'user.home'}; 
                   9571:         }
                   9572:     }
                   9573:     my %host_servers =
                   9574:         &Apache::lonnet::get_servers($udom,'library');
                   9575:     unless ($host_servers{$course_server}) {
                   9576:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9577:     }
1.84      www      9578: # ------------------------------------------------------------- Make the course
                   9579:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9580:                       $course_server);
1.84      www      9581:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9582:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9583:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9584: 	return 'error: no such course';
                   9585:     }
1.271     www      9586: # ----------------------------------------------------------------- Course made
1.516     raeburn  9587: # log existence
1.1029    raeburn  9588:     my $now = time;
1.918     raeburn  9589:     my $newcourse = {
                   9590:                     $udom.'_'.$uname => {
1.921     raeburn  9591:                                      description => $description,
                   9592:                                      inst_code   => $inst_code,
                   9593:                                      owner       => $course_owner,
                   9594:                                      type        => $crstype,
1.1029    raeburn  9595:                                      creator     => $env{'user.name'}.':'.
                   9596:                                                     $env{'user.domain'},
                   9597:                                      created     => $now,
                   9598:                                      context     => $context,
1.918     raeburn  9599:                                                 },
                   9600:                     };
1.921     raeburn  9601:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9602: # set toplevel url
1.271     www      9603:     my $topurl=$url;
                   9604:     unless ($nonstandard) {
                   9605: # ------------------------------------------ For standard courses, make top url
                   9606:         my $mapurl=&clutter($url);
1.278     www      9607:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9608:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9609: <map>
                   9610: <resource id="1" type="start"></resource>
                   9611: <resource id="2" src="$mapurl"></resource>
                   9612: <resource id="3" type="finish"></resource>
                   9613: <link index="1" from="1" to="2"></link>
                   9614: <link index="2" from="2" to="3"></link>
                   9615: </map>
                   9616: ENDINITMAP
                   9617:         $topurl=&declutter(
1.638     albertel 9618:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9619:                           );
                   9620:     }
                   9621: # ----------------------------------------------------------- Write preferences
1.84      www      9622:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9623:                      ('description'              => $description,
                   9624:                       'url'                      => $topurl,
                   9625:                       'internal.creator'         => $env{'user.name'}.':'.
                   9626:                                                     $env{'user.domain'},
                   9627:                       'internal.created'         => $now,
                   9628:                       'internal.creationcontext' => $context)
                   9629:                     );
1.84      www      9630:     return '/'.$udom.'/'.$uname;
                   9631: }
                   9632: 
1.1011    raeburn  9633: # ------------------------------------------------------------------- Create ID
                   9634: sub generate_coursenum {
1.1038    raeburn  9635:     my ($udom,$crstype) = @_;
1.1011    raeburn  9636:     my $domdesc = &domain($udom);
                   9637:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9638:     my $first;
                   9639:     if ($crstype eq 'Community') {
                   9640:         $first = '0';
                   9641:     } else {
                   9642:         $first = int(1+rand(9)); 
                   9643:     } 
                   9644:     my $uname=$first.
1.1011    raeburn  9645:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9646:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9647:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9648: # ----------------------------------------------- Make sure that does not exist
                   9649:     my $uhome=&homeserver($uname,$udom,'true');
                   9650:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9651:         if ($crstype eq 'Community') {
                   9652:             $first = '0';
                   9653:         } else {
                   9654:             $first = int(1+rand(9));
                   9655:         }
                   9656:         $uname=$first.
1.1011    raeburn  9657:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9658:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9659:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9660:         $uhome=&homeserver($uname,$udom,'true');
                   9661:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9662:             return 'error: unable to generate unique course-ID';
                   9663:         }
                   9664:     }
                   9665:     return $uname;
                   9666: }
                   9667: 
1.813     albertel 9668: sub is_course {
1.1167    droeschl 9669:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9670:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  9671:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   9672:     my $uhome=&homeserver($cnum,$cdom);
                   9673:     my $iscourse;
                   9674:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   9675:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   9676:     } else {
                   9677:         my $hashid = $cdom.':'.$cnum;
                   9678:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   9679:         unless (defined($cached)) {
                   9680:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   9681:                                         $cnum,undef,undef,'.');
                   9682:             $iscourse = 0;
                   9683:             if (exists($courses{$cdom.'_'.$cnum})) {
                   9684:                 $iscourse = 1;
                   9685:             }
                   9686:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   9687:         }
                   9688:     }
                   9689:     return unless($iscourse);
1.1167    droeschl 9690:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9691: }
                   9692: 
1.1015    raeburn  9693: sub store_userdata {
                   9694:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9695:     my $result;
1.1016    raeburn  9696:     if ($datakey ne '') {
1.1013    raeburn  9697:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9698:             if ($udom eq '' || $uname eq '') {
                   9699:                 $udom = $env{'user.domain'};
                   9700:                 $uname = $env{'user.name'};
                   9701:             }
                   9702:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9703:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9704:                 $result = 'error: no_host';
                   9705:             } else {
                   9706:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9707:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9708: 
                   9709:                 my $namevalue='';
                   9710:                 foreach my $key (keys(%{$storehash})) {
                   9711:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9712:                 }
                   9713:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9714:                 unless ($namespace eq 'courserequests') {
                   9715:                     $datakey = &escape($datakey);
                   9716:                 }
1.1105    raeburn  9717:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9718:                                   $namevalue,$uhome);
1.1013    raeburn  9719:             }
                   9720:         } else {
                   9721:             $result = 'error: data to store was not a hash reference'; 
                   9722:         }
                   9723:     } else {
                   9724:         $result= 'error: invalid requestkey'; 
                   9725:     }
                   9726:     return $result;
                   9727: }
                   9728: 
1.21      www      9729: # ---------------------------------------------------------- Assign Custom Role
                   9730: 
                   9731: sub assigncustomrole {
1.957     raeburn  9732:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9733:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9734:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9735: }
                   9736: 
                   9737: # ----------------------------------------------------------------- Revoke Role
                   9738: 
                   9739: sub revokerole {
1.957     raeburn  9740:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9741:     my $now=time;
1.965     raeburn  9742:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9743: }
                   9744: 
                   9745: # ---------------------------------------------------------- Revoke Custom Role
                   9746: 
                   9747: sub revokecustomrole {
1.957     raeburn  9748:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9749:     my $now=time;
1.357     www      9750:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9751:            $deleteflag,$selfenroll,$context);
1.17      www      9752: }
                   9753: 
1.533     banghart 9754: # ------------------------------------------------------------ Disk usage
1.535     albertel 9755: sub diskusage {
1.955     raeburn  9756:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9757:     $directorypath =~ s/\/$//;
                   9758:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9759:                        .&escape($getpropath).':'.&escape($uname).':'
                   9760:                        .&escape($udom),homeserver($uname,$udom));
                   9761:     if ($listing eq 'unknown_cmd') {
                   9762:         if ($getpropath) {
                   9763:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9764:         }
                   9765:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9766:     }
1.514     albertel 9767:     return $listing;
1.512     banghart 9768: }
                   9769: 
1.566     banghart 9770: sub is_locked {
1.1096    raeburn  9771:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9772:     my @check;
                   9773:     my $is_locked;
1.1093    raeburn  9774:     push (@check,$file_name);
1.613     albertel 9775:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9776: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9777:     my ($tmp)=keys(%locked);
                   9778:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9779:     
1.566     banghart 9780:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9781:         $is_locked = 'false';
                   9782:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9783:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9784:                $is_locked = 'true';
1.1096    raeburn  9785:                if (ref($which) eq 'ARRAY') {
                   9786:                    push(@{$which},$entry);
                   9787:                } else {
                   9788:                    last;
                   9789:                }
1.745     raeburn  9790:            }
                   9791:        }
1.566     banghart 9792:     } else {
                   9793:         $is_locked = 'false';
                   9794:     }
1.1093    raeburn  9795:     return $is_locked;
1.566     banghart 9796: }
                   9797: 
1.759     albertel 9798: sub declutter_portfile {
                   9799:     my ($file) = @_;
1.833     albertel 9800:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9801:     return $file;
                   9802: }
                   9803: 
1.559     banghart 9804: # ------------------------------------------------------------- Mark as Read Only
                   9805: 
                   9806: sub mark_as_readonly {
                   9807:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9808:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9809:     my ($tmp)=keys(%current_permissions);
                   9810:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9811:     foreach my $file (@{$files}) {
1.759     albertel 9812: 	$file = &declutter_portfile($file);
1.561     banghart 9813:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9814:     }
1.613     albertel 9815:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9816:     return;
                   9817: }
                   9818: 
1.572     banghart 9819: # ------------------------------------------------------------Save Selected Files
                   9820: 
                   9821: sub save_selected_files {
                   9822:     my ($user, $path, @files) = @_;
                   9823:     my $filename = $user."savedfiles";
1.573     banghart 9824:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  9825:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 9826:     foreach my $file (@files) {
1.620     albertel 9827:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9828:     }
                   9829:     foreach my $file (@other_files) {
1.574     banghart 9830:         print (OUT $file."\n");
1.572     banghart 9831:     }
1.574     banghart 9832:     close (OUT);
1.572     banghart 9833:     return 'ok';
                   9834: }
                   9835: 
1.574     banghart 9836: sub clear_selected_files {
                   9837:     my ($user) = @_;
                   9838:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  9839:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 9840:     print (OUT undef);
                   9841:     close (OUT);
                   9842:     return ("ok");    
                   9843: }
                   9844: 
1.572     banghart 9845: sub files_in_path {
                   9846:     my ($user, $path) = @_;
                   9847:     my $filename = $user."savedfiles";
                   9848:     my %return_files;
1.1172.2.96  raeburn  9849:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 9850:     while (my $line_in = <IN>) {
1.574     banghart 9851:         chomp ($line_in);
                   9852:         my @paths_and_file = split (m!/!, $line_in);
                   9853:         my $file_part = pop (@paths_and_file);
                   9854:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9855:         $path_part.='/';
                   9856:         my $path_and_file = $path_part.$file_part;
                   9857:         if ($path_part eq $path) {
                   9858:             $return_files{$file_part}= 'selected';
                   9859:         }
                   9860:     }
1.574     banghart 9861:     close (IN);
                   9862:     return (\%return_files);
1.572     banghart 9863: }
                   9864: 
                   9865: # called in portfolio select mode, to show files selected NOT in current directory
                   9866: sub files_not_in_path {
                   9867:     my ($user, $path) = @_;
                   9868:     my $filename = $user."savedfiles";
                   9869:     my @return_files;
                   9870:     my $path_part;
1.1172.2.96  raeburn  9871:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 9872:     while (my $line = <IN>) {
1.572     banghart 9873:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9874:         my @paths_and_file = split(m|/|, $line);
                   9875:         my $file_part = pop(@paths_and_file);
                   9876:         chomp($file_part);
                   9877:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9878:         $path_part .= '/';
                   9879:         my $path_and_file = $path_part.$file_part;
                   9880:         if ($path_part ne $path) {
1.800     albertel 9881:             push(@return_files, ($path_and_file));
1.572     banghart 9882:         }
                   9883:     }
1.800     albertel 9884:     close(OUT);
1.574     banghart 9885:     return (@return_files);
1.572     banghart 9886: }
                   9887: 
1.745     raeburn  9888: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9889: 
1.745     raeburn  9890: sub get_portfile_permissions {
                   9891:     my ($domain,$user) = @_;
1.613     albertel 9892:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9893:     my ($tmp)=keys(%current_permissions);
                   9894:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9895:     return \%current_permissions;
                   9896: }
                   9897: 
                   9898: #---------------------------------------------Get portfolio file access controls
                   9899: 
1.749     raeburn  9900: sub get_access_controls {
1.745     raeburn  9901:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9902:     my %access;
                   9903:     my $real_file = $file;
                   9904:     $file =~ s/\.meta$//;
1.745     raeburn  9905:     if (defined($file)) {
1.749     raeburn  9906:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9907:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9908:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9909:             }
                   9910:         }
1.745     raeburn  9911:     } else {
1.749     raeburn  9912:         foreach my $key (keys(%{$current_permissions})) {
                   9913:             if ($key =~ /\0accesscontrol$/) {
                   9914:                 if (defined($group)) {
                   9915:                     if ($key !~ m-^\Q$group\E/-) {
                   9916:                         next;
                   9917:                     }
                   9918:                 }
                   9919:                 my ($fullpath) = split(/\0/,$key);
                   9920:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9921:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9922:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9923:                     }
                   9924:                 }
                   9925:             }
                   9926:         }
                   9927:     }
                   9928:     return %access;
                   9929: }
                   9930: 
                   9931: sub modify_access_controls {
                   9932:     my ($file_name,$changes,$domain,$user)=@_;
                   9933:     my ($outcome,$deloutcome);
                   9934:     my %store_permissions;
                   9935:     my %new_values;
                   9936:     my %new_control;
                   9937:     my %translation;
                   9938:     my @deletions = ();
                   9939:     my $now = time;
                   9940:     if (exists($$changes{'activate'})) {
                   9941:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9942:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9943:             my $numnew = scalar(@newitems);
                   9944:             for (my $i=0; $i<$numnew; $i++) {
                   9945:                 my $newkey = $newitems[$i];
                   9946:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9947:                 if ($newkey =~ /^\d+:/) { 
                   9948:                     $newkey =~ s/^(\d+)/$newid/;
                   9949:                     $translation{$1} = $newid;
                   9950:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9951:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9952:                     $translation{$1} = $newid;
                   9953:                 }
1.749     raeburn  9954:                 $new_values{$file_name."\0".$newkey} = 
                   9955:                                           $$changes{'activate'}{$newitems[$i]};
                   9956:                 $new_control{$newkey} = $now;
                   9957:             }
                   9958:         }
                   9959:     }
                   9960:     my %todelete;
                   9961:     my %changed_items;
                   9962:     foreach my $action ('delete','update') {
                   9963:         if (exists($$changes{$action})) {
                   9964:             if (ref($$changes{$action}) eq 'HASH') {
                   9965:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9966:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9967:                     if ($action eq 'delete') { 
                   9968:                         $todelete{$itemnum} = 1;
                   9969:                     } else {
                   9970:                         $changed_items{$itemnum} = $key;
                   9971:                     }
                   9972:                 }
1.745     raeburn  9973:             }
                   9974:         }
1.749     raeburn  9975:     }
                   9976:     # get lock on access controls for file.
                   9977:     my $lockhash = {
                   9978:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9979:                                                        ':'.$env{'user.domain'},
                   9980:                    }; 
                   9981:     my $tries = 0;
                   9982:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9983:    
1.1172.2.79  raeburn  9984:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9985:         $tries ++;
1.1172.2.79  raeburn  9986:         sleep(0.1);
1.749     raeburn  9987:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9988:     }
                   9989:     if ($gotlock eq 'ok') {
                   9990:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9991:         my ($tmp)=keys(%curr_permissions);
                   9992:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9993:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9994:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9995:             if (ref($curr_controls) eq 'HASH') {
                   9996:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9997:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9998:                     if (defined($todelete{$itemnum})) {
                   9999:                         push(@deletions,$file_name."\0".$control_item);
                   10000:                     } else {
                   10001:                         if (defined($changed_items{$itemnum})) {
                   10002:                             $new_control{$changed_items{$itemnum}} = $now;
                   10003:                             push(@deletions,$file_name."\0".$control_item);
                   10004:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10005:                         } else {
                   10006:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10007:                         }
                   10008:                     }
1.745     raeburn  10009:                 }
                   10010:             }
                   10011:         }
1.970     raeburn  10012:         my ($group);
                   10013:         if (&is_course($domain,$user)) {
                   10014:             ($group,my $file) = split(/\//,$file_name,2);
                   10015:         }
1.749     raeburn  10016:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10017:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10018:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10019:         #  remove lock
                   10020:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10021:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10022:         my $sqlresult =
1.970     raeburn  10023:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10024:                                     $group);
1.749     raeburn  10025:     } else {
                   10026:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10027:     }
1.749     raeburn  10028:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10029: }
                   10030: 
1.827     raeburn  10031: sub make_public_indefinitely {
                   10032:     my ($requrl) = @_;
                   10033:     my $now = time;
                   10034:     my $action = 'activate';
                   10035:     my $aclnum = 0;
                   10036:     if (&is_portfolio_url($requrl)) {
                   10037:         my (undef,$udom,$unum,$file_name,$group) =
                   10038:             &parse_portfolio_url($requrl);
                   10039:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10040:         my %access_controls = &get_access_controls($current_perms,
                   10041:                                                    $group,$file_name);
                   10042:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10043:             my ($num,$scope,$end,$start) = 
                   10044:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10045:             if ($scope eq 'public') {
                   10046:                 if ($start <= $now && $end == 0) {
                   10047:                     $action = 'none';
                   10048:                 } else {
                   10049:                     $action = 'update';
                   10050:                     $aclnum = $num;
                   10051:                 }
                   10052:                 last;
                   10053:             }
                   10054:         }
                   10055:         if ($action eq 'none') {
                   10056:              return 'ok';
                   10057:         } else {
                   10058:             my %changes;
                   10059:             my $newend = 0;
                   10060:             my $newstart = $now;
                   10061:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10062:             $changes{$action}{$newkey} = {
                   10063:                 type => 'public',
                   10064:                 time => {
                   10065:                     start => $newstart,
                   10066:                     end   => $newend,
                   10067:                 },
                   10068:             };
                   10069:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10070:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10071:             return $outcome;
                   10072:         }
                   10073:     } else {
                   10074:         return 'invalid';
                   10075:     }
                   10076: }
                   10077: 
1.745     raeburn  10078: #------------------------------------------------------Get Marked as Read Only
                   10079: 
                   10080: sub get_marked_as_readonly {
                   10081:     my ($domain,$user,$what,$group) = @_;
                   10082:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10083:     my @readonly_files;
1.629     banghart 10084:     my $cmp1=$what;
                   10085:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10086:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10087:         if (defined($group)) {
                   10088:             if ($file_name !~ m-^\Q$group\E/-) {
                   10089:                 next;
                   10090:             }
                   10091:         }
1.561     banghart 10092:         if (ref($value) eq "ARRAY"){
                   10093:             foreach my $stored_what (@{$value}) {
1.629     banghart 10094:                 my $cmp2=$stored_what;
1.759     albertel 10095:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10096:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10097:                 }
1.629     banghart 10098:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10099:                     push(@readonly_files, $file_name);
1.745     raeburn  10100:                     last;
1.563     banghart 10101:                 } elsif (!defined($what)) {
                   10102:                     push(@readonly_files, $file_name);
1.745     raeburn  10103:                     last;
1.561     banghart 10104:                 }
                   10105:             }
1.745     raeburn  10106:         }
1.561     banghart 10107:     }
                   10108:     return @readonly_files;
                   10109: }
1.577     banghart 10110: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10111: 
1.577     banghart 10112: sub get_marked_as_readonly_hash {
1.745     raeburn  10113:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10114:     my %readonly_files;
1.745     raeburn  10115:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10116:         if (defined($group)) {
                   10117:             if ($file_name !~ m-^\Q$group\E/-) {
                   10118:                 next;
                   10119:             }
                   10120:         }
1.577     banghart 10121:         if (ref($value) eq "ARRAY"){
                   10122:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10123:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10124:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10125:                         if ($lock_descriptor eq 'graded') {
                   10126:                             $readonly_files{$file_name} = 'graded';
                   10127:                         } elsif ($lock_descriptor eq 'handback') {
                   10128:                             $readonly_files{$file_name} = 'handback';
                   10129:                         } else {
                   10130:                             if (!exists($readonly_files{$file_name})) {
                   10131:                                 $readonly_files{$file_name} = 'locked';
                   10132:                             }
                   10133:                         }
1.745     raeburn  10134:                     }
1.750     banghart 10135:                 } 
1.577     banghart 10136:             }
                   10137:         } 
                   10138:     }
                   10139:     return %readonly_files;
                   10140: }
1.559     banghart 10141: # ------------------------------------------------------------ Unmark as Read Only
                   10142: 
                   10143: sub unmark_as_readonly {
1.629     banghart 10144:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10145:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10146:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10147:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10148:     my $symb_crs = $what;
                   10149:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10150:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10151:     my ($tmp)=keys(%current_permissions);
                   10152:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10153:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10154:     foreach my $file (@readonly_files) {
1.759     albertel 10155: 	my $clean_file = &declutter_portfile($file);
                   10156: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10157: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10158:         my @new_locks;
                   10159:         my @del_keys;
                   10160:         if (ref($current_locks) eq "ARRAY"){
                   10161:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10162:                 my $compare=$locker;
1.749     raeburn  10163:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10164:                     $compare=join('',@{$locker});
1.746     raeburn  10165:                     if ($compare ne $symb_crs) {
                   10166:                         push(@new_locks, $locker);
                   10167:                     }
1.563     banghart 10168:                 }
                   10169:             }
1.650     albertel 10170:             if (scalar(@new_locks) > 0) {
1.563     banghart 10171:                 $current_permissions{$file} = \@new_locks;
                   10172:             } else {
                   10173:                 push(@del_keys, $file);
1.613     albertel 10174:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10175:                 delete($current_permissions{$file});
1.563     banghart 10176:             }
                   10177:         }
1.561     banghart 10178:     }
1.613     albertel 10179:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10180:     return;
                   10181: }
1.512     banghart 10182: 
1.17      www      10183: # ------------------------------------------------------------ Directory lister
                   10184: 
                   10185: sub dirlist {
1.955     raeburn  10186:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10187:     $uri=~s/^\///;
                   10188:     $uri=~s/\/$//;
1.253     stredwic 10189:     my ($udom, $uname);
1.955     raeburn  10190:     if ($getuserdir) {
1.253     stredwic 10191:         $udom = $userdomain;
                   10192:         $uname = $username;
1.955     raeburn  10193:     } else {
                   10194:         (undef,$udom,$uname)=split(/\//,$uri);
                   10195:         if(defined($userdomain)) {
                   10196:             $udom = $userdomain;
                   10197:         }
                   10198:         if(defined($username)) {
                   10199:             $uname = $username;
                   10200:         }
1.253     stredwic 10201:     }
1.955     raeburn  10202:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10203: 
1.955     raeburn  10204:     $dirRoot = $perlvar{'lonDocRoot'};
                   10205:     if (defined($getpropath)) {
                   10206:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10207:         $dirRoot =~ s/\/$//;
1.955     raeburn  10208:     } elsif (defined($getuserdir)) {
                   10209:         my $subdir=$uname.'__';
                   10210:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10211:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10212:                    ."/$udom/$subdir/$uname";
                   10213:     } elsif (defined($alternateRoot)) {
                   10214:         $dirRoot = $alternateRoot;
1.751     banghart 10215:     }
1.253     stredwic 10216: 
                   10217:     if($udom) {
                   10218:         if($uname) {
1.1135    raeburn  10219:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10220:             if ($uhome eq 'no_host') {
                   10221:                 return ([],'no_host');
                   10222:             }
1.955     raeburn  10223:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10224:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10225:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10226:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10227:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10228:             } else {
                   10229:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10230:             }
1.605     matthew  10231:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10232:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10233:                 @listing_results = split(/:/,$listing);
                   10234:             } else {
                   10235:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10236:             }
1.1135    raeburn  10237:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10238:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10239:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10240:                 return ([],$listing);
                   10241:             } else {
                   10242:                 return (\@listing_results);
1.1135    raeburn  10243:             }
1.955     raeburn  10244:         } elsif(!$alternateRoot) {
1.1136    raeburn  10245:             my (%allusers,%listerror);
1.841     albertel 10246: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10247:  	    foreach my $tryserver (keys(%servers)) {
                   10248:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10249:                                   &escape($udom),$tryserver);
                   10250:                 if ($listing eq 'unknown_cmd') {
                   10251: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10252: 				      $udom, $tryserver);
                   10253:                 } else {
                   10254:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10255:                 }
1.841     albertel 10256: 		if ($listing eq 'unknown_cmd') {
                   10257: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10258: 				      $udom, $tryserver);
                   10259: 		    @listing_results = split(/:/,$listing);
                   10260: 		} else {
                   10261: 		    @listing_results =
                   10262: 			map { &unescape($_); } split(/:/,$listing);
                   10263: 		}
1.1136    raeburn  10264:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10265:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10266:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10267:                     $listerror{$tryserver} = $listing;
                   10268:                 } else {
1.841     albertel 10269: 		    foreach my $line (@listing_results) {
                   10270: 			my ($entry) = split(/&/,$line,2);
                   10271: 			$allusers{$entry} = 1;
                   10272: 		    }
                   10273: 		}
1.253     stredwic 10274:             }
1.1136    raeburn  10275:             my @alluserslist=();
1.800     albertel 10276:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10277:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10278:             }
1.1172.2.80  raeburn  10279:             if (!%listerror) {
                   10280:                 # no errors
                   10281:                 return (\@alluserslist);
                   10282:             } elsif (scalar(keys(%servers)) == 1) {
                   10283:                 # one library server, one error
                   10284:                 my ($key) = keys(%listerror);
                   10285:                 return (\@alluserslist, $listerror{$key});
                   10286:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10287:                 # con_lost indicates that we might miss data from at least one
                   10288:                 # library server
                   10289:                 return (\@alluserslist, 'con_lost');
                   10290:             } else {
                   10291:                 # multiple library servers and no con_lost -> data should be
                   10292:                 # complete.
                   10293:                 return (\@alluserslist);
                   10294:             }
                   10295: 
1.253     stredwic 10296:         } else {
1.1136    raeburn  10297:             return ([],'missing username');
1.253     stredwic 10298:         }
1.955     raeburn  10299:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10300:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10301:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10302:         return (\@all_domains);
1.955     raeburn  10303:     } else {
1.1136    raeburn  10304:         return ([],'missing domain');
1.275     stredwic 10305:     }
                   10306: }
                   10307: 
                   10308: # --------------------------------------------- GetFileTimestamp
                   10309: # This function utilizes dirlist and returns the date stamp for
                   10310: # when it was last modified.  It will also return an error of -1
                   10311: # if an error occurs
                   10312: 
                   10313: sub GetFileTimestamp {
1.955     raeburn  10314:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10315:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10316:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10317:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10318:                                     undef,$getuserdir);
                   10319:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10320:         return -1;
                   10321:     }
                   10322:     if (ref($fileref) eq 'ARRAY') {
                   10323:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10324:         # @stats contains first the filename, then the stat output
                   10325:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10326:     } else {
                   10327:         return -1;
1.253     stredwic 10328:     }
1.26      www      10329: }
                   10330: 
1.712     albertel 10331: sub stat_file {
                   10332:     my ($uri) = @_;
1.787     albertel 10333:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10334: 
1.955     raeburn  10335:     my ($udom,$uname,$file);
1.712     albertel 10336:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10337: 	($udom,$uname,$file) =
1.811     albertel 10338: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10339: 	$file = 'userfiles/'.$file;
                   10340:     }
                   10341:     if ($uri =~ m-^/res/-) {
                   10342: 	($udom,$uname) = 
1.807     albertel 10343: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10344: 	$file = $uri;
                   10345:     }
                   10346: 
                   10347:     if (!$udom || !$uname || !$file) {
                   10348: 	# unable to handle the uri
                   10349: 	return ();
                   10350:     }
1.956     raeburn  10351:     my $getpropath;
                   10352:     if ($file =~ /^userfiles\//) {
                   10353:         $getpropath = 1;
                   10354:     }
1.1136    raeburn  10355:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10356:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10357:         return ();
                   10358:     } else {
                   10359:         if (ref($listref) eq 'ARRAY') {
                   10360:             my @stats = split('&',$listref->[0]);
                   10361: 	    shift(@stats); #filename is first
                   10362: 	    return @stats;
                   10363:         }
1.712     albertel 10364:     }
                   10365:     return ();
                   10366: }
                   10367: 
1.26      www      10368: # -------------------------------------------------------- Value of a Condition
                   10369: 
1.713     albertel 10370: # gets the value of a specific preevaluated condition
                   10371: #    stored in the string  $env{user.state.<cid>}
                   10372: # or looks up a condition reference in the bighash and if if hasn't
                   10373: # already been evaluated recurses into docondval to get the value of
                   10374: # the condition, then memoizing it to 
                   10375: #   $env{user.state.<cid>.<condition>}
1.40      www      10376: sub directcondval {
                   10377:     my $number=shift;
1.620     albertel 10378:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10379: 	&Apache::lonuserstate::evalstate();
                   10380:     }
1.713     albertel 10381:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10382: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10383:     } elsif ($number =~ /^_/) {
                   10384: 	my $sub_condition;
                   10385: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10386: 		&GDBM_READER(),0640)) {
                   10387: 	    $sub_condition=$bighash{'conditions'.$number};
                   10388: 	    untie(%bighash);
                   10389: 	}
                   10390: 	my $value = &docondval($sub_condition);
1.949     raeburn  10391: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10392: 	return $value;
                   10393:     }
1.620     albertel 10394:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10395:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10396:     } else {
                   10397:        return 2;
                   10398:     }
                   10399: }
                   10400: 
1.713     albertel 10401: # get the collection of conditions for this resource
1.26      www      10402: sub condval {
                   10403:     my $condidx=shift;
1.54      www      10404:     my $allpathcond='';
1.713     albertel 10405:     foreach my $cond (split(/\|/,$condidx)) {
                   10406: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10407: 	    $allpathcond.=
                   10408: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10409: 	}
1.191     harris41 10410:     }
1.54      www      10411:     $allpathcond=~s/\|$//;
1.713     albertel 10412:     return &docondval($allpathcond);
                   10413: }
                   10414: 
                   10415: #evaluates an expression of conditions
                   10416: sub docondval {
                   10417:     my ($allpathcond) = @_;
                   10418:     my $result=0;
                   10419:     if ($env{'request.course.id'}
                   10420: 	&& defined($allpathcond)) {
                   10421: 	my $operand='|';
                   10422: 	my @stack;
                   10423: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10424: 	    if ($chunk eq '(') {
                   10425: 		push @stack,($operand,$result);
                   10426: 	    } elsif ($chunk eq ')') {
                   10427: 		my $before=pop @stack;
                   10428: 		if (pop @stack eq '&') {
                   10429: 		    $result=$result>$before?$before:$result;
                   10430: 		} else {
                   10431: 		    $result=$result>$before?$result:$before;
                   10432: 		}
                   10433: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10434: 		$operand=$chunk;
                   10435: 	    } else {
                   10436: 		my $new=directcondval($chunk);
                   10437: 		if ($operand eq '&') {
                   10438: 		    $result=$result>$new?$new:$result;
                   10439: 		} else {
                   10440: 		    $result=$result>$new?$result:$new;
                   10441: 		}
                   10442: 	    }
                   10443: 	}
1.26      www      10444:     }
                   10445:     return $result;
1.421     albertel 10446: }
                   10447: 
                   10448: # ---------------------------------------------------- Devalidate courseresdata
                   10449: 
                   10450: sub devalidatecourseresdata {
                   10451:     my ($coursenum,$coursedomain)=@_;
                   10452:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10453:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10454: }
                   10455: 
1.763     www      10456: 
1.200     www      10457: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10458: #
                   10459: #  Parameters:
                   10460: #      $coursenum    - Number of the course.
                   10461: #      $coursedomain - Domain at which the course was created.
                   10462: #  Returns:
                   10463: #     A hash of the course parameters along (I think) with timestamps
                   10464: #     and version info.
1.877     foxr     10465: 
1.624     albertel 10466: sub get_courseresdata {
                   10467:     my ($coursenum,$coursedomain)=@_;
1.200     www      10468:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10469:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10470:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10471:     my %dumpreply;
1.417     albertel 10472:     unless (defined($cached)) {
1.624     albertel 10473: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10474: 	$result=\%dumpreply;
1.251     albertel 10475: 	my ($tmp) = keys(%dumpreply);
                   10476: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10477: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10478: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10479: 	    return $tmp;
1.416     albertel 10480: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10481: 	    $result=undef;
1.599     albertel 10482: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10483: 	}
                   10484:     }
1.624     albertel 10485:     return $result;
                   10486: }
                   10487: 
1.633     albertel 10488: sub devalidateuserresdata {
                   10489:     my ($uname,$udom)=@_;
                   10490:     my $hashid="$udom:$uname";
                   10491:     &devalidate_cache_new('userres',$hashid);
                   10492: }
                   10493: 
1.624     albertel 10494: sub get_userresdata {
                   10495:     my ($uname,$udom)=@_;
                   10496:     #most student don\'t have any data set, check if there is some data
                   10497:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10498: 
                   10499:     my $hashid="$udom:$uname";
                   10500:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10501:     if (!defined($cached)) {
                   10502: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10503: 	$result=\%resourcedata;
                   10504: 	&do_cache_new('userres',$hashid,$result,600);
                   10505:     }
                   10506:     my ($tmp)=keys(%$result);
                   10507:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10508: 	return $result;
                   10509:     }
                   10510:     #error 2 occurs when the .db doesn't exist
                   10511:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10512:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10513: 	    &logthis("<font color=\"blue\">WARNING:".
                   10514: 		     " Trying to get resource data for ".
                   10515: 		     $uname." at ".$udom.": ".
                   10516: 		     $tmp."</font>");
                   10517:         }
1.624     albertel 10518:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10519: 	#&EXT_cache_set($udom,$uname);
                   10520: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10521: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10522:     }
                   10523:     return $tmp;
                   10524: }
1.879     foxr     10525: #----------------------------------------------- resdata - return resource data
                   10526: #  Purpose:
                   10527: #    Return resource data for either users or for a course.
                   10528: #  Parameters:
                   10529: #     $name      - Course/user name.
                   10530: #     $domain    - Name of the domain the user/course is registered on.
                   10531: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10532: #     @which     - Array of names of resources desired.
                   10533: #  Returns:
                   10534: #     The value of the first reasource in @which that is found in the
                   10535: #     resource hash.
                   10536: #  Exceptional Conditions:
                   10537: #     If the $type passed in is not valid (not the string 'course' or 
                   10538: #     'user', an undefined  reference is returned.
                   10539: #     If none of the resources are found, an undef is returned
1.624     albertel 10540: sub resdata {
                   10541:     my ($name,$domain,$type,@which)=@_;
                   10542:     my $result;
                   10543:     if ($type eq 'course') {
                   10544: 	$result=&get_courseresdata($name,$domain);
                   10545:     } elsif ($type eq 'user') {
                   10546: 	$result=&get_userresdata($name,$domain);
                   10547:     }
                   10548:     if (!ref($result)) { return $result; }    
1.251     albertel 10549:     foreach my $item (@which) {
1.927     albertel 10550: 	if (defined($result->{$item->[0]})) {
                   10551: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10552: 	}
1.250     albertel 10553:     }
1.291     albertel 10554:     return undef;
1.200     www      10555: }
                   10556: 
1.1172.2.31  raeburn  10557: sub get_numsuppfiles {
                   10558:     my ($cnum,$cdom,$ignorecache)=@_;
                   10559:     my $hashid=$cnum.':'.$cdom;
                   10560:     my ($suppcount,$cached);
                   10561:     unless ($ignorecache) {
                   10562:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10563:     }
                   10564:     unless (defined($cached)) {
                   10565:         my $chome=&homeserver($cnum,$cdom);
                   10566:         unless ($chome eq 'no_host') {
                   10567:             ($suppcount,my $errors) = (0,0);
                   10568:             my $suppmap = 'supplemental.sequence';
                   10569:             ($suppcount,$errors) =
                   10570:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10571:         }
                   10572:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10573:     }
                   10574:     return $suppcount;
                   10575: }
                   10576: 
1.379     matthew  10577: #
                   10578: # EXT resource caching routines
                   10579: #
                   10580: 
                   10581: sub clear_EXT_cache_status {
1.383     albertel 10582:     &delenv('cache.EXT.');
1.379     matthew  10583: }
                   10584: 
                   10585: sub EXT_cache_status {
                   10586:     my ($target_domain,$target_user) = @_;
1.383     albertel 10587:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10588:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10589:         # We know already the user has no data
                   10590:         return 1;
                   10591:     } else {
                   10592:         return 0;
                   10593:     }
                   10594: }
                   10595: 
                   10596: sub EXT_cache_set {
                   10597:     my ($target_domain,$target_user) = @_;
1.383     albertel 10598:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10599:     #&appenv({$cachename => time});
1.379     matthew  10600: }
                   10601: 
1.28      www      10602: # --------------------------------------------------------- Value of a Variable
1.58      www      10603: sub EXT {
1.715     albertel 10604: 
1.1172.2.28  raeburn  10605:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10606:     unless ($varname) { return ''; }
1.218     albertel 10607:     #get real user name/domain, courseid and symb
                   10608:     my $courseid;
1.359     albertel 10609:     my $publicuser;
1.427     www      10610:     if ($symbparm) {
                   10611: 	$symbparm=&get_symb_from_alias($symbparm);
                   10612:     }
1.218     albertel 10613:     if (!($uname && $udom)) {
1.790     albertel 10614:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10615:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10616:     } else {
1.620     albertel 10617: 	$courseid=$env{'request.course.id'};
1.218     albertel 10618:     }
1.48      www      10619:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10620:     my $rest;
1.320     albertel 10621:     if (defined($therest[0])) {
1.48      www      10622:        $rest=join('.',@therest);
                   10623:     } else {
                   10624:        $rest='';
                   10625:     }
1.320     albertel 10626: 
1.57      www      10627:     my $qualifierrest=$qualifier;
                   10628:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10629:     my $spacequalifierrest=$space;
                   10630:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10631:     if ($realm eq 'user') {
1.48      www      10632: # --------------------------------------------------------------- user.resource
                   10633: 	if ($space eq 'resource') {
1.651     albertel 10634: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10635: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10636: 		 &&
1.744     albertel 10637: 		 ($symbparm eq &symbread()) ) {	
                   10638: 		# if we are in the middle of processing the resource the
                   10639: 		# get the value we are planning on committing
                   10640:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10641:                     return $Apache::lonhomework::results{$qualifierrest};
                   10642:                 } else {
                   10643:                     return $Apache::lonhomework::history{$qualifierrest};
                   10644:                 }
1.335     albertel 10645: 	    } else {
1.359     albertel 10646: 		my %restored;
1.620     albertel 10647: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10648: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10649: 		} else {
                   10650: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10651: 		}
1.335     albertel 10652: 		return $restored{$qualifierrest};
                   10653: 	    }
1.48      www      10654: # ----------------------------------------------------------------- user.access
                   10655:         } elsif ($space eq 'access') {
1.218     albertel 10656: 	    # FIXME - not supporting calls for a specific user
1.48      www      10657:             return &allowed($qualifier,$rest);
                   10658: # ------------------------------------------ user.preferences, user.environment
                   10659:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10660: 	    if (($uname eq $env{'user.name'}) &&
                   10661: 		($udom eq $env{'user.domain'})) {
                   10662: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10663: 	    } else {
1.359     albertel 10664: 		my %returnhash;
                   10665: 		if (!$publicuser) {
                   10666: 		    %returnhash=&userenvironment($udom,$uname,
                   10667: 						 $qualifierrest);
                   10668: 		}
1.218     albertel 10669: 		return $returnhash{$qualifierrest};
                   10670: 	    }
1.48      www      10671: # ----------------------------------------------------------------- user.course
                   10672:         } elsif ($space eq 'course') {
1.218     albertel 10673: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10674:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10675: # ------------------------------------------------------------------- user.role
                   10676:         } elsif ($space eq 'role') {
1.218     albertel 10677: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10678:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10679:             if ($qualifier eq 'value') {
                   10680: 		return $role;
                   10681:             } elsif ($qualifier eq 'extent') {
                   10682:                 return $where;
                   10683:             }
                   10684: # ----------------------------------------------------------------- user.domain
                   10685:         } elsif ($space eq 'domain') {
1.218     albertel 10686:             return $udom;
1.48      www      10687: # ------------------------------------------------------------------- user.name
                   10688:         } elsif ($space eq 'name') {
1.218     albertel 10689:             return $uname;
1.48      www      10690: # ---------------------------------------------------- Any other user namespace
1.29      www      10691:         } else {
1.359     albertel 10692: 	    my %reply;
                   10693: 	    if (!$publicuser) {
                   10694: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10695: 	    }
                   10696: 	    return $reply{$qualifierrest};
1.48      www      10697:         }
1.236     www      10698:     } elsif ($realm eq 'query') {
                   10699: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10700:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10701: 						[$spacequalifierrest]);
1.620     albertel 10702: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10703:    } elsif ($realm eq 'request') {
1.48      www      10704: # ------------------------------------------------------------- request.browser
                   10705:         if ($space eq 'browser') {
1.1145    bisitz   10706:             return $env{'browser.'.$qualifier};
1.57      www      10707: # ------------------------------------------------------------ request.filename
                   10708:         } else {
1.620     albertel 10709:             return $env{'request.'.$spacequalifierrest};
1.29      www      10710:         }
1.28      www      10711:     } elsif ($realm eq 'course') {
1.48      www      10712: # ---------------------------------------------------------- course.description
1.620     albertel 10713:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10714:     } elsif ($realm eq 'resource') {
1.165     www      10715: 
1.620     albertel 10716: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10717: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10718: 	}
1.693     albertel 10719: 
1.1172.2.30  raeburn  10720:         if ($qualifier eq '') {
                   10721: 	    if ($space eq 'title') {
                   10722: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10723: 	        return &gettitle($symbparm);
                   10724: 	    }
1.693     albertel 10725: 	
1.1172.2.30  raeburn  10726: 	    if ($space eq 'map') {
                   10727: 	        my ($map) = &decode_symb($symbparm);
                   10728: 	        return &symbread($map);
                   10729: 	    }
                   10730:             if ($space eq 'maptitle') {
                   10731:                 my ($map) = &decode_symb($symbparm);
                   10732:                 return &gettitle($map);
                   10733:             }
                   10734: 	    if ($space eq 'filename') {
                   10735: 	        if ($symbparm) {
                   10736: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10737: 	        }
                   10738: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10739: 	    }
1.1172.2.30  raeburn  10740: 
                   10741:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10742:                 if ($space eq 'visibleparts') {
                   10743:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10744:                     my $item;
                   10745:                     if (ref($navmap)) {
                   10746:                         my $res = $navmap->getBySymb($symbparm);
                   10747:                         my $parts = $res->parts();
                   10748:                         if (ref($parts) eq 'ARRAY') {
                   10749:                             $item = join(',',@{$parts});
                   10750:                         }
                   10751:                         undef($navmap);
                   10752:                     }
                   10753:                     return $item;
                   10754:                 }
                   10755:             }
                   10756:         }
1.693     albertel 10757: 
                   10758: 	my ($section, $group, @groups);
1.593     albertel 10759: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10760:         if (($courseid eq '') && ($cid)) {
                   10761:             $courseid = $cid;
                   10762:         }
                   10763: 	if (($symbparm && $courseid) && 
                   10764: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10765: 
1.218     albertel 10766: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10767: 
1.60      www      10768: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10769: 	    my $symbp=$symbparm;
1.735     albertel 10770: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10771: 
                   10772: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10773: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10774: 
1.620     albertel 10775: 	    if (($env{'user.name'} eq $uname) &&
                   10776: 		($env{'user.domain'} eq $udom)) {
                   10777: 		$section=$env{'request.course.sec'};
1.733     raeburn  10778:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10779:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10780: 	    } else {
1.539     albertel 10781: 		if (! defined($usection)) {
1.551     albertel 10782: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10783: 		} else {
                   10784: 		    $section = $usection;
                   10785: 		}
1.733     raeburn  10786:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10787: 	    }
                   10788: 
                   10789: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10790: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10791: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10792: 
1.593     albertel 10793: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10794: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10795: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10796: 
1.60      www      10797: # ----------------------------------------------------------- first, check user
1.624     albertel 10798: 
                   10799: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10800: 				       ([$courselevelr,'resource'],
                   10801: 					[$courselevelm,'map'     ],
                   10802: 					[$courselevel, 'course'  ]));
1.931     albertel 10803: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10804: 
1.594     albertel 10805: # ------------------------------------------------ second, check some of course
1.684     raeburn  10806:             my $coursereply;
1.691     raeburn  10807:             if (@groups > 0) {
                   10808:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10809:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10810:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10811:             }
1.96      www      10812: 
1.684     raeburn  10813: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10814: 				  $env{'course.'.$courseid.'.domain'},
                   10815: 				  'course',
                   10816: 				  ([$seclevelr,   'resource'],
                   10817: 				   [$seclevelm,   'map'     ],
                   10818: 				   [$seclevel,    'course'  ],
                   10819: 				   [$courselevelr,'resource']));
                   10820: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10821: 
1.60      www      10822: # ------------------------------------------------------ third, check map parms
1.218     albertel 10823: 	    my %parmhash=();
                   10824: 	    my $thisparm='';
                   10825: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10826: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10827: 		    &GDBM_READER(),0640)) {
1.218     albertel 10828: 		$thisparm=$parmhash{$symbparm};
                   10829: 		untie(%parmhash);
                   10830: 	    }
1.927     albertel 10831: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10832: 	}
1.594     albertel 10833: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10834: 
1.218     albertel 10835: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10836: 	my $filename;
                   10837: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10838: 	if ($symbparm) {
1.409     www      10839: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10840: 	} else {
1.620     albertel 10841: 	    $filename=$env{'request.filename'};
1.282     albertel 10842: 	}
                   10843: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10844: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10845: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10846: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10847: 
1.927     albertel 10848: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10849: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10850: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10851: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10852: 				     $env{'course.'.$courseid.'.domain'},
                   10853: 				     'course',
1.927     albertel 10854: 				     ([$courselevelm,'map'   ],
                   10855: 				      [$courselevel, 'course']));
                   10856: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10857: 	}
1.145     www      10858: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10859: 	unless ($space eq '0') {
1.336     albertel 10860: 	    my @parts=split(/_/,$space);
                   10861: 	    my $id=pop(@parts);
                   10862: 	    my $part=join('_',@parts);
                   10863: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10864: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10865: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10866: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10867: 	}
1.395     albertel 10868: 	if ($recurse) { return undef; }
                   10869: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10870: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10871: # ---------------------------------------------------- Any other user namespace
                   10872:     } elsif ($realm eq 'environment') {
                   10873: # ----------------------------------------------------------------- environment
1.620     albertel 10874: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10875: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10876: 	} else {
1.770     albertel 10877: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10878: 		return '';
                   10879: 	    }
1.219     albertel 10880: 	    my %returnhash=&userenvironment($udom,$uname,
                   10881: 					    $spacequalifierrest);
                   10882: 	    return $returnhash{$spacequalifierrest};
                   10883: 	}
1.28      www      10884:     } elsif ($realm eq 'system') {
1.48      www      10885: # ----------------------------------------------------------------- system.time
                   10886: 	if ($space eq 'time') {
                   10887: 	    return time;
                   10888:         }
1.696     albertel 10889:     } elsif ($realm eq 'server') {
                   10890: # ----------------------------------------------------------------- system.time
                   10891: 	if ($space eq 'name') {
                   10892: 	    return $ENV{'SERVER_NAME'};
                   10893:         }
1.28      www      10894:     }
1.48      www      10895:     return '';
1.61      www      10896: }
                   10897: 
1.927     albertel 10898: sub get_reply {
                   10899:     my ($reply_value) = @_;
1.940     raeburn  10900:     if (ref($reply_value) eq 'ARRAY') {
                   10901:         if (wantarray) {
                   10902: 	    return @$reply_value;
                   10903:         }
                   10904:         return $reply_value->[0];
                   10905:     } else {
                   10906:         return $reply_value;
1.927     albertel 10907:     }
                   10908: }
                   10909: 
1.691     raeburn  10910: sub check_group_parms {
                   10911:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10912:     my @groupitems = ();
                   10913:     my $resultitem;
1.927     albertel 10914:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10915:     foreach my $group (@{$groups}) {
                   10916:         foreach my $level (@levels) {
1.927     albertel 10917:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10918:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10919:         }
                   10920:     }
                   10921:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10922:                             $env{'course.'.$courseid.'.domain'},
                   10923:                                      'course',@groupitems);
                   10924:     return $coursereply;
                   10925: }
                   10926: 
                   10927: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10928:     my ($courseid,@groups) = @_;
                   10929:     @groups = sort(@groups);
1.691     raeburn  10930:     return @groups;
                   10931: }
                   10932: 
1.395     albertel 10933: sub packages_tab_default {
                   10934:     my ($uri,$varname)=@_;
                   10935:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10936: 
                   10937:     my (@extension,@specifics,$do_default);
                   10938:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10939: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10940: 	if ($pack_type eq 'default') {
                   10941: 	    $do_default=1;
                   10942: 	} elsif ($pack_type eq 'extension') {
                   10943: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10944: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10945: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10946: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10947: 	}
                   10948:     }
                   10949:     # first look for a package that matches the requested part id
                   10950:     foreach my $package (@specifics) {
                   10951: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10952: 	next if ($pack_part ne $part);
                   10953: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10954: 	    return $packagetab{"$pack_type&$name&default"};
                   10955: 	}
                   10956:     }
                   10957:     # look for any possible matching non extension_ package
                   10958:     foreach my $package (@specifics) {
                   10959: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10960: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10961: 	    return $packagetab{"$pack_type&$name&default"};
                   10962: 	}
1.585     albertel 10963: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10964: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10965: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10966: 	}
                   10967:     }
1.738     albertel 10968:     # look for any posible extension_ match
                   10969:     foreach my $package (@extension) {
                   10970: 	my ($package,$pack_type)=@{$package};
                   10971: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10972: 	    return $packagetab{"$pack_type&$name&default"};
                   10973: 	}
                   10974: 	if (defined($packagetab{$package."&$name&default"})) {
                   10975: 	    return $packagetab{$package."&$name&default"};
                   10976: 	}
                   10977:     }
                   10978:     # look for a global default setting
                   10979:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10980: 	return $packagetab{"default&$name&default"};
                   10981:     }
1.395     albertel 10982:     return undef;
                   10983: }
                   10984: 
1.334     albertel 10985: sub add_prefix_and_part {
                   10986:     my ($prefix,$part)=@_;
                   10987:     my $keyroot;
                   10988:     if (defined($prefix) && $prefix !~ /^__/) {
                   10989: 	# prefix that has a part already
                   10990: 	$keyroot=$prefix;
                   10991:     } elsif (defined($prefix)) {
                   10992: 	# prefix that is missing a part
                   10993: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10994:     } else {
                   10995: 	# no prefix at all
                   10996: 	if (defined($part)) { $keyroot='_'.$part; }
                   10997:     }
                   10998:     return $keyroot;
                   10999: }
                   11000: 
1.71      www      11001: # ---------------------------------------------------------------- Get metadata
                   11002: 
1.599     albertel 11003: my %metaentry;
1.1070    www      11004: my %importedpartids;
1.71      www      11005: sub metadata {
1.176     www      11006:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11007:     $uri=&declutter($uri);
1.288     albertel 11008:     # if it is a non metadata possible uri return quickly
1.529     albertel 11009:     if (($uri eq '') || 
                   11010: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11011: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11012:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11013: 	return undef;
                   11014:     }
1.1172.2.49  raeburn  11015:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11016: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11017: 	return undef;
1.288     albertel 11018:     }
1.73      www      11019:     my $filename=$uri;
                   11020:     $uri=~s/\.meta$//;
1.172     www      11021: #
                   11022: # Is the metadata already cached?
1.177     www      11023: # Look at timestamp of caching
1.172     www      11024: # Everything is cached by the main uri, libraries are never directly cached
                   11025: #
1.428     albertel 11026:     if (!defined($liburi)) {
1.599     albertel 11027: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11028: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11029:     }
                   11030:     {
1.1069    www      11031: # Imported parts would go here
1.1070    www      11032:         my %importedids=();
                   11033:         my @origfileimportpartids=();
1.1069    www      11034:         my $importedparts=0;
1.172     www      11035: #
                   11036: # Is this a recursive call for a library?
                   11037: #
1.599     albertel 11038: #	if (! exists($metacache{$uri})) {
                   11039: #	    $metacache{$uri}={};
                   11040: #	}
1.924     albertel 11041: 	my $cachetime = 60*60;
1.171     www      11042:         if ($liburi) {
                   11043: 	    $liburi=&declutter($liburi);
                   11044:             $filename=$liburi;
1.401     bowersj2 11045:         } else {
1.599     albertel 11046: 	    &devalidate_cache_new('meta',$uri);
                   11047: 	    undef(%metaentry);
1.401     bowersj2 11048: 	}
1.140     www      11049:         my %metathesekeys=();
1.73      www      11050:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11051: 	my $metastring;
1.1140    www      11052: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11053: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11054: 	    $metastring = 
1.929     albertel 11055: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11056: 					  ('grade_target' => 'meta'));
                   11057: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11058: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11059:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11060: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11061: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11062: 	    $metastring=&getfile($file);
1.489     albertel 11063: 	}
1.208     albertel 11064:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11065:         my $token;
1.140     www      11066:         undef %metathesekeys;
1.71      www      11067:         while ($token=$parser->get_token) {
1.339     albertel 11068: 	    if ($token->[0] eq 'S') {
                   11069: 		if (defined($token->[2]->{'package'})) {
1.172     www      11070: #
                   11071: # This is a package - get package info
                   11072: #
1.339     albertel 11073: 		    my $package=$token->[2]->{'package'};
                   11074: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11075: 		    if (defined($token->[2]->{'id'})) { 
                   11076: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11077: 		    }
1.599     albertel 11078: 		    if ($metaentry{':packages'}) {
                   11079: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11080: 		    } else {
1.599     albertel 11081: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11082: 		    }
1.736     albertel 11083: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11084: 			my $part=$keyroot;
                   11085: 			$part=~s/^\_//;
1.736     albertel 11086: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11087: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11088: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11089: 			    # ignore package.tab specified default values
                   11090:                             # here &package_tab_default() will fetch those
                   11091: 			    if ($subp eq 'default') { next; }
1.736     albertel 11092: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11093: 			    my $unikey;
                   11094: 			    if ($pack =~ /_0$/) {
                   11095: 				$unikey='parameter_0_'.$name;
                   11096: 				$part=0;
                   11097: 			    } else {
                   11098: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11099: 			    }
1.339     albertel 11100: 			    if ($subp eq 'display') {
                   11101: 				$value.=' [Part: '.$part.']';
                   11102: 			    }
1.599     albertel 11103: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11104: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11105: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11106: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11107: 			    }
1.599     albertel 11108: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11109: 				$metaentry{':'.$unikey}=
                   11110: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11111: 			    }
1.339     albertel 11112: 			}
                   11113: 		    }
                   11114: 		} else {
1.172     www      11115: #
                   11116: # This is not a package - some other kind of start tag
1.339     albertel 11117: #
                   11118: 		    my $entry=$token->[1];
1.1068    www      11119: 		    my $unikey='';
1.175     www      11120: 
1.339     albertel 11121: 		    if ($entry eq 'import') {
1.175     www      11122: #
                   11123: # Importing a library here
1.339     albertel 11124: #
1.1067    www      11125:                         my $location=$parser->get_text('/import');
                   11126:                         my $dir=$filename;
                   11127:                         $dir=~s|[^/]*$||;
                   11128:                         $location=&filelocation($dir,$location);
1.1069    www      11129:                        
1.1068    www      11130:                         my $importmode=$token->[2]->{'importmode'};
                   11131:                         if ($importmode eq 'problem') {
1.1069    www      11132: # Import as problem/response
1.1068    www      11133:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11134:                         } elsif ($importmode eq 'part') {
                   11135: # Import as part(s)
1.1069    www      11136:                            $importedparts=1;
                   11137: # We need to get the original file and the imported file to get the part order correct
                   11138: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11139: # Load and inspect original file
1.1070    www      11140:                            if ($#origfileimportpartids<0) {
                   11141:                               undef(%importedpartids);
                   11142:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11143:                               my $origfile=&getfile($origfilelocation);
                   11144:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11145:                            }
                   11146: 
1.1069    www      11147: # Load and inspect imported file
                   11148:                            my $impfile=&getfile($location);
                   11149:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11150:                            if ($#impfilepartids>=0) {
                   11151: # This problem had parts
1.1070    www      11152:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11153:                            } else {
                   11154: # Importing by turning a single problem into a problem part
                   11155: # It gets the import-tags ID as part-ID
                   11156:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11157:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11158:                            }
1.1068    www      11159:                         } else {
                   11160: # Normal import
                   11161:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11162:                            if (defined($token->[2]->{'id'})) {
                   11163:                               $unikey.='_'.$token->[2]->{'id'};
                   11164:                            }
1.1067    www      11165:                         }
                   11166: 
1.339     albertel 11167: 			if ($depthcount<20) {
1.736     albertel 11168: 			    my $metadata = 
                   11169: 				&metadata($uri,'keys', $location,$unikey,
                   11170: 					  $depthcount+1);
                   11171: 			    foreach my $meta (split(',',$metadata)) {
                   11172: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11173: 				$metathesekeys{$meta}=1;
1.339     albertel 11174: 			    }
1.1068    www      11175: 			
                   11176:                         }
1.1067    www      11177: 		    } else {
                   11178: #
                   11179: # Not importing, some other kind of non-package, non-library start tag
                   11180: # 
                   11181:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11182:                         if (defined($token->[2]->{'id'})) {
                   11183:                             $unikey.='_'.$token->[2]->{'id'};
                   11184:                         }
1.339     albertel 11185: 			if (defined($token->[2]->{'name'})) { 
                   11186: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11187: 			}
                   11188: 			$metathesekeys{$unikey}=1;
1.736     albertel 11189: 			foreach my $param (@{$token->[3]}) {
                   11190: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11191: 				$token->[2]->{$param};
1.339     albertel 11192: 			}
                   11193: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11194: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11195: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11196: 		 # only ws inside the tag, and not in default, so use default
                   11197: 		 # as value
1.599     albertel 11198: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11199: 			} elsif ( $internaltext =~ /\S/ ) {
                   11200: 		  # something interesting inside the tag
                   11201: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11202: 			} else {
1.908     albertel 11203: 		  # no interesting values, don't set a default
1.339     albertel 11204: 			}
1.172     www      11205: # end of not-a-package not-a-library import
1.339     albertel 11206: 		    }
1.172     www      11207: # end of not-a-package start tag
1.339     albertel 11208: 		}
1.172     www      11209: # the next is the end of "start tag"
1.339     albertel 11210: 	    }
                   11211: 	}
1.483     albertel 11212: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11213: 	$extension = lc($extension);
                   11214: 	if ($extension eq 'htm') { $extension='html'; }
                   11215: 
1.737     albertel 11216: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11217: 	    #no specific packages #how's our extension
                   11218: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11219: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11220: 					 \%metathesekeys);
                   11221: 	}
1.883     albertel 11222: 
                   11223: 	if (!exists($metaentry{':packages'})
                   11224: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11225: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11226: 		#no specific packages well let's get default then
                   11227: 		if ($key!~/^default&/) { next; }
1.488     albertel 11228: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11229: 					     \%metathesekeys);
                   11230: 	    }
                   11231: 	}
1.338     www      11232: # are there custom rights to evaluate
1.599     albertel 11233: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11234: 
1.338     www      11235:     #
                   11236:     # Importing a rights file here
1.339     albertel 11237:     #
                   11238: 	    unless ($depthcount) {
1.599     albertel 11239: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11240: 		my $dir=$filename;
                   11241: 		$dir=~s|[^/]*$||;
                   11242: 		$location=&filelocation($dir,$location);
1.736     albertel 11243: 		my $rights_metadata =
                   11244: 		    &metadata($uri,'keys',$location,'_rights',
                   11245: 			      $depthcount+1);
                   11246: 		foreach my $rights (split(',',$rights_metadata)) {
                   11247: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11248: 		    $metathesekeys{$rights}=1;
1.339     albertel 11249: 		}
                   11250: 	    }
                   11251: 	}
1.737     albertel 11252: 	# uniqifiy package listing
                   11253: 	my %seen;
                   11254: 	my @uniq_packages =
                   11255: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11256: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11257: 
1.1070    www      11258:         if ($importedparts) {
                   11259: # We had imported parts and need to rebuild partorder
                   11260:            $metaentry{':partorder'}='';
                   11261:            $metathesekeys{'partorder'}=1;
                   11262:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11263:                if ($origfileimportpartids[$index] eq 'part') {
                   11264: # original part, part of the problem
                   11265:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11266:                } else {
                   11267: # we have imported parts at this position
                   11268:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11269:                }
                   11270:            }
                   11271:            $metaentry{':partorder'}=~s/^\,//;
                   11272:         }
                   11273: 
1.737     albertel 11274: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11275: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11276: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11277: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11278: # this is the end of "was not already recently cached
1.71      www      11279:     }
1.599     albertel 11280:     return $metaentry{':'.$what};
1.261     albertel 11281: }
                   11282: 
1.488     albertel 11283: sub metadata_create_package_def {
1.483     albertel 11284:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11285:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11286:     if ($subp eq 'default') { next; }
                   11287:     
1.599     albertel 11288:     if (defined($metaentry{':packages'})) {
                   11289: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11290:     } else {
1.599     albertel 11291: 	$metaentry{':packages'}=$package;
1.483     albertel 11292:     }
                   11293:     my $value=$packagetab{$key};
                   11294:     my $unikey;
                   11295:     $unikey='parameter_0_'.$name;
1.599     albertel 11296:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11297:     $$metathesekeys{$unikey}=1;
1.599     albertel 11298:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11299: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11300:     }
1.599     albertel 11301:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11302: 	$metaentry{':'.$unikey}=
                   11303: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11304:     }
                   11305: }
                   11306: 
1.261     albertel 11307: sub metadata_generate_part0 {
                   11308:     my ($metadata,$metacache,$uri) = @_;
                   11309:     my %allnames;
1.737     albertel 11310:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11311: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11312: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11313: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11314: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11315: 	    $allnames{$name}=$part;
                   11316: 	  }
                   11317: 	}
                   11318:     }
                   11319:     foreach my $name (keys(%allnames)) {
                   11320:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11321:       my $key=":parameter_0_$name";
1.261     albertel 11322:       $$metacache{"$key.part"}='0';
                   11323:       $$metacache{"$key.name"}=$name;
1.428     albertel 11324:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11325: 					   $allnames{$name}.'_'.$name.
                   11326: 					   '.type'};
1.428     albertel 11327:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11328: 			     '.display'};
1.644     www      11329:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11330:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11331:       $$metacache{"$key.display"}=$olddis;
                   11332:     }
1.71      www      11333: }
                   11334: 
1.764     albertel 11335: # ------------------------------------------------------ Devalidate title cache
                   11336: 
                   11337: sub devalidate_title_cache {
                   11338:     my ($url)=@_;
                   11339:     if (!$env{'request.course.id'}) { return; }
                   11340:     my $symb=&symbread($url);
                   11341:     if (!$symb) { return; }
                   11342:     my $key=$env{'request.course.id'}."\0".$symb;
                   11343:     &devalidate_cache_new('title',$key);
                   11344: }
                   11345: 
1.1014    droeschl 11346: # ------------------------------------------------- Get the title of a course
                   11347: 
                   11348: sub current_course_title {
                   11349:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11350: }
1.301     www      11351: # ------------------------------------------------- Get the title of a resource
                   11352: 
                   11353: sub gettitle {
                   11354:     my $urlsymb=shift;
                   11355:     my $symb=&symbread($urlsymb);
1.534     albertel 11356:     if ($symb) {
1.620     albertel 11357: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11358: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11359: 	if (defined($cached)) { 
                   11360: 	    return $result;
                   11361: 	}
1.534     albertel 11362: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11363: 	my $title='';
1.907     albertel 11364: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11365: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11366: 	} else {
                   11367: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11368: 		    &GDBM_READER(),0640)) {
                   11369: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11370: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11371: 		untie(%bighash);
                   11372: 	    }
1.534     albertel 11373: 	}
                   11374: 	$title=~s/\&colon\;/\:/gs;
                   11375: 	if ($title) {
1.1159    www      11376: # Remember both $symb and $title for dynamic metadata
                   11377:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11378:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11379: # Cache this title and then return it
1.599     albertel 11380: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11381: 	}
                   11382: 	$urlsymb=$url;
                   11383:     }
                   11384:     my $title=&metadata($urlsymb,'title');
                   11385:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11386:     return $title;
1.301     www      11387: }
1.613     albertel 11388: 
1.614     albertel 11389: sub get_slot {
                   11390:     my ($which,$cnum,$cdom)=@_;
                   11391:     if (!$cnum || !$cdom) {
1.790     albertel 11392: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11393: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11394: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11395:     }
1.703     albertel 11396:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11397:     my %slotinfo;
                   11398:     if (exists($remembered{$key})) {
                   11399: 	$slotinfo{$which} = $remembered{$key};
                   11400:     } else {
                   11401: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11402: 	&Apache::lonhomework::showhash(%slotinfo);
                   11403: 	my ($tmp)=keys(%slotinfo);
                   11404: 	if ($tmp=~/^error:/) { return (); }
                   11405: 	$remembered{$key} = $slotinfo{$which};
                   11406:     }
1.616     albertel 11407:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11408: 	return %{$slotinfo{$which}};
                   11409:     }
                   11410:     return $slotinfo{$which};
1.614     albertel 11411: }
1.1150    raeburn  11412: 
                   11413: sub get_reservable_slots {
                   11414:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11415:     my $now = time;
                   11416:     my $reservable_info;
                   11417:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11418:     if (exists($remembered{$key})) {
                   11419:         $reservable_info = $remembered{$key};
                   11420:     } else {
                   11421:         my %resv;
                   11422:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11423:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11424:         $reservable_info = \%resv;
                   11425:         $remembered{$key} = $reservable_info;
                   11426:     }
                   11427:     return $reservable_info;
                   11428: }
                   11429: 
                   11430: sub get_course_slots {
                   11431:     my ($cnum,$cdom) = @_;
                   11432:     my $hashid=$cnum.':'.$cdom;
                   11433:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11434:     if (defined($cached)) {
                   11435:         if (ref($result) eq 'HASH') {
                   11436:             return %{$result};
                   11437:         }
                   11438:     } else {
                   11439:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11440:         my ($tmp) = keys(%slots);
                   11441:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11442:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11443:             return %slots;
                   11444:         }
                   11445:     }
                   11446:     return;
                   11447: }
                   11448: 
                   11449: sub devalidate_slots_cache {
                   11450:     my ($cnum,$cdom)=@_;
                   11451:     my $hashid=$cnum.':'.$cdom;
                   11452:     &devalidate_cache_new('allslots',$hashid);
                   11453: }
                   11454: 
1.1172.2.8  raeburn  11455: sub get_coursechange {
                   11456:     my ($cdom,$cnum) = @_;
                   11457:     if ($cdom eq '' || $cnum eq '') {
                   11458:         return unless ($env{'request.course.id'});
                   11459:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11460:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11461:     }
                   11462:     my $hashid=$cdom.'_'.$cnum;
                   11463:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11464:     if ((defined($cached)) && ($change ne '')) {
                   11465:         return $change;
                   11466:     } else {
                   11467:         my %crshash;
                   11468:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11469:         if ($crshash{'internal.contentchange'} eq '') {
                   11470:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11471:             if ($change eq '') {
                   11472:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11473:                 $change = $crshash{'internal.created'};
                   11474:             }
                   11475:         } else {
                   11476:             $change = $crshash{'internal.contentchange'};
                   11477:         }
                   11478:         my $cachetime = 600;
                   11479:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11480:     }
                   11481:     return $change;
                   11482: }
                   11483: 
                   11484: sub devalidate_coursechange_cache {
                   11485:     my ($cnum,$cdom)=@_;
                   11486:     my $hashid=$cnum.':'.$cdom;
                   11487:     &devalidate_cache_new('crschange',$hashid);
                   11488: }
                   11489: 
1.31      www      11490: # ------------------------------------------------- Update symbolic store links
                   11491: 
                   11492: sub symblist {
                   11493:     my ($mapname,%newhash)=@_;
1.438     www      11494:     $mapname=&deversion(&declutter($mapname));
1.31      www      11495:     my %hash;
1.620     albertel 11496:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11497:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11498:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11499: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11500: 		next if ($url eq 'last_known'
                   11501: 			 && $env{'form.no_update_last_known'});
                   11502: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11503: 						    $newhash{$url}->[1],
                   11504: 						    $newhash{$url}->[0]);
1.191     harris41 11505:             }
1.31      www      11506:             if (untie(%hash)) {
                   11507: 		return 'ok';
                   11508:             }
                   11509:         }
                   11510:     }
                   11511:     return 'error';
1.212     www      11512: }
                   11513: 
                   11514: # --------------------------------------------------------------- Verify a symb
                   11515: 
                   11516: sub symbverify {
1.1172.2.11  raeburn  11517:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11518:     my $thisfn=$thisurl;
1.439     www      11519:     $thisfn=&declutter($thisfn);
1.215     www      11520: # direct jump to resource in page or to a sequence - will construct own symbs
                   11521:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11522: # check URL part
1.409     www      11523:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11524: 
1.431     www      11525:     unless ($url eq $thisfn) { return 0; }
1.213     www      11526: 
1.216     www      11527:     $symb=&symbclean($symb);
1.510     www      11528:     $thisurl=&deversion($thisurl);
1.439     www      11529:     $thisfn=&deversion($thisfn);
1.213     www      11530: 
                   11531:     my %bighash;
                   11532:     my $okay=0;
1.431     www      11533: 
1.620     albertel 11534:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11535:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11536:         my $noclutter;
1.1032    raeburn  11537:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11538:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11539:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11540:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11541:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11542:                 $noclutter = 1;
                   11543:             }
                   11544:         }
                   11545:         my $ids;
                   11546:         if ($noclutter) {
                   11547:             $ids=$bighash{'ids_'.$thisurl};
                   11548:         } else {
                   11549:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11550:         }
1.1102    raeburn  11551:         unless ($ids) {
1.1172.2.13  raeburn  11552:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11553:             $ids=$bighash{$idkey};
1.216     www      11554:         }
                   11555:         if ($ids) {
                   11556: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11557:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11558:                 $symb =~ s/\?.+$//;
                   11559:             }
1.800     albertel 11560: 	    foreach my $id (split(/\,/,$ids)) {
                   11561: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11562:                if (
                   11563:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11564:    eq $symb) {
1.1172.2.11  raeburn  11565:                    if (ref($encstate)) {
                   11566:                        $$encstate = $bighash{'encrypted_'.$id};
                   11567:                    }
1.1172.2.13  raeburn  11568:                    if (($env{'request.role.adv'}) ||
                   11569:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11570:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11571:                        $okay=1;
                   11572:                        last;
                   11573:                    }
                   11574:                }
                   11575:            }
1.216     www      11576:         }
1.213     www      11577: 	untie(%bighash);
                   11578:     }
                   11579:     return $okay;
1.31      www      11580: }
                   11581: 
1.210     www      11582: # --------------------------------------------------------------- Clean-up symb
                   11583: 
                   11584: sub symbclean {
                   11585:     my $symb=shift;
1.568     albertel 11586:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11587: # remove version from map
                   11588:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11589: 
1.210     www      11590: # remove version from URL
                   11591:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11592: 
1.507     www      11593: # remove wrapper
                   11594: 
1.510     www      11595:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11596:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11597:     return $symb;
1.409     www      11598: }
                   11599: 
                   11600: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11601: 
                   11602: sub encode_symb {
                   11603:     my ($map,$resid,$url)=@_;
                   11604:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11605: }
1.409     www      11606: 
                   11607: sub decode_symb {
1.568     albertel 11608:     my $symb=shift;
                   11609:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11610:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11611:     return (&fixversion($map),$resid,&fixversion($url));
                   11612: }
                   11613: 
                   11614: sub fixversion {
                   11615:     my $fn=shift;
1.609     banghart 11616:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11617:     my %bighash;
                   11618:     my $uri=&clutter($fn);
1.620     albertel 11619:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11620: # is this cached?
1.599     albertel 11621:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11622:     if (defined($cached)) { return $result; }
                   11623: # unfortunately not cached, or expired
1.620     albertel 11624:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11625: 	    &GDBM_READER(),0640)) {
                   11626:  	if ($bighash{'version_'.$uri}) {
                   11627:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11628:  	    unless (($version eq 'mostrecent') || 
                   11629: 		    ($version==&getversion($uri))) {
1.440     www      11630:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11631:  	    }
                   11632:  	}
                   11633:  	untie %bighash;
1.413     www      11634:     }
1.599     albertel 11635:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11636: }
                   11637: 
                   11638: sub deversion {
                   11639:     my $url=shift;
                   11640:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11641:     return $url;
1.210     www      11642: }
                   11643: 
1.31      www      11644: # ------------------------------------------------------ Return symb list entry
                   11645: 
                   11646: sub symbread {
1.1172.2.66  raeburn  11647:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11648:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11649:     if (defined($env{$cache_str})) {
                   11650:         if ($ignorecachednull) {
                   11651:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11652:         } else {
                   11653:             return $env{$cache_str};
                   11654:         }
                   11655:     }
1.242     www      11656: # no filename provided? try from environment
1.1172.2.54  raeburn  11657:     unless ($thisfn) {
1.620     albertel 11658:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11659:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11660:         }
                   11661:         $thisfn=$env{'request.filename'};
1.44      www      11662:     }
1.569     albertel 11663:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11664: # is that filename actually a symb? Verify, clean, and return
                   11665:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11666: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11667: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11668: 	}
1.242     www      11669:     }
1.44      www      11670:     $thisfn=declutter($thisfn);
1.31      www      11671:     my %hash;
1.37      www      11672:     my %bighash;
                   11673:     my $syval='';
1.620     albertel 11674:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11675:         my $targetfn = $thisfn;
1.609     banghart 11676:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11677:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11678:         }
1.687     albertel 11679: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11680: 	    $targetfn=$1;
                   11681: 	}
1.620     albertel 11682:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11683:                       &GDBM_READER(),0640)) {
1.481     raeburn  11684: 	    $syval=$hash{$targetfn};
1.37      www      11685:             untie(%hash);
                   11686:         }
                   11687: # ---------------------------------------------------------- There was an entry
                   11688:         if ($syval) {
1.601     albertel 11689: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11690: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11691: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11692: 		    #return $env{$cache_str}='';
1.601     albertel 11693: 		#}    
                   11694: 		#$syval.=$1;
                   11695: 	    #}
1.37      www      11696:         } else {
                   11697: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11698:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11699:                             &GDBM_READER(),0640)) {
1.37      www      11700: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11701:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11702:               unless ($ids) { 
                   11703:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11704:               }
                   11705:               unless ($ids) {
                   11706: # alias?
                   11707: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11708:               }
1.37      www      11709:               if ($ids) {
                   11710: # ------------------------------------------------------------------- Has ID(s)
                   11711:                  my @possibilities=split(/\,/,$ids);
1.39      www      11712:                  if ($#possibilities==0) {
                   11713: # ----------------------------------------------- There is only one possibility
1.37      www      11714: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11715: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11716: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11717:                      if (ref($possibles) eq 'HASH') {
                   11718:                          $possibles->{$syval} = 1;
                   11719:                      }
                   11720:                      if ($checkforblock) {
                   11721:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11722:                          if (@blockers) {
                   11723:                              $syval = '';
                   11724:                              return;
                   11725:                          }
                   11726:                      }
                   11727:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11728: # ------------------------------------------ There is more than one possibility
                   11729:                      my $realpossible=0;
1.800     albertel 11730:                      foreach my $id (@possibilities) {
                   11731: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11732:                          my $canaccess;
                   11733:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11734:                              $canaccess = 1;
                   11735:                          } else {
                   11736:                              $canaccess = &allowed('bre',$file);
                   11737:                          }
                   11738:                          if ($canaccess) {
                   11739:          		     my ($mapid,$resid)=split(/\./,$id);
                   11740:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11741:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11742:                                                              $resid,$thisfn);
                   11743:                                  if (ref($possibles) eq 'HASH') {
                   11744:                                      $possibles->{$syval} = 1;
                   11745:                                  }
                   11746:                                  if ($checkforblock) {
                   11747:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11748:                                      unless (@blockers > 0) {
                   11749:                                          $syval = $poss_syval;
                   11750:                                          $realpossible++;
                   11751:                                      }
                   11752:                                  } else {
                   11753:                                      $syval = $poss_syval;
                   11754:                                      $realpossible++;
                   11755:                                  }
                   11756:                              }
1.39      www      11757: 			 }
1.191     harris41 11758:                      }
1.39      www      11759: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11760:                  } else {
                   11761:                      $syval='';
1.37      www      11762:                  }
                   11763: 	      }
1.1172.2.66  raeburn  11764:               untie(%bighash);
1.481     raeburn  11765:            }
1.31      www      11766:         }
1.62      www      11767:         if ($syval) {
1.620     albertel 11768: 	    return $env{$cache_str}=$syval;
1.62      www      11769:         }
1.31      www      11770:     }
1.949     raeburn  11771:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11772:     return $env{$cache_str}='';
1.31      www      11773: }
                   11774: 
                   11775: # ---------------------------------------------------------- Return random seed
                   11776: 
1.32      www      11777: sub numval {
                   11778:     my $txt=shift;
                   11779:     $txt=~tr/A-J/0-9/;
                   11780:     $txt=~tr/a-j/0-9/;
                   11781:     $txt=~tr/K-T/0-9/;
                   11782:     $txt=~tr/k-t/0-9/;
                   11783:     $txt=~tr/U-Z/0-5/;
                   11784:     $txt=~tr/u-z/0-5/;
                   11785:     $txt=~s/\D//g;
1.564     albertel 11786:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11787:     return int($txt);
1.368     albertel 11788: }
                   11789: 
1.484     albertel 11790: sub numval2 {
                   11791:     my $txt=shift;
                   11792:     $txt=~tr/A-J/0-9/;
                   11793:     $txt=~tr/a-j/0-9/;
                   11794:     $txt=~tr/K-T/0-9/;
                   11795:     $txt=~tr/k-t/0-9/;
                   11796:     $txt=~tr/U-Z/0-5/;
                   11797:     $txt=~tr/u-z/0-5/;
                   11798:     $txt=~s/\D//g;
                   11799:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11800:     my $total;
                   11801:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11802:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11803:     return int($total);
                   11804: }
                   11805: 
1.575     albertel 11806: sub numval3 {
                   11807:     use integer;
                   11808:     my $txt=shift;
                   11809:     $txt=~tr/A-J/0-9/;
                   11810:     $txt=~tr/a-j/0-9/;
                   11811:     $txt=~tr/K-T/0-9/;
                   11812:     $txt=~tr/k-t/0-9/;
                   11813:     $txt=~tr/U-Z/0-5/;
                   11814:     $txt=~tr/u-z/0-5/;
                   11815:     $txt=~s/\D//g;
                   11816:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11817:     my $total;
                   11818:     foreach my $val (@txts) { $total+=$val; }
                   11819:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11820:     return $total;
                   11821: }
                   11822: 
1.675     albertel 11823: sub digest {
                   11824:     my ($data)=@_;
                   11825:     my $digest=&Digest::MD5::md5($data);
                   11826:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11827:     my ($e,$f);
                   11828:     {
                   11829:         use integer;
                   11830:         $e=($a+$b);
                   11831:         $f=($c+$d);
                   11832:         if ($_64bit) {
                   11833:             $e=(($e<<32)>>32);
                   11834:             $f=(($f<<32)>>32);
                   11835:         }
                   11836:     }
                   11837:     if (wantarray) {
                   11838: 	return ($e,$f);
                   11839:     } else {
                   11840: 	my $g;
                   11841: 	{
                   11842: 	    use integer;
                   11843: 	    $g=($e+$f);
                   11844: 	    if ($_64bit) {
                   11845: 		$g=(($g<<32)>>32);
                   11846: 	    }
                   11847: 	}
                   11848: 	return $g;
                   11849:     }
                   11850: }
                   11851: 
1.368     albertel 11852: sub latest_rnd_algorithm_id {
1.675     albertel 11853:     return '64bit5';
1.366     albertel 11854: }
1.32      www      11855: 
1.503     albertel 11856: sub get_rand_alg {
                   11857:     my ($courseid)=@_;
1.790     albertel 11858:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11859:     if ($courseid) {
1.620     albertel 11860: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11861:     }
                   11862:     return &latest_rnd_algorithm_id();
                   11863: }
                   11864: 
1.562     albertel 11865: sub validCODE {
                   11866:     my ($CODE)=@_;
                   11867:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11868:     return 0;
                   11869: }
                   11870: 
1.491     albertel 11871: sub getCODE {
1.620     albertel 11872:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11873:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11874: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11875: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11876: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11877:     }
                   11878:     return undef;
                   11879: }
1.1133    foxr     11880: #
                   11881: #  Determines the random seed for a specific context:
                   11882: #
                   11883: # parameters:
                   11884: #   symb      - in course context the symb for the seed.
                   11885: #   course_id - The course id of the form domain_coursenum.
                   11886: #   domain    - Domain for the user.
                   11887: #   course    - Course for the user.
                   11888: #   cenv      - environment of the course.
                   11889: #
                   11890: # NOTE:
                   11891: #   All parameters are picked out of the environment if missing
                   11892: #   or not defined.
                   11893: #   If a symb cannot be determined the current time is used instead.
                   11894: #
                   11895: #  For a given well defined symb, courside, domain, username,
                   11896: #  and course environment, the seed is reproducible.
                   11897: #
1.31      www      11898: sub rndseed {
1.1133    foxr     11899:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11900:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11901:     if (!defined($symb)) {
1.366     albertel 11902: 	unless ($symb=$wsymb) { return time; }
                   11903:     }
1.1146    foxr     11904:     if (!defined $courseid) { 
                   11905: 	$courseid=$wcourseid; 
                   11906:     }
                   11907:     if (!defined $domain) { $domain=$wdomain; }
                   11908:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11909: 
                   11910:     my $which;
                   11911:     if (defined($cenv->{'rndseed'})) {
                   11912: 	$which = $cenv->{'rndseed'};
                   11913:     } else {
                   11914: 	$which =&get_rand_alg($courseid);
                   11915:     }
1.491     albertel 11916:     if (defined(&getCODE())) {
1.675     albertel 11917: 	if ($which eq '64bit5') {
                   11918: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11919: 	} elsif ($which eq '64bit4') {
1.575     albertel 11920: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11921: 	} else {
                   11922: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11923: 	}
1.675     albertel 11924:     } elsif ($which eq '64bit5') {
                   11925: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11926:     } elsif ($which eq '64bit4') {
                   11927: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11928:     } elsif ($which eq '64bit3') {
                   11929: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11930:     } elsif ($which eq '64bit2') {
                   11931: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11932:     } elsif ($which eq '64bit') {
                   11933: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11934:     }
                   11935:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11936: }
                   11937: 
                   11938: sub rndseed_32bit {
                   11939:     my ($symb,$courseid,$domain,$username)=@_;
                   11940:     {
                   11941: 	use integer;
                   11942: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11943: 	my $symbseed=numval($symb) << 22;
                   11944: 	my $namechck=unpack("%32C*",$username) << 17;
                   11945: 	my $nameseed=numval($username) << 12;
                   11946: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11947: 	my $courseseed=unpack("%32C*",$courseid);
                   11948: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11949: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11950: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11951: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11952: 	return $num;
                   11953:     }
                   11954: }
                   11955: 
                   11956: sub rndseed_64bit {
                   11957:     my ($symb,$courseid,$domain,$username)=@_;
                   11958:     {
                   11959: 	use integer;
                   11960: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11961: 	my $symbseed=numval($symb) << 10;
                   11962: 	my $namechck=unpack("%32S*",$username);
                   11963: 	
                   11964: 	my $nameseed=numval($username) << 21;
                   11965: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11966: 	my $courseseed=unpack("%32S*",$courseid);
                   11967: 	
                   11968: 	my $num1=$symbchck+$symbseed+$namechck;
                   11969: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11970: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11971: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11972: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11973: 	return "$num1,$num2";
1.155     albertel 11974:     }
1.366     albertel 11975: }
                   11976: 
1.443     albertel 11977: sub rndseed_64bit2 {
                   11978:     my ($symb,$courseid,$domain,$username)=@_;
                   11979:     {
                   11980: 	use integer;
                   11981: 	# strings need to be an even # of cahracters long, it it is odd the
                   11982:         # last characters gets thrown away
                   11983: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11984: 	my $symbseed=numval($symb) << 10;
                   11985: 	my $namechck=unpack("%32S*",$username.' ');
                   11986: 	
                   11987: 	my $nameseed=numval($username) << 21;
1.501     albertel 11988: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11989: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11990: 	
                   11991: 	my $num1=$symbchck+$symbseed+$namechck;
                   11992: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11993: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11994: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11995: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11996: 	return "$num1,$num2";
                   11997:     }
                   11998: }
                   11999: 
                   12000: sub rndseed_64bit3 {
                   12001:     my ($symb,$courseid,$domain,$username)=@_;
                   12002:     {
                   12003: 	use integer;
                   12004: 	# strings need to be an even # of cahracters long, it it is odd the
                   12005:         # last characters gets thrown away
                   12006: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12007: 	my $symbseed=numval2($symb) << 10;
                   12008: 	my $namechck=unpack("%32S*",$username.' ');
                   12009: 	
                   12010: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12011: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12012: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12013: 	
                   12014: 	my $num1=$symbchck+$symbseed+$namechck;
                   12015: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12016: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12017: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12018: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12019: 	
1.503     albertel 12020: 	return "$num1:$num2";
1.443     albertel 12021:     }
                   12022: }
                   12023: 
1.575     albertel 12024: sub rndseed_64bit4 {
                   12025:     my ($symb,$courseid,$domain,$username)=@_;
                   12026:     {
                   12027: 	use integer;
                   12028: 	# strings need to be an even # of cahracters long, it it is odd the
                   12029:         # last characters gets thrown away
                   12030: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12031: 	my $symbseed=numval3($symb) << 10;
                   12032: 	my $namechck=unpack("%32S*",$username.' ');
                   12033: 	
                   12034: 	my $nameseed=numval3($username) << 21;
                   12035: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12036: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12037: 	
                   12038: 	my $num1=$symbchck+$symbseed+$namechck;
                   12039: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12040: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12041: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12042: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12043: 	
1.575     albertel 12044: 	return "$num1:$num2";
                   12045:     }
                   12046: }
                   12047: 
1.675     albertel 12048: sub rndseed_64bit5 {
                   12049:     my ($symb,$courseid,$domain,$username)=@_;
                   12050:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12051:     return "$num1:$num2";
                   12052: }
                   12053: 
1.366     albertel 12054: sub rndseed_CODE_64bit {
                   12055:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12056:     {
1.366     albertel 12057: 	use integer;
1.443     albertel 12058: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12059: 	my $symbseed=numval2($symb);
1.491     albertel 12060: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12061: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12062: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12063: 	my $num1=$symbseed+$CODEchck;
                   12064: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12065: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12066: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12067: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12068: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12069: 	return "$num1:$num2";
1.366     albertel 12070:     }
                   12071: }
                   12072: 
1.575     albertel 12073: sub rndseed_CODE_64bit4 {
                   12074:     my ($symb,$courseid,$domain,$username)=@_;
                   12075:     {
                   12076: 	use integer;
                   12077: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12078: 	my $symbseed=numval3($symb);
                   12079: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12080: 	my $CODEseed=numval3(&getCODE());
                   12081: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12082: 	my $num1=$symbseed+$CODEchck;
                   12083: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12084: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12085: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12086: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12087: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12088: 	return "$num1:$num2";
                   12089:     }
                   12090: }
                   12091: 
1.675     albertel 12092: sub rndseed_CODE_64bit5 {
                   12093:     my ($symb,$courseid,$domain,$username)=@_;
                   12094:     my $code = &getCODE();
                   12095:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12096:     return "$num1:$num2";
                   12097: }
                   12098: 
1.366     albertel 12099: sub setup_random_from_rndseed {
                   12100:     my ($rndseed)=@_;
1.503     albertel 12101:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12102: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12103:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12104:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12105:         } else {
                   12106:             &Math::Random::random_set_seed($num1,$num2);
                   12107:         }
1.366     albertel 12108:     } else {
                   12109: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12110:     }
1.36      albertel 12111: }
                   12112: 
1.474     albertel 12113: sub latest_receipt_algorithm_id {
1.835     albertel 12114:     return 'receipt3';
1.474     albertel 12115: }
                   12116: 
1.480     www      12117: sub recunique {
                   12118:     my $fucourseid=shift;
                   12119:     my $unique;
1.835     albertel 12120:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12121: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12122: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12123:     } else {
                   12124: 	$unique=$perlvar{'lonReceipt'};
                   12125:     }
                   12126:     return unpack("%32C*",$unique);
                   12127: }
                   12128: 
                   12129: sub recprefix {
                   12130:     my $fucourseid=shift;
                   12131:     my $prefix;
1.835     albertel 12132:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12133: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12134: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12135:     } else {
                   12136: 	$prefix=$perlvar{'lonHostID'};
                   12137:     }
                   12138:     return unpack("%32C*",$prefix);
                   12139: }
                   12140: 
1.76      www      12141: sub ireceipt {
1.474     albertel 12142:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12143: 
                   12144:     my $return =&recprefix($fucourseid).'-';
                   12145: 
                   12146:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12147: 	$env{'request.state'} eq 'construct') {
                   12148: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12149: 	return $return;
                   12150:     }
                   12151: 
1.76      www      12152:     my $cuname=unpack("%32C*",$funame);
                   12153:     my $cudom=unpack("%32C*",$fudom);
                   12154:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12155:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12156:     my $cunique=&recunique($fucourseid);
1.474     albertel 12157:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12158:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12159: 
1.790     albertel 12160: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12161: 			       
                   12162: 	$return.= ($cunique%$cuname+
                   12163: 		   $cunique%$cudom+
                   12164: 		   $cusymb%$cuname+
                   12165: 		   $cusymb%$cudom+
                   12166: 		   $cucourseid%$cuname+
                   12167: 		   $cucourseid%$cudom+
                   12168: 		   $cpart%$cuname+
                   12169: 		   $cpart%$cudom);
                   12170:     } else {
                   12171: 	$return.= ($cunique%$cuname+
                   12172: 		   $cunique%$cudom+
                   12173: 		   $cusymb%$cuname+
                   12174: 		   $cusymb%$cudom+
                   12175: 		   $cucourseid%$cuname+
                   12176: 		   $cucourseid%$cudom);
                   12177:     }
                   12178:     return $return;
1.76      www      12179: }
                   12180: 
                   12181: sub receipt {
1.474     albertel 12182:     my ($part)=@_;
1.790     albertel 12183:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12184:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12185: }
1.260     ng       12186: 
1.790     albertel 12187: sub whichuser {
                   12188:     my ($passedsymb)=@_;
                   12189:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12190:     if (defined($env{'form.grade_symb'})) {
                   12191: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12192: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12193: 	if (!$allowed &&
                   12194: 	    exists($env{'request.course.sec'}) &&
                   12195: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12196: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12197: 			      '/'.$env{'request.course.sec'});
                   12198: 	}
                   12199: 	if ($allowed) {
                   12200: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12201: 	    $courseid=$tmp_courseid;
                   12202: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12203: 	    ($name)=&get_env_multiple('form.grade_username');
                   12204: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12205: 	}
                   12206:     }
                   12207:     if (!$passedsymb) {
                   12208: 	$symb=&symbread();
                   12209:     } else {
                   12210: 	$symb=$passedsymb;
                   12211:     }
                   12212:     $courseid=$env{'request.course.id'};
                   12213:     $domain=$env{'user.domain'};
                   12214:     $name=$env{'user.name'};
                   12215:     if ($name eq 'public' && $domain eq 'public') {
                   12216: 	if (!defined($env{'form.username'})) {
                   12217: 	    $env{'form.username'}.=time.rand(10000000);
                   12218: 	}
                   12219: 	$name.=$env{'form.username'};
                   12220:     }
                   12221:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12222: 
                   12223: }
                   12224: 
1.36      albertel 12225: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12226: # returns either the contents of the file or 
                   12227: # -1 if the file doesn't exist
1.481     raeburn  12228: #
                   12229: # if the target is a file that was uploaded via DOCS, 
                   12230: # a check will be made to see if a current copy exists on the local server,
                   12231: # if it does this will be served, otherwise a copy will be retrieved from
                   12232: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12233: # the local server.   
1.472     albertel 12234: 
1.36      albertel 12235: sub getfile {
1.538     albertel 12236:     my ($file) = @_;
1.609     banghart 12237:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12238:     &repcopy($file);
                   12239:     return &readfile($file);
                   12240: }
                   12241: 
                   12242: sub repcopy_userfile {
                   12243:     my ($file)=@_;
1.1142    raeburn  12244:     my $londocroot = $perlvar{'lonDocRoot'};
                   12245:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12246:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12247:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12248: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12249:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12250:     if (-e "$file") {
1.828     www      12251: # we already have a local copy, check it out
1.538     albertel 12252: 	my @fileinfo = stat($file);
1.828     www      12253: 	my $rtncode;
                   12254: 	my $info;
1.538     albertel 12255: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12256: 	if ($lwpresp ne 'ok') {
1.828     www      12257: # there is no such file anymore, even though we had a local copy
1.482     albertel 12258: 	    if ($rtncode eq '404') {
1.538     albertel 12259: 		unlink($file);
1.482     albertel 12260: 	    }
                   12261: 	    return -1;
                   12262: 	}
                   12263: 	if ($info < $fileinfo[9]) {
1.828     www      12264: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12265: 	    return 'ok';
1.828     www      12266: 	} else {
                   12267: # the file is outdated, get rid of it
                   12268: 	    unlink($file);
1.482     albertel 12269: 	}
1.828     www      12270:     }
                   12271: # one way or the other, at this point, we don't have the file
                   12272: # construct the correct path for the file
                   12273:     my @parts = ($cdom,$cnum); 
                   12274:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12275: 	push @parts, split(/\//,$1);
                   12276:     }
                   12277:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12278:     foreach my $part (@parts) {
                   12279: 	$path .= '/'.$part;
                   12280: 	if (!-e $path) {
                   12281: 	    mkdir($path,0770);
1.482     albertel 12282: 	}
                   12283:     }
1.828     www      12284: # now the path exists for sure
                   12285: # get a user agent
                   12286:     my $ua=new LWP::UserAgent;
                   12287:     my $transferfile=$file.'.in.transfer';
                   12288: # FIXME: this should flock
                   12289:     if (-e $transferfile) { return 'ok'; }
                   12290:     my $request;
                   12291:     $uri=~s/^\///;
1.980     raeburn  12292:     my $homeserver = &homeserver($cnum,$cdom);
                   12293:     my $protocol = $protocol{$homeserver};
                   12294:     $protocol = 'http' if ($protocol ne 'https');
                   12295:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12296:     my $response=$ua->request($request,$transferfile);
                   12297: # did it work?
                   12298:     if ($response->is_error()) {
                   12299: 	unlink($transferfile);
                   12300: 	&logthis("Userfile repcopy failed for $uri");
                   12301: 	return -1;
                   12302:     }
                   12303: # worked, rename the transfer file
                   12304:     rename($transferfile,$file);
1.607     raeburn  12305:     return 'ok';
1.481     raeburn  12306: }
                   12307: 
1.517     albertel 12308: sub tokenwrapper {
                   12309:     my $uri=shift;
1.980     raeburn  12310:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12311:     $uri=~s|^/||;
1.620     albertel 12312:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12313:     my $token=$1;
1.552     albertel 12314:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12315:     if ($udom && $uname && $file) {
                   12316: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12317:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12318:         my $homeserver = &homeserver($uname,$udom);
                   12319:         my $protocol = $protocol{$homeserver};
                   12320:         $protocol = 'http' if ($protocol ne 'https');
                   12321:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12322:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12323:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12324:     } else {
                   12325:         return '/adm/notfound.html';
                   12326:     }
                   12327: }
                   12328: 
1.828     www      12329: # call with reqtype HEAD: get last modification time
                   12330: # call with reqtype GET: get the file contents
                   12331: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12332: #
1.481     raeburn  12333: sub getuploaded {
                   12334:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12335:     $uri=~s/^\///;
1.980     raeburn  12336:     my $homeserver = &homeserver($cnum,$cdom);
                   12337:     my $protocol = $protocol{$homeserver};
                   12338:     $protocol = 'http' if ($protocol ne 'https');
                   12339:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12340:     my $ua=new LWP::UserAgent;
                   12341:     my $request=new HTTP::Request($reqtype,$uri);
                   12342:     my $response=$ua->request($request);
                   12343:     $$rtncode = $response->code;
1.482     albertel 12344:     if (! $response->is_success()) {
                   12345: 	return 'failed';
                   12346:     }      
                   12347:     if ($reqtype eq 'HEAD') {
1.486     www      12348: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12349:     } elsif ($reqtype eq 'GET') {
                   12350: 	$$info = $response->content;
1.472     albertel 12351:     }
1.482     albertel 12352:     return 'ok';
1.36      albertel 12353: }
                   12354: 
1.481     raeburn  12355: sub readfile {
                   12356:     my $file = shift;
                   12357:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12358:     my $fh;
1.1172.2.96  raeburn  12359:     open($fh,"<",$file);
1.481     raeburn  12360:     my $a='';
1.800     albertel 12361:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12362:     return $a;
                   12363: }
                   12364: 
1.36      albertel 12365: sub filelocation {
1.590     banghart 12366:     my ($dir,$file) = @_;
                   12367:     my $location;
                   12368:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12369: 
                   12370:     if ($file =~ m-^/adm/-) {
                   12371: 	$file=~s-^/adm/wrapper/-/-;
                   12372: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12373:     }
1.882     albertel 12374: 
1.1139    www      12375:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12376:         $location = $file;
1.609     banghart 12377:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12378:         my ($udom,$uname,$filename)=
1.811     albertel 12379:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12380:         my $home=&homeserver($uname,$udom);
                   12381:         my $is_me=0;
                   12382:         my @ids=&current_machine_ids();
                   12383:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12384:         if ($is_me) {
1.1117    foxr     12385:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12386:         } else {
                   12387:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12388:   	      $udom.'/'.$uname.'/'.$filename;
                   12389:         }
1.882     albertel 12390:     } elsif ($file =~ m-^/adm/-) {
                   12391: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12392:     } else {
                   12393:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12394:         $file=~s:^/(res|priv)/:/:;
                   12395:         my $space=$1;
1.590     banghart 12396:         if ( !( $file =~ m:^/:) ) {
                   12397:             $location = $dir. '/'.$file;
                   12398:         } else {
1.1142    raeburn  12399:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12400:         }
1.59      albertel 12401:     }
1.590     banghart 12402:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12403:     while ($location=~m{/\.\./}) {
                   12404: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12405: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12406: 	} else {
                   12407: 	    $location=~ s{/\.\./}{/}g;
                   12408: 	}
                   12409:     } #remove dir/..
1.590     banghart 12410:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12411:     return $location;
1.46      www      12412: }
1.36      albertel 12413: 
1.46      www      12414: sub hreflocation {
                   12415:     my ($dir,$file)=@_;
1.980     raeburn  12416:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12417: 	$file=filelocation($dir,$file);
1.700     albertel 12418:     } elsif ($file=~m-^/adm/-) {
                   12419: 	$file=~s-^/adm/wrapper/-/-;
                   12420: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12421:     }
                   12422:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12423: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12424:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12425: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12426: 	        {/uploaded/$1/$2/}x;
1.46      www      12427:     }
1.913     albertel 12428:     if ($file=~ m{^/userfiles/}) {
                   12429: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12430:     }
1.462     albertel 12431:     return $file;
1.465     albertel 12432: }
                   12433: 
1.1139    www      12434: 
                   12435: 
                   12436: 
                   12437: 
1.465     albertel 12438: sub current_machine_domains {
1.853     albertel 12439:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12440: }
                   12441: 
                   12442: sub machine_domains {
                   12443:     my ($hostname) = @_;
1.465     albertel 12444:     my @domains;
1.838     albertel 12445:     my %hostname = &all_hostnames();
1.465     albertel 12446:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12447: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12448: 	if ($hostname eq $name) {
1.844     albertel 12449: 	    push(@domains,&host_domain($id));
1.465     albertel 12450: 	}
                   12451:     }
                   12452:     return @domains;
                   12453: }
                   12454: 
                   12455: sub current_machine_ids {
1.853     albertel 12456:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12457: }
                   12458: 
                   12459: sub machine_ids {
                   12460:     my ($hostname) = @_;
                   12461:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12462:     my @ids;
1.888     albertel 12463:     my %name_to_host = &all_names();
1.889     albertel 12464:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12465: 	return @{ $name_to_host{$hostname} };
                   12466:     }
                   12467:     return;
1.31      www      12468: }
                   12469: 
1.824     raeburn  12470: sub additional_machine_domains {
                   12471:     my @domains;
1.1172.2.96  raeburn  12472:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  12473:     while( my $line = <$fh>) {
                   12474:         $line =~ s/\s//g;
                   12475:         push(@domains,$line);
                   12476:     }
                   12477:     return @domains;
                   12478: }
                   12479: 
                   12480: sub default_login_domain {
                   12481:     my $domain = $perlvar{'lonDefDomain'};
                   12482:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12483:     foreach my $posdom (&current_machine_domains(),
                   12484:                         &additional_machine_domains()) {
                   12485:         if (lc($posdom) eq lc($testdomain)) {
                   12486:             $domain=$posdom;
                   12487:             last;
                   12488:         }
                   12489:     }
                   12490:     return $domain;
                   12491: }
                   12492: 
1.31      www      12493: # ------------------------------------------------------------- Declutters URLs
                   12494: 
                   12495: sub declutter {
                   12496:     my $thisfn=shift;
1.569     albertel 12497:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12498:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12499:         $thisfn=~s{^/home/httpd/html}{};
                   12500:     }
1.31      www      12501:     $thisfn=~s/^\///;
1.697     albertel 12502:     $thisfn=~s|^adm/wrapper/||;
                   12503:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12504:     $thisfn=~s/^res\///;
1.1172    bisitz   12505:     $thisfn=~s/^priv\///;
1.1032    raeburn  12506:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12507:         $thisfn=~s/\?.+$//;
                   12508:     }
1.268     www      12509:     return $thisfn;
                   12510: }
                   12511: 
                   12512: # ------------------------------------------------------------- Clutter up URLs
                   12513: 
                   12514: sub clutter {
                   12515:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12516:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12517: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12518:        $thisfn='/res'.$thisfn; 
                   12519:     }
1.1031    raeburn  12520:     if ($thisfn !~m|^/adm|) {
                   12521: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12522: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12523: 	} else {
                   12524: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12525: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12526: 	    if ($embstyle eq 'ssi'
                   12527: 		|| ($embstyle eq 'hdn')
                   12528: 		|| ($embstyle eq 'rat')
                   12529: 		|| ($embstyle eq 'prv')
                   12530: 		|| ($embstyle eq 'ign')) {
                   12531: 		#do nothing with these
                   12532: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12533: 		|| ($embstyle eq 'emb')
                   12534: 		|| ($embstyle eq 'wrp')) {
                   12535: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12536: 	    } elsif ($embstyle eq 'unk'
                   12537: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12538: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12539: 	    } else {
1.718     www      12540: #		&logthis("Got a blank emb style");
1.695     albertel 12541: 	    }
1.694     albertel 12542: 	}
                   12543:     }
1.31      www      12544:     return $thisfn;
1.12      www      12545: }
                   12546: 
1.787     albertel 12547: sub clutter_with_no_wrapper {
                   12548:     my $uri = &clutter(shift);
                   12549:     if ($uri =~ m-^/adm/-) {
                   12550: 	$uri =~ s-^/adm/wrapper/-/-;
                   12551: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12552:     }
                   12553:     return $uri;
                   12554: }
                   12555: 
1.557     albertel 12556: sub freeze_escape {
                   12557:     my ($value)=@_;
                   12558:     if (ref($value)) {
                   12559: 	$value=&nfreeze($value);
                   12560: 	return '__FROZEN__'.&escape($value);
                   12561:     }
                   12562:     return &escape($value);
                   12563: }
                   12564: 
1.11      www      12565: 
1.557     albertel 12566: sub thaw_unescape {
                   12567:     my ($value)=@_;
                   12568:     if ($value =~ /^__FROZEN__/) {
                   12569: 	substr($value,0,10,undef);
                   12570: 	$value=&unescape($value);
                   12571: 	return &thaw($value);
                   12572:     }
                   12573:     return &unescape($value);
                   12574: }
                   12575: 
1.436     albertel 12576: sub correct_line_ends {
                   12577:     my ($result)=@_;
                   12578:     $$result =~s/\r\n/\n/mg;
                   12579:     $$result =~s/\r/\n/mg;
1.415     albertel 12580: }
1.1       albertel 12581: # ================================================================ Main Program
                   12582: 
1.184     www      12583: sub goodbye {
1.204     albertel 12584:    &logthis("Starting Shut down");
1.443     albertel 12585: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12586:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12587: #converted
1.599     albertel 12588: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12589:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12590: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12591: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12592: #1.1 only
1.870     albertel 12593: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12594: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12595: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12596: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12597:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12598:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12599:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12600:    &flushcourselogs();
                   12601:    &logthis("Shutting down");
                   12602: }
                   12603: 
1.852     albertel 12604: sub get_dns {
1.1172.2.17  raeburn  12605:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12606:     if (!$ignore_cache) {
                   12607: 	my ($content,$cached)=
                   12608: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12609: 	if ($cached) {
1.1172.2.17  raeburn  12610: 	    &$func($content,$hashref);
1.869     albertel 12611: 	    return;
                   12612: 	}
                   12613:     }
                   12614: 
                   12615:     my %alldns;
1.1172.2.96  raeburn  12616:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   12617:         foreach my $dns (<$config>) {
                   12618: 	    next if ($dns !~ /^\^(\S*)/x);
                   12619:             my $line = $1;
                   12620:             my ($host,$protocol) = split(/:/,$line);
                   12621:             if ($protocol ne 'https') {
                   12622:                 $protocol = 'http';
                   12623:             }
                   12624: 	    $alldns{$host} = $protocol;
1.979     raeburn  12625:         }
1.1172.2.96  raeburn  12626:         close($config);
1.869     albertel 12627:     }
                   12628:     while (%alldns) {
1.1172.2.52  raeburn  12629: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12630: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12631:         $ua->timeout(30);
1.979     raeburn  12632: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12633: 	my $response=$ua->request($request);
1.979     raeburn  12634:         delete($alldns{$dns});
1.852     albertel 12635: 	next if ($response->is_error());
                   12636: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12637:         unless ($nocache) {
1.1172.2.23  raeburn  12638: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12639:         }
                   12640: 	&$func(\@content,$hashref);
1.869     albertel 12641: 	return;
1.852     albertel 12642:     }
                   12643:     close($config);
1.871     albertel 12644:     my $which = (split('/',$url))[3];
                   12645:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.96  raeburn  12646:     open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12647:     my @content = <$config>;
1.1172.2.17  raeburn  12648:     &$func(\@content,$hashref);
                   12649:     return;
                   12650: }
                   12651: 
                   12652: # ------------------------------------------------------Get DNS checksums file
                   12653: sub parse_dns_checksums_tab {
                   12654:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12655:     my $lonhost = $perlvar{'lonHostID'};
                   12656:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12657:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12658:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12659:     my $webconfdir = '/etc/httpd/conf';
                   12660:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12661:         $webconfdir = '/etc/apache2';
                   12662:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12663:         if ($1 >= 10) {
                   12664:             $webconfdir = '/etc/apache2';
                   12665:         }
                   12666:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12667:         if ($1 >= 10.0) {
                   12668:             $webconfdir = '/etc/apache2';
                   12669:         }
                   12670:     }
1.1172.2.17  raeburn  12671:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12672:     my (%chksum,%revnum);
                   12673:     if (ref($lines) eq 'ARRAY') {
                   12674:         chomp(@{$lines});
1.1172.2.34  raeburn  12675:         my $version = shift(@{$lines});
                   12676:         if ($version eq $release) {
1.1172.2.17  raeburn  12677:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12678:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12679:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12680:                     if ($webconfdir eq '/etc/apache2') {
                   12681:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12682:                     }
                   12683:                 }
1.1172.2.34  raeburn  12684:                 $chksum{$file} = $shasum;
                   12685:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12686:             }
                   12687:             if (ref($hashref) eq 'HASH') {
                   12688:                 %{$hashref} = (
                   12689:                                 sums     => \%chksum,
                   12690:                                 versions => \%revnum,
                   12691:                               );
                   12692:             }
                   12693:         }
                   12694:     }
1.869     albertel 12695:     return;
1.852     albertel 12696: }
1.1172.2.17  raeburn  12697: 
                   12698: sub fetch_dns_checksums {
                   12699:     my %checksums;
1.1172.2.34  raeburn  12700:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12701:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12702:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12703:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12704:              \%checksums);
                   12705:     return \%checksums;
                   12706: }
                   12707: 
1.327     albertel 12708: # ------------------------------------------------------------ Read domain file
                   12709: {
1.852     albertel 12710:     my $loaded;
1.846     albertel 12711:     my %domain;
                   12712: 
1.852     albertel 12713:     sub parse_domain_tab {
                   12714: 	my ($lines) = @_;
                   12715: 	foreach my $line (@$lines) {
                   12716: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12717: 
1.846     albertel 12718: 	    chomp($line);
1.852     albertel 12719: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12720: 	    my %this_domain;
                   12721: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12722: 			       'lang_def', 'city', 'longi', 'lati',
                   12723: 			       'primary') {
                   12724: 		$this_domain{$field} = shift(@elements);
                   12725: 	    }
                   12726: 	    $domain{$name} = \%this_domain;
1.852     albertel 12727: 	}
                   12728:     }
1.864     albertel 12729: 
                   12730:     sub reset_domain_info {
                   12731: 	undef($loaded);
                   12732: 	undef(%domain);
                   12733:     }
                   12734: 
1.852     albertel 12735:     sub load_domain_tab {
1.1172.2.70  raeburn  12736: 	my ($ignore_cache,$nocache) = @_;
                   12737: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12738: 	my $fh;
1.1172.2.96  raeburn  12739: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 12740: 	    my @lines = <$fh>;
                   12741: 	    &parse_domain_tab(\@lines);
1.448     albertel 12742: 	}
1.852     albertel 12743: 	close($fh);
                   12744: 	$loaded = 1;
1.327     albertel 12745:     }
1.846     albertel 12746: 
                   12747:     sub domain {
1.852     albertel 12748: 	&load_domain_tab() if (!$loaded);
                   12749: 
1.846     albertel 12750: 	my ($name,$what) = @_;
                   12751: 	return if ( !exists($domain{$name}) );
                   12752: 
                   12753: 	if (!$what) {
                   12754: 	    return $domain{$name}{'description'};
                   12755: 	}
                   12756: 	return $domain{$name}{$what};
                   12757:     }
1.974     raeburn  12758: 
                   12759:     sub domain_info {
                   12760:         &load_domain_tab() if (!$loaded);
                   12761:         return %domain;
                   12762:     }
                   12763: 
1.327     albertel 12764: }
                   12765: 
                   12766: 
1.1       albertel 12767: # ------------------------------------------------------------- Read hosts file
                   12768: {
1.838     albertel 12769:     my %hostname;
1.844     albertel 12770:     my %hostdom;
1.845     albertel 12771:     my %libserv;
1.852     albertel 12772:     my $loaded;
1.888     albertel 12773:     my %name_to_host;
1.1074    raeburn  12774:     my %internetdom;
1.1107    raeburn  12775:     my %LC_dns_serv;
1.852     albertel 12776: 
                   12777:     sub parse_hosts_tab {
                   12778: 	my ($file) = @_;
                   12779: 	foreach my $configline (@$file) {
                   12780: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12781:             chomp($configline);
                   12782: 	    if ($configline =~ /^\^/) {
                   12783:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12784:                     $LC_dns_serv{$1} = 1;
                   12785:                 }
                   12786:                 next;
                   12787:             }
1.1074    raeburn  12788: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12789: 	    $name=~s/\s//g;
                   12790: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  12791:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   12792:                     my $curr = $hostname{$id};
                   12793:                     my $skip;
                   12794:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   12795:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   12796:                             $skip = 1;
                   12797:                         } else {
                   12798:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   12799:                         }
                   12800:                     }
                   12801:                     unless ($skip) {
                   12802:                         push(@{$name_to_host{$name}},$id);
                   12803:                     }
                   12804:                 } else {
                   12805:                     push(@{$name_to_host{$name}},$id);
                   12806:                 }
1.852     albertel 12807: 		$hostname{$id}=$name;
                   12808: 		$hostdom{$id}=$domain;
                   12809: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12810:                 if (defined($protocol)) {
                   12811:                     if ($protocol eq 'https') {
                   12812:                         $protocol{$id} = $protocol;
                   12813:                     } else {
                   12814:                         $protocol{$id} = 'http'; 
                   12815:                     }
1.968     raeburn  12816:                 } else {
1.969     raeburn  12817:                     $protocol{$id} = 'http';
1.968     raeburn  12818:                 }
1.1074    raeburn  12819:                 if (defined($intdom)) {
                   12820:                     $internetdom{$id} = $intdom;
                   12821:                 }
1.852     albertel 12822: 	    }
                   12823: 	}
                   12824:     }
1.864     albertel 12825:     
                   12826:     sub reset_hosts_info {
1.897     albertel 12827: 	&purge_remembered();
1.864     albertel 12828: 	&reset_domain_info();
                   12829: 	&reset_hosts_ip_info();
1.892     albertel 12830: 	undef(%name_to_host);
1.864     albertel 12831: 	undef(%hostname);
                   12832: 	undef(%hostdom);
                   12833: 	undef(%libserv);
                   12834: 	undef($loaded);
                   12835:     }
1.1       albertel 12836: 
1.852     albertel 12837:     sub load_hosts_tab {
1.1172.2.70  raeburn  12838: 	my ($ignore_cache,$nocache) = @_;
                   12839: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  12840: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 12841: 	my @config = <$config>;
                   12842: 	&parse_hosts_tab(\@config);
                   12843: 	close($config);
                   12844: 	$loaded=1;
1.1       albertel 12845:     }
1.852     albertel 12846: 
1.838     albertel 12847:     sub hostname {
1.852     albertel 12848: 	&load_hosts_tab() if (!$loaded);
                   12849: 
1.838     albertel 12850: 	my ($lonid) = @_;
                   12851: 	return $hostname{$lonid};
                   12852:     }
1.845     albertel 12853: 
1.838     albertel 12854:     sub all_hostnames {
1.852     albertel 12855: 	&load_hosts_tab() if (!$loaded);
                   12856: 
1.838     albertel 12857: 	return %hostname;
                   12858:     }
1.845     albertel 12859: 
1.888     albertel 12860:     sub all_names {
1.1172.2.70  raeburn  12861:         my ($ignore_cache,$nocache) = @_;
                   12862: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12863: 
                   12864: 	return %name_to_host;
                   12865:     }
                   12866: 
1.974     raeburn  12867:     sub all_host_domain {
                   12868:         &load_hosts_tab() if (!$loaded);
                   12869:         return %hostdom;
                   12870:     }
                   12871: 
1.845     albertel 12872:     sub is_library {
1.852     albertel 12873: 	&load_hosts_tab() if (!$loaded);
                   12874: 
1.845     albertel 12875: 	return exists($libserv{$_[0]});
                   12876:     }
                   12877: 
                   12878:     sub all_library {
1.852     albertel 12879: 	&load_hosts_tab() if (!$loaded);
                   12880: 
1.845     albertel 12881: 	return %libserv;
                   12882:     }
                   12883: 
1.1062    droeschl 12884:     sub unique_library {
                   12885: 	#2x reverse removes all hostnames that appear more than once
                   12886:         my %unique = reverse &all_library();
                   12887:         return reverse %unique;
                   12888:     }
                   12889: 
1.841     albertel 12890:     sub get_servers {
1.852     albertel 12891: 	&load_hosts_tab() if (!$loaded);
                   12892: 
1.841     albertel 12893: 	my ($domain,$type) = @_;
                   12894: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12895: 	                                          : %hostname;
                   12896: 	my %result;
1.842     albertel 12897: 	if (ref($domain) eq 'ARRAY') {
                   12898: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12899: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12900: 		    $result{$host} = $hostname;
                   12901: 		}
                   12902: 	    }
                   12903: 	} else {
                   12904: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12905: 		if ($hostdom{$host} eq $domain) {
                   12906: 		    $result{$host} = $hostname;
                   12907: 		}
1.841     albertel 12908: 	    }
                   12909: 	}
                   12910: 	return %result;
                   12911:     }
1.845     albertel 12912: 
1.1062    droeschl 12913:     sub get_unique_servers {
                   12914:         my %unique = reverse &get_servers(@_);
                   12915: 	return reverse %unique;
                   12916:     }
                   12917: 
1.844     albertel 12918:     sub host_domain {
1.852     albertel 12919: 	&load_hosts_tab() if (!$loaded);
                   12920: 
1.844     albertel 12921: 	my ($lonid) = @_;
                   12922: 	return $hostdom{$lonid};
                   12923:     }
                   12924: 
1.841     albertel 12925:     sub all_domains {
1.852     albertel 12926: 	&load_hosts_tab() if (!$loaded);
                   12927: 
1.841     albertel 12928: 	my %seen;
                   12929: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12930: 	return @uniq;
                   12931:     }
1.1074    raeburn  12932: 
                   12933:     sub internet_dom {
                   12934:         &load_hosts_tab() if (!$loaded);
                   12935: 
                   12936:         my ($lonid) = @_;
                   12937:         return $internetdom{$lonid};
                   12938:     }
1.1107    raeburn  12939: 
                   12940:     sub is_LC_dns {
                   12941:         &load_hosts_tab() if (!$loaded);
                   12942: 
                   12943:         my ($hostname) = @_;
                   12944:         return exists($LC_dns_serv{$hostname});
                   12945:     }
                   12946: 
1.1       albertel 12947: }
                   12948: 
1.847     albertel 12949: { 
                   12950:     my %iphost;
1.856     albertel 12951:     my %name_to_ip;
                   12952:     my %lonid_to_ip;
1.869     albertel 12953: 
1.847     albertel 12954:     sub get_hosts_from_ip {
                   12955: 	my ($ip) = @_;
                   12956: 	my %iphosts = &get_iphost();
                   12957: 	if (ref($iphosts{$ip})) {
                   12958: 	    return @{$iphosts{$ip}};
                   12959: 	}
                   12960: 	return;
1.839     albertel 12961:     }
1.864     albertel 12962:     
                   12963:     sub reset_hosts_ip_info {
                   12964: 	undef(%iphost);
                   12965: 	undef(%name_to_ip);
                   12966: 	undef(%lonid_to_ip);
                   12967:     }
1.856     albertel 12968: 
                   12969:     sub get_host_ip {
                   12970: 	my ($lonid) = @_;
                   12971: 	if (exists($lonid_to_ip{$lonid})) {
                   12972: 	    return $lonid_to_ip{$lonid};
                   12973: 	}
                   12974: 	my $name=&hostname($lonid);
                   12975:    	my $ip = gethostbyname($name);
                   12976: 	return if (!$ip || length($ip) ne 4);
                   12977: 	$ip=inet_ntoa($ip);
                   12978: 	$name_to_ip{$name}   = $ip;
                   12979: 	$lonid_to_ip{$lonid} = $ip;
                   12980: 	return $ip;
                   12981:     }
1.847     albertel 12982:     
                   12983:     sub get_iphost {
1.1172.2.70  raeburn  12984: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 12985: 
1.869     albertel 12986: 	if (!$ignore_cache) {
                   12987: 	    if (%iphost) {
                   12988: 		return %iphost;
                   12989: 	    }
                   12990: 	    my ($ip_info,$cached)=
                   12991: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12992: 	    if ($cached) {
                   12993: 		%iphost      = %{$ip_info->[0]};
                   12994: 		%name_to_ip  = %{$ip_info->[1]};
                   12995: 		%lonid_to_ip = %{$ip_info->[2]};
                   12996: 		return %iphost;
                   12997: 	    }
                   12998: 	}
1.894     albertel 12999: 
                   13000: 	# get yesterday's info for fallback
                   13001: 	my %old_name_to_ip;
                   13002: 	my ($ip_info,$cached)=
                   13003: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13004: 	if ($cached) {
                   13005: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13006: 	}
                   13007: 
1.1172.2.70  raeburn  13008: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13009: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13010: 	    my $ip;
                   13011: 	    if (!exists($name_to_ip{$name})) {
                   13012: 		$ip = gethostbyname($name);
                   13013: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13014: 		    if (defined($old_name_to_ip{$name})) {
                   13015: 			$ip = $old_name_to_ip{$name};
                   13016: 			&logthis("Can't find $name defaulting to old $ip");
                   13017: 		    } else {
                   13018: 			&logthis("Name $name no IP found");
                   13019: 			next;
                   13020: 		    }
                   13021: 		} else {
                   13022: 		    $ip=inet_ntoa($ip);
1.847     albertel 13023: 		}
                   13024: 		$name_to_ip{$name} = $ip;
                   13025: 	    } else {
                   13026: 		$ip = $name_to_ip{$name};
1.653     albertel 13027: 	    }
1.888     albertel 13028: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13029: 		$lonid_to_ip{$id} = $ip;
                   13030: 	    }
                   13031: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13032: 	}
1.1172.2.70  raeburn  13033:         unless ($nocache) {
                   13034: 	    &do_cache_new('iphost','iphost',
                   13035: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13036: 		          48*60*60);
                   13037:         }
1.869     albertel 13038: 
1.847     albertel 13039: 	return %iphost;
1.598     albertel 13040:     }
                   13041: 
1.992     raeburn  13042:     #
                   13043:     #  Given a DNS returns the loncapa host name for that DNS 
                   13044:     # 
                   13045:     sub host_from_dns {
                   13046:         my ($dns) = @_;
                   13047:         my @hosts;
                   13048:         my $ip;
                   13049: 
1.993     raeburn  13050:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13051:             $ip = $name_to_ip{$dns};
                   13052:         }
                   13053:         if (!$ip) {
                   13054:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13055:             if (length($ip) == 4) { 
                   13056: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13057:             }
                   13058:         }
                   13059:         if ($ip) {
                   13060: 	    @hosts = get_hosts_from_ip($ip);
                   13061: 	    return $hosts[0];
                   13062:         }
                   13063:         return undef;
1.986     foxr     13064:     }
1.992     raeburn  13065: 
1.1074    raeburn  13066:     sub get_internet_names {
                   13067:         my ($lonid) = @_;
                   13068:         return if ($lonid eq '');
                   13069:         my ($idnref,$cached)=
                   13070:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13071:         if ($cached) {
                   13072:             return $idnref;
                   13073:         }
                   13074:         my $ip = &get_host_ip($lonid);
                   13075:         my @hosts = &get_hosts_from_ip($ip);
                   13076:         my %iphost = &get_iphost();
                   13077:         my (@idns,%seen);
                   13078:         foreach my $id (@hosts) {
                   13079:             my $dom = &host_domain($id);
                   13080:             my $prim_id = &domain($dom,'primary');
                   13081:             my $prim_ip = &get_host_ip($prim_id);
                   13082:             next if ($seen{$prim_ip});
                   13083:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13084:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13085:                     my $intdom = &internet_dom($id);
                   13086:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13087:                         push(@idns,$intdom);
                   13088:                     }
                   13089:                 }
                   13090:             }
                   13091:             $seen{$prim_ip} = 1;
                   13092:         }
1.1172.2.23  raeburn  13093:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13094:     }
                   13095: 
1.986     foxr     13096: }
                   13097: 
1.1079    raeburn  13098: sub all_loncaparevs {
1.1172.2.39  raeburn  13099:     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  13100: }
                   13101: 
1.1172.2.27  raeburn  13102: # ------------------------------------------------------- Read loncaparev table
                   13103: {
                   13104:     sub load_loncaparevs {
                   13105:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13106:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13107:                 while (my $configline=<$config>) {
                   13108:                     chomp($configline);
                   13109:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13110:                     $loncaparevs{$hostid}=$loncaparev;
                   13111:                 }
                   13112:                 close($config);
                   13113:             }
                   13114:         }
                   13115:     }
                   13116: }
                   13117: 
                   13118: # ----------------------------------------------------- Read serverhostID table
                   13119: {
                   13120:     sub load_serverhomeIDs {
                   13121:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13122:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13123:                 while (my $configline=<$config>) {
                   13124:                     chomp($configline);
                   13125:                     my ($name,$id)=split(/:/,$configline);
                   13126:                     $serverhomeIDs{$name}=$id;
                   13127:                 }
                   13128:                 close($config);
                   13129:             }
                   13130:         }
                   13131:     }
                   13132: }
                   13133: 
                   13134: 
1.862     albertel 13135: BEGIN {
                   13136: 
                   13137: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13138:     unless ($readit) {
                   13139: {
                   13140:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13141:     %perlvar = (%perlvar,%{$configvars});
                   13142: }
                   13143: 
                   13144: 
1.1       albertel 13145: # ------------------------------------------------------ Read spare server file
                   13146: {
1.1172.2.96  raeburn  13147:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13148: 
                   13149:     while (my $configline=<$config>) {
                   13150:        chomp($configline);
1.284     matthew  13151:        if ($configline) {
1.784     albertel 13152: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13153: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13154: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13155:        }
                   13156:     }
1.448     albertel 13157:     close($config);
1.1       albertel 13158: }
1.11      www      13159: # ------------------------------------------------------------ Read permissions
                   13160: {
1.1172.2.96  raeburn  13161:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13162: 
                   13163:     while (my $configline=<$config>) {
1.448     albertel 13164: 	chomp($configline);
                   13165: 	if ($configline) {
                   13166: 	    my ($role,$perm)=split(/ /,$configline);
                   13167: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13168: 	}
1.11      www      13169:     }
1.448     albertel 13170:     close($config);
1.11      www      13171: }
                   13172: 
                   13173: # -------------------------------------------- Read plain texts for permissions
                   13174: {
1.1172.2.96  raeburn  13175:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13176: 
                   13177:     while (my $configline=<$config>) {
1.448     albertel 13178: 	chomp($configline);
                   13179: 	if ($configline) {
1.742     raeburn  13180: 	    my ($short,@plain)=split(/:/,$configline);
                   13181:             %{$prp{$short}} = ();
                   13182: 	    if (@plain > 0) {
                   13183:                 $prp{$short}{'std'} = $plain[0];
                   13184:                 for (my $i=1; $i<@plain; $i++) {
                   13185:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13186:                 }
                   13187:             }
1.448     albertel 13188: 	}
1.135     www      13189:     }
1.448     albertel 13190:     close($config);
1.135     www      13191: }
                   13192: 
                   13193: # ---------------------------------------------------------- Read package table
                   13194: {
1.1172.2.96  raeburn  13195:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13196: 
                   13197:     while (my $configline=<$config>) {
1.483     albertel 13198: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13199: 	chomp($configline);
                   13200: 	my ($short,$plain)=split(/:/,$configline);
                   13201: 	my ($pack,$name)=split(/\&/,$short);
                   13202: 	if ($plain ne '') {
                   13203: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13204: 	    $packagetab{$short}=$plain; 
                   13205: 	}
1.11      www      13206:     }
1.448     albertel 13207:     close($config);
1.329     matthew  13208: }
                   13209: 
1.1172.2.27  raeburn  13210: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13211: 
1.1172.2.27  raeburn  13212: &load_loncaparevs();
                   13213: 
                   13214: # ------------------------------------------------------- Read serverhostID table
                   13215: 
                   13216: &load_serverhomeIDs();
1.1074    raeburn  13217: 
1.1172.2.27  raeburn  13218: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13219: {
                   13220:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13221:     if (-e $file) {
                   13222:         my $parser = HTML::LCParser->new($file);
                   13223:         while (my $token = $parser->get_token()) {
                   13224:             if ($token->[0] eq 'S') {
                   13225:                 my $item = $token->[1];
                   13226:                 my $name = $token->[2]{'name'};
                   13227:                 my $value = $token->[2]{'value'};
                   13228:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13229:                     my $release = $parser->get_text();
                   13230:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13231:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13232:                 }
                   13233:             }
                   13234:         }
                   13235:     }
1.1073    raeburn  13236: }
                   13237: 
1.1138    raeburn  13238: # ---------------------------------------------------------- Read managers table
                   13239: {
                   13240:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  13241:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13242:             while (my $configline=<$config>) {
                   13243:                 chomp($configline);
                   13244:                 next if ($configline =~ /^\#/);
                   13245:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13246:                     $managerstab{$configline} = 1;
                   13247:                 }
                   13248:             }
                   13249:             close($config);
                   13250:         }
                   13251:     }
                   13252: }
                   13253: 
1.329     matthew  13254: # ------------- set up temporary directory
                   13255: {
1.1117    foxr     13256:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13257: 
1.11      www      13258: }
                   13259: 
1.794     albertel 13260: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13261: 				'compress_threshold'=> 20_000,
                   13262:  			        });
1.185     www      13263: 
1.281     www      13264: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13265: $dumpcount=0;
1.958     www      13266: $locknum=0;
1.22      www      13267: 
1.163     harris41 13268: &logtouch();
1.672     albertel 13269: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13270: $readit=1;
1.564     albertel 13271:     {
                   13272: 	use integer;
                   13273: 	my $test=(2**32)+1;
1.568     albertel 13274: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13275: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13276:     }
1.195     www      13277: }
1.1       albertel 13278: }
1.179     www      13279: 
1.1       albertel 13280: 1;
1.191     harris41 13281: __END__
                   13282: 
1.243     albertel 13283: =pod
                   13284: 
1.191     harris41 13285: =head1 NAME
                   13286: 
1.243     albertel 13287: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13288: 
                   13289: =head1 SYNOPSIS
                   13290: 
1.243     albertel 13291: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13292: 
                   13293:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13294: 
1.243     albertel 13295: Common parameters:
                   13296: 
                   13297: =over 4
                   13298: 
                   13299: =item *
                   13300: 
                   13301: $uname : an internal username (if $cname expecting a course Id specifically)
                   13302: 
                   13303: =item *
                   13304: 
                   13305: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13306: 
                   13307: =item *
                   13308: 
                   13309: $symb : a resource instance identifier
                   13310: 
                   13311: =item *
                   13312: 
                   13313: $namespace : the name of a .db file that contains the data needed or
                   13314: being set.
                   13315: 
                   13316: =back
                   13317: 
1.394     bowersj2 13318: =head1 OVERVIEW
1.191     harris41 13319: 
1.394     bowersj2 13320: lonnet provides subroutines which interact with the
                   13321: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13322: about classes, users, and resources.
1.243     albertel 13323: 
                   13324: For many of these objects you can also use this to store data about
                   13325: them or modify them in various ways.
1.191     harris41 13326: 
1.394     bowersj2 13327: =head2 Symbs
1.191     harris41 13328: 
1.394     bowersj2 13329: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13330: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13331: map, the resource number of the resource in the map, and the URL of
                   13332: the resource itself. The latter is somewhat redundant, but might help
                   13333: if maps change.
                   13334: 
                   13335: An example is
                   13336: 
                   13337:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13338: 
                   13339: The respective map entry is
                   13340: 
                   13341:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13342:   title="Problem 2">
                   13343:  </resource>
                   13344: 
                   13345: Symbs are used by the random number generator, as well as to store and
                   13346: restore data specific to a certain instance of for example a problem.
                   13347: 
                   13348: =head2 Storing And Retrieving Data
                   13349: 
                   13350: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13351: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13352: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13353: is is the non-critical message twin of cstore. These functions are for
                   13354: handlers to store a perl hash to a user's permanent data space in an
                   13355: easy manner, and to retrieve it again on another call. It is expected
                   13356: that a handler would use this once at the beginning to retrieve data,
                   13357: and then again once at the end to send only the new data back.
                   13358: 
                   13359: The data is stored in the user's data directory on the user's
                   13360: homeserver under the ID of the course.
                   13361: 
                   13362: The hash that is returned by restore will have all of the previous
                   13363: value for all of the elements of the hash.
                   13364: 
                   13365: Example:
                   13366: 
                   13367:  #creating a hash
                   13368:  my %hash;
                   13369:  $hash{'foo'}='bar';
                   13370: 
                   13371:  #storing it
                   13372:  &Apache::lonnet::cstore(\%hash);
                   13373: 
                   13374:  #changing a value
                   13375:  $hash{'foo'}='notbar';
                   13376: 
                   13377:  #adding a new value
                   13378:  $hash{'bar'}='foo';
                   13379:  &Apache::lonnet::cstore(\%hash);
                   13380: 
                   13381:  #retrieving the hash
                   13382:  my %history=&Apache::lonnet::restore();
                   13383: 
                   13384:  #print the hash
                   13385:  foreach my $key (sort(keys(%history))) {
                   13386:    print("\%history{$key} = $history{$key}");
                   13387:  }
                   13388: 
                   13389: Will print out:
1.191     harris41 13390: 
1.394     bowersj2 13391:  %history{1:foo} = bar
                   13392:  %history{1:keys} = foo:timestamp
                   13393:  %history{1:timestamp} = 990455579
                   13394:  %history{2:bar} = foo
                   13395:  %history{2:foo} = notbar
                   13396:  %history{2:keys} = foo:bar:timestamp
                   13397:  %history{2:timestamp} = 990455580
                   13398:  %history{bar} = foo
                   13399:  %history{foo} = notbar
                   13400:  %history{timestamp} = 990455580
                   13401:  %history{version} = 2
                   13402: 
                   13403: Note that the special hash entries C<keys>, C<version> and
                   13404: C<timestamp> were added to the hash. C<version> will be equal to the
                   13405: total number of versions of the data that have been stored. The
                   13406: C<timestamp> attribute will be the UNIX time the hash was
                   13407: stored. C<keys> is available in every historical section to list which
                   13408: keys were added or changed at a specific historical revision of a
                   13409: hash.
                   13410: 
                   13411: B<Warning>: do not store the hash that restore returns directly. This
                   13412: will cause a mess since it will restore the historical keys as if the
                   13413: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13414: 
1.394     bowersj2 13415: Calling convention:
1.191     harris41 13416: 
1.1172.2.27  raeburn  13417:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13418:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13419: 
1.394     bowersj2 13420: For more detailed information, see lonnet specific documentation.
1.191     harris41 13421: 
1.394     bowersj2 13422: =head1 RETURN MESSAGES
1.191     harris41 13423: 
1.394     bowersj2 13424: =over 4
1.191     harris41 13425: 
1.394     bowersj2 13426: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13427: 
1.394     bowersj2 13428: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13429: when the connection is brought back up
1.191     harris41 13430: 
1.394     bowersj2 13431: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13432: for later delivery
1.191     harris41 13433: 
1.967     bisitz   13434: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13435: 
1.394     bowersj2 13436: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13437: that was requested
1.191     harris41 13438: 
1.243     albertel 13439: =back
1.191     harris41 13440: 
1.243     albertel 13441: =head1 PUBLIC SUBROUTINES
1.191     harris41 13442: 
1.243     albertel 13443: =head2 Session Environment Functions
1.191     harris41 13444: 
1.243     albertel 13445: =over 4
1.191     harris41 13446: 
1.394     bowersj2 13447: =item * 
                   13448: X<appenv()>
1.949     raeburn  13449: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13450: the user envirnoment file, and will be restored for each access this
1.620     albertel 13451: user makes during this session, also modifies the %env for the current
1.949     raeburn  13452: process. Optional rolesarrayref - if defined contains a reference to an array
                   13453: of roles which are exempt from the restriction on modifying user.role entries 
                   13454: in the user's environment.db and in %env.    
1.191     harris41 13455: 
                   13456: =item *
1.394     bowersj2 13457: X<delenv()>
1.987     raeburn  13458: B<delenv($delthis,$regexp)>: removes all items from the session
                   13459: environment file that begin with $delthis. If the 
                   13460: optional second arg - $regexp - is true, $delthis is treated as a 
                   13461: regular expression, otherwise \Q$delthis\E is used. 
                   13462: The values are also deleted from the current processes %env.
1.191     harris41 13463: 
1.795     albertel 13464: =item * get_env_multiple($name) 
                   13465: 
                   13466: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13467: values may be defined and end up as an array ref.
                   13468: 
                   13469: returns an array of values
                   13470: 
1.243     albertel 13471: =back
                   13472: 
                   13473: =head2 User Information
1.191     harris41 13474: 
1.243     albertel 13475: =over 4
1.191     harris41 13476: 
                   13477: =item *
1.394     bowersj2 13478: X<queryauthenticate()>
                   13479: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13480: authentication scheme
                   13481: 
                   13482: =item *
1.394     bowersj2 13483: X<authenticate()>
1.1073    raeburn  13484: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13485: authenticate user from domain's lib servers (first use the current
                   13486: one). C<$upass> should be the users password.
1.1073    raeburn  13487: $checkdefauth is optional (value is 1 if a check should be made to
                   13488:    authenticate user using default authentication method, and allow
                   13489:    account creation if username does not have account in the domain).
                   13490: $clientcancheckhost is optional (value is 1 if checking whether the
                   13491:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13492: 
                   13493: =item *
1.394     bowersj2 13494: X<homeserver()>
                   13495: B<homeserver($uname,$udom)>: find the server which has
                   13496: the user's directory and files (there must be only one), this caches
                   13497: the answer, and also caches if there is a borken connection.
1.191     harris41 13498: 
                   13499: =item *
1.394     bowersj2 13500: X<idget()>
                   13501: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13502: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13503: username, and only 1 username per ID in a specific domain) (returns
                   13504: hash: id=>name,id=>name)
1.191     harris41 13505: 
                   13506: =item *
1.394     bowersj2 13507: X<idrget()>
                   13508: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13509: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13510: 
                   13511: =item *
1.394     bowersj2 13512: X<idput()>
                   13513: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13514: 
                   13515: =item *
1.394     bowersj2 13516: X<rolesinit()>
1.1169    droeschl 13517: B<rolesinit($udom,$username)>: get user privileges.
                   13518: returns user role, first access and timer interval hashes
1.243     albertel 13519: 
                   13520: =item *
1.1171    droeschl 13521: X<privileged()>
                   13522: B<privileged($username,$domain)>: returns a true if user has a
                   13523: privileged and active role (i.e. su or dc), false otherwise.
                   13524: 
                   13525: =item *
1.551     albertel 13526: X<getsection()>
                   13527: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13528: course $cname, return section name/number or '' for "not in course"
                   13529: and '-1' for "no section"
                   13530: 
                   13531: =item *
1.394     bowersj2 13532: X<userenvironment()>
                   13533: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13534: passed in @what from the requested user's environment, returns a hash
                   13535: 
1.858     raeburn  13536: =item * 
                   13537: X<userlog_query()>
1.859     albertel 13538: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13539: activity.log file. %filters defines filters applied when parsing the
                   13540: log file. These can be start or end timestamps, or the type of action
                   13541: - log to look for Login or Logout events, check for Checkin or
                   13542: Checkout, role for role selection. The response is in the form
                   13543: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13544: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13545: 
1.243     albertel 13546: =back
                   13547: 
                   13548: =head2 User Roles
                   13549: 
                   13550: =over 4
                   13551: 
                   13552: =item *
                   13553: 
1.1172.2.65  raeburn  13554: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13555: returns codes for allowed actions.
                   13556: 
                   13557: The first argument is required, all others are optional.
                   13558: 
                   13559: $priv is the privilege being checked.
                   13560: $uri contains additional information about what is being checked for access (e.g.,
                   13561: URL, course ID etc.).
                   13562: $symb is the unique resource instance identifier in a course; if needed,
                   13563: but not provided, it will be retrieved via a call to &symbread().
                   13564: $role is the role for which a priv is being checked (only used if priv is evb).
                   13565: $clientip is the user's IP address (only used when checking for access to portfolio
                   13566: files).
                   13567: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13568: prevents recursive calls to &allowed.
                   13569: 
1.243     albertel 13570:  F: full access
                   13571:  U,I,K: authentication modes (cxx only)
                   13572:  '': forbidden
                   13573:  1: user needs to choose course
                   13574:  2: browse allowed
1.766     albertel 13575:  A: passphrase authentication needed
1.1172.2.65  raeburn  13576:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13577: 
                   13578: =item *
                   13579: 
1.1172.2.13  raeburn  13580: constructaccess($url,$setpriv) : check for access to construction space URL
                   13581: 
                   13582: See if the owner domain and name in the URL match those in the
                   13583: expected environment.  If so, return three element list
                   13584: ($ownername,$ownerdomain,$ownerhome).
                   13585: 
                   13586: Otherwise return the null string.
                   13587: 
                   13588: If second argument 'setpriv' is true, it assigns the privileges,
                   13589: and returns the same three element list, unless the owner has
                   13590: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13591: in which case the null string is returned.
                   13592: 
                   13593: =item *
                   13594: 
1.1172.2.84  raeburn  13595: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13596: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13597: for system, domain, and course level. $uname and $udom are optional (current
                   13598: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13599: 
                   13600: =item *
                   13601: 
1.988     raeburn  13602: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13603: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13604: $type is Course (default) or Community.
1.988     raeburn  13605: If $forcedefault evaluates to true, text returned will be default 
                   13606: text for $type. Otherwise, if this is a course, the text returned 
                   13607: will be a custom name for the role (if defined in the course's 
                   13608: environment).  If no custom name is defined the default is returned.
                   13609:    
1.832     raeburn  13610: =item *
                   13611: 
1.1172.2.23  raeburn  13612: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13613: All arguments are optional. Returns a hash of a roles, either for
                   13614: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13615: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13616: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13617: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13618: For each key, value is set to colon-separated start and end times for
                   13619: the role.  If no username and domain are specified, will default to
1.934     raeburn  13620: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13621: of role statuses (active, future or previous), roles 
                   13622: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13623: to restrict the list of roles reported. If no array ref is 
                   13624: provided for types, will default to return only active roles.
1.834     albertel 13625: 
1.1172.2.13  raeburn  13626: =item *
                   13627: 
                   13628: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13629: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13630: 
                   13631: Additional optional arguments are: $type (if role checking is to be restricted
                   13632: to certain user status types -- previous (expired roles), active (currently
                   13633: available roles) or future (roles available in the future), and
                   13634: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13635: have active Domain Coordinator role in course's domain or in additional
                   13636: domains (specified in 'Domains to check for privileged users' in course
                   13637: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13638: 
                   13639: =item *
                   13640: 
                   13641: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13642: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13643: $possdomains and $possroles are optional array refs -- to domains to check and
                   13644: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13645: users' roles.db to check for a dc or su role in any domain. This can be
                   13646: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13647: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13648: this then allows &privileged_by_domain() to be used, which caches the identity
                   13649: of privileged users, eliminating the need for repeated calls to &dump().
                   13650: 
                   13651: =item *
                   13652: 
                   13653: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13654: where the outer hash keys are domains specified in the $possdomains array ref,
                   13655: next inner hash keys are privileged roles specified in the $roles array ref,
                   13656: and the innermost hash contains key = value pairs for username:domain = end:start
                   13657: for active or future "privileged" users with that role in that domain. To avoid
                   13658: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13659: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13660: 
1.243     albertel 13661: =back
                   13662: 
                   13663: =head2 User Modification
                   13664: 
                   13665: =over 4
                   13666: 
                   13667: =item *
                   13668: 
1.957     raeburn  13669: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13670: user for the level given by URL.  Optional start and end dates (leave empty
                   13671: string or zero for "no date")
1.191     harris41 13672: 
                   13673: =item *
                   13674: 
1.243     albertel 13675: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13676: change a users, password, possible return values are: ok,
                   13677: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13678: refused
1.191     harris41 13679: 
                   13680: =item *
                   13681: 
1.243     albertel 13682: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13683: 
                   13684: =item *
                   13685: 
1.1058    raeburn  13686: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13687:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13688: 
                   13689: will update user information (firstname,middlename,lastname,generation,
                   13690: permanentemail), and if forceid is true, student/employee ID also.
                   13691: A user's institutional affiliation(s) can also be updated.
                   13692: User information fields will not be overwritten with empty entries 
                   13693: unless the field is included in the $candelete array reference.
                   13694: This array is included when a single user is modified via "Manage Users",
                   13695: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13696: 
                   13697: =item *
                   13698: 
1.286     matthew  13699: modifystudent
                   13700: 
1.957     raeburn  13701: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13702: The course id is resolved based on the current user's environment.  
                   13703: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13704: associated with a course.
                   13705: 
1.297     matthew  13706: This call is essentially a wrapper for lonnet::modifyuser and
                   13707: lonnet::modify_student_enrollment
1.286     matthew  13708: 
                   13709: Inputs: 
                   13710: 
                   13711: =over 4
                   13712: 
1.957     raeburn  13713: =item B<$udom> Student's loncapa domain
1.286     matthew  13714: 
1.957     raeburn  13715: =item B<$uname> Student's loncapa login name
1.286     matthew  13716: 
1.964     bisitz   13717: =item B<$uid> Student/Employee ID
1.286     matthew  13718: 
1.957     raeburn  13719: =item B<$umode> Student's authentication mode
1.286     matthew  13720: 
1.957     raeburn  13721: =item B<$upass> Student's password
1.286     matthew  13722: 
1.957     raeburn  13723: =item B<$first> Student's first name
1.286     matthew  13724: 
1.957     raeburn  13725: =item B<$middle> Student's middle name
1.286     matthew  13726: 
1.957     raeburn  13727: =item B<$last> Student's last name
1.286     matthew  13728: 
1.957     raeburn  13729: =item B<$gene> Student's generation
1.286     matthew  13730: 
1.957     raeburn  13731: =item B<$usec> Student's section in course
1.286     matthew  13732: 
                   13733: =item B<$end> Unix time of the roles expiration
                   13734: 
                   13735: =item B<$start> Unix time of the roles start date
                   13736: 
                   13737: =item B<$forceid> If defined, allow $uid to be changed
                   13738: 
                   13739: =item B<$desiredhome> server to use as home server for student
                   13740: 
1.957     raeburn  13741: =item B<$email> Student's permanent e-mail address
                   13742: 
                   13743: =item B<$type> Type of enrollment (auto or manual)
                   13744: 
1.963     raeburn  13745: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13746: 
                   13747: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13748: 
1.963     raeburn  13749: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13750: 
1.963     raeburn  13751: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13752: 
1.1172.2.19  raeburn  13753: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13754: 
                   13755: =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  13756: 
1.286     matthew  13757: =back
1.297     matthew  13758: 
                   13759: =item *
                   13760: 
                   13761: modify_student_enrollment
                   13762: 
1.1172.2.31  raeburn  13763: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13764: 'role.request.course' must be defined for this function to proceed.
                   13765: 
                   13766: Inputs:
                   13767: 
                   13768: =over 4
                   13769: 
1.1172.2.31  raeburn  13770: =item $udom, student's domain
1.297     matthew  13771: 
1.1172.2.31  raeburn  13772: =item $uname, student's name
1.297     matthew  13773: 
1.1172.2.31  raeburn  13774: =item $uid, student's user id
1.297     matthew  13775: 
1.1172.2.31  raeburn  13776: =item $first, student's first name
1.297     matthew  13777: 
                   13778: =item $middle
                   13779: 
                   13780: =item $last
                   13781: 
                   13782: =item $gene
                   13783: 
                   13784: =item $usec
                   13785: 
                   13786: =item $end
                   13787: 
                   13788: =item $start
                   13789: 
1.957     raeburn  13790: =item $type
                   13791: 
                   13792: =item $locktype
                   13793: 
                   13794: =item $cid
                   13795: 
                   13796: =item $selfenroll
                   13797: 
                   13798: =item $context
                   13799: 
1.1172.2.19  raeburn  13800: =item $credits, number of credits student will earn from this class
                   13801: 
1.1172.2.76  raeburn  13802: =item $instsec, institutional course section code for student
                   13803: 
1.297     matthew  13804: =back
                   13805: 
1.191     harris41 13806: 
                   13807: =item *
                   13808: 
1.243     albertel 13809: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13810: custom role; give a custom role to a user for the level given by URL.  Specify
                   13811: name and domain of role author, and role name
1.191     harris41 13812: 
                   13813: =item *
                   13814: 
1.243     albertel 13815: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13816: 
                   13817: =item *
                   13818: 
1.243     albertel 13819: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13820: 
                   13821: =back
                   13822: 
                   13823: =head2 Course Infomation
                   13824: 
                   13825: =over 4
1.191     harris41 13826: 
                   13827: =item *
                   13828: 
1.1118    foxr     13829: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13830: specified course id, including all environment settings for the
                   13831: course, the description of the course will be in the hash under the
                   13832: key 'description'
1.191     harris41 13833: 
1.1118    foxr     13834: $options is an optional parameter that if supplied is a hash reference that controls
                   13835: what how this function works.  It has the following key/values:
                   13836: 
                   13837: =over 4
                   13838: 
                   13839: =item freshen_cache
                   13840: 
                   13841: If defined, and the environment cache for the course is valid, it is 
                   13842: returned in the returned hash.
                   13843: 
                   13844: =item one_time
                   13845: 
                   13846: If defined, the last cache time is set to _now_
                   13847: 
                   13848: =item user
                   13849: 
                   13850: If defined, the supplied username is used instead of the current user.
                   13851: 
                   13852: 
                   13853: =back
                   13854: 
1.191     harris41 13855: =item *
                   13856: 
1.624     albertel 13857: resdata($name,$domain,$type,@which) : request for current parameter
                   13858: setting for a specific $type, where $type is either 'course' or 'user',
                   13859: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  13860: answers for 10 minutes.
1.243     albertel 13861: 
1.877     foxr     13862: =item *
                   13863: 
                   13864: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13865: data base, returning a hash that is keyed by the resource name and has
                   13866: values that are the resource value.  I believe that the timestamps and
                   13867: versions are also returned.
                   13868: 
1.1172.2.31  raeburn  13869: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13870: supplemental content area. This routine caches the number of files for
                   13871: 10 minutes.
                   13872: 
1.243     albertel 13873: =back
                   13874: 
                   13875: =head2 Course Modification
                   13876: 
                   13877: =over 4
1.191     harris41 13878: 
                   13879: =item *
                   13880: 
1.243     albertel 13881: writecoursepref($courseid,%prefs) : write preferences (environment
                   13882: database) for a course
1.191     harris41 13883: 
                   13884: =item *
                   13885: 
1.1011    raeburn  13886: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13887: 
                   13888: =item *
                   13889: 
1.1038    raeburn  13890: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13891: 
1.1167    droeschl 13892: =item *
                   13893: 
                   13894: is_course($courseid), is_course($cdom, $cnum)
                   13895: 
                   13896: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13897: two component version $cdom, $cnum. It checks if the specified course exists.
                   13898: 
                   13899: Returns:
                   13900:     undef if the course doesn't exist, otherwise
                   13901:     in scalar context the combined courseid.
                   13902:     in list context the two components of the course identifier, domain and 
                   13903:     courseid.    
                   13904: 
1.243     albertel 13905: =back
                   13906: 
                   13907: =head2 Resource Subroutines
                   13908: 
                   13909: =over 4
1.191     harris41 13910: 
                   13911: =item *
                   13912: 
1.243     albertel 13913: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13914: 
                   13915: =item *
                   13916: 
1.243     albertel 13917: repcopy($filename) : subscribes to the requested file, and attempts to
                   13918: replicate from the owning library server, Might return
1.607     raeburn  13919: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13920: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13921: resource. Expects the local filesystem pathname
                   13922: (/home/httpd/html/res/....)
                   13923: 
                   13924: =back
                   13925: 
                   13926: =head2 Resource Information
                   13927: 
                   13928: =over 4
1.191     harris41 13929: 
                   13930: =item *
                   13931: 
1.1172.2.28  raeburn  13932: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13933: and returns the value of a variety of different possible values,
                   13934: $varname should be a request string, and the other parameters can be
                   13935: used to specify who and what one is asking about. Ordinarily, $cid 
                   13936: does not need to be specified, as it is retrived from 
                   13937: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13938: within lonuserstate::loadmap() when initializing a course, before
                   13939: $env{'request.course.id'} has been set, so it needs to be provided
                   13940: in that one case.
1.243     albertel 13941: 
                   13942: Possible values for $varname are environment.lastname (or other item
                   13943: from the envirnment hash), user.name (or someother aspect about the
                   13944: user), resource.0.maxtries (or some other part and parameter of a
                   13945: resource)
1.204     albertel 13946: 
                   13947: =item *
                   13948: 
1.243     albertel 13949: directcondval($number) : get current value of a condition; reads from a state
                   13950: string
1.204     albertel 13951: 
                   13952: =item *
                   13953: 
1.243     albertel 13954: condval($condidx) : value of condition index based on state
1.204     albertel 13955: 
                   13956: =item *
                   13957: 
1.243     albertel 13958: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13959: resource's metadata, $what should be either a specific key, or either
                   13960: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13961: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13962: 
                   13963: this function automatically caches all requests
1.191     harris41 13964: 
                   13965: =item *
                   13966: 
1.243     albertel 13967: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13968: network of library servers; returns file handle of where SQL and regex results
                   13969: will be stored for query
1.191     harris41 13970: 
                   13971: =item *
                   13972: 
1.1172.2.66  raeburn  13973: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   13974: return symbolic list entry (all arguments optional).
                   13975: 
                   13976: Args: filename is the filename (including path) for the file for which a symb
                   13977: is required; donotrecurse, if true will prevent calls to allowed() being made
                   13978: to check access status if more than one resource was found in the bighash
                   13979: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   13980: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   13981: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13982: cause possible symbs to be checked to determine if they are subject to content
                   13983: blocking, if so they will not be included as possible symbs; possibles is a
                   13984: ref to a hash, which, as a side effect, will be populated with all possible
                   13985: symbs (content blocking not tested).
                   13986: 
1.243     albertel 13987: returns the data handle
1.191     harris41 13988: 
                   13989: =item *
                   13990: 
1.1172.2.17  raeburn  13991: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13992: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13993: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13994: on failure, user must be in a course, as it assumes the existence of
                   13995: the course initial hash, and uses $env('request.course.id'}.  The third
                   13996: arg is an optional reference to a scalar.  If this arg is passed in the
                   13997: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13998: encrypted; otherwise it will be null.
1.243     albertel 13999: 
1.191     harris41 14000: =item *
                   14001: 
1.243     albertel 14002: symbclean($symb) : removes versions numbers from a symb, returns the
                   14003: cleaned symb
1.191     harris41 14004: 
                   14005: =item *
                   14006: 
1.243     albertel 14007: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14008: course map, user must be in a course for it to work.
1.191     harris41 14009: 
                   14010: =item *
                   14011: 
1.243     albertel 14012: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14013: 
                   14014: =item *
                   14015: 
1.243     albertel 14016: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14017: a random seed, all arguments are optional, if they aren't sent it uses the
                   14018: environment to derive them. Note: if symb isn't sent and it can't get one
                   14019: from &symbread it will use the current time as its return value
1.191     harris41 14020: 
                   14021: =item *
                   14022: 
1.243     albertel 14023: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14024: unfakeable, receipt
1.191     harris41 14025: 
                   14026: =item *
                   14027: 
1.620     albertel 14028: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14029: 
                   14030: =item *
                   14031: 
1.243     albertel 14032: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14033: 
                   14034: =item *
                   14035: 
1.243     albertel 14036: 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 14037: 
                   14038: =item *
                   14039: 
1.243     albertel 14040: 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 14041: 
                   14042: =item *
                   14043: 
1.243     albertel 14044: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14045: 
                   14046: =item *
                   14047: 
1.243     albertel 14048: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14049: forcing spreadsheet to reevaluate the resource scores next time.
                   14050: 
1.1172.2.13  raeburn  14051: =item *
                   14052: 
                   14053: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14054: when viewing in course context.
                   14055: 
                   14056:  input: six args -- filename (decluttered), course number, course domain,
                   14057:                     url, symb (if registered) and group (if this is a
                   14058:                     group item -- e.g., bulletin board, group page etc.).
                   14059: 
                   14060:  output: array of five scalars --
                   14061:          $cfile -- url for file editing if editable on current server
                   14062:          $home -- homeserver of resource (i.e., for author if published,
                   14063:                                           or course if uploaded.).
                   14064:          $switchserver --  1 if server switch will be needed.
                   14065:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14066:          $forceview -- 1 if icon/link should be to go to view mode
                   14067: 
                   14068: =item *
                   14069: 
                   14070: is_course_upload($file,$cnum,$cdom)
                   14071: 
                   14072: Used in course context to determine if current file was uploaded to
                   14073: the course (i.e., would be found in /userfiles/docs on the course's
                   14074: homeserver.
                   14075: 
                   14076:   input: 3 args -- filename (decluttered), course number and course domain.
                   14077:   output: boolean -- 1 if file was uploaded.
                   14078: 
1.243     albertel 14079: =back
                   14080: 
                   14081: =head2 Storing/Retreiving Data
                   14082: 
                   14083: =over 4
1.191     harris41 14084: 
                   14085: =item *
                   14086: 
1.1172.2.64  raeburn  14087: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14088: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14089: the remaining args aren't required and if they aren't passed or are '' they will
                   14090: be derived from the env (with the exception of $laststore, which is an
                   14091: optional arg used when a user's submission is stored in grading).
                   14092: $laststore is $version=$timestamp, where $version is the most recent version
                   14093: number retrieved for the corresponding $symb in the $namespace db file, and
                   14094: $timestamp is the timestamp for that transaction (UNIX time).
                   14095: $laststore is currently only passed when cstore() is called by
                   14096: structuretags::finalize_storage().
1.191     harris41 14097: 
                   14098: =item *
                   14099: 
1.1172.2.64  raeburn  14100: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14101: but uses critical subroutine
1.191     harris41 14102: 
                   14103: =item *
                   14104: 
1.243     albertel 14105: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14106: all args are optional
1.191     harris41 14107: 
                   14108: =item *
                   14109: 
1.717     albertel 14110: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14111: dumps the complete (or key matching regexp) namespace into a hash
                   14112: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14113: normally &store()ed into
                   14114: 
                   14115: $range should be either an integer '100' (give me the first 100
                   14116:                                            matching records)
                   14117:               or be  two integers sperated by a - with no spaces
                   14118:                  '30-50' (give me the 30th through the 50th matching
                   14119:                           records)
                   14120: 
                   14121: 
                   14122: =item *
                   14123: 
1.1172.2.59  raeburn  14124: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14125: replaces a &store() version of data with a replacement set of data
                   14126: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14127: reference. If $tolog is true, the transaction is logged in the courselog
                   14128: with an action=PUTSTORE.
1.717     albertel 14129: 
                   14130: =item *
                   14131: 
1.243     albertel 14132: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14133: works very similar to store/cstore, but all data is stored in a
                   14134: temporary location and can be reset using tmpreset, $storehash should
                   14135: be a hash reference, returns nothing on success
1.191     harris41 14136: 
                   14137: =item *
                   14138: 
1.243     albertel 14139: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14140: similar to restore, but all data is stored in a temporary location and
                   14141: can be reset using tmpreset. Returns a hash of values on success,
                   14142: error string otherwise.
1.191     harris41 14143: 
                   14144: =item *
                   14145: 
1.243     albertel 14146: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14147: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14148: 
                   14149: =item *
                   14150: 
1.243     albertel 14151: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14152: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14153: 
                   14154: =item *
                   14155: 
1.243     albertel 14156: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14157: namesp ($udom and $uname are optional)
1.191     harris41 14158: 
                   14159: =item *
                   14160: 
1.702     albertel 14161: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14162: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14163: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14164: 
1.702     albertel 14165: $range should be either an integer '100' (give me the first 100
                   14166:                                            matching records)
                   14167:               or be  two integers sperated by a - with no spaces
                   14168:                  '30-50' (give me the 30th through the 50th matching
                   14169:                           records)
1.449     matthew  14170: =item *
                   14171: 
                   14172: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14173: $store can be a scalar, an array reference, or if the amount to be 
                   14174: incremented is > 1, a hash reference.
                   14175: 
                   14176: ($udom and $uname are optional)
1.191     harris41 14177: 
                   14178: =item *
                   14179: 
1.243     albertel 14180: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14181: ($udom and $uname are optional)
1.191     harris41 14182: 
                   14183: =item *
                   14184: 
1.243     albertel 14185: cput($namespace,$storehash,$udom,$uname) : critical put
                   14186: ($udom and $uname are optional)
1.191     harris41 14187: 
                   14188: =item *
                   14189: 
1.748     albertel 14190: newput($namespace,$storehash,$udom,$uname) :
                   14191: 
                   14192: Attempts to store the items in the $storehash, but only if they don't
                   14193: currently exist, if this succeeds you can be certain that you have 
                   14194: successfully created a new key value pair in the $namespace db.
                   14195: 
                   14196: 
                   14197: Args:
                   14198:  $namespace: name of database to store values to
                   14199:  $storehash: hashref to store to the db
                   14200:  $udom: (optional) domain of user containing the db
                   14201:  $uname: (optional) name of user caontaining the db
                   14202: 
                   14203: Returns:
                   14204:  'ok' -> succeeded in storing all keys of $storehash
                   14205:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14206:                         least <key> already existed in the db (other
                   14207:                         requested keys may also already exist)
1.967     bisitz   14208:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14209:  'con_lost' -> unable to contact request server
                   14210:  'refused' -> action was not allowed by remote machine
                   14211: 
                   14212: 
                   14213: =item *
                   14214: 
1.243     albertel 14215: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14216: reference filled in from namesp (encrypts the return communication)
                   14217: ($udom and $uname are optional)
1.191     harris41 14218: 
                   14219: =item *
                   14220: 
1.243     albertel 14221: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14222: critical subroutine
                   14223: 
1.806     raeburn  14224: =item *
                   14225: 
1.860     raeburn  14226: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14227: array reference filled in from namespace found in domain level on either
                   14228: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14229: 
                   14230: =item *
                   14231: 
1.860     raeburn  14232: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14233: domain level either on specified domain server ($uhome) or primary domain 
                   14234: server ($udom and $uhome are optional)
1.806     raeburn  14235: 
1.943     raeburn  14236: =item * 
                   14237: 
1.1172.2.35  raeburn  14238: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14239: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14240: the target domain.
                   14241: 
                   14242: May also include additional key => value pairs for the following groups:
                   14243: 
                   14244: =over
                   14245: 
                   14246: =item
                   14247: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14248: 
                   14249: =over
                   14250: 
                   14251: =item defaultquota, authorquota
                   14252: 
                   14253: =back
                   14254: 
                   14255: =item
                   14256: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14257: portfolio for users).
                   14258: 
                   14259: =over
                   14260: 
                   14261: =item
                   14262: aboutme, blog, webdav, portfolio
                   14263: 
                   14264: =back
                   14265: 
                   14266: =item
                   14267: requestcourses: ability to request courses, and how requests are processed.
                   14268: 
                   14269: =over
                   14270: 
                   14271: =item
1.1172.2.37  raeburn  14272: official, unofficial, community, textbook
1.1172.2.35  raeburn  14273: 
                   14274: =back
                   14275: 
                   14276: =item
                   14277: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14278: 
                   14279: =over
                   14280: 
                   14281: =item
1.1172.2.44  raeburn  14282: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  14283: 
                   14284: =back
                   14285: 
                   14286: =item
                   14287: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14288: for course's uploaded content.
                   14289: 
                   14290: =over
                   14291: 
                   14292: =item
1.1172.2.68  raeburn  14293: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   14294: communityquota, textbookquota
1.1172.2.35  raeburn  14295: 
                   14296: =back
                   14297: 
                   14298: =item
                   14299: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14300: on your servers.
                   14301: 
                   14302: =over
                   14303: 
                   14304: =item
                   14305: remotesessions, hostedsessions
                   14306: 
                   14307: =back
                   14308: 
                   14309: =back
                   14310: 
                   14311: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14312: utility to create a configuration.db file on a domain's primary library server
                   14313: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14314: -- corresponding values are authentication type (internal, krb4, krb5,
                   14315: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   14316: will be available. Values are retrieved from cache (if current), unless the
                   14317: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14318: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14319: 
                   14320: Typical usage:
1.943     raeburn  14321: 
1.1172.2.35  raeburn  14322: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14323: 
1.243     albertel 14324: =back
                   14325: 
                   14326: =head2 Network Status Functions
                   14327: 
                   14328: =over 4
1.191     harris41 14329: 
                   14330: =item *
                   14331: 
1.1137    raeburn  14332: dirlist() : return directory list based on URI (first arg).
                   14333: 
                   14334: Inputs: 1 required, 5 optional.
                   14335: 
                   14336: =over
                   14337: 
                   14338: =item 
                   14339: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14340: 
                   14341: =item
                   14342: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14343: 
                   14344: =item
                   14345: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14346: 
                   14347: =item
                   14348: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14349: 
                   14350: =item
                   14351: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14352: 
                   14353: =item 
                   14354: $alternateRoot - path to prepend in place of path from $uri.
                   14355: 
                   14356: =back
                   14357: 
                   14358: Returns: Array of up to two items.
                   14359: 
                   14360: =over
                   14361: 
                   14362: a reference to an array of files/subdirectories
                   14363: 
                   14364: =over
                   14365: 
                   14366: Each element in the array of files/subdirectories is a & separated list of
                   14367: item name and the result of running stat on the item.  If dirlist was requested
                   14368: for a file instead of a directory, the item name will be ''. For a directory 
                   14369: listing, if the item is a metadata file, the element will end &N&M 
                   14370: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14371: default copyright set (1).  
                   14372: 
                   14373: =back
                   14374: 
                   14375: a scalar containing error condition (if encountered).
                   14376: 
                   14377: =over
                   14378: 
                   14379: =item 
                   14380: no_host (no homeserver identified for $username:$domain).
                   14381: 
                   14382: =item 
                   14383: no_such_host (server contacted for listing not identified as valid host).
                   14384: 
                   14385: =item 
                   14386: con_lost (connection to remote server failed).
                   14387: 
                   14388: =item 
                   14389: refused (invalid $username:$domain received on lond side).
                   14390: 
                   14391: =item 
                   14392: no_such_dir (directory at specified path on lond side does not exist). 
                   14393: 
                   14394: =item 
                   14395: empty (directory at specified path on lond side is empty).
                   14396: 
                   14397: =over
                   14398: 
                   14399: This is currently not encountered because the &ls3, &ls2, 
                   14400: &ls (_handler) routines on the lond side do not filter out
                   14401: . and .. from a directory listing. 
                   14402: 
                   14403: =back
                   14404: 
                   14405: =back
                   14406: 
                   14407: =back
1.191     harris41 14408: 
                   14409: =item *
                   14410: 
1.243     albertel 14411: spareserver() : find server with least workload from spare.tab
                   14412: 
1.986     foxr     14413: 
                   14414: =item *
                   14415: 
                   14416: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14417: if there is no corresponding loncapa host.
                   14418: 
1.243     albertel 14419: =back
                   14420: 
1.986     foxr     14421: 
1.243     albertel 14422: =head2 Apache Request
                   14423: 
                   14424: =over 4
1.191     harris41 14425: 
                   14426: =item *
                   14427: 
1.243     albertel 14428: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14429: localhost, posts hash
                   14430: 
                   14431: =back
                   14432: 
                   14433: =head2 Data to String to Data
                   14434: 
                   14435: =over 4
1.191     harris41 14436: 
                   14437: =item *
                   14438: 
1.243     albertel 14439: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14440: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14441: 
                   14442: =item *
                   14443: 
1.243     albertel 14444: hashref2str($hashref) : convert a hashref into a string complete with
                   14445: escaping and '=' and '&' separators, supports elements that are
                   14446: arrayrefs and hashrefs
1.191     harris41 14447: 
                   14448: =item *
                   14449: 
1.243     albertel 14450: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14451: with escaping and '&' separators, supports elements that are arrayrefs
                   14452: and hashrefs
1.191     harris41 14453: 
                   14454: =item *
                   14455: 
1.243     albertel 14456: str2hash($string) : convert string to hash using unescaping and
                   14457: splitting on '=' and '&', supports elements that are arrayrefs and
                   14458: hashrefs
1.191     harris41 14459: 
                   14460: =item *
                   14461: 
1.243     albertel 14462: str2array($string) : convert string to hash using unescaping and
                   14463: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14464: 
                   14465: =back
                   14466: 
                   14467: =head2 Logging Routines
                   14468: 
                   14469: 
                   14470: These routines allow one to make log messages in the lonnet.log and
                   14471: lonnet.perm logfiles.
1.191     harris41 14472: 
1.1119    foxr     14473: =over 4
                   14474: 
1.191     harris41 14475: =item *
                   14476: 
1.243     albertel 14477: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14478: 
                   14479: =item *
                   14480: 
1.243     albertel 14481: logthis() : append message to the normal lonnet.log file, it gets
                   14482: preiodically rolled over and deleted.
1.191     harris41 14483: 
                   14484: =item *
                   14485: 
1.243     albertel 14486: logperm() : append a permanent message to lonnet.perm.log, this log
                   14487: file never gets deleted by any automated portion of the system, only
                   14488: messages of critical importance should go in here.
                   14489: 
1.1119    foxr     14490: 
1.243     albertel 14491: =back
                   14492: 
                   14493: =head2 General File Helper Routines
                   14494: 
                   14495: =over 4
1.191     harris41 14496: 
                   14497: =item *
                   14498: 
1.481     raeburn  14499: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14500: (a) files in /uploaded
                   14501:   (i) If a local copy of the file exists - 
                   14502:       compares modification date of local copy with last-modified date for 
                   14503:       definitive version stored on home server for course. If local copy is 
                   14504:       stale, requests a new version from the home server and stores it. 
                   14505:       If the original has been removed from the home server, then local copy 
                   14506:       is unlinked.
                   14507:   (ii) If local copy does not exist -
                   14508:       requests the file from the home server and stores it. 
                   14509:   
                   14510:   If $caller is 'uploadrep':  
                   14511:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14512:     for request for files originally uploaded via DOCS. 
                   14513:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14514:   
                   14515:   Otherwise:
                   14516:      This indicates a call from the content generation phase of the request.
                   14517:      -  returns the entire contents of the file or -1.
                   14518:      
                   14519: (b) files in /res
                   14520:    - returns the entire contents of a file or -1; 
                   14521:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14522: 
1.712     albertel 14523: 
                   14524: =item *
                   14525: 
                   14526: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14527:                   reference
                   14528: 
                   14529: returns either a stat() list of data about the file or an empty list
                   14530: if the file doesn't exist or couldn't find out about it (connection
                   14531: problems or user unknown)
                   14532: 
1.191     harris41 14533: =item *
                   14534: 
1.243     albertel 14535: filelocation($dir,$file) : returns file system location of a file
                   14536: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14537: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14538: and a file of ../bob will become /a/bob)
1.191     harris41 14539: 
                   14540: =item *
                   14541: 
                   14542: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14543: filelocation except for hrefs
                   14544: 
                   14545: =item *
                   14546: 
1.1172.2.49  raeburn  14547: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14548: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14549: 
1.243     albertel 14550: =back
                   14551: 
1.608     albertel 14552: =head2 Usererfile file routines (/uploaded*)
                   14553: 
                   14554: =over 4
                   14555: 
                   14556: =item *
                   14557: 
                   14558: userfileupload(): main rotine for putting a file in a user or course's
                   14559:                   filespace, arguments are,
                   14560: 
1.620     albertel 14561:  formname - required - this is the name of the element in $env where the
1.608     albertel 14562:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14563:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14564:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14565:  context - if coursedoc, store the file in the course of the active role
                   14566:              of the current user; 
                   14567:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14568:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14569:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14570:          if undefined, it will be placed in "unknown"
                   14571: 
                   14572:  (This routine calls clean_filename() to remove any dangerous
                   14573:  characters from the filename, and then calls finuserfileupload() to
                   14574:  complete the transaction)
                   14575: 
                   14576:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14577:  and /adm/notfound.html if unsuccessful
                   14578: 
                   14579: =item *
                   14580: 
                   14581: clean_filename(): routine for cleaing a filename up for storage in
                   14582:                  userfile space, argument is:
                   14583: 
                   14584:  filename - proposed filename
                   14585: 
                   14586: returns: the new clean filename
                   14587: 
                   14588: =item *
                   14589: 
1.1090    raeburn  14590: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14591: userspace, probably shouldn't be called directly
                   14592: 
                   14593:   docuname: username or courseid of destination for the file
                   14594:   docudom: domain of user/course of destination for the file
                   14595:   formname: same as for userfileupload()
1.1090    raeburn  14596:   fname: filename (including subdirectories) for the file
                   14597:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14598:   allfiles: reference to hash used to store objects found by parser
                   14599:   codebase: reference to hash used for codebases of java objects found by parser
                   14600:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14601:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14602:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14603:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14604:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14605:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14606:   mimetype: reference to scalar to accommodate mime type determined
                   14607:             from File::MMagic if $parser = parse.
1.608     albertel 14608: 
                   14609:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14610:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14611:  was 'overwrite').
                   14612:  
1.608     albertel 14613: 
                   14614: =item *
                   14615: 
                   14616: renameuserfile(): renames an existing userfile to a new name
                   14617: 
                   14618:   Args:
                   14619:    docuname: username or courseid of destination for the file
                   14620:    docudom: domain of user/course of destination for the file
                   14621:    old: current file name (including any subdirs under userfiles)
                   14622:    new: desired file name (including any subdirs under userfiles)
                   14623: 
                   14624: =item *
                   14625: 
                   14626: mkdiruserfile(): creates a directory is a userfiles dir
                   14627: 
                   14628:   Args:
                   14629:    docuname: username or courseid of destination for the file
                   14630:    docudom: domain of user/course of destination for the file
                   14631:    dir: dir to create (including any subdirs under userfiles)
                   14632: 
                   14633: =item *
                   14634: 
                   14635: removeuserfile(): removes a file that exists in userfiles
                   14636: 
                   14637:   Args:
                   14638:    docuname: username or courseid of destination for the file
                   14639:    docudom: domain of user/course of destination for the file
                   14640:    fname: filname to delete (including any subdirs under userfiles)
                   14641: 
                   14642: =item *
                   14643: 
                   14644: removeuploadedurl(): convience function for removeuserfile()
                   14645: 
                   14646:   Args:
                   14647:    url:  a full /uploaded/... url to delete
                   14648: 
1.747     albertel 14649: =item * 
                   14650: 
                   14651: get_portfile_permissions():
                   14652:   Args:
                   14653:     domain: domain of user or course contain the portfolio files
                   14654:     user: name of user or num of course contain the portfolio files
                   14655:   Returns:
                   14656:     hashref of a dump of the proper file_permissions.db
                   14657:    
                   14658: 
                   14659: =item * 
                   14660: 
                   14661: get_access_controls():
                   14662: 
                   14663: Args:
                   14664:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14665:   group: (optional) the group you want the files associated with
                   14666:   file: (optional) the file you want access info on
                   14667: 
                   14668: Returns:
1.749     raeburn  14669:     a hash (keys are file names) of hashes containing
                   14670:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14671:         values are XML containing access control settings (see below) 
1.747     albertel 14672: 
                   14673: Internal notes:
                   14674: 
1.749     raeburn  14675:  access controls are stored in file_permissions.db as key=value pairs.
                   14676:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14677:         where scope -> public,guest,course,group,domains or users.
                   14678:               end -> UNIX time for end of access (0 -> no end date)
                   14679:               start -> UNIX time for start of access
                   14680: 
                   14681:     value -> XML description of access control
                   14682:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14683:             <start></start>
                   14684:             <end></end>
                   14685: 
                   14686:             <password></password>  for scope type = guest
                   14687: 
                   14688:             <domain></domain>     for scope type = course or group
                   14689:             <number></number>
                   14690:             <roles id="">
                   14691:              <role></role>
                   14692:              <access></access>
                   14693:              <section></section>
                   14694:              <group></group>
                   14695:             </roles>
                   14696: 
                   14697:             <dom></dom>         for scope type = domains
                   14698: 
                   14699:             <users>             for scope type = users
                   14700:              <user>
                   14701:               <uname></uname>
                   14702:               <udom></udom>
                   14703:              </user>
                   14704:             </users>
                   14705:            </scope> 
                   14706:               
                   14707:  Access data is also aggregated for each file in an additional key=value pair:
                   14708:  key -> path to file/file_name\0accesscontrol 
                   14709:  value -> reference to hash
                   14710:           hash contains key = value pairs
                   14711:           where key = uniqueID:scope_end_start
                   14712:                 value = UNIX time record was last updated
                   14713: 
                   14714:           Used to improve speed of look-ups of access controls for each file.  
                   14715:  
                   14716:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14717: 
1.1172.2.13  raeburn  14718: =item *
                   14719: 
1.749     raeburn  14720: modify_access_controls():
                   14721: 
                   14722: Modifies access controls for a portfolio file
                   14723: Args
                   14724: 1. file name
                   14725: 2. reference to hash of required changes,
                   14726: 3. domain
                   14727: 4. username
                   14728:   where domain,username are the domain of the portfolio owner 
                   14729:   (either a user or a course) 
                   14730: 
                   14731: Returns:
                   14732: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14733: 2. result of deletions ('ok' or 'error', with error message).
                   14734: 3. reference to hash of any new or updated access controls.
                   14735: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14736:    key = integer (inbound ID)
1.1172.2.13  raeburn  14737:    value = uniqueID
                   14738: 
                   14739: =item *
                   14740: 
                   14741: get_timebased_id():
                   14742: 
                   14743: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14744: course via the Course Editor (e.g., folders, composite pages,
                   14745: group bulletin boards).
                   14746: 
                   14747: Args: (first three required; six others optional)
                   14748: 
                   14749: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14750:    docssequence, or name of group
                   14751: 
                   14752: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14753:    e.g., num, boardids
                   14754: 
                   14755: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14756:    file will be named nohist_namespace.db
                   14757: 
                   14758: 4. cdom: domain of course; default is current course domain from %env
                   14759: 
                   14760: 5. cnum: course number; default is current course number from %env
                   14761: 
                   14762: 6. idtype: set to concat if an additional digit is to be appended to the
                   14763:    unix timestamp to form the suffix, if the plain timestamp is already
                   14764:    in use.  Default is to not do this, but simply increment the unix
                   14765:    timestamp by 1 until a unique key is obtained.
                   14766: 
                   14767: 7. who: holder of locking key; defaults to user:domain for user.
                   14768: 
                   14769: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14770:    retrying); default is 3.
                   14771: 
                   14772: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14773: 
                   14774: Returns:
                   14775: 
                   14776: 1. suffix obtained (numeric)
                   14777: 
                   14778: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14779: 
                   14780: 3. error: contains (localized) error message if an error occurred.
                   14781: 
1.747     albertel 14782: 
1.608     albertel 14783: =back
                   14784: 
1.243     albertel 14785: =head2 HTTP Helper Routines
                   14786: 
                   14787: =over 4
                   14788: 
1.191     harris41 14789: =item *
                   14790: 
                   14791: escape() : unpack non-word characters into CGI-compatible hex codes
                   14792: 
                   14793: =item *
                   14794: 
                   14795: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14796: 
1.243     albertel 14797: =back
                   14798: 
                   14799: =head1 PRIVATE SUBROUTINES
                   14800: 
                   14801: =head2 Underlying communication routines (Shouldn't call)
                   14802: 
                   14803: =over 4
                   14804: 
                   14805: =item *
                   14806: 
                   14807: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14808: 
                   14809: =item *
                   14810: 
                   14811: reply() : uses subreply to send a message to remote machine, logs all failures
                   14812: 
                   14813: =item *
                   14814: 
                   14815: critical() : passes a critical message to another server; if cannot
                   14816: get through then place message in connection buffer directory and
                   14817: returns con_delayed, if incapable of saving message, returns
                   14818: con_failed
                   14819: 
                   14820: =item *
                   14821: 
                   14822: reconlonc() : tries to reconnect lonc client processes.
                   14823: 
                   14824: =back
                   14825: 
                   14826: =head2 Resource Access Logging
                   14827: 
                   14828: =over 4
                   14829: 
                   14830: =item *
                   14831: 
                   14832: flushcourselogs() : flush (save) buffer logs and access logs
                   14833: 
                   14834: =item *
                   14835: 
                   14836: courselog($what) : save message for course in hash
                   14837: 
                   14838: =item *
                   14839: 
                   14840: courseacclog($what) : save message for course using &courselog().  Perform
                   14841: special processing for specific resource types (problems, exams, quizzes, etc).
                   14842: 
1.191     harris41 14843: =item *
                   14844: 
                   14845: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14846: as a PerlChildExitHandler
1.243     albertel 14847: 
                   14848: =back
                   14849: 
                   14850: =head2 Other
                   14851: 
                   14852: =over 4
                   14853: 
                   14854: =item *
                   14855: 
                   14856: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14857: 
                   14858: =back
                   14859: 
                   14860: =cut
1.877     foxr     14861: 

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