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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.67! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.66 2015/04/20 01:04:28 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.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.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.550     foxr      105: my $max_connection_retries = 10;     # 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") {	
                    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.448     albertel  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.448     albertel  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    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.
                    373: 	sleep(1);
                    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.850     albertel  391:         sleep(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:     my $hostname = &hostname($lonid);
                    421:     if ($lonid) {
                    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.448     albertel  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') {
                    467: 	&reconlonc("$perlvar{'lonSockDir'}/$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;
                    479: 		if (open($dfh,">$dfilename")) {
                    480: 		    print $dfh "$cmd\n"; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
                    484:             sleep 2;
                    485:             my $wcmd='';
                    486:             {
1.448     albertel  487: 		my $dfh;
                    488: 		if (open($dfh,"<$dfilename")) {
                    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.36  raeburn   604:     my ($r,$name,$userhashref) = @_;
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.916     albertel  619:     return undef if (!-e "$lonidsdir/$handle.id");
                    620: 
1.917     albertel  621:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    622:     return undef if (!$opened);
1.916     albertel  623: 
                    624:     flock($idf,LOCK_SH);
                    625:     my %disk_env;
                    626:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    627: 	    &GDBM_READER(),0640)) {
                    628: 	return undef;	
                    629:     }
                    630: 
                    631:     if (!defined($disk_env{'user.name'})
                    632: 	|| !defined($disk_env{'user.domain'})) {
                    633: 	return undef;
                    634:     }
1.1172.2.18  raeburn   635: 
1.1172.2.36  raeburn   636:     if (ref($userhashref) eq 'HASH') {
                    637:         $userhashref->{'name'} = $disk_env{'user.name'};
                    638:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   639:     }
                    640: 
1.916     albertel  641:     return $handle;
                    642: }
                    643: 
1.830     albertel  644: sub timed_flock {
                    645:     my ($file,$lock_type) = @_;
                    646:     my $failed=0;
                    647:     eval {
                    648: 	local $SIG{__DIE__}='DEFAULT';
                    649: 	local $SIG{ALRM}=sub {
                    650: 	    $failed=1;
                    651: 	    die("failed lock");
                    652: 	};
                    653: 	alarm(13);
                    654: 	flock($file,$lock_type);
                    655: 	alarm(0);
                    656:     };
                    657:     if ($failed) {
                    658: 	return undef;
                    659:     } else {
                    660: 	return 1;
                    661:     }
                    662: }
                    663: 
1.5       www       664: # ---------------------------------------------------------- Append Environment
                    665: 
                    666: sub appenv {
1.949     raeburn   667:     my ($newenv,$roles) = @_;
                    668:     if (ref($newenv) eq 'HASH') {
                    669:         foreach my $key (keys(%{$newenv})) {
                    670:             my $refused = 0;
                    671: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    672:                 $refused = 1;
                    673:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   674:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   675:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    676:                         $refused = 0;
                    677:                     }
                    678:                 }
                    679:             }
                    680:             if ($refused) {
                    681:                 &logthis("<font color=\"blue\">WARNING: ".
                    682:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    683:                          .'</font>');
                    684: 	        delete($newenv->{$key});
                    685:             } else {
                    686:                 $env{$key}=$newenv->{$key};
                    687:             }
                    688:         }
                    689:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    690:         if ($opened
                    691: 	    && &timed_flock($env_file,LOCK_EX)
                    692: 	    &&
                    693: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    694: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    695: 	    while (my ($key,$value) = each(%{$newenv})) {
                    696: 	        $disk_env{$key} = $value;
                    697: 	    }
                    698: 	    untie(%disk_env);
1.35      www       699:         }
1.191     harris41  700:     }
1.56      www       701:     return 'ok';
                    702: }
                    703: # ----------------------------------------------------- Delete from Environment
                    704: 
                    705: sub delenv {
1.1104    raeburn   706:     my ($delthis,$regexp,$roles) = @_;
                    707:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    708:         my $refused = 1;
                    709:         if (ref($roles) eq 'ARRAY') {
                    710:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    711:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    712:                 $refused = 0;
                    713:             }
                    714:         }
                    715:         if ($refused) {
                    716:             &logthis("<font color=\"blue\">WARNING: ".
                    717:                      "Attempt to delete from environment ".$delthis);
                    718:             return 'error';
                    719:         }
1.56      www       720:     }
1.917     albertel  721:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    722:     if ($opened
1.915     albertel  723: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  724: 	&&
                    725: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    726: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  727: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   728: 	    if ($regexp) {
                    729:                 if ($key=~/^$delthis/) {
                    730:                     delete($env{$key});
                    731:                     delete($disk_env{$key});
                    732:                 } 
                    733:             } else {
                    734:                 if ($key=~/^\Q$delthis\E/) {
                    735: 		    delete($env{$key});
                    736: 		    delete($disk_env{$key});
                    737: 	        }
                    738:             }
1.448     albertel  739: 	}
1.783     albertel  740: 	untie(%disk_env);
1.5       www       741:     }
                    742:     return 'ok';
1.369     albertel  743: }
                    744: 
1.790     albertel  745: sub get_env_multiple {
                    746:     my ($name) = @_;
                    747:     my @values;
                    748:     if (defined($env{$name})) {
                    749:         # exists is it an array
                    750:         if (ref($env{$name})) {
                    751:             @values=@{ $env{$name} };
                    752:         } else {
                    753:             $values[0]=$env{$name};
                    754:         }
                    755:     }
                    756:     return(@values);
                    757: }
                    758: 
1.958     www       759: # ------------------------------------------------------------------- Locking
                    760: 
                    761: sub set_lock {
                    762:     my ($text)=@_;
                    763:     $locknum++;
                    764:     my $id=$$.'-'.$locknum;
                    765:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    766:              'session.lock.'.$id => $text});
                    767:     return $id;
                    768: }
                    769: 
                    770: sub get_locks {
                    771:     my $num=0;
                    772:     my %texts=();
                    773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    774:        if ($lock=~/\w/) {
                    775:           $num++;
                    776:           $texts{$lock}=$env{'session.lock.'.$lock};
                    777:        }
                    778:    }
                    779:    return ($num,%texts);
                    780: }
                    781: 
                    782: sub remove_lock {
                    783:     my ($id)=@_;
                    784:     my $newlocks='';
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if (($lock=~/\w/) && ($lock ne $id)) {
                    787:           $newlocks.=','.$lock;
                    788:        }
                    789:     }
                    790:     &appenv({'session.locks' => $newlocks});
                    791:     &delenv('session.lock.'.$id);
                    792: }
                    793: 
                    794: sub remove_all_locks {
                    795:     my $activelocks=$env{'session.locks'};
                    796:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    797:        if ($lock=~/\w/) {
                    798:           &remove_lock($lock);
                    799:        }
                    800:     }
                    801: }
                    802: 
                    803: 
1.369     albertel  804: # ------------------------------------------ Find out current server userload
                    805: sub userload {
                    806:     my $numusers=0;
                    807:     {
                    808: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    809: 	my $filename;
                    810: 	my $curtime=time;
                    811: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  812: 	    next if ($filename eq '.' || $filename eq '..');
                    813: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  814: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  815: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  816: 	}
                    817: 	closedir(LONIDS);
                    818:     }
                    819:     my $userloadpercent=0;
                    820:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    821:     if ($maxuserload) {
1.371     albertel  822: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  823:     }
1.372     albertel  824:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  825:     return $userloadpercent;
1.283     www       826: }
                    827: 
1.1       albertel  828: # ------------------------------ Find server with least workload from spare.tab
1.11      www       829: 
1.1       albertel  830: sub spareserver {
1.1083    raeburn   831:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  832:     my $spare_server;
1.370     albertel  833:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  834:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    835:                                                      :  $userloadpercent;
1.1083    raeburn   836:     my ($uint_dom,$remotesessions);
                    837:     if (($udom ne '') && (&domain($udom) ne '')) {
                    838:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    839:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    840:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    841:         $remotesessions = $udomdefaults{'remotesessions'};
                    842:     }
1.1123    raeburn   843:     my $spareshash = &this_host_spares($udom);
                    844:     if (ref($spareshash) eq 'HASH') {
                    845:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    846:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   847:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    848:                                              $try_server));
1.1123    raeburn   849: 	        ($spare_server, $lowest_load) =
                    850: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    851:             }
1.1083    raeburn   852:         }
1.784     albertel  853: 
1.1123    raeburn   854:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    855: 
                    856:         if (!$found_server) {
                    857:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    858: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   859:                     next unless (&spare_can_host($udom,$uint_dom,
                    860:                                                  $remotesessions,$try_server));
1.1123    raeburn   861: 	            ($spare_server, $lowest_load) =
                    862: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    863:                 }
                    864: 	    }
                    865:         }
1.784     albertel  866:     }
                    867: 
                    868:     if (!$want_server_name) {
1.968     raeburn   869:         my $protocol = 'http';
                    870:         if ($protocol{$spare_server} eq 'https') {
                    871:             $protocol = $protocol{$spare_server};
                    872:         }
1.1001    raeburn   873:         if (defined($spare_server)) {
                    874:             my $hostname = &hostname($spare_server);
1.1083    raeburn   875:             if (defined($hostname)) {
1.1001    raeburn   876: 	        $spare_server = $protocol.'://'.$hostname;
                    877:             }
                    878:         }
1.784     albertel  879:     }
                    880:     return $spare_server;
                    881: }
                    882: 
                    883: sub compare_server_load {
1.1172.2.41  raeburn   884:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    885: 
                    886:     if ($required) {
                    887:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    888:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    889:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    890:         if (($major eq '' && $minor eq '') ||
                    891:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    892:             return ($spare_server,$lowest_load);
                    893:         }
                    894:     }
1.784     albertel  895: 
                    896:     my $loadans     = &reply('load',    $try_server);
                    897:     my $userloadans = &reply('userload',$try_server);
                    898: 
                    899:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   900: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  901:     }
                    902: 
                    903:     my $load;
                    904:     if ($loadans =~ /\d/) {
                    905: 	if ($userloadans =~ /\d/) {
                    906: 	    #both are numbers, pick the bigger one
                    907: 	    $load = ($loadans > $userloadans) ? $loadans 
                    908: 		                              : $userloadans;
1.411     albertel  909: 	} else {
1.784     albertel  910: 	    $load = $loadans;
1.411     albertel  911: 	}
1.784     albertel  912:     } else {
                    913: 	$load = $userloadans;
                    914:     }
                    915: 
                    916:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    917: 	$spare_server = $try_server;
                    918: 	$lowest_load  = $load;
1.370     albertel  919:     }
1.784     albertel  920:     return ($spare_server,$lowest_load);
1.202     matthew   921: }
1.914     albertel  922: 
                    923: # --------------------------- ask offload servers if user already has a session
                    924: sub find_existing_session {
                    925:     my ($udom,$uname) = @_;
1.1123    raeburn   926:     my $spareshash = &this_host_spares($udom);
                    927:     if (ref($spareshash) eq 'HASH') {
                    928:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    929:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    930:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    931:             }
                    932:         }
                    933:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    936:             }
                    937:         }
1.914     albertel  938:     }
                    939:     return;
                    940: }
                    941: 
                    942: # -------------------------------- ask if server already has a session for user
                    943: sub has_user_session {
                    944:     my ($lonid,$udom,$uname) = @_;
                    945:     my $result = &reply(join(':','userhassession',
                    946: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    947:     return 1 if ($result eq 'ok');
                    948: 
                    949:     return 0;
                    950: }
                    951: 
1.1076    raeburn   952: # --------- determine least loaded server in a user's domain which allows login
                    953: 
                    954: sub choose_server {
1.1172.2.47  raeburn   955:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   956:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   957:     my %servers = &get_servers($udom);
1.1076    raeburn   958:     my $lowest_load = 30000;
1.1172.2.47  raeburn   959:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    960:     if ($skiploadbal) {
                    961:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    962:         unless (defined($cached)) {
                    963:             my $cachetime = 60*60*24;
                    964:             my %domconfig =
                    965:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    966:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    967:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    968:                                            $cachetime);
                    969:             }
                    970:         }
                    971:     }
1.1076    raeburn   972:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   973:         my $loginvia;
1.1172.2.47  raeburn   974:         if ($skiploadbal) {
                    975:             if (ref($balancers) eq 'HASH') {
                    976:                 next if (exists($balancers->{$lonhost}));
                    977:             }
                    978:         }
1.1115    raeburn   979:         if ($checkloginvia) {
                    980:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   981:             if ($loginvia) {
                    982:                 my ($server,$path) = split(/:/,$loginvia);
                    983:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   984:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   985:                 if ($login_host eq $server) {
                    986:                     $portal_path = $path;
1.1151    raeburn   987:                     $isredirect = 1;
1.1116    raeburn   988:                 }
                    989:             } else {
                    990:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   991:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   992:                 if ($login_host eq $lonhost) {
                    993:                     $portal_path = '';
1.1151    raeburn   994:                     $isredirect = ''; 
1.1116    raeburn   995:                 }
                    996:             }
                    997:         } else {
1.1076    raeburn   998:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn   999:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1000:         }
                   1001:     }
                   1002:     if ($login_host ne '') {
1.1116    raeburn  1003:         $hostname = &hostname($login_host);
1.1076    raeburn  1004:     }
1.1151    raeburn  1005:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1006: }
                   1007: 
1.202     matthew  1008: # --------------------------------------------- Try to change a user's password
                   1009: 
                   1010: sub changepass {
1.799     raeburn  1011:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1012:     $currentpass = &escape($currentpass);
                   1013:     $newpass     = &escape($newpass);
1.1030    raeburn  1014:     my $lonhost = $perlvar{'lonHostID'};
                   1015:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1016: 		       $server);
                   1017:     if (! $answer) {
                   1018: 	&logthis("No reply on password change request to $server ".
                   1019: 		 "by $uname in domain $udom.");
                   1020:     } elsif ($answer =~ "^ok") {
                   1021:         &logthis("$uname in $udom successfully changed their password ".
                   1022: 		 "on $server.");
                   1023:     } elsif ($answer =~ "^pwchange_failure") {
                   1024: 	&logthis("$uname in $udom was unable to change their password ".
                   1025: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1026: 		 "or pwchange");
                   1027:     } elsif ($answer =~ "^non_authorized") {
                   1028:         &logthis("$uname in $udom did not get their password correct when ".
                   1029: 		 "attempting to change it on $server.");
                   1030:     } elsif ($answer =~ "^auth_mode_error") {
                   1031:         &logthis("$uname in $udom attempted to change their password despite ".
                   1032: 		 "not being locally or internally authenticated on $server.");
                   1033:     } elsif ($answer =~ "^unknown_user") {
                   1034:         &logthis("$uname in $udom attempted to change their password ".
                   1035: 		 "on $server but were unable to because $server is not ".
                   1036: 		 "their home server.");
                   1037:     } elsif ($answer =~ "^refused") {
                   1038: 	&logthis("$server refused to change $uname in $udom password because ".
                   1039: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1040:     } elsif ($answer =~ "invalid_client") {
                   1041:         &logthis("$server refused to change $uname in $udom password because ".
                   1042:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1043:     }
                   1044:     return $answer;
1.1       albertel 1045: }
                   1046: 
1.169     harris41 1047: # ----------------------- Try to determine user's current authentication scheme
                   1048: 
                   1049: sub queryauthenticate {
                   1050:     my ($uname,$udom)=@_;
1.456     albertel 1051:     my $uhome=&homeserver($uname,$udom);
                   1052:     if (!$uhome) {
                   1053: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1054: 	return 'no_host';
                   1055:     }
                   1056:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1057:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1058: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1059:     }
1.456     albertel 1060:     return $answer;
1.169     harris41 1061: }
                   1062: 
1.1       albertel 1063: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1064: 
1.1       albertel 1065: sub authenticate {
1.1073    raeburn  1066:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1067:     $upass=&escape($upass);
                   1068:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1069:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1070:     my $newhome;
1.836     www      1071:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1072: # Maybe the machine was offline and only re-appeared again recently?
                   1073:         &reconlonc();
                   1074: # One more
1.952     raeburn  1075: 	$uhome=&homeserver($uname,$udom,1);
                   1076:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1077:             if (defined(&domain($udom,'primary'))) {
                   1078:                 $newhome=&domain($udom,'primary');
                   1079:             }
                   1080:             if ($newhome ne '') {
                   1081:                 $uhome = $newhome;
                   1082:             }
                   1083:         }
1.836     www      1084: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1085: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1086: 	    return 'no_host';
                   1087:         }
1.1       albertel 1088:     }
1.1073    raeburn  1089:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1090:     if ($answer eq 'authorized') {
1.952     raeburn  1091:         if ($newhome) {
                   1092:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1093:             return 'no_account_on_host'; 
                   1094:         } else {
                   1095:             &logthis("User $uname at $udom authorized by $uhome");
                   1096:             return $uhome;
                   1097:         }
1.471     albertel 1098:     }
                   1099:     if ($answer eq 'non_authorized') {
                   1100: 	&logthis("User $uname at $udom rejected by $uhome");
                   1101: 	return 'no_host'; 
1.9       www      1102:     }
1.471     albertel 1103:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1104:     return 'no_host';
                   1105: }
                   1106: 
1.1073    raeburn  1107: sub can_host_session {
1.1074    raeburn  1108:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1109:     my $canhost = 1;
1.1074    raeburn  1110:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1111:     if (ref($remotesessions) eq 'HASH') {
                   1112:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1113:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1114:                 $canhost = 0;
                   1115:             } else {
                   1116:                 $canhost = 1;
                   1117:             }
                   1118:         }
                   1119:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1120:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1121:                 $canhost = 1;
                   1122:             } else {
                   1123:                 $canhost = 0;
                   1124:             }
                   1125:         }
                   1126:         if ($canhost) {
                   1127:             if ($remotesessions->{'version'} ne '') {
                   1128:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1129:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1130:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1131:                         my $major = $1;
                   1132:                         my $minor = $2;
                   1133:                         if (($major < $reqmajor ) ||
                   1134:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1135:                             $canhost = 0;
                   1136:                         }
                   1137:                     } else {
                   1138:                         $canhost = 0;
                   1139:                     }
                   1140:                 }
                   1141:             }
                   1142:         }
                   1143:     }
                   1144:     if ($canhost) {
                   1145:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1146:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1147:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1148:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1149:                 if (($uint_dom ne '') && 
                   1150:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1151:                     $canhost = 0;
                   1152:                 } else {
                   1153:                     $canhost = 1;
                   1154:                 }
                   1155:             }
                   1156:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1157:                 if (($uint_dom ne '') && 
                   1158:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1159:                     $canhost = 1;
                   1160:                 } else {
                   1161:                     $canhost = 0;
                   1162:                 }
                   1163:             }
                   1164:         }
                   1165:     }
                   1166:     return $canhost;
                   1167: }
                   1168: 
1.1083    raeburn  1169: sub spare_can_host {
                   1170:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1171:     my $canhost=1;
1.1172.2.62  raeburn  1172:     my $try_server_hostname = &hostname($try_server);
                   1173:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1174:     my $serverhomedom = &host_domain($serverhomeID);
                   1175:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1176:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1177:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1178:             $canhost = 0;
                   1179:         }
                   1180:     }
                   1181:     if (($canhost) && ($uint_dom)) {
                   1182:         my @intdoms;
                   1183:         my $internet_names = &get_internet_names($try_server);
                   1184:         if (ref($internet_names) eq 'ARRAY') {
                   1185:             @intdoms = @{$internet_names};
                   1186:         }
                   1187:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1188:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1189:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1190:                                          $remotesessions,
                   1191:                                          $defdomdefaults{'hostedsessions'});
                   1192:         }
1.1083    raeburn  1193:     }
                   1194:     return $canhost;
                   1195: }
                   1196: 
1.1123    raeburn  1197: sub this_host_spares {
                   1198:     my ($dom) = @_;
1.1126    raeburn  1199:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1200:     my @hosts = &current_machine_ids();
                   1201:     foreach my $lonhost (@hosts) {
                   1202:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1203:             $dom_in_use = $dom;
                   1204:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1205:             last;
                   1206:         }
                   1207:     }
1.1126    raeburn  1208:     if ($dom_in_use ne '') {
                   1209:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1210:     }
                   1211:     if (ref($result) ne 'HASH') {
                   1212:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1213:         $dom_in_use = &host_domain($lonhost_in_use);
                   1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1215:         if (ref($result) ne 'HASH') {
                   1216:             $result = \%spareid;
                   1217:         }
                   1218:     }
                   1219:     return $result;
                   1220: }
                   1221: 
                   1222: sub spares_for_offload  {
                   1223:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1224:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1225:     if (defined($cached)) {
                   1226:         return $result;
                   1227:     } else {
1.1126    raeburn  1228:         my $cachetime = 60*60*24;
                   1229:         my %domconfig =
                   1230:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1231:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1232:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1233:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1234:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1235:                 }
                   1236:             }
                   1237:         }
                   1238:     }
1.1126    raeburn  1239:     return;
1.1123    raeburn  1240: }
                   1241: 
1.1129    raeburn  1242: sub get_lonbalancer_config {
                   1243:     my ($servers) = @_;
                   1244:     my ($currbalancer,$currtargets);
                   1245:     if (ref($servers) eq 'HASH') {
                   1246:         foreach my $server (keys(%{$servers})) {
                   1247:             my %what = (
                   1248:                          spareid => 1,
                   1249:                          perlvar => 1,
                   1250:                        );
                   1251:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1252:             if ($result eq 'ok') {
                   1253:                 if (ref($returnhash) eq 'HASH') {
                   1254:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1255:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1256:                             $currbalancer = $server;
                   1257:                             $currtargets = {};
                   1258:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1259:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1260:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1261:                                 }
                   1262:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1263:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1264:                                 }
                   1265:                             }
                   1266:                             last;
                   1267:                         }
                   1268:                     }
                   1269:                 }
                   1270:             }
                   1271:         }
                   1272:     }
                   1273:     return ($currbalancer,$currtargets);
                   1274: }
                   1275: 
                   1276: sub check_loadbalancing {
                   1277:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1278:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1279:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1280:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1281:     my @hosts = &current_machine_ids();
1.1129    raeburn  1282:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1283:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1284:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1285:     my $serverhomedom = &host_domain($lonhost);
                   1286: 
                   1287:     my $cachetime = 60*60*24;
                   1288: 
                   1289:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1290:         $dom_in_use = $udom;
                   1291:         $homeintdom = 1;
                   1292:     } else {
                   1293:         $dom_in_use = $serverhomedom;
                   1294:     }
                   1295:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1296:     unless (defined($cached)) {
                   1297:         my %domconfig =
                   1298:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1299:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1300:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1301:         }
                   1302:     }
                   1303:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1304:         ($is_balancer,$currtargets,$currrules) =
                   1305:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1306:         if ($is_balancer) {
                   1307:             if (ref($currrules) eq 'HASH') {
                   1308:                 if ($homeintdom) {
                   1309:                     if ($uname ne '') {
                   1310:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1311:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1312:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1313:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1314:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1315:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1316:                             }
                   1317:                         }
                   1318:                         if ($rule_in_effect eq '') {
                   1319:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1320:                             if ($userenv{'inststatus'} ne '') {
                   1321:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1322:                                 my ($othertitle,$usertypes,$types) =
                   1323:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1324:                                 if (ref($types) eq 'ARRAY') {
                   1325:                                     foreach my $type (@{$types}) {
                   1326:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1327:                                             if (exists($currrules->{$type})) {
                   1328:                                                 $rule_in_effect = $currrules->{$type};
                   1329:                                             }
                   1330:                                         }
                   1331:                                     }
                   1332:                                 }
                   1333:                             } else {
                   1334:                                 if (exists($currrules->{'default'})) {
                   1335:                                     $rule_in_effect = $currrules->{'default'};
                   1336:                                 }
                   1337:                             }
                   1338:                         }
                   1339:                     } else {
                   1340:                         if (exists($currrules->{'default'})) {
                   1341:                             $rule_in_effect = $currrules->{'default'};
                   1342:                         }
                   1343:                     }
                   1344:                 } else {
                   1345:                     if ($currrules->{'_LC_external'} ne '') {
                   1346:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1347:                     }
                   1348:                 }
                   1349:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1350:                                                        $uname,$udom);
                   1351:             }
                   1352:         }
                   1353:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1354:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1355:         unless (defined($cached)) {
                   1356:             my %domconfig =
                   1357:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1358:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1359:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1360:             }
                   1361:         }
                   1362:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1363:             ($is_balancer,$currtargets,$currrules) =
                   1364:                 &check_balancer_result($result,@hosts);
                   1365:             if ($is_balancer) {
1.1129    raeburn  1366:                 if (ref($currrules) eq 'HASH') {
                   1367:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1368:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1369:                     }
                   1370:                 }
                   1371:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1372:                                                        $uname,$udom);
                   1373:             }
                   1374:         } else {
                   1375:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1376:                 $is_balancer = 1;
                   1377:                 $offloadto = &this_host_spares($dom_in_use);
                   1378:             }
                   1379:         }
                   1380:     } else {
                   1381:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1382:             $is_balancer = 1;
                   1383:             $offloadto = &this_host_spares($dom_in_use);
                   1384:         }
                   1385:     }
1.1172.2.5  raeburn  1386:     if ($is_balancer) {
                   1387:         my $lowest_load = 30000;
                   1388:         if (ref($offloadto) eq 'HASH') {
                   1389:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1390:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1391:                     ($otherserver,$lowest_load) =
                   1392:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1393:                 }
1.1129    raeburn  1394:             }
1.1172.2.5  raeburn  1395:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1396: 
1.1172.2.5  raeburn  1397:             if (!$found_server) {
                   1398:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1399:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1400:                         ($otherserver,$lowest_load) =
                   1401:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1402:                     }
                   1403:                 }
                   1404:             }
                   1405:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1406:             if (@{$offloadto} == 1) {
                   1407:                 $otherserver = $offloadto->[0];
                   1408:             } elsif (@{$offloadto} > 1) {
                   1409:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1410:                     ($otherserver,$lowest_load) =
                   1411:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1412:                 }
                   1413:             }
                   1414:         }
1.1172.2.5  raeburn  1415:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1416:             $is_balancer = 0;
                   1417:             if ($uname ne '' && $udom ne '') {
                   1418:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1419: 
                   1420:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1421:                              'user.loadbalcheck.time' => time});
                   1422:                 }
1.1129    raeburn  1423:             }
                   1424:         }
                   1425:     }
                   1426:     return ($is_balancer,$otherserver);
                   1427: }
                   1428: 
1.1172.2.12  raeburn  1429: sub check_balancer_result {
                   1430:     my ($result,@hosts) = @_;
                   1431:     my ($is_balancer,$currtargets,$currrules);
                   1432:     if (ref($result) eq 'HASH') {
                   1433:         if ($result->{'lonhost'} ne '') {
                   1434:             my $currbalancer = $result->{'lonhost'};
                   1435:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1436:                 $is_balancer = 1;
                   1437:                 $currtargets = $result->{'targets'};
                   1438:                 $currrules = $result->{'rules'};
                   1439:             }
                   1440:         } else {
                   1441:             foreach my $key (keys(%{$result})) {
                   1442:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1443:                     (ref($result->{$key}) eq 'HASH')) {
                   1444:                     $is_balancer = 1;
                   1445:                     $currrules = $result->{$key}{'rules'};
                   1446:                     $currtargets = $result->{$key}{'targets'};
                   1447:                     last;
                   1448:                 }
                   1449:             }
                   1450:         }
                   1451:     }
                   1452:     return ($is_balancer,$currtargets,$currrules);
                   1453: }
                   1454: 
1.1129    raeburn  1455: sub get_loadbalancer_targets {
                   1456:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1457:     my $offloadto;
1.1172.2.4  raeburn  1458:     if ($rule_in_effect eq 'none') {
                   1459:         return [$perlvar{'lonHostID'}];
                   1460:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1461:         $offloadto = $currtargets;
                   1462:     } else {
                   1463:         if ($rule_in_effect eq 'homeserver') {
                   1464:             my $homeserver = &homeserver($uname,$udom);
                   1465:             if ($homeserver ne 'no_host') {
                   1466:                 $offloadto = [$homeserver];
                   1467:             }
                   1468:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1469:             my %domconfig =
                   1470:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1471:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1472:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1473:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1474:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1475:                     }
                   1476:                 }
                   1477:             } else {
1.1172.2.7  raeburn  1478:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1479:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1480:                 if (&hostname($remotebalancer) ne '') {
                   1481:                     $offloadto = [$remotebalancer];
                   1482:                 }
                   1483:             }
                   1484:         } elsif (&hostname($rule_in_effect) ne '') {
                   1485:             $offloadto = [$rule_in_effect];
                   1486:         }
                   1487:     }
                   1488:     return $offloadto;
                   1489: }
                   1490: 
1.1127    raeburn  1491: sub internet_dom_servers {
                   1492:     my ($dom) = @_;
                   1493:     my (%uniqservers,%servers);
                   1494:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1495:     my @machinedoms = &machine_domains($primaryserver);
                   1496:     foreach my $mdom (@machinedoms) {
                   1497:         my %currservers = %servers;
                   1498:         my %server = &get_servers($mdom);
                   1499:         %servers = (%currservers,%server);
                   1500:     }
                   1501:     my %by_hostname;
                   1502:     foreach my $id (keys(%servers)) {
                   1503:         push(@{$by_hostname{$servers{$id}}},$id);
                   1504:     }
                   1505:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1506:         if (@{$by_hostname{$hostname}} > 1) {
                   1507:             my $match = 0;
                   1508:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1509:                 if (&host_domain($id) eq $dom) {
                   1510:                     $uniqservers{$id} = $hostname;
                   1511:                     $match = 1;
                   1512:                 }
                   1513:             }
                   1514:             unless ($match) {
                   1515:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1516:             }
                   1517:         } else {
                   1518:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1519:         }
                   1520:     }
                   1521:     return %uniqservers;
                   1522: }
                   1523: 
1.1       albertel 1524: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1525: 
1.599     albertel 1526: my %homecache;
1.1       albertel 1527: sub homeserver {
1.230     stredwic 1528:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1529:     my $index="$uname:$udom";
1.426     albertel 1530: 
1.599     albertel 1531:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1532: 
                   1533:     my %servers = &get_servers($udom,'library');
                   1534:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1535:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1536: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1537: 
                   1538: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1539: 	if ($answer eq 'found') {
                   1540: 	    delete($badServerCache{$tryserver}); 
                   1541: 	    return $homecache{$index}=$tryserver;
                   1542: 	} elsif ($answer eq 'no_host') {
                   1543: 	    $badServerCache{$tryserver}=1;
                   1544: 	}
1.1       albertel 1545:     }    
                   1546:     return 'no_host';
1.70      www      1547: }
                   1548: 
                   1549: # ------------------------------------- Find the usernames behind a list of IDs
                   1550: 
                   1551: sub idget {
                   1552:     my ($udom,@ids)=@_;
                   1553:     my %returnhash=();
                   1554:     
1.841     albertel 1555:     my %servers = &get_servers($udom,'library');
                   1556:     foreach my $tryserver (keys(%servers)) {
                   1557: 	my $idlist=join('&',@ids);
                   1558: 	$idlist=~tr/A-Z/a-z/; 
                   1559: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1560: 	my @answer=();
                   1561: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1562: 	    @answer=split(/\&/,$reply);
                   1563: 	}                    ;
                   1564: 	my $i;
                   1565: 	for ($i=0;$i<=$#ids;$i++) {
                   1566: 	    if ($answer[$i]) {
                   1567: 		$returnhash{$ids[$i]}=$answer[$i];
                   1568: 	    } 
                   1569: 	}
                   1570:     } 
1.70      www      1571:     return %returnhash;
                   1572: }
                   1573: 
                   1574: # ------------------------------------- Find the IDs behind a list of usernames
                   1575: 
                   1576: sub idrget {
                   1577:     my ($udom,@unames)=@_;
                   1578:     my %returnhash=();
1.800     albertel 1579:     foreach my $uname (@unames) {
                   1580:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1581:     }
1.70      www      1582:     return %returnhash;
                   1583: }
                   1584: 
                   1585: # ------------------------------- Store away a list of names and associated IDs
                   1586: 
                   1587: sub idput {
                   1588:     my ($udom,%ids)=@_;
                   1589:     my %servers=();
1.800     albertel 1590:     foreach my $uname (keys(%ids)) {
                   1591: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1592:         my $uhom=&homeserver($uname,$udom);
1.70      www      1593:         if ($uhom ne 'no_host') {
1.800     albertel 1594:             my $id=&escape($ids{$uname});
1.70      www      1595:             $id=~tr/A-Z/a-z/;
1.800     albertel 1596:             my $esc_unam=&escape($uname);
1.70      www      1597: 	    if ($servers{$uhom}) {
1.800     albertel 1598: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1599:             } else {
1.800     albertel 1600:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1601:             }
                   1602:         }
1.191     harris41 1603:     }
1.800     albertel 1604:     foreach my $server (keys(%servers)) {
                   1605:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1606:     }
1.344     www      1607: }
                   1608: 
1.1172.2.30  raeburn  1609: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1610: 
                   1611: sub iddel {
                   1612:     my ($udom,$idshashref,$uhome)=@_;
                   1613:     my %result=();
                   1614:     unless (ref($idshashref) eq 'HASH') {
                   1615:         return %result;
                   1616:     }
                   1617:     my %servers=();
                   1618:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1619:         my $uhom;
                   1620:         if ($uhome) {
                   1621:             $uhom = $uhome;
                   1622:         } else {
                   1623:             $uhom=&homeserver($uname,$udom);
                   1624:         }
                   1625:         if ($uhom ne 'no_host') {
                   1626:             if ($servers{$uhom}) {
                   1627:                 $servers{$uhom}.='&'.&escape($id);
                   1628:             } else {
                   1629:                 $servers{$uhom}=&escape($id);
                   1630:             }
                   1631:         }
                   1632:     }
                   1633:     foreach my $server (keys(%servers)) {
                   1634:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1635:     }
                   1636:     return %result;
                   1637: }
                   1638: 
1.1023    raeburn  1639: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1640: sub dump_dom {
1.1165    droeschl 1641:     my ($namespace, $udom, $regexp) = @_;
                   1642: 
                   1643:     $udom ||= $env{'user.domain'};
                   1644: 
                   1645:     return () unless $udom;
                   1646: 
                   1647:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1648: }
                   1649: 
1.1023    raeburn  1650: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1651: 
                   1652: sub get_dom {
1.860     raeburn  1653:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1654:     return if ($udom eq 'public');
1.806     raeburn  1655:     my $items='';
                   1656:     foreach my $item (@$storearr) {
                   1657:         $items.=&escape($item).'&';
                   1658:     }
                   1659:     $items=~s/\&$//;
1.860     raeburn  1660:     if (!$udom) {
                   1661:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1662:         return if ($udom eq 'public');
1.860     raeburn  1663:         if (defined(&domain($udom,'primary'))) {
                   1664:             $uhome=&domain($udom,'primary');
                   1665:         } else {
1.874     albertel 1666:             undef($uhome);
1.860     raeburn  1667:         }
                   1668:     } else {
                   1669:         if (!$uhome) {
                   1670:             if (defined(&domain($udom,'primary'))) {
                   1671:                 $uhome=&domain($udom,'primary');
                   1672:             }
                   1673:         }
                   1674:     }
                   1675:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1676:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1677:         my %returnhash;
1.875     albertel 1678:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1679:             return %returnhash;
                   1680:         }
1.806     raeburn  1681:         my @pairs=split(/\&/,$rep);
                   1682:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1683:             return @pairs;
                   1684:         }
                   1685:         my $i=0;
                   1686:         foreach my $item (@$storearr) {
                   1687:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1688:             $i++;
                   1689:         }
                   1690:         return %returnhash;
                   1691:     } else {
1.880     banghart 1692:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1693:     }
                   1694: }
                   1695: 
                   1696: # -------------------------------------------- put items in domain db files 
                   1697: 
                   1698: sub put_dom {
1.860     raeburn  1699:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1700:     if (!$udom) {
                   1701:         $udom=$env{'user.domain'};
                   1702:         if (defined(&domain($udom,'primary'))) {
                   1703:             $uhome=&domain($udom,'primary');
                   1704:         } else {
1.874     albertel 1705:             undef($uhome);
1.860     raeburn  1706:         }
                   1707:     } else {
                   1708:         if (!$uhome) {
                   1709:             if (defined(&domain($udom,'primary'))) {
                   1710:                 $uhome=&domain($udom,'primary');
                   1711:             }
                   1712:         }
                   1713:     } 
                   1714:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1715:         my $items='';
                   1716:         foreach my $item (keys(%$storehash)) {
                   1717:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1718:         }
                   1719:         $items=~s/\&$//;
                   1720:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1721:     } else {
1.860     raeburn  1722:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1723:     }
                   1724: }
                   1725: 
1.1023    raeburn  1726: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1727: sub newput_dom {
1.1023    raeburn  1728:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1729:     my $result;
                   1730:     if (!$udom) {
                   1731:         $udom=$env{'user.domain'};
                   1732:     }
1.1023    raeburn  1733:     if ($udom) {
                   1734:         my $uname = &get_domainconfiguser($udom);
                   1735:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1736:     }
                   1737:     return $result;
                   1738: }
                   1739: 
1.1023    raeburn  1740: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1741: sub del_dom {
1.1023    raeburn  1742:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1743:     if (ref($storearr) eq 'ARRAY') {
                   1744:         if (!$udom) {
                   1745:             $udom=$env{'user.domain'};
                   1746:         }
1.1023    raeburn  1747:         if ($udom) {
                   1748:             my $uname = &get_domainconfiguser($udom); 
                   1749:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1750:         }
                   1751:     }
                   1752: }
                   1753: 
1.1023    raeburn  1754: # ----------------------------------construct domainconfig user for a domain 
                   1755: sub get_domainconfiguser {
                   1756:     my ($udom) = @_;
                   1757:     return $udom.'-domainconfig';
                   1758: }
                   1759: 
1.837     raeburn  1760: sub retrieve_inst_usertypes {
                   1761:     my ($udom) = @_;
                   1762:     my (%returnhash,@order);
1.989     raeburn  1763:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1764:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1765:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1766:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1767:     } else {
                   1768:         if (defined(&domain($udom,'primary'))) {
                   1769:             my $uhome=&domain($udom,'primary');
                   1770:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1771:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1772:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1773:                 return (\%returnhash,\@order);
                   1774:             }
                   1775:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1776:             my @pairs=split(/\&/,$hashitems);
                   1777:             foreach my $item (@pairs) {
                   1778:                 my ($key,$value)=split(/=/,$item,2);
                   1779:                 $key = &unescape($key);
                   1780:                 next if ($key =~ /^error: 2 /);
                   1781:                 $returnhash{$key}=&thaw_unescape($value);
                   1782:             }
                   1783:             my @esc_order = split(/\&/,$orderitems);
                   1784:             foreach my $item (@esc_order) {
                   1785:                 push(@order,&unescape($item));
                   1786:             }
                   1787:         } else {
1.1172.2.44  raeburn  1788:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1789:         }
1.1172.2.44  raeburn  1790:         return (\%returnhash,\@order);
1.837     raeburn  1791:     }
                   1792: }
                   1793: 
1.868     raeburn  1794: sub is_domainimage {
                   1795:     my ($url) = @_;
                   1796:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1797:         if (&domain($1) ne '') {
                   1798:             return '1';
                   1799:         }
                   1800:     }
                   1801:     return;
                   1802: }
                   1803: 
1.899     raeburn  1804: sub inst_directory_query {
                   1805:     my ($srch) = @_;
                   1806:     my $udom = $srch->{'srchdomain'};
                   1807:     my %results;
                   1808:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1809:     my $outcome;
1.899     raeburn  1810:     if ($homeserver ne '') {
1.904     albertel 1811: 	my $queryid=&reply("querysend:instdirsearch:".
                   1812: 			   &escape($srch->{'srchby'}).':'.
                   1813: 			   &escape($srch->{'srchterm'}).':'.
                   1814: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1815: 	my $host=&hostname($homeserver);
                   1816: 	if ($queryid !~/^\Q$host\E\_/) {
                   1817: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1818: 	    return;
                   1819: 	}
                   1820: 	my $response = &get_query_reply($queryid);
                   1821: 	my $maxtries = 5;
                   1822: 	my $tries = 1;
                   1823: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1824: 	    $response = &get_query_reply($queryid);
                   1825: 	    $tries ++;
                   1826: 	}
                   1827: 
                   1828:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1829:             if ($response eq 'unavailable') {
                   1830:                 $outcome = $response;
                   1831:             } else {
                   1832:                 $outcome = 'ok';
                   1833:                 my @matches = split(/\n/,$response);
                   1834:                 foreach my $match (@matches) {
                   1835:                     my ($key,$value) = split(/=/,$match);
                   1836:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1837:                 }
1.899     raeburn  1838:             }
                   1839:         }
                   1840:     }
1.909     raeburn  1841:     return ($outcome,%results);
1.899     raeburn  1842: }
                   1843: 
                   1844: sub usersearch {
                   1845:     my ($srch) = @_;
                   1846:     my $dom = $srch->{'srchdomain'};
                   1847:     my %results;
                   1848:     my %libserv = &all_library();
                   1849:     my $query = 'usersearch';
                   1850:     foreach my $tryserver (keys(%libserv)) {
                   1851:         if (&host_domain($tryserver) eq $dom) {
                   1852:             my $host=&hostname($tryserver);
                   1853:             my $queryid=
1.911     raeburn  1854:                 &reply("querysend:".&escape($query).':'.
                   1855:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1856:                        &escape($srch->{'srchtype'}).':'.
                   1857:                        &escape($srch->{'srchterm'}),$tryserver);
                   1858:             if ($queryid !~/^\Q$host\E\_/) {
                   1859:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1860:                 next;
1.899     raeburn  1861:             }
                   1862:             my $reply = &get_query_reply($queryid);
                   1863:             my $maxtries = 1;
                   1864:             my $tries = 1;
                   1865:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1866:                 $reply = &get_query_reply($queryid);
                   1867:                 $tries ++;
                   1868:             }
                   1869:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1870:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1871:             } else {
1.911     raeburn  1872:                 my @matches;
                   1873:                 if ($reply =~ /\n/) {
                   1874:                     @matches = split(/\n/,$reply);
                   1875:                 } else {
                   1876:                     @matches = split(/\&/,$reply);
                   1877:                 }
1.899     raeburn  1878:                 foreach my $match (@matches) {
                   1879:                     my ($uname,$udom,%userhash);
1.911     raeburn  1880:                     foreach my $entry (split(/:/,$match)) {
                   1881:                         my ($key,$value) =
                   1882:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1883:                         $userhash{$key} = $value;
                   1884:                         if ($key eq 'username') {
                   1885:                             $uname = $value;
                   1886:                         } elsif ($key eq 'domain') {
                   1887:                             $udom = $value;
1.911     raeburn  1888:                         }
1.899     raeburn  1889:                     }
                   1890:                     $results{$uname.':'.$udom} = \%userhash;
                   1891:                 }
                   1892:             }
                   1893:         }
                   1894:     }
                   1895:     return %results;
                   1896: }
                   1897: 
1.912     raeburn  1898: sub get_instuser {
                   1899:     my ($udom,$uname,$id) = @_;
                   1900:     my $homeserver = &domain($udom,'primary');
                   1901:     my ($outcome,%results);
                   1902:     if ($homeserver ne '') {
                   1903:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1904:                            &escape($id).':'.&escape($udom),$homeserver);
                   1905:         my $host=&hostname($homeserver);
                   1906:         if ($queryid !~/^\Q$host\E\_/) {
                   1907:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1908:             return;
                   1909:         }
                   1910:         my $response = &get_query_reply($queryid);
                   1911:         my $maxtries = 5;
                   1912:         my $tries = 1;
                   1913:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1914:             $response = &get_query_reply($queryid);
                   1915:             $tries ++;
                   1916:         }
                   1917:         if (!&error($response) && $response ne 'refused') {
                   1918:             if ($response eq 'unavailable') {
                   1919:                 $outcome = $response;
                   1920:             } else {
                   1921:                 $outcome = 'ok';
                   1922:                 my @matches = split(/\n/,$response);
                   1923:                 foreach my $match (@matches) {
                   1924:                     my ($key,$value) = split(/=/,$match);
                   1925:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1926:                 }
                   1927:             }
                   1928:         }
                   1929:     }
                   1930:     my %userinfo;
                   1931:     if (ref($results{$uname}) eq 'HASH') {
                   1932:         %userinfo = %{$results{$uname}};
                   1933:     } 
                   1934:     return ($outcome,%userinfo);
                   1935: }
                   1936: 
                   1937: sub inst_rulecheck {
1.923     raeburn  1938:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1939:     my %returnhash;
                   1940:     if ($udom ne '') {
                   1941:         if (ref($rules) eq 'ARRAY') {
                   1942:             @{$rules} = map {&escape($_);} (@{$rules});
                   1943:             my $rulestr = join(':',@{$rules});
                   1944:             my $homeserver=&domain($udom,'primary');
                   1945:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1946:                 my $response;
                   1947:                 if ($item eq 'username') {                
                   1948:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1949:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1950:                                               $homeserver));
1.923     raeburn  1951:                 } elsif ($item eq 'id') {
                   1952:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1953:                                               ':'.&escape($id).':'.$rulestr,
                   1954:                                               $homeserver));
1.945     raeburn  1955:                 } elsif ($item eq 'selfcreate') {
                   1956:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1957:                                                &escape($udom).':'.&escape($uname).
                   1958:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1959:                 }
1.912     raeburn  1960:                 if ($response ne 'refused') {
                   1961:                     my @pairs=split(/\&/,$response);
                   1962:                     foreach my $item (@pairs) {
                   1963:                         my ($key,$value)=split(/=/,$item,2);
                   1964:                         $key = &unescape($key);
                   1965:                         next if ($key =~ /^error: 2 /);
                   1966:                         $returnhash{$key}=&thaw_unescape($value);
                   1967:                     }
                   1968:                 }
                   1969:             }
                   1970:         }
                   1971:     }
                   1972:     return %returnhash;
                   1973: }
                   1974: 
                   1975: sub inst_userrules {
1.923     raeburn  1976:     my ($udom,$check) = @_;
1.912     raeburn  1977:     my (%ruleshash,@ruleorder);
                   1978:     if ($udom ne '') {
                   1979:         my $homeserver=&domain($udom,'primary');
                   1980:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1981:             my $response;
                   1982:             if ($check eq 'id') {
                   1983:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1984:                                  $homeserver);
1.943     raeburn  1985:             } elsif ($check eq 'email') {
                   1986:                 $response=&reply('instemailrules:'.&escape($udom),
                   1987:                                  $homeserver);
1.923     raeburn  1988:             } else {
                   1989:                 $response=&reply('instuserrules:'.&escape($udom),
                   1990:                                  $homeserver);
                   1991:             }
1.912     raeburn  1992:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1993:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1994:                 ($response ne 'no_such_host')) {
                   1995:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1996:                 my @pairs=split(/\&/,$hashitems);
                   1997:                 foreach my $item (@pairs) {
                   1998:                     my ($key,$value)=split(/=/,$item,2);
                   1999:                     $key = &unescape($key);
                   2000:                     next if ($key =~ /^error: 2 /);
                   2001:                     $ruleshash{$key}=&thaw_unescape($value);
                   2002:                 }
                   2003:                 my @esc_order = split(/\&/,$orderitems);
                   2004:                 foreach my $item (@esc_order) {
                   2005:                     push(@ruleorder,&unescape($item));
                   2006:                 }
                   2007:             }
                   2008:         }
                   2009:     }
                   2010:     return (\%ruleshash,\@ruleorder);
                   2011: }
                   2012: 
1.976     raeburn  2013: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2014: 
                   2015: sub get_domain_defaults {
1.1172.2.35  raeburn  2016:     my ($domain,$ignore_cache) = @_;
                   2017:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2018:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2019:     unless ($ignore_cache) {
                   2020:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2021:         if (defined($cached)) {
                   2022:             if (ref($result) eq 'HASH') {
                   2023:                 return %{$result};
                   2024:             }
1.943     raeburn  2025:         }
                   2026:     }
                   2027:     my %domdefaults;
                   2028:     my %domconfig =
1.989     raeburn  2029:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2030:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2031:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2032:                                   'requestauthor','selfenrollment',
                   2033:                                   'coursecategories'],$domain);
1.1172.2.41  raeburn  2034:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2035:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2036:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2037:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2038:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2039:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2040:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2041:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2042:     } else {
                   2043:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2044:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2045:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2046:     }
1.976     raeburn  2047:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2048:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2049:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2050:         } else {
                   2051:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2052:         }
1.1172.2.6  raeburn  2053:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2054:         foreach my $item (@usertools) {
                   2055:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2056:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2057:             }
                   2058:         }
1.1172.2.29  raeburn  2059:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2060:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2061:         }
1.976     raeburn  2062:     }
1.985     raeburn  2063:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2064:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2065:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2066:         }
                   2067:     }
1.1172.2.9  raeburn  2068:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2069:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2070:     }
1.989     raeburn  2071:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2072:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2073:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2074:         }
                   2075:     }
1.1047    raeburn  2076:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2077:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2078:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2079:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2080:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2081:         }
1.1172.2.41  raeburn  2082:         foreach my $type (@coursetypes) {
                   2083:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2084:                 unless ($type eq 'community') {
                   2085:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2086:                 }
                   2087:             }
                   2088:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2089:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2090:             }
1.1172.2.60  raeburn  2091:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2092:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2093:                     $domdefaults{$type.'postsubtimeout'} =
                   2094:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2095:                 }
                   2096:             }
1.1172.2.30  raeburn  2097:         }
1.1172.2.67! raeburn  2098:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
        !          2099:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
        !          2100:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
        !          2101:                 if (@clonecodes) {
        !          2102:                     $domdefaults{'canclone'} = join('+',@clonecodes);
        !          2103:                 }
        !          2104:             }
        !          2105:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
        !          2106:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
        !          2107:         }
1.1047    raeburn  2108:     }
1.1073    raeburn  2109:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2110:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2111:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2112:         }
                   2113:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2114:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2115:         }
1.1172.2.62  raeburn  2116:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2117:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2118:         }
1.1073    raeburn  2119:     }
1.1172.2.41  raeburn  2120:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2121:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2122:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2123:                             'approval','limit');
                   2124:             foreach my $type (@coursetypes) {
                   2125:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2126:                     my @mgrdc = ();
                   2127:                     foreach my $item (@settings) {
                   2128:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2129:                             push(@mgrdc,$item);
                   2130:                         }
                   2131:                     }
                   2132:                     if (@mgrdc) {
                   2133:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2134:                     }
                   2135:                 }
                   2136:             }
                   2137:         }
                   2138:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2139:             foreach my $type (@coursetypes) {
                   2140:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2141:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2142:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2143:                     }
                   2144:                 }
                   2145:             }
                   2146:         }
                   2147:     }
1.1172.2.46  raeburn  2148:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2149:         $domdefaults{'catauth'} = 'std';
                   2150:         $domdefaults{'catunauth'} = 'std';
                   2151:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2152:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2153:         }
                   2154:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2155:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2156:         }
                   2157:     }
1.1172.2.23  raeburn  2158:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2159:     return %domdefaults;
                   2160: }
                   2161: 
1.344     www      2162: # --------------------------------------------------- Assign a key to a student
                   2163: 
                   2164: sub assign_access_key {
1.364     www      2165: #
                   2166: # a valid key looks like uname:udom#comments
                   2167: # comments are being appended
                   2168: #
1.498     www      2169:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2170:     $kdom=
1.620     albertel 2171:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2172:     $knum=
1.620     albertel 2173:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2174:     $cdom=
1.620     albertel 2175:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2176:     $cnum=
1.620     albertel 2177:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2178:     $udom=$env{'user.name'} unless (defined($udom));
                   2179:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2180:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2181:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2182:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2183:                                                   # assigned to this person
                   2184:                                                   # - this should not happen,
1.345     www      2185:                                                   # unless something went wrong
                   2186:                                                   # the first time around
                   2187: # ready to assign
1.364     www      2188:         $logentry=$1.'; '.$logentry;
1.496     www      2189:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2190:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2191: # key now belongs to user
1.346     www      2192: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2193:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2194:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2195:                 return 'ok';
                   2196:             } else {
                   2197:                 return 
                   2198:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2199: 	    }
                   2200:         } else {
                   2201:             return 'error: Could not assign key, try again later.';
                   2202:         }
1.364     www      2203:     } elsif (!$existing{$ckey}) {
1.345     www      2204: # the key does not exist
                   2205: 	return 'error: The key does not exist';
                   2206:     } else {
                   2207: # the key is somebody else's
                   2208: 	return 'error: The key is already in use';
                   2209:     }
1.344     www      2210: }
                   2211: 
1.364     www      2212: # ------------------------------------------ put an additional comment on a key
                   2213: 
                   2214: sub comment_access_key {
                   2215: #
                   2216: # a valid key looks like uname:udom#comments
                   2217: # comments are being appended
                   2218: #
                   2219:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2220:     $cdom=
1.620     albertel 2221:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2222:     $cnum=
1.620     albertel 2223:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2224:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2225:     if ($existing{$ckey}) {
                   2226:         $existing{$ckey}.='; '.$logentry;
                   2227: # ready to assign
1.367     www      2228:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2229:                                                  $cdom,$cnum) eq 'ok') {
                   2230: 	    return 'ok';
                   2231:         } else {
                   2232: 	    return 'error: Count not store comment.';
                   2233:         }
                   2234:     } else {
                   2235: # the key does not exist
                   2236: 	return 'error: The key does not exist';
                   2237:     }
                   2238: }
                   2239: 
1.344     www      2240: # ------------------------------------------------------ Generate a set of keys
                   2241: 
                   2242: sub generate_access_keys {
1.364     www      2243:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2244:     $cdom=
1.620     albertel 2245:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2246:     $cnum=
1.620     albertel 2247:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2248:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2249:     unless (($cdom) && ($cnum)) { return 0; }
                   2250:     if ($number>10000) { return 0; }
                   2251:     sleep(2); # make sure don't get same seed twice
                   2252:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2253:     my $total=0;
                   2254:     for (my $i=1;$i<=$number;$i++) {
                   2255:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2256:                   sprintf("%lx",int(100000*rand)).'-'.
                   2257:                   sprintf("%lx",int(100000*rand));
                   2258:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2259:        $newkey=~s/0/h/g; # and also 0 and O
                   2260:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2261:        if ($existing{$newkey}) {
                   2262:            $i--;
                   2263:        } else {
1.364     www      2264: 	  if (&put('accesskeys',
                   2265:               { $newkey => '# generated '.localtime().
1.620     albertel 2266:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2267:                            '; '.$logentry },
                   2268: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2269:               $total++;
                   2270: 	  }
                   2271:        }
                   2272:     }
1.620     albertel 2273:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2274:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2275:     return $total;
                   2276: }
                   2277: 
                   2278: # ------------------------------------------------------- Validate an accesskey
                   2279: 
                   2280: sub validate_access_key {
                   2281:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2282:     $cdom=
1.620     albertel 2283:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2284:     $cnum=
1.620     albertel 2285:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2286:     $udom=$env{'user.domain'} unless (defined($udom));
                   2287:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2288:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2289:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2290: }
                   2291: 
                   2292: # ------------------------------------- Find the section of student in a course
1.652     albertel 2293: sub devalidate_getsection_cache {
                   2294:     my ($udom,$unam,$courseid)=@_;
                   2295:     my $hashid="$udom:$unam:$courseid";
                   2296:     &devalidate_cache_new('getsection',$hashid);
                   2297: }
1.298     matthew  2298: 
1.815     albertel 2299: sub courseid_to_courseurl {
                   2300:     my ($courseid) = @_;
                   2301:     #already url style courseid
                   2302:     return $courseid if ($courseid =~ m{^/});
                   2303: 
                   2304:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2305: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2306: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2307: 	return "/$cdom/$cnum";
                   2308:     }
                   2309: 
                   2310:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2311:     if (exists($courseinfo{'num'})) {
                   2312: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2313:     }
                   2314: 
                   2315:     return undef;
                   2316: }
                   2317: 
1.298     matthew  2318: sub getsection {
                   2319:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2320:     my $cachetime=1800;
1.551     albertel 2321: 
                   2322:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2323:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2324:     if (defined($cached)) { return $result; }
                   2325: 
1.298     matthew  2326:     my %Pending; 
                   2327:     my %Expired;
                   2328:     #
                   2329:     # Each role can either have not started yet (pending), be active, 
                   2330:     #    or have expired.
                   2331:     #
                   2332:     # If there is an active role, we are done.
                   2333:     #
                   2334:     # If there is more than one role which has not started yet, 
                   2335:     #     choose the one which will start sooner
                   2336:     # If there is one role which has not started yet, return it.
                   2337:     #
                   2338:     # If there is more than one expired role, choose the one which ended last.
                   2339:     # If there is a role which has expired, return it.
                   2340:     #
1.815     albertel 2341:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2342:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2343:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2344:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2345:         my $section=$1;
                   2346:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2347:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2348:         my $now=time;
1.548     albertel 2349:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2350:             $Expired{$end}=$section;
                   2351:             next;
                   2352:         }
1.548     albertel 2353:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2354:             $Pending{$start}=$section;
                   2355:             next;
                   2356:         }
1.599     albertel 2357:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2358:     }
                   2359:     #
                   2360:     # Presumedly there will be few matching roles from the above
                   2361:     # loop and the sorting time will be negligible.
                   2362:     if (scalar(keys(%Pending))) {
                   2363:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2364:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2365:     } 
                   2366:     if (scalar(keys(%Expired))) {
                   2367:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2368:         my $time = pop(@sorted);
1.599     albertel 2369:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2370:     }
1.599     albertel 2371:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2372: }
1.70      www      2373: 
1.599     albertel 2374: sub save_cache {
                   2375:     &purge_remembered();
1.722     albertel 2376:     #&Apache::loncommon::validate_page();
1.620     albertel 2377:     undef(%env);
1.780     albertel 2378:     undef($env_loaded);
1.599     albertel 2379: }
1.452     albertel 2380: 
1.599     albertel 2381: my $to_remember=-1;
                   2382: my %remembered;
                   2383: my %accessed;
                   2384: my $kicks=0;
                   2385: my $hits=0;
1.849     albertel 2386: sub make_key {
                   2387:     my ($name,$id) = @_;
1.872     albertel 2388:     if (length($id) > 65 
                   2389: 	&& length(&escape($id)) > 200) {
                   2390: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2391:     }
1.849     albertel 2392:     return &escape($name.':'.$id);
                   2393: }
                   2394: 
1.599     albertel 2395: sub devalidate_cache_new {
                   2396:     my ($name,$id,$debug) = @_;
                   2397:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2398:     $id=&make_key($name,$id);
1.599     albertel 2399:     $memcache->delete($id);
                   2400:     delete($remembered{$id});
                   2401:     delete($accessed{$id});
                   2402: }
                   2403: 
                   2404: sub is_cached_new {
                   2405:     my ($name,$id,$debug) = @_;
1.849     albertel 2406:     $id=&make_key($name,$id);
1.599     albertel 2407:     if (exists($remembered{$id})) {
1.1133    foxr     2408: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2409: 	$accessed{$id}=[&gettimeofday()];
                   2410: 	$hits++;
                   2411: 	return ($remembered{$id},1);
                   2412:     }
                   2413:     my $value = $memcache->get($id);
                   2414:     if (!(defined($value))) {
                   2415: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2416: 	return (undef,undef);
1.416     albertel 2417:     }
1.599     albertel 2418:     if ($value eq '__undef__') {
                   2419: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2420: 	$value=undef;
                   2421:     }
                   2422:     &make_room($id,$value,$debug);
                   2423:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2424:     return ($value,1);
                   2425: }
                   2426: 
                   2427: sub do_cache_new {
                   2428:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2429:     $id=&make_key($name,$id);
1.599     albertel 2430:     my $setvalue=$value;
                   2431:     if (!defined($setvalue)) {
                   2432: 	$setvalue='__undef__';
                   2433:     }
1.623     albertel 2434:     if (!defined($time) ) {
                   2435: 	$time=600;
                   2436:     }
1.599     albertel 2437:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2438:     my $result = $memcache->set($id,$setvalue,$time);
                   2439:     if (! $result) {
1.872     albertel 2440: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2441: 	$memcache->disconnect_all();
1.872     albertel 2442:     }
1.600     albertel 2443:     # need to make a copy of $value
1.919     albertel 2444:     &make_room($id,$value,$debug);
1.599     albertel 2445:     return $value;
                   2446: }
                   2447: 
                   2448: sub make_room {
                   2449:     my ($id,$value,$debug)=@_;
1.919     albertel 2450: 
                   2451:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2452:                                     : $value;
1.599     albertel 2453:     if ($to_remember<0) { return; }
                   2454:     $accessed{$id}=[&gettimeofday()];
                   2455:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2456:     my $to_kick;
                   2457:     my $max_time=0;
                   2458:     foreach my $other (keys(%accessed)) {
                   2459: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2460: 	    $to_kick=$other;
                   2461: 	    $max_time=&tv_interval($accessed{$other});
                   2462: 	}
                   2463:     }
                   2464:     delete($remembered{$to_kick});
                   2465:     delete($accessed{$to_kick});
                   2466:     $kicks++;
                   2467:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2468:     return;
                   2469: }
                   2470: 
1.599     albertel 2471: sub purge_remembered {
1.604     albertel 2472:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2473:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2474:     undef(%remembered);
                   2475:     undef(%accessed);
1.428     albertel 2476: }
1.70      www      2477: # ------------------------------------- Read an entry from a user's environment
                   2478: 
                   2479: sub userenvironment {
                   2480:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2481:     my $items;
                   2482:     foreach my $item (@what) {
                   2483:         $items.=&escape($item).'&';
                   2484:     }
                   2485:     $items=~s/\&$//;
1.70      www      2486:     my %returnhash=();
1.1009    raeburn  2487:     my $uhome = &homeserver($unam,$udom);
                   2488:     unless ($uhome eq 'no_host') {
                   2489:         my @answer=split(/\&/, 
                   2490:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2491:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2492:             return %returnhash;
                   2493:         }
1.1009    raeburn  2494:         my $i;
                   2495:         for ($i=0;$i<=$#what;$i++) {
                   2496: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2497:         }
1.70      www      2498:     }
                   2499:     return %returnhash;
1.1       albertel 2500: }
                   2501: 
1.617     albertel 2502: # ---------------------------------------------------------- Get a studentphoto
                   2503: sub studentphoto {
                   2504:     my ($udom,$unam,$ext) = @_;
                   2505:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2506:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2507:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2508:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2509:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2510:             } else {
                   2511:                 my ($result,$perm_reqd)=
1.707     albertel 2512: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2513:                 if ($result eq 'ok') {
                   2514:                     if (!($perm_reqd eq 'yes')) {
                   2515:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2516:                     }
                   2517:                 }
                   2518:             }
                   2519:         }
                   2520:     } else {
                   2521:         my ($result,$perm_reqd) = 
1.707     albertel 2522: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2523:         if ($result eq 'ok') {
                   2524:             if (!($perm_reqd eq 'yes')) {
                   2525:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2526:             }
                   2527:         }
                   2528:     }
                   2529:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2530: }
                   2531: 
                   2532: sub retrievestudentphoto {
                   2533:     my ($udom,$unam,$ext,$type) = @_;
                   2534:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2535:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2536:     if ($ret eq 'ok') {
                   2537:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2538:         if ($type eq 'thumbnail') {
                   2539:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2540:         }
                   2541:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2542:         return $tokenurl;
                   2543:     } else {
                   2544:         if ($type eq 'thumbnail') {
                   2545:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2546:         } else { 
                   2547:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2548:         }
1.617     albertel 2549:     }
                   2550: }
                   2551: 
1.263     www      2552: # -------------------------------------------------------------------- New chat
                   2553: 
                   2554: sub chatsend {
1.724     raeburn  2555:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2556:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2557:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2558:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2559:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2560: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2561: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2562: }
                   2563: 
                   2564: # ------------------------------------------ Find current version of a resource
                   2565: 
                   2566: sub getversion {
                   2567:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2568:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2569:     return &currentversion(&filelocation('',$fname));
                   2570: }
                   2571: 
                   2572: sub currentversion {
                   2573:     my $fname=shift;
                   2574:     my $author=$fname;
                   2575:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2576:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2577:     my $home=&homeserver($uname,$udom);
1.292     www      2578:     if ($home eq 'no_host') { 
                   2579:         return -1; 
                   2580:     }
1.1112    www      2581:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2582:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2583: 	return -1;
                   2584:     }
1.1112    www      2585:     return $answer;
1.263     www      2586: }
                   2587: 
1.1111    www      2588: #
                   2589: # Return special version number of resource if set by override, empty otherwise
                   2590: #
                   2591: sub usedversion {
                   2592:     my $fname=shift;
                   2593:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2594:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2595:     if ($urlversion) { return $urlversion; }
                   2596:     return '';
                   2597: }
                   2598: 
1.1       albertel 2599: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2600: 
1.1       albertel 2601: sub subscribe {
                   2602:     my $fname=shift;
1.761     raeburn  2603:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2604:     $fname=~s/[\n\r]//g;
1.1       albertel 2605:     my $author=$fname;
                   2606:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2607:     my ($udom,$uname)=split(/\//,$author);
                   2608:     my $home=homeserver($uname,$udom);
1.335     albertel 2609:     if ($home eq 'no_host') {
                   2610:         return 'not_found';
1.1       albertel 2611:     }
                   2612:     my $answer=reply("sub:$fname",$home);
1.64      www      2613:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2614: 	$answer.=' by '.$home;
                   2615:     }
1.1       albertel 2616:     return $answer;
                   2617: }
                   2618:     
1.8       www      2619: # -------------------------------------------------------------- Replicate file
                   2620: 
                   2621: sub repcopy {
                   2622:     my $filename=shift;
1.23      www      2623:     $filename=~s/\/+/\//g;
1.1142    raeburn  2624:     my $londocroot = $perlvar{'lonDocRoot'};
                   2625:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2626:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2627:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2628: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2629: 	return &repcopy_userfile($filename);
                   2630:     }
1.532     albertel 2631:     $filename=~s/[\n\r]//g;
1.8       www      2632:     my $transname="$filename.in.transfer";
1.828     www      2633: # FIXME: this should flock
1.607     raeburn  2634:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2635:     my $remoteurl=subscribe($filename);
1.64      www      2636:     if ($remoteurl =~ /^con_lost by/) {
                   2637: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2638:            return 'unavailable';
1.8       www      2639:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2640: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2641: 	   return 'not_found';
1.64      www      2642:     } elsif ($remoteurl =~ /^rejected by/) {
                   2643: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2644:            return 'forbidden';
1.20      www      2645:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2646:            return 'ok';
1.8       www      2647:     } else {
1.290     www      2648:         my $author=$filename;
                   2649:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2650:         my ($udom,$uname)=split(/\//,$author);
                   2651:         my $home=homeserver($uname,$udom);
                   2652:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2653:            my @parts=split(/\//,$filename);
                   2654:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2655:            if ($path ne "$londocroot/res") {
1.8       www      2656:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2657: 	       return 'bad_request';
1.8       www      2658:            }
                   2659:            my $count;
                   2660:            for ($count=5;$count<$#parts;$count++) {
                   2661:                $path.="/$parts[$count]";
                   2662:                if ((-e $path)!=1) {
                   2663: 		   mkdir($path,0777);
                   2664:                }
                   2665:            }
                   2666:            my $ua=new LWP::UserAgent;
                   2667:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2668:            my $response=$ua->request($request,$transname);
                   2669:            if ($response->is_error()) {
                   2670: 	       unlink($transname);
                   2671:                my $message=$response->status_line;
1.672     albertel 2672:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2673:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2674:                return 'unavailable';
1.8       www      2675:            } else {
1.16      www      2676: 	       if ($remoteurl!~/\.meta$/) {
                   2677:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2678:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2679:                   if ($mresponse->is_error()) {
                   2680: 		      unlink($filename.'.meta');
                   2681:                       &logthis(
1.672     albertel 2682:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2683:                   }
                   2684: 	       }
1.8       www      2685:                rename($transname,$filename);
1.607     raeburn  2686:                return 'ok';
1.8       www      2687:            }
1.290     www      2688:        }
1.8       www      2689:     }
1.330     www      2690: }
                   2691: 
                   2692: # ------------------------------------------------ Get server side include body
                   2693: sub ssi_body {
1.381     albertel 2694:     my ($filelink,%form)=@_;
1.606     matthew  2695:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2696:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2697:     }
1.953     www      2698:     my $output='';
                   2699:     my $response;
1.980     raeburn  2700:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2701:        ($output,$response)=&externalssi($filelink);
1.953     www      2702:     } else {
1.1004    droeschl 2703:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2704:        $filelink .= 'inhibitmenu=yes';
1.953     www      2705:        ($output,$response)=&ssi($filelink,%form);
                   2706:     }
1.778     albertel 2707:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2708:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2709:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2710:     if (wantarray) {
                   2711:         return ($output, $response);
                   2712:     } else {
                   2713:         return $output;
                   2714:     }
1.8       www      2715: }
                   2716: 
1.15      www      2717: # --------------------------------------------------------- Server Side Include
                   2718: 
1.782     albertel 2719: sub absolute_url {
                   2720:     my ($host_name) = @_;
                   2721:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2722:     if ($host_name eq '') {
                   2723: 	$host_name = $ENV{'SERVER_NAME'};
                   2724:     }
                   2725:     return $protocol.$host_name;
                   2726: }
                   2727: 
1.942     foxr     2728: #
                   2729: #   Server side include.
                   2730: # Parameters:
                   2731: #  fn     Possibly encrypted resource name/id.
                   2732: #  form   Hash that describes how the rendering should be done
                   2733: #         and other things.
1.944     foxr     2734: # Returns:
1.950     raeburn  2735: #   Scalar context: The content of the response.
                   2736: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2737: #     
1.15      www      2738: sub ssi {
                   2739: 
1.944     foxr     2740:     my ($fn,%form)=@_;
1.15      www      2741:     my $ua=new LWP::UserAgent;
1.23      www      2742:     my $request;
1.711     albertel 2743: 
                   2744:     $form{'no_update_last_known'}=1;
1.895     albertel 2745:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2746:     if (%form) {
1.782     albertel 2747:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2748:       $request->content(join('&',map {
                   2749:             my $name = escape($_);
                   2750:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2751:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2752:             : &escape($form{$_}) );
                   2753:         } keys(%form)));
1.23      www      2754:     } else {
1.782     albertel 2755:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2756:     }
                   2757: 
1.15      www      2758:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2759:     my $response= $ua->request($request);
1.944     foxr     2760:     if (wantarray) {
1.1172.2.3  raeburn  2761: 	return ($response->content, $response);
1.944     foxr     2762:     } else {
1.1172.2.3  raeburn  2763: 	return $response->content;
1.942     foxr     2764:     }
1.324     www      2765: }
                   2766: 
                   2767: sub externalssi {
                   2768:     my ($url)=@_;
                   2769:     my $ua=new LWP::UserAgent;
                   2770:     my $request=new HTTP::Request('GET',$url);
                   2771:     my $response=$ua->request($request);
1.954     raeburn  2772:     if (wantarray) {
                   2773:         return ($response->content, $response);
                   2774:     } else {
                   2775:         return $response->content;
                   2776:     }
1.15      www      2777: }
1.254     www      2778: 
1.492     albertel 2779: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2780: 
                   2781: sub allowuploaded {
                   2782:     my ($srcurl,$url)=@_;
                   2783:     $url=&clutter(&declutter($url));
                   2784:     my $dir=$url;
                   2785:     $dir=~s/\/[^\/]+$//;
                   2786:     my %httpref=();
                   2787:     my $httpurl=&hreflocation('',$url);
                   2788:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2789:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2790: }
1.477     raeburn  2791: 
1.1172.2.13  raeburn  2792: #
                   2793: # Determine if the current user should be able to edit a particular resource,
                   2794: # when viewing in course context.
                   2795: # (a) When viewing resource used to determine if "Edit" item is included in
                   2796: #     Functions.
                   2797: # (b) When displaying folder contents in course editor, used to determine if
                   2798: #     "Edit" link will be displayed alongside resource.
                   2799: #
                   2800: #  input: six args -- filename (decluttered), course number, course domain,
                   2801: #                   url, symb (if registered) and group (if this is a group
                   2802: #                   item -- e.g., bulletin board, group page etc.).
                   2803: #  output: array of five scalars --
                   2804: #          $cfile -- url for file editing if editable on current server
                   2805: #          $home -- homeserver of resource (i.e., for author if published,
                   2806: #                                           or course if uploaded.).
                   2807: #          $switchserver --  1 if server switch will be needed.
                   2808: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2809: #          $forceview -- 1 if icon/link should be to go to view mode
                   2810: #
                   2811: 
                   2812: sub can_edit_resource {
                   2813:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2814:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2815: #
                   2816: # For aboutme pages user can only edit his/her own.
                   2817: #
                   2818:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2819:         my ($sdom,$sname) = ($1,$2);
                   2820:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2821:             $home = $env{'user.home'};
                   2822:             $cfile = $resurl;
                   2823:             if ($env{'form.forceedit'}) {
                   2824:                 $forceview = 1;
                   2825:             } else {
                   2826:                 $forceedit = 1;
                   2827:             }
                   2828:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2829:         } else {
                   2830:             return;
                   2831:         }
                   2832:     }
                   2833: 
                   2834:     if ($env{'request.course.id'}) {
                   2835:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2836:         if ($group ne '') {
                   2837: # if this is a group homepage or group bulletin board, check group privs
                   2838:             my $allowed = 0;
                   2839:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2840:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2841:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2842:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2843:                     $allowed = 1;
                   2844:                 }
                   2845:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2846:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2847:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2848:                     $allowed = 1;
                   2849:                 }
                   2850:             }
                   2851:             if ($allowed) {
                   2852:                 $home=&homeserver($cnum,$cdom);
                   2853:                 if ($env{'form.forceedit'}) {
                   2854:                     $forceview = 1;
                   2855:                 } else {
                   2856:                     $forceedit = 1;
                   2857:                 }
                   2858:                 $cfile = $resurl;
                   2859:             } else {
                   2860:                 return;
                   2861:             }
                   2862:         } else {
1.1172.2.15  raeburn  2863:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2864:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2865:                     return;
                   2866:                 }
                   2867:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2868: #
                   2869: # No edit allowed where CC has switched to student role.
                   2870: #
                   2871:                 return;
                   2872:             }
                   2873:         }
                   2874:     }
                   2875: 
                   2876:     if ($file ne '') {
                   2877:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2878:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2879:                 $uploaded = 1;
                   2880:                 $incourse = 1;
                   2881:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2882:                     $cfile = &hreflocation('',$file);
                   2883:                     if ($env{'form.forceedit'}) {
                   2884:                         $forceview = 1;
                   2885:                     } else {
                   2886:                         $forceedit = 1;
                   2887:                     }
                   2888:                 }
                   2889:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2890:                 $incourse = 1;
                   2891:                 if ($env{'form.forceedit'}) {
                   2892:                     $forceview = 1;
                   2893:                 } else {
                   2894:                     $forceedit = 1;
                   2895:                 }
                   2896:                 $cfile = $resurl;
                   2897:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2898:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2899:                     $incourse = 1;
                   2900:                     if ($env{'form.forceedit'}) {
                   2901:                         $forceview = 1;
                   2902:                     } else {
                   2903:                         $forceedit = 1;
                   2904:                     }
                   2905:                     $cfile = $resurl;
                   2906:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2907:                     $incourse = 1;
                   2908:                     $cfile = $resurl.'/smpedit';
                   2909:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2910:                     $incourse = 1;
                   2911:                     if ($env{'form.forceedit'}) {
                   2912:                         $forceview = 1;
                   2913:                     } else {
                   2914:                         $forceedit = 1;
                   2915:                     }
                   2916:                     $cfile = $resurl;
1.1172.2.15  raeburn  2917:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2918:                     $incourse = 1;
                   2919:                     if ($env{'form.forceedit'}) {
                   2920:                         $forceview = 1;
                   2921:                     } else {
                   2922:                         $forceedit = 1;
                   2923:                     }
                   2924:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2925:                 }
                   2926:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2927:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2928:                 if (&is_on_map($template)) {
                   2929:                     $incourse = 1;
                   2930:                     $forceview = 1;
                   2931:                     $cfile = $template;
                   2932:                 }
                   2933:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2934:                     $incourse = 1;
                   2935:                     if ($env{'form.forceedit'}) {
                   2936:                         $forceview = 1;
                   2937:                     } else {
                   2938:                         $forceedit = 1;
                   2939:                     }
                   2940:                     $cfile = $resurl;
                   2941:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2942:                 $incourse = 1;
                   2943:                 $forceview = 1;
                   2944:                 if ($symb) {
                   2945:                     my ($map,$id,$res)=&decode_symb($symb);
                   2946:                     $env{'request.symb'} = $symb;
                   2947:                     $cfile = &clutter($res);
                   2948:                 } else {
                   2949:                     $cfile = $env{'form.suppurl'};
                   2950:                     $cfile =~ s{^http://}{};
                   2951:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2952:                 }
1.1172.2.31  raeburn  2953:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2954:                 if ($env{'form.forceedit'}) {
                   2955:                     $forceview = 1;
                   2956:                 } else {
                   2957:                     $forceedit = 1;
                   2958:                 }
                   2959:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2960:             }
                   2961:         }
                   2962:         if ($uploaded || $incourse) {
                   2963:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2964:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2965:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2966:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2967:             # Check that the user has permission to edit this resource
                   2968:             my $setpriv = 1;
                   2969:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2970:             if (defined($cfudom)) {
                   2971:                 $home=&homeserver($cfuname,$cfudom);
                   2972:                 $cfile=$file;
                   2973:             }
                   2974:         }
                   2975:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2976:             (($home ne '') && ($home ne 'no_host'))) {
                   2977:             my @ids=&current_machine_ids();
                   2978:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2979:                 $switchserver=1;
                   2980:             }
                   2981:         }
                   2982:     }
                   2983:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2984: }
                   2985: 
                   2986: sub is_course_upload {
                   2987:     my ($file,$cnum,$cdom) = @_;
                   2988:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2989:     $uploadpath =~ s{^\/}{};
                   2990:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2991:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2992:         return 1;
                   2993:     }
                   2994:     return;
                   2995: }
                   2996: 
                   2997: sub in_course {
                   2998:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2999:     if ($hideprivileged) {
                   3000:         my $skipuser;
1.1172.2.23  raeburn  3001:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3002:         my @possdoms = ($cdom);
                   3003:         if ($coursehash{'checkforpriv'}) {
                   3004:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3005:         }
                   3006:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3007:             $skipuser = 1;
                   3008:             if ($coursehash{'nothideprivileged'}) {
                   3009:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3010:                     my $user;
                   3011:                     if ($item =~ /:/) {
                   3012:                         $user = $item;
                   3013:                     } else {
                   3014:                         $user = join(':',split(/[\@]/,$item));
                   3015:                     }
                   3016:                     if ($user eq $uname.':'.$udom) {
                   3017:                         undef($skipuser);
                   3018:                         last;
                   3019:                     }
                   3020:                 }
                   3021:             }
                   3022:             if ($skipuser) {
                   3023:                 return 0;
                   3024:             }
                   3025:         }
                   3026:     }
                   3027:     $type ||= 'any';
                   3028:     if (!defined($cdom) || !defined($cnum)) {
                   3029:         my $cid  = $env{'request.course.id'};
                   3030:         $cdom = $env{'course.'.$cid.'.domain'};
                   3031:         $cnum = $env{'course.'.$cid.'.num'};
                   3032:     }
                   3033:     my $typesref;
                   3034:     if (($type eq 'any') || ($type eq 'all')) {
                   3035:         $typesref = ['active','previous','future'];
                   3036:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3037:         $typesref = [$type];
                   3038:     }
                   3039:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3040:                               $typesref,undef,[$cdom]);
                   3041:     my ($tmp) = keys(%roles);
                   3042:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3043:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3044:     if (@course_roles > 0) {
                   3045:         return 1;
                   3046:     }
                   3047:     return 0;
                   3048: }
                   3049: 
1.478     albertel 3050: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3051: # input: action, courseID, current domain, intended
1.637     raeburn  3052: #        path to file, source of file, instruction to parse file for objects,
                   3053: #        ref to hash for embedded objects,
                   3054: #        ref to hash for codebase of java objects.
1.1095    raeburn  3055: #        reference to scalar to accommodate mime type determined
                   3056: #          from File::MMagic if $parser = parse.
1.637     raeburn  3057: #
1.485     raeburn  3058: # output: url to file (if action was uploaddoc), 
                   3059: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3060: #
1.478     albertel 3061: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3062: # course.
1.477     raeburn  3063: #
1.478     albertel 3064: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3065: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3066: #          course's home server.
1.477     raeburn  3067: #
1.478     albertel 3068: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3069: #          be copied from $source (current location) to 
                   3070: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3071: #         and will then be copied to
                   3072: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3073: #         course's home server.
1.485     raeburn  3074: #
1.481     raeburn  3075: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3076: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3077: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3078: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3079: #         in course's home server.
1.637     raeburn  3080: #
1.477     raeburn  3081: 
                   3082: sub process_coursefile {
1.1095    raeburn  3083:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3084:         $mimetype)=@_;
1.477     raeburn  3085:     my $fetchresult;
1.638     albertel 3086:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3087:     if ($action eq 'propagate') {
1.638     albertel 3088:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3089: 			     $home);
1.481     raeburn  3090:     } else {
1.477     raeburn  3091:         my $fpath = '';
                   3092:         my $fname = $file;
1.478     albertel 3093:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3094:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3095:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3096:         if ($action eq 'copy') {
                   3097:             if ($source eq '') {
                   3098:                 $fetchresult = 'no source file';
                   3099:                 return $fetchresult;
                   3100:             } else {
                   3101:                 my $destination = $filepath.'/'.$fname;
                   3102:                 rename($source,$destination);
                   3103:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3104:                                  $home);
1.481     raeburn  3105:             }
                   3106:         } elsif ($action eq 'uploaddoc') {
                   3107:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3108:             print $fh $env{'form.'.$source};
1.481     raeburn  3109:             close($fh);
1.637     raeburn  3110:             if ($parser eq 'parse') {
1.1024    raeburn  3111:                 my $mm = new File::MMagic;
1.1095    raeburn  3112:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3113:                 if ($type eq 'text/html') {
1.1024    raeburn  3114:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3115:                     unless ($parse_result eq 'ok') {
                   3116:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3117:                     }
1.637     raeburn  3118:                 }
1.1095    raeburn  3119:                 if (ref($mimetype)) {
                   3120:                     $$mimetype = $type;
                   3121:                 } 
1.637     raeburn  3122:             }
1.477     raeburn  3123:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3124:                                  $home);
1.481     raeburn  3125:             if ($fetchresult eq 'ok') {
                   3126:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3127:             } else {
                   3128:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3129:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3130:                 return '/adm/notfound.html';
                   3131:             }
1.477     raeburn  3132:         }
                   3133:     }
1.485     raeburn  3134:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3135:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3136:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3137:     }
                   3138:     return $fetchresult;
                   3139: }
                   3140: 
1.637     raeburn  3141: sub build_filepath {
                   3142:     my ($fpath) = @_;
                   3143:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3144:     unless ($fpath eq '') {
                   3145:         my @parts=split('/',$fpath);
                   3146:         foreach my $part (@parts) {
                   3147:             $filepath.= '/'.$part;
                   3148:             if ((-e $filepath)!=1) {
                   3149:                 mkdir($filepath,0777);
                   3150:             }
                   3151:         }
                   3152:     }
                   3153:     return $filepath;
                   3154: }
                   3155: 
                   3156: sub store_edited_file {
1.638     albertel 3157:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3158:     my $file = $primary_url;
                   3159:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3160:     my $fpath = '';
                   3161:     my $fname = $file;
                   3162:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3163:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3164:     my $filepath = &build_filepath($fpath);
                   3165:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3166:     print $fh $content;
                   3167:     close($fh);
1.638     albertel 3168:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3169:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3170: 			  $home);
1.637     raeburn  3171:     if ($$fetchresult eq 'ok') {
                   3172:         return '/uploaded/'.$fpath.'/'.$fname;
                   3173:     } else {
1.638     albertel 3174:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3175: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3176:         return '/adm/notfound.html';
                   3177:     }
                   3178: }
                   3179: 
1.531     albertel 3180: sub clean_filename {
1.831     albertel 3181:     my ($fname,$args)=@_;
1.315     www      3182: # Replace Windows backslashes by forward slashes
1.257     www      3183:     $fname=~s/\\/\//g;
1.831     albertel 3184:     if (!$args->{'keep_path'}) {
                   3185:         # Get rid of everything but the actual filename
                   3186: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3187:     }
1.315     www      3188: # Replace spaces by underscores
                   3189:     $fname=~s/\s+/\_/g;
                   3190: # Replace all other weird characters by nothing
1.831     albertel 3191:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3192: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3193: # numbers
                   3194:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3195:     return $fname;
                   3196: }
1.1051    raeburn  3197: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3198: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3199: # image with the same aspect ratio as the original, but with dimensions which do 
                   3200: # not exceed $resizewidth and $resizeheight.
                   3201:  
1.984     neumanie 3202: sub resizeImage {
1.1051    raeburn  3203:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3204:     my $ima = Image::Magick->new;
                   3205:     my $resized;
                   3206:     if (-e $img_path) {
                   3207:         $ima->Read($img_path);
                   3208:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3209:             my $width = $ima->Get('width');
                   3210:             my $height = $ima->Get('height');
                   3211:             if ($width > $resizewidth) {
                   3212: 	        my $factor = $width/$resizewidth;
                   3213:                 my $newheight = $height/$factor;
                   3214:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3215:                 $resized = 1;
                   3216:             }
                   3217:         }
                   3218:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3219:             my $width = $ima->Get('width');
                   3220:             my $height = $ima->Get('height');
                   3221:             if ($height > $resizeheight) {
                   3222:                 my $factor = $height/$resizeheight;
                   3223:                 my $newwidth = $width/$factor;
                   3224:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3225:                 $resized = 1;
                   3226:             }
                   3227:         }
                   3228:         if ($resized) {
                   3229:             $ima->Write($img_path);
                   3230:         }
                   3231:     }
                   3232:     return;
1.977     amueller 3233: }
                   3234: 
1.608     albertel 3235: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3236: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3237: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3238: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3239: #                                    canceloverwrite, or ''. 
                   3240: #                   if 'coursedoc': upload to the current course
                   3241: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3242: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3243: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3244: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3245: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3246: #        $allfiles - reference to hash for embedded objects
                   3247: #        $codebase - reference to hash for codebase of java objects
                   3248: #        $desuname - username for permanent storage of uploaded file
                   3249: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3250: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3251: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3252: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3253: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3254: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3255: #                    from File::MMagic.
1.858     raeburn  3256: # 
1.686     albertel 3257: # output: url of file in userspace, or error: <message> 
                   3258: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3259: 
1.531     albertel 3260: sub userfileupload {
1.1090    raeburn  3261:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3262:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3263:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3264:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3265:     $fname=&clean_filename($fname);
1.1090    raeburn  3266:     # See if there is anything left
1.257     www      3267:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3268:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3269:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3270:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3271:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3272:         my $now = time;
1.1090    raeburn  3273:         my $filepath;
1.1095    raeburn  3274:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3275:              $filepath = 'tmp/helprequests/'.$now;
                   3276:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3277:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3278:                          '_'.$env{'user.domain'}.'/pending';
                   3279:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3280:             my ($docuname,$docudom);
                   3281:             if ($destudom) {
                   3282:                 $docudom = $destudom;
                   3283:             } else {
                   3284:                 $docudom = $env{'user.domain'};
                   3285:             }
                   3286:             if ($destuname) {
                   3287:                 $docuname = $destuname;
                   3288:             } else {
                   3289:                 $docuname = $env{'user.name'};
                   3290:             }
                   3291:             if (exists($env{'form.group'})) {
                   3292:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3293:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3294:             }
                   3295:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3296:             if ($context eq 'canceloverwrite') {
                   3297:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3298:                 if (-e  $tempfile) {
                   3299:                     my @info = stat($tempfile);
                   3300:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3301:                         unlink($tempfile);
                   3302:                     }
                   3303:                 }
                   3304:                 return;
1.523     raeburn  3305:             }
                   3306:         }
1.1090    raeburn  3307:         # Create the directory if not present
1.741     raeburn  3308:         my @parts=split(/\//,$filepath);
                   3309:         my $fullpath = $perlvar{'lonDaemons'};
                   3310:         for (my $i=0;$i<@parts;$i++) {
                   3311:             $fullpath .= '/'.$parts[$i];
                   3312:             if ((-e $fullpath)!=1) {
                   3313:                 mkdir($fullpath,0777);
                   3314:             }
                   3315:         }
                   3316:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3317:         print $fh $env{'form.'.$formname};
                   3318:         close($fh);
1.1090    raeburn  3319:         if ($context eq 'existingfile') {
                   3320:             my @info = stat($fullpath.'/'.$fname);
                   3321:             return ($fullpath.'/'.$fname,$info[9]);
                   3322:         } else {
                   3323:             return $fullpath.'/'.$fname;
                   3324:         }
1.523     raeburn  3325:     }
1.995     raeburn  3326:     if ($subdir eq 'scantron') {
                   3327:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3328:     } else {
1.995     raeburn  3329:         $fname="$subdir/$fname";
                   3330:     }
1.1090    raeburn  3331:     if ($context eq 'coursedoc') {
1.638     albertel 3332: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3333: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3334:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3335:             return &finishuserfileupload($docuname,$docudom,
                   3336: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3337: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3338:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3339:         } else {
1.1172.2.21  raeburn  3340:             if ($env{'form.folder'}) {
                   3341:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3342:             }
1.638     albertel 3343:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3344: 				       $fname,$formname,$parser,
1.1095    raeburn  3345: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3346:         }
1.719     banghart 3347:     } elsif (defined($destuname)) {
                   3348:         my $docuname=$destuname;
                   3349:         my $docudom=$destudom;
1.860     raeburn  3350: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3351: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3352:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3353:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3354:     } else {
1.638     albertel 3355:         my $docuname=$env{'user.name'};
                   3356:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3357:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3358:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3359:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3360:         }
1.860     raeburn  3361: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3362: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3363:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3364:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3365:     }
1.271     www      3366: }
                   3367: 
                   3368: sub finishuserfileupload {
1.860     raeburn  3369:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3370:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3371:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3372:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3373:   
1.860     raeburn  3374:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3375:     $file=$fname;
                   3376:     if ($fname=~m|/|) {
                   3377:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3378: 	$path.=$fnamepath.'/';
                   3379:     }
1.259     www      3380:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3381:     my $count;
                   3382:     for ($count=4;$count<=$#parts;$count++) {
                   3383:         $filepath.="/$parts[$count]";
                   3384:         if ((-e $filepath)!=1) {
                   3385: 	    mkdir($filepath,0777);
                   3386:         }
                   3387:     }
1.984     neumanie 3388: 
1.258     www      3389: # Save the file
                   3390:     {
1.701     albertel 3391: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3392: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3393: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3394: 	    return '/adm/notfound.html';
                   3395: 	}
1.1090    raeburn  3396:         if ($context eq 'overwrite') {
1.1117    foxr     3397:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3398:             my $target = $filepath.'/'.$file;
                   3399:             if (-e $source) {
                   3400:                 my @info = stat($source);
                   3401:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3402:                     unless (&File::Copy::move($source,$target)) {
                   3403:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3404:                         return "Moving from $source failed";
                   3405:                     }
                   3406:                 } else {
                   3407:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3408:                 }
                   3409:             } else {
                   3410:                 return "Temporary file: $source missing";
                   3411:             }
                   3412:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3413: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3414: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3415: 	    return '/adm/notfound.html';
                   3416: 	}
1.570     albertel 3417: 	close(FH);
1.1051    raeburn  3418:         if ($resizewidth && $resizeheight) {
                   3419:             my $mm = new File::MMagic;
                   3420:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3421:             if ($mime_type =~ m{^image/}) {
                   3422: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3423:             }  
1.977     amueller 3424: 	}
1.258     www      3425:     }
1.1152    raeburn  3426:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3427:         if (ref($mimetype)) {
                   3428:             if ($$mimetype eq '') {
                   3429:                 my $mm = new File::MMagic;
                   3430:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3431:                 $$mimetype = $type;
                   3432:             }
                   3433:         }
                   3434:     }
1.637     raeburn  3435:     if ($parser eq 'parse') {
1.1152    raeburn  3436:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3437:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3438:                                                        $allfiles,$codebase);
                   3439:             unless ($parse_result eq 'ok') {
                   3440:                 &logthis('Failed to parse '.$filepath.$file.
                   3441: 	   	         ' for embedded media: '.$parse_result); 
                   3442:             }
1.637     raeburn  3443:         }
                   3444:     }
1.860     raeburn  3445:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3446:         my $input = $filepath.'/'.$file;
                   3447:         my $output = $filepath.'/'.'tn-'.$file;
                   3448:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3449:         system("convert -sample $thumbsize $input $output");
                   3450:         if (-e $filepath.'/'.'tn-'.$file) {
                   3451:             $fetchthumb  = 1; 
                   3452:         }
                   3453:     }
1.858     raeburn  3454:  
1.259     www      3455: # Notify homeserver to grep it
                   3456: #
1.984     neumanie 3457:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3458:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3459:     if ($fetchresult eq 'ok') {
1.860     raeburn  3460:         if ($fetchthumb) {
                   3461:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3462:             if ($thumbresult ne 'ok') {
                   3463:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3464:                          $docuhome.': '.$thumbresult);
                   3465:             }
                   3466:         }
1.259     www      3467: #
1.258     www      3468: # Return the URL to it
1.494     albertel 3469:         return '/uploaded/'.$path.$file;
1.263     www      3470:     } else {
1.494     albertel 3471:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3472: 		 ': '.$fetchresult);
1.263     www      3473:         return '/adm/notfound.html';
1.858     raeburn  3474:     }
1.493     albertel 3475: }
                   3476: 
1.637     raeburn  3477: sub extract_embedded_items {
1.961     raeburn  3478:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3479:     my @state = ();
1.1164    raeburn  3480:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3481:     my %javafiles = (
                   3482:                       codebase => '',
                   3483:                       code => '',
                   3484:                       archive => ''
                   3485:                     );
                   3486:     my %mediafiles = (
                   3487:                       src => '',
                   3488:                       movie => '',
                   3489:                      );
1.648     raeburn  3490:     my $p;
                   3491:     if ($content) {
                   3492:         $p = HTML::LCParser->new($content);
                   3493:     } else {
1.961     raeburn  3494:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3495:     }
1.641     albertel 3496:     while (my $t=$p->get_token()) {
1.640     albertel 3497: 	if ($t->[0] eq 'S') {
                   3498: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3499: 	    push(@state, $tagname);
1.648     raeburn  3500:             if (lc($tagname) eq 'allow') {
                   3501:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3502:             }
1.640     albertel 3503: 	    if (lc($tagname) eq 'img') {
                   3504: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3505: 	    }
1.886     albertel 3506: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3507:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3508: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3509:                 }
1.886     albertel 3510: 	    }
1.645     raeburn  3511:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3512:                 my $src;
1.645     raeburn  3513:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3514:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3515:                 } else {
1.1164    raeburn  3516:                     if ($attr->{'src'} ne '') {
                   3517:                         $src = $attr->{'src'};
                   3518:                         &add_filetype($allfiles,$src,'src');
                   3519:                     }
                   3520:                 }
                   3521:                 my $text = $p->get_trimmed_text();
                   3522:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3523:                     my @swfargs = split(/,/,$1);
                   3524:                     foreach my $item (@swfargs) {
                   3525:                         $item =~ s/["']//g;
                   3526:                         $item =~ s/^\s+//;
                   3527:                         $item =~ s/\s+$//;
                   3528:                     }
                   3529:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3530:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3531:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3532:                         } else {
                   3533:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3534:                         }
                   3535:                     }
1.645     raeburn  3536:                 }
                   3537:             }
                   3538:             if (lc($tagname) eq 'link') {
                   3539:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3540:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3541:                 }
                   3542:             }
1.640     albertel 3543: 	    if (lc($tagname) eq 'object' ||
                   3544: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3545: 		foreach my $item (keys(%javafiles)) {
                   3546: 		    $javafiles{$item} = '';
                   3547: 		}
1.1164    raeburn  3548:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3549:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3550:                 }
1.640     albertel 3551: 	    }
                   3552: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3553: 		my $name = lc($attr->{'name'});
                   3554: 		foreach my $item (keys(%javafiles)) {
                   3555: 		    if ($name eq $item) {
                   3556: 			$javafiles{$item} = $attr->{'value'};
                   3557: 			last;
                   3558: 		    }
                   3559: 		}
1.1164    raeburn  3560:                 my $pathfrom;
1.640     albertel 3561: 		foreach my $item (keys(%mediafiles)) {
                   3562: 		    if ($name eq $item) {
1.1164    raeburn  3563:                         $pathfrom = $attr->{'value'};
                   3564:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3565: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3566: 			last;
                   3567: 		    }
                   3568: 		}
1.1164    raeburn  3569:                 if ($name eq 'flashvars') {
                   3570:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3571:                 }
                   3572:                 if ($pathfrom ne '') {
                   3573:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3574:                                          $pathfrom);
                   3575:                 }
1.640     albertel 3576: 	    }
                   3577: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3578: 		foreach my $item (keys(%javafiles)) {
                   3579: 		    if ($attr->{$item}) {
                   3580: 			$javafiles{$item} = $attr->{$item};
                   3581: 			last;
                   3582: 		    }
                   3583: 		}
                   3584: 		foreach my $item (keys(%mediafiles)) {
                   3585: 		    if ($attr->{$item}) {
                   3586: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3587: 			last;
                   3588: 		    }
                   3589: 		}
1.1164    raeburn  3590:                 if (lc($tagname) eq 'embed') {
                   3591:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3592:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3593:                                              $attr->{'src'});
                   3594:                     }
                   3595:                 }
1.640     albertel 3596: 	    }
1.1172.2.35  raeburn  3597:             if (lc($tagname) eq 'iframe') {
                   3598:                 my $src = $attr->{'src'} ;
                   3599:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3600:                     &add_filetype($allfiles,$src,'src');
                   3601:                 } elsif ($src =~ m{^/}) {
                   3602:                     if ($env{'request.course.id'}) {
                   3603:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3604:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3605:                         my $url = &hreflocation('',$fullpath);
                   3606:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3607:                             my $relpath = $1;
                   3608:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3609:                                 &add_filetype($allfiles,$1,'src');
                   3610:                             }
                   3611:                         }
                   3612:                     }
                   3613:                 }
                   3614:             }
1.1164    raeburn  3615:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3616:                 pop(@state);
1.1164    raeburn  3617:             }
1.640     albertel 3618: 	} elsif ($t->[0] eq 'E') {
                   3619: 	    my ($tagname) = ($t->[1]);
                   3620: 	    if ($javafiles{'codebase'} ne '') {
                   3621: 		$javafiles{'codebase'} .= '/';
                   3622: 	    }  
                   3623: 	    if (lc($tagname) eq 'applet' ||
                   3624: 		lc($tagname) eq 'object' ||
                   3625: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3626: 		) {
                   3627: 		foreach my $item (keys(%javafiles)) {
                   3628: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3629: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3630: 			&add_filetype($allfiles,$file,$item);
                   3631: 		    }
                   3632: 		}
                   3633: 	    } 
                   3634: 	    pop @state;
                   3635: 	}
                   3636:     }
1.1164    raeburn  3637:     foreach my $id (sort(keys(%flashvars))) {
                   3638:         if ($shockwave{$id} ne '') {
                   3639:             my @pairs = split(/\&/,$flashvars{$id});
                   3640:             foreach my $pair (@pairs) {
                   3641:                 my ($key,$value) = split(/\=/,$pair);
                   3642:                 if ($key eq 'thumb') {
                   3643:                     &add_filetype($allfiles,$value,$key);
                   3644:                 } elsif ($key eq 'content') {
                   3645:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3646:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3647:                     if ($ext ne '') {
                   3648:                         &add_filetype($allfiles,$path.$value,$ext);
                   3649:                     }
                   3650:                 }
                   3651:             }
                   3652:         }
                   3653:     }
1.637     raeburn  3654:     return 'ok';
                   3655: }
                   3656: 
1.639     albertel 3657: sub add_filetype {
                   3658:     my ($allfiles,$file,$type)=@_;
                   3659:     if (exists($allfiles->{$file})) {
                   3660: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3661: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3662: 	}
                   3663:     } else {
                   3664: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3665:     }
                   3666: }
                   3667: 
1.1164    raeburn  3668: sub embedded_dependency {
                   3669:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3670:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3671:         if (($identifier ne '') &&
                   3672:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3673:             ($pathfrom ne '')) {
                   3674:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3675:             foreach my $dep (@{$related->{$identifier}}) {
                   3676:                 &add_filetype($allfiles,$path.$dep,'object');
                   3677:             }
                   3678:         }
                   3679:     }
                   3680:     return;
                   3681: }
                   3682: 
1.493     albertel 3683: sub removeuploadedurl {
1.984     neumanie 3684:     my ($url)=@_;	
                   3685:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3686:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3687: }
                   3688: 
                   3689: sub removeuserfile {
                   3690:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3691:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3692:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3693:     if ($result eq 'ok') {	
1.798     raeburn  3694:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3695:             my $metafile = $fname.'.meta';
                   3696:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3697: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3698:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3699:             my $sqlresult = 
1.823     albertel 3700:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3701:                                         'portfolio_metadata',$group,
                   3702:                                         'delete');
1.798     raeburn  3703:         }
                   3704:     }
                   3705:     return $result;
1.257     www      3706: }
1.15      www      3707: 
1.530     albertel 3708: sub mkdiruserfile {
                   3709:     my ($docuname,$docudom,$dir)=@_;
                   3710:     my $home=&homeserver($docuname,$docudom);
                   3711:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3712: }
                   3713: 
1.531     albertel 3714: sub renameuserfile {
                   3715:     my ($docuname,$docudom,$old,$new)=@_;
                   3716:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3717:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3718:                         &escape("$old").':'.&escape("$new"),$home);
                   3719:     if ($result eq 'ok') {
                   3720:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3721:             my $oldmeta = $old.'.meta';
                   3722:             my $newmeta = $new.'.meta';
                   3723:             my $metaresult = 
                   3724:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3725: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3726:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3727:             my $sqlresult = 
1.823     albertel 3728:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3729:                                         'portfolio_metadata',$group,
                   3730:                                         'delete');
1.798     raeburn  3731:         }
                   3732:     }
                   3733:     return $result;
1.531     albertel 3734: }
                   3735: 
1.14      www      3736: # ------------------------------------------------------------------------- Log
                   3737: 
                   3738: sub log {
                   3739:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3740:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3741: }
                   3742: 
                   3743: # ------------------------------------------------------------------ Course Log
1.352     www      3744: #
                   3745: # This routine flushes several buffers of non-mission-critical nature
                   3746: #
1.157     www      3747: 
                   3748: sub flushcourselogs {
1.352     www      3749:     &logthis('Flushing log buffers');
                   3750: #
                   3751: # course logs
                   3752: # This is a log of all transactions in a course, which can be used
                   3753: # for data mining purposes
                   3754: #
                   3755: # It also collects the courseid database, which lists last transaction
                   3756: # times and course titles for all courseids
                   3757: #
                   3758:     my %courseidbuffer=();
1.921     raeburn  3759:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3760:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3761: 		          &escape($courselogs{$crsid}),
                   3762: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3763: 	    delete $courselogs{$crsid};
                   3764:         } else {
                   3765:             &logthis('Failed to flush log buffer for '.$crsid);
                   3766:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3767:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3768:                         " exceeded maximum size, deleting.</font>");
                   3769:                delete $courselogs{$crsid};
                   3770:             }
1.352     www      3771:         }
1.920     raeburn  3772:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3773:             'description' => $coursedescrbuf{$crsid},
                   3774:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3775:             'type'        => $coursetypebuf{$crsid},
                   3776:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3777:         };
1.191     harris41 3778:     }
1.352     www      3779: #
                   3780: # Write course id database (reverse lookup) to homeserver of courses 
                   3781: # Is used in pickcourse
                   3782: #
1.840     albertel 3783:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3784:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3785:                                     $courseidbuffer{$crs_home},
                   3786:                                     $crs_home,'timeonly');
1.352     www      3787:     }
                   3788: #
                   3789: # File accesses
                   3790: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3791: #
1.449     matthew  3792:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3793:         if ($entry =~ /___count$/) {
                   3794:             my ($dom,$name);
1.807     albertel 3795:             ($dom,$name,undef)=
1.811     albertel 3796: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3797:             if (! defined($dom) || $dom eq '' || 
                   3798:                 ! defined($name) || $name eq '') {
1.620     albertel 3799:                 my $cid = $env{'request.course.id'};
                   3800:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3801:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3802:             }
1.450     matthew  3803:             my $value = $accesshash{$entry};
                   3804:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3805:             my %temphash=($url => $value);
1.449     matthew  3806:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3807:             if ($result eq 'ok') {
                   3808:                 delete $accesshash{$entry};
                   3809:             }
                   3810:         } else {
1.811     albertel 3811:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3812:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3813:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3814:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3815:                 delete $accesshash{$entry};
                   3816:             }
1.185     www      3817:         }
1.191     harris41 3818:     }
1.352     www      3819: #
                   3820: # Roles
                   3821: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3822: #
1.800     albertel 3823:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3824:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3825: 	    split(/\:/,$entry);
                   3826:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3827:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3828:                 $rudom,$runame) eq 'ok') {
                   3829: 	    delete $userrolehash{$entry};
                   3830:         }
                   3831:     }
1.662     raeburn  3832: #
                   3833: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3834: #
                   3835:     my %domrolebuffer = ();
1.1000    raeburn  3836:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3837:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3838:         if ($domrolebuffer{$rudom}) {
                   3839:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3840:                       '='.&escape($domainrolehash{$entry});
                   3841:         } else {
                   3842:             $domrolebuffer{$rudom}.=&escape($entry).
                   3843:                       '='.&escape($domainrolehash{$entry});
                   3844:         }
                   3845:         delete $domainrolehash{$entry};
                   3846:     }
                   3847:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3848: 	my %servers = &get_servers($dom,'library');
                   3849: 	foreach my $tryserver (keys(%servers)) {
                   3850: 	    unless (&reply('domroleput:'.$dom.':'.
                   3851: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3852: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3853: 	    }
1.662     raeburn  3854:         }
                   3855:     }
1.186     www      3856:     $dumpcount++;
1.157     www      3857: }
                   3858: 
                   3859: sub courselog {
                   3860:     my $what=shift;
1.158     www      3861:     $what=time.':'.$what;
1.620     albertel 3862:     unless ($env{'request.course.id'}) { return ''; }
                   3863:     $coursedombuf{$env{'request.course.id'}}=
                   3864:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3865:     $coursenumbuf{$env{'request.course.id'}}=
                   3866:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3867:     $coursehombuf{$env{'request.course.id'}}=
                   3868:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3869:     $coursedescrbuf{$env{'request.course.id'}}=
                   3870:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3871:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3872:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3873:     $courseownerbuf{$env{'request.course.id'}}=
                   3874:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3875:     $coursetypebuf{$env{'request.course.id'}}=
                   3876:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3877:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3878: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3879:     } else {
1.620     albertel 3880: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3881:     }
1.620     albertel 3882:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3883: 	&flushcourselogs();
                   3884:     }
1.158     www      3885: }
                   3886: 
                   3887: sub courseacclog {
                   3888:     my $fnsymb=shift;
1.620     albertel 3889:     unless ($env{'request.course.id'}) { return ''; }
                   3890:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3891:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3892:         $what.=':POST';
1.583     matthew  3893:         # FIXME: Probably ought to escape things....
1.800     albertel 3894: 	foreach my $key (keys(%env)) {
                   3895:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3896:                 my $formitem = $1;
                   3897:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3898:                     $what.=':'.$formitem.'='.$env{$key};
                   3899:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3900:                     $what.=':'.$formitem.'='.$env{$key};
                   3901:                 }
1.158     www      3902:             }
1.191     harris41 3903:         }
1.583     matthew  3904:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3905:         # FIXME: We should not be depending on a form parameter that someone
                   3906:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3907:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3908:             $what.= ':POST';
                   3909:             # FIXME: Probably ought to escape things....
                   3910:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3911:                                  'crsdiscuss') {
1.620     albertel 3912:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3913:             }
                   3914:         }
1.158     www      3915:     }
                   3916:     &courselog($what);
1.149     www      3917: }
                   3918: 
1.185     www      3919: sub countacc {
                   3920:     my $url=&declutter(shift);
1.458     matthew  3921:     return if (! defined($url) || $url eq '');
1.620     albertel 3922:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3923: #
                   3924: # Mark that this url was used in this course
                   3925: #
1.620     albertel 3926:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3927: #
                   3928: # Increase the access count for this resource in this child process
                   3929: #
1.281     www      3930:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3931:     $accesshash{$key}++;
1.185     www      3932: }
1.349     www      3933: 
1.361     www      3934: sub linklog {
                   3935:     my ($from,$to)=@_;
                   3936:     $from=&declutter($from);
                   3937:     $to=&declutter($to);
                   3938:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3939:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3940: }
1.1160    www      3941: 
                   3942: sub statslog {
                   3943:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3944:     if ($users<2) { return; }
                   3945:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3946:             'course'       => $env{'request.course.id'},
                   3947:             'sections'     => '"all"',
                   3948:             'num_students' => $users,
                   3949:             'part'         => $part,
                   3950:             'symb'         => $symb,
                   3951:             'mean_tries'   => $av_attempts,
                   3952:             'deg_of_diff'  => $degdiff});
                   3953:     foreach my $key (keys(%dynstore)) {
                   3954:         $accesshash{$key}=$dynstore{$key};
                   3955:     }
                   3956: }
1.361     www      3957:   
1.349     www      3958: sub userrolelog {
                   3959:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3960:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3961:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3962:        $userrolehash
                   3963:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3964:                     =$tend.':'.$tstart;
1.662     raeburn  3965:     }
1.1169    droeschl 3966:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3967:        $userrolehash
                   3968:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3969:                     =$tend.':'.$tstart;
                   3970:     }
1.1169    droeschl 3971:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3972:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3973:        $domainrolehash
                   3974:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3975:                     = $tend.':'.$tstart;
                   3976:     }
1.351     www      3977: }
                   3978: 
1.957     raeburn  3979: sub courserolelog {
                   3980:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3981:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3982:         my $cdom = $1;
                   3983:         my $cnum = $2;
                   3984:         my $sec = $3;
                   3985:         my $namespace = 'rolelog';
                   3986:         my %storehash = (
                   3987:                            role    => $trole,
                   3988:                            start   => $tstart,
                   3989:                            end     => $tend,
                   3990:                            selfenroll => $selfenroll,
                   3991:                            context    => $context,
                   3992:                         );
                   3993:         if ($trole eq 'gr') {
                   3994:             $namespace = 'groupslog';
                   3995:             $storehash{'group'} = $sec;
                   3996:         } else {
                   3997:             $storehash{'section'} = $sec;
                   3998:         }
                   3999:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4000:                    $domain,$cnum,$cdom);
                   4001:         if (($trole ne 'st') || ($sec ne '')) {
                   4002:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4003:         }
                   4004:     }
                   4005:     return;
                   4006: }
                   4007: 
1.1172.2.9  raeburn  4008: sub domainrolelog {
                   4009:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4010:     if ($area =~ m{^/($match_domain)/$}) {
                   4011:         my $cdom = $1;
                   4012:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4013:         my $namespace = 'rolelog';
                   4014:         my %storehash = (
                   4015:                            role    => $trole,
                   4016:                            start   => $tstart,
                   4017:                            end     => $tend,
                   4018:                            context => $context,
                   4019:                         );
                   4020:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4021:                    $domain,$domconfiguser,$cdom);
                   4022:     }
                   4023:     return;
                   4024: 
                   4025: }
                   4026: 
                   4027: sub coauthorrolelog {
                   4028:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4029:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4030:         my $audom = $1;
                   4031:         my $auname = $2;
                   4032:         my $namespace = 'rolelog';
                   4033:         my %storehash = (
                   4034:                            role    => $trole,
                   4035:                            start   => $tstart,
                   4036:                            end     => $tend,
                   4037:                            context => $context,
                   4038:                         );
                   4039:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4040:                    $domain,$auname,$audom);
                   4041:     }
                   4042:     return;
                   4043: }
                   4044: 
1.351     www      4045: sub get_course_adv_roles {
1.948     raeburn  4046:     my ($cid,$codes) = @_;
1.620     albertel 4047:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4048:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4049:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4050:     my %nothide=();
1.800     albertel 4051:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4052:         if ($user !~ /:/) {
                   4053: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4054:         } else {
                   4055:             $nothide{$user}=1;
                   4056:         }
1.470     www      4057:     }
1.1172.2.23  raeburn  4058:     my @possdoms = ($coursehash{'domain'});
                   4059:     if ($coursehash{'checkforpriv'}) {
                   4060:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4061:     }
1.351     www      4062:     my %returnhash=();
                   4063:     my %dumphash=
                   4064:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4065:     my $now=time;
1.997     raeburn  4066:     my %privileged;
1.1000    raeburn  4067:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4068: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4069:         if (($tstart) && ($tstart<0)) { next; }
                   4070:         if (($tend) && ($tend<$now)) { next; }
                   4071:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4072:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4073: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4074:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4075:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4076: 	if ($role eq 'cr') { next; }
1.948     raeburn  4077:         if ($codes) {
                   4078:             if ($section) { $role .= ':'.$section; }
                   4079:             if ($returnhash{$role}) {
                   4080:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4081:             } else {
                   4082:                 $returnhash{$role}=$username.':'.$domain;
                   4083:             }
1.351     www      4084:         } else {
1.988     raeburn  4085:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4086:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4087:             if ($returnhash{$key}) {
                   4088: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4089:             } else {
                   4090:                 $returnhash{$key}=$username.':'.$domain;
                   4091:             }
1.351     www      4092:         }
1.948     raeburn  4093:     }
1.400     www      4094:     return %returnhash;
                   4095: }
                   4096: 
                   4097: sub get_my_roles {
1.937     raeburn  4098:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4099:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4100:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4101:     my (%dumphash,%nothide);
1.1086    raeburn  4102:     if ($context eq 'userroles') {
1.1166    raeburn  4103:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4104:     } else {
1.1172.2.23  raeburn  4105:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4106:         if ($hidepriv) {
                   4107:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4108:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4109:                 if ($user !~ /:/) {
                   4110:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4111:                 } else {
                   4112:                     $nothide{$user} = 1;
                   4113:                 }
                   4114:             }
                   4115:         }
1.858     raeburn  4116:     }
1.400     www      4117:     my %returnhash=();
                   4118:     my $now=time;
1.999     raeburn  4119:     my %privileged;
1.800     albertel 4120:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4121:         my ($role,$tend,$tstart);
                   4122:         if ($context eq 'userroles') {
1.1149    raeburn  4123:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4124: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4125:         } else {
                   4126:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4127:         }
1.400     www      4128:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4129:         my $status = 'active';
1.939     raeburn  4130:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4131:             $status = 'previous';
                   4132:         } 
                   4133:         if (($tstart) && ($now<$tstart)) {
                   4134:             $status = 'future';
                   4135:         }
                   4136:         if (ref($types) eq 'ARRAY') {
                   4137:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4138:                 next;
                   4139:             } 
                   4140:         } else {
                   4141:             if ($status ne 'active') {
                   4142:                 next;
                   4143:             }
                   4144:         }
1.867     raeburn  4145:         my ($rolecode,$username,$domain,$section,$area);
                   4146:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4147:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4148:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4149:         } else {
                   4150:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4151:         }
1.832     raeburn  4152:         if (ref($roledoms) eq 'ARRAY') {
                   4153:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4154:                 next;
                   4155:             }
                   4156:         }
                   4157:         if (ref($roles) eq 'ARRAY') {
                   4158:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4159:                 if ($role =~ /^cr\//) {
                   4160:                     if (!grep(/^cr$/,@{$roles})) {
                   4161:                         next;
                   4162:                     }
1.1104    raeburn  4163:                 } elsif ($role =~ /^gr\//) {
                   4164:                     if (!grep(/^gr$/,@{$roles})) {
                   4165:                         next;
                   4166:                     }
1.922     raeburn  4167:                 } else {
                   4168:                     next;
                   4169:                 }
1.832     raeburn  4170:             }
1.867     raeburn  4171:         }
1.937     raeburn  4172:         if ($hidepriv) {
1.1172.2.23  raeburn  4173:             my @privroles = ('dc','su');
1.999     raeburn  4174:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4175:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4176:             } else {
1.1172.2.23  raeburn  4177:                 my $possdoms = [$domain];
                   4178:                 if (ref($roledoms) eq 'ARRAY') {
                   4179:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4180:                 }
1.1172.2.23  raeburn  4181:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4182:                     if (!$nothide{$username.':'.$domain}) {
                   4183:                         next;
                   4184:                     }
                   4185:                 }
1.937     raeburn  4186:             }
                   4187:         }
1.933     raeburn  4188:         if ($withsec) {
                   4189:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4190:                 $tstart.':'.$tend;
                   4191:         } else {
                   4192:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4193:         }
1.832     raeburn  4194:     }
1.373     www      4195:     return %returnhash;
1.399     www      4196: }
                   4197: 
                   4198: # ----------------------------------------------------- Frontpage Announcements
                   4199: #
                   4200: #
                   4201: 
                   4202: sub postannounce {
                   4203:     my ($server,$text)=@_;
1.844     albertel 4204:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4205:     unless ($text=~/\w/) { $text=''; }
                   4206:     return &reply('setannounce:'.&escape($text),$server);
                   4207: }
                   4208: 
                   4209: sub getannounce {
1.448     albertel 4210: 
                   4211:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4212: 	my $announcement='';
1.800     albertel 4213: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4214: 	close($fh);
1.399     www      4215: 	if ($announcement=~/\w/) { 
                   4216: 	    return 
                   4217:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4218:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4219: 	} else {
                   4220: 	    return '';
                   4221: 	}
                   4222:     } else {
                   4223: 	return '';
                   4224:     }
1.351     www      4225: }
1.353     www      4226: 
                   4227: # ---------------------------------------------------------- Course ID routines
                   4228: # Deal with domain's nohist_courseid.db files
                   4229: #
                   4230: 
                   4231: sub courseidput {
1.921     raeburn  4232:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4233:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4234:     my $outcome;
                   4235:     if ($caller eq 'timeonly') {
                   4236:         my $cids = '';
                   4237:         foreach my $item (keys(%$storehash)) {
                   4238:             $cids.=&escape($item).'&';
                   4239:         }
                   4240:         $cids=~s/\&$//;
                   4241:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4242:                           $coursehome);       
                   4243:     } else {
                   4244:         my $items = '';
                   4245:         foreach my $item (keys(%$storehash)) {
                   4246:             $items.= &escape($item).'='.
                   4247:                      &freeze_escape($$storehash{$item}).'&';
                   4248:         }
                   4249:         $items=~s/\&$//;
                   4250:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4251:                           $coursehome);
1.918     raeburn  4252:     }
                   4253:     if ($outcome eq 'unknown_cmd') {
                   4254:         my $what;
                   4255:         foreach my $cid (keys(%$storehash)) {
                   4256:             $what .= &escape($cid).'=';
1.921     raeburn  4257:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4258:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4259:             }
                   4260:             $what =~ s/\:$/&/;
                   4261:         }
                   4262:         $what =~ s/\&$//;  
                   4263:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4264:     } else {
                   4265:         return $outcome;
                   4266:     }
1.353     www      4267: }
                   4268: 
                   4269: sub courseiddump {
1.921     raeburn  4270:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4271:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4272:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4273:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
                   4274:         $hasuniquecode)=@_;
1.918     raeburn  4275:     my $as_hash = 1;
                   4276:     my %returnhash;
                   4277:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4278:     my %libserv = &all_library();
                   4279:     foreach my $tryserver (keys(%libserv)) {
                   4280:         if ( (  $hostidflag == 1 
                   4281: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4282: 	     || (!defined($hostidflag)) ) {
                   4283: 
1.918     raeburn  4284: 	    if (($domfilter eq '') ||
                   4285: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4286:                 my $rep;
                   4287:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4288:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4289:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4290:                                 &escape($descfilter), &escape($instcodefilter),
                   4291:                                 &escape($ownerfilter), &escape($coursefilter),
                   4292:                                 &escape($typefilter), &escape($regexp_ok),
                   4293:                                 $as_hash, &escape($selfenrollonly),
                   4294:                                 &escape($catfilter), $showhidden, $caller,
                   4295:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4296:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.38  raeburn  4297:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22  raeburn  4298:                 } else {
                   4299:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4300:                              $sincefilter.':'.&escape($descfilter).':'.
                   4301:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4302:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4303:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4304:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4305:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4306:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4307:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38  raeburn  4308:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22  raeburn  4309:                              $tryserver);
                   4310:                 }
                   4311: 
1.918     raeburn  4312:                 my @pairs=split(/\&/,$rep);
                   4313:                 foreach my $item (@pairs) {
                   4314:                     my ($key,$value)=split(/\=/,$item,2);
                   4315:                     $key = &unescape($key);
                   4316:                     next if ($key =~ /^error: 2 /);
                   4317:                     my $result = &thaw_unescape($value);
                   4318:                     if (ref($result) eq 'HASH') {
                   4319:                         $returnhash{$key}=$result;
                   4320:                     } else {
1.921     raeburn  4321:                         my @responses = split(/:/,$value);
                   4322:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4323:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4324:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4325:                         }
1.1008    raeburn  4326:                     }
1.353     www      4327:                 }
                   4328:             }
                   4329:         }
                   4330:     }
                   4331:     return %returnhash;
                   4332: }
                   4333: 
1.1055    raeburn  4334: sub courselastaccess {
                   4335:     my ($cdom,$cnum,$hostidref) = @_;
                   4336:     my %returnhash;
                   4337:     if ($cdom && $cnum) {
                   4338:         my $chome = &homeserver($cnum,$cdom);
                   4339:         if ($chome ne 'no_host') {
                   4340:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4341:             &extract_lastaccess(\%returnhash,$rep);
                   4342:         }
                   4343:     } else {
                   4344:         if (!$cdom) { $cdom=''; }
                   4345:         my %libserv = &all_library();
                   4346:         foreach my $tryserver (keys(%libserv)) {
                   4347:             if (ref($hostidref) eq 'ARRAY') {
                   4348:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4349:             } 
                   4350:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4351:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4352:                 &extract_lastaccess(\%returnhash,$rep);
                   4353:             }
                   4354:         }
                   4355:     }
                   4356:     return %returnhash;
                   4357: }
                   4358: 
                   4359: sub extract_lastaccess {
                   4360:     my ($returnhash,$rep) = @_;
                   4361:     if (ref($returnhash) eq 'HASH') {
                   4362:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4363:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4364:                  $rep eq '') {
                   4365:             my @pairs=split(/\&/,$rep);
                   4366:             foreach my $item (@pairs) {
                   4367:                 my ($key,$value)=split(/\=/,$item,2);
                   4368:                 $key = &unescape($key);
                   4369:                 next if ($key =~ /^error: 2 /);
                   4370:                 $returnhash->{$key} = &thaw_unescape($value);
                   4371:             }
                   4372:         }
                   4373:     }
                   4374:     return;
                   4375: }
                   4376: 
1.658     raeburn  4377: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4378: 
                   4379: sub dcmailput {
1.685     raeburn  4380:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4381:     my $status = &Apache::lonnet::critical(
1.740     www      4382:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4383:        &escape($message),$server);
1.662     raeburn  4384:     return $status;
                   4385: }
                   4386: 
1.658     raeburn  4387: sub dcmaildump {
                   4388:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4389:     my %returnhash=();
1.846     albertel 4390: 
                   4391:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4392:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4393:                                                          &escape($enddate).':';
                   4394: 	my @esc_senders=map { &escape($_)} @$senders;
                   4395: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4396: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4397:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4398:             if (($key) && ($value)) {
                   4399:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4400:             }
                   4401:         }
                   4402:     }
                   4403:     return %returnhash;
                   4404: }
1.662     raeburn  4405: # ---------------------------------------------------------- Domain roles
                   4406: 
                   4407: sub get_domain_roles {
                   4408:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4409:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4410:         $startdate = '.';
                   4411:     }
1.1018    raeburn  4412:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4413:         $enddate = '.';
                   4414:     }
1.922     raeburn  4415:     my $rolelist;
                   4416:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4417:         $rolelist = join('&',@{$roles});
1.922     raeburn  4418:     }
1.662     raeburn  4419:     my %personnel = ();
1.841     albertel 4420: 
                   4421:     my %servers = &get_servers($dom,'library');
                   4422:     foreach my $tryserver (keys(%servers)) {
                   4423: 	%{$personnel{$tryserver}}=();
                   4424: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4425: 					    &escape($startdate).':'.
                   4426: 					    &escape($enddate).':'.
                   4427: 					    &escape($rolelist), $tryserver))) {
                   4428: 	    my ($key,$value) = split(/\=/,$line,2);
                   4429: 	    if (($key) && ($value)) {
                   4430: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4431: 	    }
                   4432: 	}
1.662     raeburn  4433:     }
                   4434:     return %personnel;
                   4435: }
1.658     raeburn  4436: 
1.1057    www      4437: # ----------------------------------------------------------- Interval timing 
1.149     www      4438: 
1.1153    www      4439: {
                   4440: # Caches needed for speedup of navmaps
                   4441: # We don't want to cache this for very long at all (5 seconds at most)
                   4442: # 
                   4443: # The user for whom we cache
                   4444: my $cachedkey='';
                   4445: # The cached times for this user
                   4446: my %cachedtimes=();
                   4447: # When this was last done
1.1172.2.66  raeburn  4448: my $cachedtime='';
1.1153    www      4449: 
                   4450: sub load_all_first_access {
1.1154    raeburn  4451:     my ($uname,$udom)=@_;
1.1156    www      4452:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4453:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4454:         return;
                   4455:     }
                   4456:     $cachedtime=time;
                   4457:     $cachedkey=$uname.':'.$udom;
                   4458:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4459: }
                   4460: 
1.504     albertel 4461: sub get_first_access {
1.1162    raeburn  4462:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4463:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4464:     if ($argsymb) { $symb=$argsymb; }
                   4465:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4466:     if ($argmap) { $map = $argmap; }
1.926     albertel 4467:     if ($type eq 'course') {
                   4468: 	$res='course';
                   4469:     } elsif ($type eq 'map') {
1.588     albertel 4470: 	$res=&symbread($map);
                   4471:     } else {
                   4472: 	$res=$symb;
                   4473:     }
1.1153    www      4474:     &load_all_first_access($uname,$udom);
                   4475:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4476: }
                   4477: 
                   4478: sub set_first_access {
1.1162    raeburn  4479:     my ($type,$interval)=@_;
1.790     albertel 4480:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4481:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4482:     if ($type eq 'course') {
                   4483: 	$res='course';
                   4484:     } elsif ($type eq 'map') {
1.588     albertel 4485: 	$res=&symbread($map);
                   4486:     } else {
                   4487: 	$res=$symb;
                   4488:     }
1.1153    www      4489:     $cachedkey='';
1.1162    raeburn  4490:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4491:     if (!$firstaccess) {
1.1162    raeburn  4492:         my $start = time;
                   4493: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4494:                           $udom,$uname);
                   4495:         if ($putres eq 'ok') {
                   4496:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4497:                  $udom,$uname); 
                   4498:             &appenv(
                   4499:                      {
                   4500:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4501:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4502:                      }
                   4503:                   );
                   4504:         }
                   4505:         return $putres;
1.505     albertel 4506:     }
                   4507:     return 'already_set';
1.504     albertel 4508: }
1.1153    www      4509: }
1.1172.2.32  raeburn  4510: 
                   4511: sub checkout {
                   4512:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4513:     my $now=time;
                   4514:     my $lonhost=$perlvar{'lonHostID'};
                   4515:     my $infostr=&escape(
                   4516:                  'CHECKOUTTOKEN&'.
                   4517:                  $tuname.'&'.
                   4518:                  $tudom.'&'.
                   4519:                  $tcrsid.'&'.
                   4520:                  $symb.'&'.
                   4521:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4522:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4523:     if ($token=~/^error\:/) {
                   4524:         &logthis("<font color=\"blue\">WARNING: ".
                   4525:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4526:                  "</font>");
                   4527:         return '';
                   4528:     }
                   4529: 
                   4530:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4531:     $token=~tr/a-z/A-Z/;
                   4532: 
                   4533:     my %infohash=('resource.0.outtoken' => $token,
                   4534:                   'resource.0.checkouttime' => $now,
                   4535:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4536: 
                   4537:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4538:        return '';
                   4539:     } else {
                   4540:         &logthis("<font color=\"blue\">WARNING: ".
                   4541:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4542:                  "</font>");
                   4543:     }
                   4544: 
                   4545:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4546:                          &escape('Checkout '.$infostr.' - '.
                   4547:                                                  $token)) ne 'ok') {
                   4548:         return '';
                   4549:     } else {
                   4550:         &logthis("<font color=\"blue\">WARNING: ".
                   4551:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4552:                  "</font>");
                   4553:     }
                   4554:     return $token;
                   4555: }
                   4556: 
                   4557: # ------------------------------------------------------------ Check in an item
                   4558: 
                   4559: sub checkin {
                   4560:     my $token=shift;
                   4561:     my $now=time;
                   4562:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4563:     $lonhost=~tr/A-Z/a-z/;
                   4564:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4565:     $dtoken=~s/\W/\_/g;
                   4566:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4567:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4568: 
                   4569:     unless (($tuname) && ($tudom)) {
                   4570:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4571:         return '';
                   4572:     }
                   4573: 
                   4574:     unless (&allowed('mgr',$tcrsid)) {
                   4575:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4576:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4577:         return '';
                   4578:     }
                   4579: 
                   4580:     my %infohash=('resource.0.intoken' => $token,
                   4581:                   'resource.0.checkintime' => $now,
                   4582:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4583: 
                   4584:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4585:        return '';
                   4586:     }
                   4587: 
                   4588:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4589:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4590:         return '';
                   4591:     }
                   4592: 
                   4593:     return ($symb,$tuname,$tudom,$tcrsid);
                   4594: }
                   4595: 
1.110     www      4596: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4597: 
                   4598: sub expirespread {
                   4599:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4600:     my $cid=$env{'request.course.id'}; 
1.110     www      4601:     if ($cid) {
                   4602:        my $now=time;
                   4603:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4604:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4605:                             $env{'course.'.$cid.'.num'}.
1.110     www      4606: 	        	    ':nohist_expirationdates:'.
                   4607:                             &escape($key).'='.$now,
1.620     albertel 4608:                             $env{'course.'.$cid.'.home'})
1.110     www      4609:     }
                   4610:     return 'ok';
1.14      www      4611: }
                   4612: 
1.109     www      4613: # ----------------------------------------------------- Devalidate Spreadsheets
                   4614: 
                   4615: sub devalidate {
1.325     www      4616:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4617:     my $cid=$env{'request.course.id'}; 
1.109     www      4618:     if ($cid) {
1.391     matthew  4619:         # delete the stored spreadsheets for
                   4620:         # - the student level sheet of this user in course's homespace
                   4621:         # - the assessment level sheet for this resource 
                   4622:         #   for this user in user's homespace
1.553     albertel 4623: 	# - current conditional state info
1.325     www      4624: 	my $key=$uname.':'.$udom.':';
1.109     www      4625:         my $status=
1.299     matthew  4626: 	    &del('nohist_calculatedsheets',
1.391     matthew  4627: 		 [$key.'studentcalc:'],
1.620     albertel 4628: 		 $env{'course.'.$cid.'.domain'},
                   4629: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4630: 		.' '.
                   4631: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4632: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4633:         unless ($status eq 'ok ok') {
                   4634:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4635:                     $uname.' at '.$udom.' for '.
1.109     www      4636: 		    $symb.': '.$status);
1.133     albertel 4637:         }
1.553     albertel 4638: 	&delenv('user.state.'.$cid);
1.109     www      4639:     }
                   4640: }
                   4641: 
1.265     albertel 4642: sub get_scalar {
                   4643:     my ($string,$end) = @_;
                   4644:     my $value;
                   4645:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4646: 	$value = $1;
                   4647:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4648: 	$value = $1;
                   4649:     }
                   4650:     return &unescape($value);
                   4651: }
                   4652: 
                   4653: sub array2str {
                   4654:   my (@array) = @_;
                   4655:   my $result=&arrayref2str(\@array);
                   4656:   $result=~s/^__ARRAY_REF__//;
                   4657:   $result=~s/__END_ARRAY_REF__$//;
                   4658:   return $result;
                   4659: }
                   4660: 
1.204     albertel 4661: sub arrayref2str {
                   4662:   my ($arrayref) = @_;
1.265     albertel 4663:   my $result='__ARRAY_REF__';
1.204     albertel 4664:   foreach my $elem (@$arrayref) {
1.265     albertel 4665:     if(ref($elem) eq 'ARRAY') {
                   4666:       $result.=&arrayref2str($elem).'&';
                   4667:     } elsif(ref($elem) eq 'HASH') {
                   4668:       $result.=&hashref2str($elem).'&';
                   4669:     } elsif(ref($elem)) {
                   4670:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4671:     } else {
                   4672:       $result.=&escape($elem).'&';
                   4673:     }
                   4674:   }
                   4675:   $result=~s/\&$//;
1.265     albertel 4676:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4677:   return $result;
                   4678: }
                   4679: 
1.168     albertel 4680: sub hash2str {
1.204     albertel 4681:   my (%hash) = @_;
                   4682:   my $result=&hashref2str(\%hash);
1.265     albertel 4683:   $result=~s/^__HASH_REF__//;
                   4684:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4685:   return $result;
                   4686: }
                   4687: 
                   4688: sub hashref2str {
                   4689:   my ($hashref)=@_;
1.265     albertel 4690:   my $result='__HASH_REF__';
1.800     albertel 4691:   foreach my $key (sort(keys(%$hashref))) {
                   4692:     if (ref($key) eq 'ARRAY') {
                   4693:       $result.=&arrayref2str($key).'=';
                   4694:     } elsif (ref($key) eq 'HASH') {
                   4695:       $result.=&hashref2str($key).'=';
                   4696:     } elsif (ref($key)) {
1.265     albertel 4697:       $result.='=';
1.800     albertel 4698:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4699:     } else {
1.1132    raeburn  4700: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4701:     }
                   4702: 
1.800     albertel 4703:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4704:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4705:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4706:       $result.=&hashref2str($hashref->{$key}).'&';
                   4707:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4708:        $result.='&';
1.800     albertel 4709:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4710:     } else {
1.800     albertel 4711:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4712:     }
                   4713:   }
1.168     albertel 4714:   $result=~s/\&$//;
1.265     albertel 4715:   $result .= '__END_HASH_REF__';
1.168     albertel 4716:   return $result;
                   4717: }
                   4718: 
                   4719: sub str2hash {
1.265     albertel 4720:     my ($string)=@_;
                   4721:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4722:     return %$hash;
                   4723: }
                   4724: 
                   4725: sub str2hashref {
1.168     albertel 4726:   my ($string) = @_;
1.265     albertel 4727: 
                   4728:   my %hash;
                   4729: 
                   4730:   if($string !~ /^__HASH_REF__/) {
                   4731:       if (! ($string eq '' || !defined($string))) {
                   4732: 	  $hash{'error'}='Not hash reference';
                   4733:       }
                   4734:       return (\%hash, $string);
                   4735:   }
                   4736: 
                   4737:   $string =~ s/^__HASH_REF__//;
                   4738: 
                   4739:   while($string !~ /^__END_HASH_REF__/) {
                   4740:       #key
                   4741:       my $key='';
                   4742:       if($string =~ /^__HASH_REF__/) {
                   4743:           ($key, $string)=&str2hashref($string);
                   4744:           if(defined($key->{'error'})) {
                   4745:               $hash{'error'}='Bad data';
                   4746:               return (\%hash, $string);
                   4747:           }
                   4748:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4749:           ($key, $string)=&str2arrayref($string);
                   4750:           if($key->[0] eq 'Array reference error') {
                   4751:               $hash{'error'}='Bad data';
                   4752:               return (\%hash, $string);
                   4753:           }
                   4754:       } else {
                   4755:           $string =~ s/^(.*?)=//;
1.267     albertel 4756: 	  $key=&unescape($1);
1.265     albertel 4757:       }
                   4758:       $string =~ s/^=//;
                   4759: 
                   4760:       #value
                   4761:       my $value='';
                   4762:       if($string =~ /^__HASH_REF__/) {
                   4763:           ($value, $string)=&str2hashref($string);
                   4764:           if(defined($value->{'error'})) {
                   4765:               $hash{'error'}='Bad data';
                   4766:               return (\%hash, $string);
                   4767:           }
                   4768:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4769:           ($value, $string)=&str2arrayref($string);
                   4770:           if($value->[0] eq 'Array reference error') {
                   4771:               $hash{'error'}='Bad data';
                   4772:               return (\%hash, $string);
                   4773:           }
                   4774:       } else {
                   4775: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4776:       }
                   4777:       $string =~ s/^&//;
                   4778: 
                   4779:       $hash{$key}=$value;
1.204     albertel 4780:   }
1.265     albertel 4781: 
                   4782:   $string =~ s/^__END_HASH_REF__//;
                   4783: 
                   4784:   return (\%hash, $string);
1.204     albertel 4785: }
                   4786: 
                   4787: sub str2array {
1.265     albertel 4788:     my ($string)=@_;
                   4789:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4790:     return @$array;
                   4791: }
                   4792: 
                   4793: sub str2arrayref {
1.204     albertel 4794:   my ($string) = @_;
1.265     albertel 4795:   my @array;
                   4796: 
                   4797:   if($string !~ /^__ARRAY_REF__/) {
                   4798:       if (! ($string eq '' || !defined($string))) {
                   4799: 	  $array[0]='Array reference error';
                   4800:       }
                   4801:       return (\@array, $string);
                   4802:   }
                   4803: 
                   4804:   $string =~ s/^__ARRAY_REF__//;
                   4805: 
                   4806:   while($string !~ /^__END_ARRAY_REF__/) {
                   4807:       my $value='';
                   4808:       if($string =~ /^__HASH_REF__/) {
                   4809:           ($value, $string)=&str2hashref($string);
                   4810:           if(defined($value->{'error'})) {
                   4811:               $array[0] ='Array reference error';
                   4812:               return (\@array, $string);
                   4813:           }
                   4814:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4815:           ($value, $string)=&str2arrayref($string);
                   4816:           if($value->[0] eq 'Array reference error') {
                   4817:               $array[0] ='Array reference error';
                   4818:               return (\@array, $string);
                   4819:           }
                   4820:       } else {
                   4821: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4822:       }
                   4823:       $string =~ s/^&//;
                   4824: 
                   4825:       push(@array, $value);
1.191     harris41 4826:   }
1.265     albertel 4827: 
                   4828:   $string =~ s/^__END_ARRAY_REF__//;
                   4829: 
                   4830:   return (\@array, $string);
1.168     albertel 4831: }
                   4832: 
1.167     albertel 4833: # -------------------------------------------------------------------Temp Store
                   4834: 
1.168     albertel 4835: sub tmpreset {
                   4836:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4837:   if (!$symb) {
                   4838:     $symb=&symbread();
1.620     albertel 4839:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4840:   }
                   4841:   $symb=escape($symb);
                   4842: 
1.620     albertel 4843:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4844:   $namespace=~s/\//\_/g;
                   4845:   $namespace=~s/\W//g;
                   4846: 
1.620     albertel 4847:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4848:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4849:   if ($domain eq 'public' && $stuname eq 'public') {
                   4850:       $stuname=$ENV{'REMOTE_ADDR'};
                   4851:   }
1.1117    foxr     4852:   my $path=LONCAPA::tempdir();
1.168     albertel 4853:   my %hash;
                   4854:   if (tie(%hash,'GDBM_File',
                   4855: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4856: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4857:     foreach my $key (keys(%hash)) {
1.180     albertel 4858:       if ($key=~ /:$symb/) {
1.168     albertel 4859: 	delete($hash{$key});
                   4860:       }
                   4861:     }
                   4862:   }
                   4863: }
                   4864: 
1.167     albertel 4865: sub tmpstore {
1.168     albertel 4866:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4867: 
                   4868:   if (!$symb) {
                   4869:     $symb=&symbread();
1.620     albertel 4870:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4871:   }
                   4872:   $symb=escape($symb);
                   4873: 
                   4874:   if (!$namespace) {
                   4875:     # I don't think we would ever want to store this for a course.
                   4876:     # it seems this will only be used if we don't have a course.
1.620     albertel 4877:     #$namespace=$env{'request.course.id'};
1.168     albertel 4878:     #if (!$namespace) {
1.620     albertel 4879:       $namespace=$env{'request.state'};
1.168     albertel 4880:     #}
                   4881:   }
                   4882:   $namespace=~s/\//\_/g;
                   4883:   $namespace=~s/\W//g;
1.620     albertel 4884:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4885:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4886:   if ($domain eq 'public' && $stuname eq 'public') {
                   4887:       $stuname=$ENV{'REMOTE_ADDR'};
                   4888:   }
1.168     albertel 4889:   my $now=time;
                   4890:   my %hash;
1.1117    foxr     4891:   my $path=LONCAPA::tempdir();
1.168     albertel 4892:   if (tie(%hash,'GDBM_File',
                   4893: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4894: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4895:     $hash{"version:$symb"}++;
                   4896:     my $version=$hash{"version:$symb"};
                   4897:     my $allkeys=''; 
                   4898:     foreach my $key (keys(%$storehash)) {
                   4899:       $allkeys.=$key.':';
1.591     albertel 4900:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4901:     }
                   4902:     $hash{"$version:$symb:timestamp"}=$now;
                   4903:     $allkeys.='timestamp';
                   4904:     $hash{"$version:keys:$symb"}=$allkeys;
                   4905:     if (untie(%hash)) {
                   4906:       return 'ok';
                   4907:     } else {
                   4908:       return "error:$!";
                   4909:     }
                   4910:   } else {
                   4911:     return "error:$!";
                   4912:   }
                   4913: }
1.167     albertel 4914: 
1.168     albertel 4915: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4916: 
1.168     albertel 4917: sub tmprestore {
                   4918:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4919: 
1.168     albertel 4920:   if (!$symb) {
                   4921:     $symb=&symbread();
1.620     albertel 4922:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4923:   }
                   4924:   $symb=escape($symb);
                   4925: 
1.620     albertel 4926:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4927: 
1.620     albertel 4928:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4929:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4930:   if ($domain eq 'public' && $stuname eq 'public') {
                   4931:       $stuname=$ENV{'REMOTE_ADDR'};
                   4932:   }
1.168     albertel 4933:   my %returnhash;
                   4934:   $namespace=~s/\//\_/g;
                   4935:   $namespace=~s/\W//g;
                   4936:   my %hash;
1.1117    foxr     4937:   my $path=LONCAPA::tempdir();
1.168     albertel 4938:   if (tie(%hash,'GDBM_File',
                   4939: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4940: 	  &GDBM_READER(),0640)) {
1.168     albertel 4941:     my $version=$hash{"version:$symb"};
                   4942:     $returnhash{'version'}=$version;
                   4943:     my $scope;
                   4944:     for ($scope=1;$scope<=$version;$scope++) {
                   4945:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4946:       my @keys=split(/:/,$vkeys);
                   4947:       my $key;
                   4948:       $returnhash{"$scope:keys"}=$vkeys;
                   4949:       foreach $key (@keys) {
1.591     albertel 4950: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4951: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4952:       }
                   4953:     }
1.168     albertel 4954:     if (!(untie(%hash))) {
                   4955:       return "error:$!";
                   4956:     }
                   4957:   } else {
                   4958:     return "error:$!";
                   4959:   }
                   4960:   return %returnhash;
1.167     albertel 4961: }
                   4962: 
1.9       www      4963: # ----------------------------------------------------------------------- Store
                   4964: 
                   4965: sub store {
1.1172.2.64  raeburn  4966:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      4967:     my $home='';
                   4968: 
1.168     albertel 4969:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4970: 
1.213     www      4971:     $symb=&symbclean($symb);
1.122     albertel 4972:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4973: 
1.620     albertel 4974:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4975:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4976: 
                   4977:     &devalidate($symb,$stuname,$domain);
1.109     www      4978: 
                   4979:     $symb=escape($symb);
1.187     www      4980:     if (!$namespace) { 
1.620     albertel 4981:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4982:           return ''; 
                   4983:        } 
                   4984:     }
1.620     albertel 4985:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4986: 
                   4987:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4988:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4989: 
1.12      www      4990:     my $namevalue='';
1.800     albertel 4991:     foreach my $key (keys(%$storehash)) {
                   4992:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4993:     }
1.12      www      4994:     $namevalue=~s/\&$//;
1.187     www      4995:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  4996:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      4997: }
                   4998: 
1.47      www      4999: # -------------------------------------------------------------- Critical Store
                   5000: 
                   5001: sub cstore {
1.1172.2.64  raeburn  5002:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5003:     my $home='';
                   5004: 
1.168     albertel 5005:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5006: 
1.213     www      5007:     $symb=&symbclean($symb);
1.122     albertel 5008:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5009: 
1.620     albertel 5010:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5011:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5012: 
                   5013:     &devalidate($symb,$stuname,$domain);
1.109     www      5014: 
                   5015:     $symb=escape($symb);
1.187     www      5016:     if (!$namespace) { 
1.620     albertel 5017:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5018:           return ''; 
                   5019:        } 
                   5020:     }
1.620     albertel 5021:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5022: 
                   5023:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5024:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5025: 
1.47      www      5026:     my $namevalue='';
1.800     albertel 5027:     foreach my $key (keys(%$storehash)) {
                   5028:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5029:     }
1.47      www      5030:     $namevalue=~s/\&$//;
1.187     www      5031:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5032:     return critical
1.1172.2.64  raeburn  5033:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5034: }
                   5035: 
1.9       www      5036: # --------------------------------------------------------------------- Restore
                   5037: 
                   5038: sub restore {
1.124     www      5039:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5040:     my $home='';
                   5041: 
1.168     albertel 5042:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5043: 
1.122     albertel 5044:     if (!$symb) {
1.1172.2.26  raeburn  5045:         return if ($namespace eq 'courserequests');
                   5046:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5047:     } else {
1.1172.2.26  raeburn  5048:         unless ($namespace eq 'courserequests') {
                   5049:             $symb=&escape(&symbclean($symb));
                   5050:         }
1.122     albertel 5051:     }
1.188     www      5052:     if (!$namespace) { 
1.620     albertel 5053:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5054:           return ''; 
                   5055:        } 
                   5056:     }
1.620     albertel 5057:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5058:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5059:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5060:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5061: 
1.12      www      5062:     my %returnhash=();
1.800     albertel 5063:     foreach my $line (split(/\&/,$answer)) {
                   5064: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5065:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5066:     }
1.75      www      5067:     my $version;
                   5068:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5069:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5070:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5071:        }
1.75      www      5072:     }
1.13      www      5073:     return %returnhash;
1.34      www      5074: }
                   5075: 
                   5076: # ---------------------------------------------------------- Course Description
1.1118    foxr     5077: #
                   5078: #  
1.34      www      5079: 
                   5080: sub coursedescription {
1.731     albertel 5081:     my ($courseid,$args)=@_;
1.34      www      5082:     $courseid=~s/^\///;
1.49      www      5083:     $courseid=~s/\_/\//g;
1.34      www      5084:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5085:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5086:     my $normalid=$cdomain.'_'.$cnum;
                   5087:     # need to always cache even if we get errors otherwise we keep 
                   5088:     # trying and trying and trying to get the course description.
                   5089:     my %envhash=();
                   5090:     my %returnhash=();
1.731     albertel 5091:     
                   5092:     my $expiretime=600;
                   5093:     if ($env{'request.course.id'} eq $normalid) {
                   5094: 	$expiretime=120;
                   5095:     }
                   5096: 
                   5097:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5098:     if (!$args->{'freshen_cache'}
                   5099: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5100: 	foreach my $key (keys(%env)) {
                   5101: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5102: 	    my ($setting) = $1;
                   5103: 	    $returnhash{$setting} = $env{$key};
                   5104: 	}
                   5105: 	return %returnhash;
                   5106:     }
                   5107: 
1.1118    foxr     5108:     # get the data again
                   5109: 
1.731     albertel 5110:     if (!$args->{'one_time'}) {
                   5111: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5112:     }
1.811     albertel 5113: 
1.34      www      5114:     if ($chome ne 'no_host') {
1.302     albertel 5115:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5116:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5117: 	   my $username = $env{'user.name'}; # Defult username
                   5118: 	   if(defined $args->{'user'}) {
                   5119: 	       $username = $args->{'user'};
                   5120: 	   }
1.129     albertel 5121:            $returnhash{'home'}= $chome;
                   5122: 	   $returnhash{'domain'} = $cdomain;
                   5123: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5124:            if (!defined($returnhash{'type'})) {
                   5125:                $returnhash{'type'} = 'Course';
                   5126:            }
1.130     albertel 5127:            while (my ($name,$value) = each %returnhash) {
1.53      www      5128:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5129:            }
1.270     www      5130:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5131:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5132: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5133:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5134:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5135:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5136:        }
                   5137:     }
1.731     albertel 5138:     if (!$args->{'one_time'}) {
1.949     raeburn  5139: 	&appenv(\%envhash);
1.731     albertel 5140:     }
1.302     albertel 5141:     return %returnhash;
1.461     www      5142: }
                   5143: 
1.1080    raeburn  5144: sub update_released_required {
                   5145:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5146:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5147:         $cid = $env{'request.course.id'};
                   5148:         $cdom = $env{'course.'.$cid.'.domain'};
                   5149:         $cnum = $env{'course.'.$cid.'.num'};
                   5150:         $chome = $env{'course.'.$cid.'.home'};
                   5151:     }
                   5152:     if ($needsrelease) {
                   5153:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5154:         my $needsupdate;
                   5155:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5156:             $needsupdate = 1;
                   5157:         } else {
                   5158:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5159:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5160:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5161:                 $needsupdate = 1;
                   5162:             }
                   5163:         }
                   5164:         if ($needsupdate) {
                   5165:             my %needshash = (
                   5166:                              'internal.releaserequired' => $needsrelease,
                   5167:                             );
                   5168:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5169:             if ($putresult eq 'ok') {
                   5170:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5171:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5172:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5173:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5174:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5175:                 }
                   5176:             }
                   5177:         }
                   5178:     }
                   5179:     return;
                   5180: }
                   5181: 
1.461     www      5182: # -------------------------------------------------See if a user is privileged
                   5183: 
                   5184: sub privileged {
1.1172.2.23  raeburn  5185:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5186:     my $now = time;
1.1172.2.23  raeburn  5187:     my $roles;
                   5188:     if (ref($possroles) eq 'ARRAY') {
                   5189:         $roles = $possroles;
                   5190:     } else {
                   5191:         $roles = ['dc','su'];
                   5192:     }
                   5193:     if (ref($possdomains) eq 'ARRAY') {
                   5194:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5195:         foreach my $dom (@{$possdomains}) {
                   5196:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5197:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5198:                 foreach my $role (@{$roles}) {
                   5199:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5200:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5201:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5202:                             return 1 unless (($end && $end < $now) ||
                   5203:                                              ($start && $start > $now));
                   5204:                         }
                   5205:                     }
                   5206:                 }
                   5207:             }
                   5208:         }
                   5209:     } else {
                   5210:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5211:         my $now = time;
1.1170    droeschl 5212: 
1.1172.2.58  raeburn  5213:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5214:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5215:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5216:                 return 1 unless ($tend && $tend < $now)
                   5217:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5218:             }
1.1172.2.23  raeburn  5219:         }
                   5220:     }
1.461     www      5221:     return 0;
1.9       www      5222: }
1.1       albertel 5223: 
1.1172.2.23  raeburn  5224: sub privileged_by_domain {
                   5225:     my ($domains,$roles) = @_;
                   5226:     my %privileged = ();
                   5227:     my $cachetime = 60*60*24;
                   5228:     my $now = time;
                   5229:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5230:         return %privileged;
                   5231:     }
                   5232:     foreach my $dom (@{$domains}) {
                   5233:         next if (ref($privileged{$dom}) eq 'HASH');
                   5234:         my $needroles;
                   5235:         foreach my $role (@{$roles}) {
                   5236:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5237:             if (defined($cached)) {
                   5238:                 if (ref($result) eq 'HASH') {
                   5239:                     $privileged{$dom}{$role} = $result;
                   5240:                 }
                   5241:             } else {
                   5242:                 $needroles = 1;
                   5243:             }
                   5244:         }
                   5245:         if ($needroles) {
                   5246:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5247:             $privileged{$dom} = {};
                   5248:             foreach my $server (keys(%dompersonnel)) {
                   5249:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5250:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5251:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5252:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5253:                         next if ($end && $end < $now);
                   5254:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5255:                             $dompersonnel{$server}{$item};
                   5256:                     }
                   5257:                 }
                   5258:             }
                   5259:             if (ref($privileged{$dom}) eq 'HASH') {
                   5260:                 foreach my $role (@{$roles}) {
                   5261:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5262:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5263:                     } else {
                   5264:                         my %hash = ();
                   5265:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5266:                     }
                   5267:                 }
                   5268:             }
                   5269:         }
                   5270:     }
                   5271:     return %privileged;
                   5272: }
                   5273: 
1.103     harris41 5274: # -------------------------------------------------------- Get user privileges
1.11      www      5275: 
                   5276: sub rolesinit {
1.1169    droeschl 5277:     my ($domain, $username) = @_;
                   5278:     my %userroles = ('user.login.time' => time);
                   5279:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5280: 
                   5281:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5282:     # also, blocking can be triggered by an activating timer
                   5283:     # it's saved in the user's %env.
                   5284:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5285:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5286:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5287:         %timerintchk, %timerintenv);
                   5288: 
1.1162    raeburn  5289:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5290:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5291:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5292:     }
1.1169    droeschl 5293: 
1.1162    raeburn  5294:     foreach my $key (keys(%timerinterval)) {
                   5295:         my ($cid,$rest) = split(/\0/,$key);
                   5296:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5297:     }
1.1169    droeschl 5298: 
1.11      www      5299:     my %allroles=();
1.1162    raeburn  5300:     my %allgroups=();
1.11      www      5301: 
1.1172.2.58  raeburn  5302:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5303:         my $role = $rolesdump{$area};
                   5304:         $area =~ s/\_\w\w$//;
                   5305: 
                   5306:         my ($trole, $tend, $tstart, $group_privs);
                   5307: 
                   5308:         if ($role =~ /^cr/) {
                   5309:         # Custom role, defined by a user 
                   5310:         # e.g., user.role.cr/msu/smith/mynewrole
                   5311:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5312:                 $trole = $1;
                   5313:                 ($tend, $tstart) = split('_', $2);
                   5314:             } else {
                   5315:                 $trole = $role;
                   5316:             }
                   5317:         } elsif ($role =~ m|^gr/|) {
                   5318:         # Role of member in a group, defined within a course/community
                   5319:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5320:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5321:             next if $tstart eq '-1';
                   5322:             ($trole, $group_privs) = split(/\//, $trole);
                   5323:             $group_privs = &unescape($group_privs);
                   5324:         } else {
                   5325:         # Just a normal role, defined in roles.tab
                   5326:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5327:         }
                   5328: 
                   5329:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5330:                  $username);
                   5331:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5332: 
                   5333:         # role expired or not available yet?
                   5334:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5335:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5336: 
                   5337:         next if $area eq '' or $trole eq '';
                   5338: 
                   5339:         my $spec = "$trole.$area";
                   5340:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5341: 
                   5342:         if ($trole =~ /^cr\//) {
                   5343:         # Custom role, defined by a user
                   5344:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5345:         } elsif ($trole eq 'gr') {
                   5346:         # Role of a member in a group, defined within a course/community
                   5347:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5348:             next;
                   5349:         } else {
                   5350:         # Normal role, defined in roles.tab
                   5351:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5352:         }
                   5353: 
                   5354:         my $cid = $tdomain.'_'.$trest;
                   5355:         unless ($firstaccchk{$cid}) {
                   5356:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5357:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5358:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5359:                         $coursetimerstarts{$cid}{$item}; 
                   5360:                 }
                   5361:             }
                   5362:             $firstaccchk{$cid} = 1;
                   5363:         }
                   5364:         unless ($timerintchk{$cid}) {
                   5365:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5366:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5367:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5368:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5369:                 }
1.12      www      5370:             }
1.1169    droeschl 5371:             $timerintchk{$cid} = 1;
1.191     harris41 5372:         }
1.11      www      5373:     }
1.1169    droeschl 5374: 
                   5375:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5376:         \%allroles, \%allgroups);
                   5377:     $env{'user.adv'} = $userroles{'user.adv'};
                   5378: 
1.1162    raeburn  5379:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5380: }
                   5381: 
1.567     raeburn  5382: sub set_arearole {
1.1172.2.19  raeburn  5383:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5384:     unless ($nolog) {
1.567     raeburn  5385: # log the associated role with the area
1.1172.2.19  raeburn  5386:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5387:     }
1.743     albertel 5388:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5389: }
                   5390: 
                   5391: sub custom_roleprivs {
                   5392:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5393:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5394:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5395:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5396:         my ($rdummy,$roledef)=
                   5397:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5398:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5399:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5400:             if (defined($syspriv)) {
1.1043    raeburn  5401:                 if ($trest =~ /^$match_community$/) {
                   5402:                     $syspriv =~ s/bre\&S//; 
                   5403:                 }
1.567     raeburn  5404:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5405:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5406:             }
                   5407:             if ($tdomain ne '') {
                   5408:                 if (defined($dompriv)) {
                   5409:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5410:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5411:                 }
                   5412:                 if (($trest ne '') && (defined($coursepriv))) {
                   5413:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5414:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5415:                 }
                   5416:             }
                   5417:         }
                   5418:     }
                   5419: }
                   5420: 
1.678     raeburn  5421: sub group_roleprivs {
                   5422:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5423:     my $access = 1;
                   5424:     my $now = time;
                   5425:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5426:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5427:     if ($access) {
1.811     albertel 5428:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5429:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5430:     }
                   5431: }
1.567     raeburn  5432: 
                   5433: sub standard_roleprivs {
                   5434:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5435:     if (defined($pr{$trole.':s'})) {
                   5436:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5437:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5438:     }
                   5439:     if ($tdomain ne '') {
                   5440:         if (defined($pr{$trole.':d'})) {
                   5441:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5442:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5443:         }
                   5444:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5445:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5446:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5447:         }
                   5448:     }
                   5449: }
                   5450: 
                   5451: sub set_userprivs {
1.1064    raeburn  5452:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5453:     my $author=0;
                   5454:     my $adv=0;
1.678     raeburn  5455:     my %grouproles = ();
                   5456:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5457:         my @groupkeys; 
1.1000    raeburn  5458:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5459:             push(@groupkeys,$role);
                   5460:         }
                   5461:         if (ref($groups_roles) eq 'HASH') {
                   5462:             foreach my $key (keys(%{$groups_roles})) {
                   5463:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5464:                     push(@groupkeys,$key);
                   5465:                 }
                   5466:             }
                   5467:         }
                   5468:         if (@groupkeys > 0) {
                   5469:             foreach my $role (@groupkeys) {
                   5470:                 my ($trole,$area,$sec,$extendedarea);
                   5471:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5472:                     $trole = $1;
                   5473:                     $area = $2;
                   5474:                     $sec = $3;
                   5475:                     $extendedarea = $area.$sec;
                   5476:                     if (exists($$allgroups{$area})) {
                   5477:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5478:                             my $spec = $trole.'.'.$extendedarea;
                   5479:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5480:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5481:                         }
1.678     raeburn  5482:                     }
                   5483:                 }
                   5484:             }
                   5485:         }
                   5486:     }
1.800     albertel 5487:     foreach my $group (keys(%grouproles)) {
                   5488:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5489:     }
1.800     albertel 5490:     foreach my $role (keys(%{$allroles})) {
                   5491:         my %thesepriv;
1.941     raeburn  5492:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5493:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5494:             if ($item ne '') {
                   5495:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5496:                 if ($restrictions eq '') {
                   5497:                     $thesepriv{$privilege}='F';
                   5498:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5499:                     $thesepriv{$privilege}.=$restrictions;
                   5500:                 }
                   5501:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5502:             }
                   5503:         }
                   5504:         my $thesestr='';
1.1104    raeburn  5505:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5506: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5507: 	}
                   5508:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5509:     }
                   5510:     return ($author,$adv);
                   5511: }
                   5512: 
1.994     raeburn  5513: sub role_status {
1.1104    raeburn  5514:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5515:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5516:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5517:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5518:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5519:             $$where = '/'.$two;
1.994     raeburn  5520:             $$trolecode=$$role.'.'.$$where;
                   5521:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5522:             $$tstatus='is';
1.1104    raeburn  5523:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5524:                 $$tstatus='future';
1.1034    raeburn  5525:                 if ($$tstart<$now) {
                   5526:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5527:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5528:                             my (%allroles,%allgroups,$group_privs,
                   5529:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5530:                             my %userroles = (
                   5531:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5532:                             );
1.1064    raeburn  5533:                             @rolecodes = ('cm'); 
1.1002    raeburn  5534:                             my $spec=$$role.'.'.$$where;
                   5535:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5536:                             if ($$role =~ /^cr\//) {
                   5537:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5538:                                 push(@rolecodes,'cr');
1.1002    raeburn  5539:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5540:                                 push(@rolecodes,$$role);
1.1002    raeburn  5541:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5542:                                                     $env{'user.name'});
1.1064    raeburn  5543:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5544:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5545:                                 $group_privs = &unescape($group_privs);
                   5546:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5547:                                 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  5548:                                 &get_groups_roles($tdomain,$trest,
                   5549:                                                   \%course_roles,\@rolecodes,
                   5550:                                                   \%groups_roles);
1.1002    raeburn  5551:                             } else {
1.1064    raeburn  5552:                                 push(@rolecodes,$$role);
1.1002    raeburn  5553:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5554:                             }
1.1064    raeburn  5555:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5556:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5557:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5558:                         }
                   5559:                     }
1.1034    raeburn  5560:                     $$tstatus = 'is';
1.1002    raeburn  5561:                 }
1.994     raeburn  5562:             }
                   5563:             if ($$tend) {
1.1104    raeburn  5564:                 if ($$tend<$update) {
1.994     raeburn  5565:                     $$tstatus='expired';
                   5566:                 } elsif ($$tend<$now) {
                   5567:                     $$tstatus='will_not';
                   5568:                 }
                   5569:             }
                   5570:         }
                   5571:     }
                   5572: }
                   5573: 
1.1104    raeburn  5574: sub get_groups_roles {
                   5575:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5576:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5577:                   (ref($rolecodes) eq 'ARRAY') && 
                   5578:                   (ref($groups_roles) eq 'HASH')); 
                   5579:     if (keys(%{$cdom_courseroles}) > 0) {
                   5580:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5581:         if ($cdom ne '' && $cnum ne '') {
                   5582:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5583:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5584:                     my $crsrole = $1;
                   5585:                     my $crssec = $2;
                   5586:                     if ($crsrole =~ /^cr/) {
                   5587:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5588:                             push(@{$rolecodes},'cr');
                   5589:                         }
                   5590:                     } else {
                   5591:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5592:                             push(@{$rolecodes},$crsrole);
                   5593:                         }
                   5594:                     }
                   5595:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5596:                     if ($crssec ne '') {
                   5597:                         $rolekey .= "/$crssec";
                   5598:                     }
                   5599:                     $rolekey .= './';
                   5600:                     $groups_roles->{$rolekey} = $rolecodes;
                   5601:                 }
                   5602:             }
                   5603:         }
                   5604:     }
                   5605:     return;
                   5606: }
                   5607: 
                   5608: sub delete_env_groupprivs {
                   5609:     my ($where,$courseroles,$possroles) = @_;
                   5610:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5611:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5612:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5613:         %{$courseroles->{$udom}} =
                   5614:             &get_my_roles('','','userroles',['active'],
                   5615:                           $possroles,[$udom],1);
                   5616:     }
                   5617:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5618:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5619:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5620:             my $area = '/'.$cdom.'/'.$cnum;
                   5621:             my $privkey = "user.priv.$crsrole.$area";
                   5622:             if ($crssec ne '') {
                   5623:                 $privkey .= '/'.$crssec;
                   5624:             }
                   5625:             $privkey .= ".$area/$group";
                   5626:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5627:         }
                   5628:     }
                   5629:     return;
                   5630: }
                   5631: 
1.994     raeburn  5632: sub check_adhoc_privs {
1.1104    raeburn  5633:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5634:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5635:     my $setprivs;
1.994     raeburn  5636:     if ($env{$cckey}) {
                   5637:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5638:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5639:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5640:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5641:             $setprivs = 1;
1.994     raeburn  5642:         }
                   5643:     } else {
1.1088    raeburn  5644:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5645:         $setprivs = 1;
1.994     raeburn  5646:     }
1.1172.2.9  raeburn  5647:     return $setprivs;
1.994     raeburn  5648: }
                   5649: 
                   5650: sub set_adhoc_privileges {
                   5651: # role can be cc or ca
1.1088    raeburn  5652:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5653:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5654:     my $spec = $role.'.'.$area;
                   5655:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5656:                                   $env{'user.name'},1);
1.994     raeburn  5657:     my %ccrole = ();
                   5658:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5659:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5660:     &appenv(\%userroles,[$role,'cm']);
                   5661:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5662:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5663:         &appenv( {'request.role'        => $spec,
                   5664:                   'request.role.domain' => $dcdom,
                   5665:                   'request.course.sec'  => ''
                   5666:                  }
                   5667:                );
                   5668:         my $tadv=0;
                   5669:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5670:         &appenv({'request.role.adv'    => $tadv});
                   5671:     }
1.994     raeburn  5672: }
                   5673: 
1.12      www      5674: # --------------------------------------------------------------- get interface
                   5675: 
                   5676: sub get {
1.131     albertel 5677:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5678:    my $items='';
1.800     albertel 5679:    foreach my $item (@$storearr) {
                   5680:        $items.=&escape($item).'&';
1.191     harris41 5681:    }
1.12      www      5682:    $items=~s/\&$//;
1.620     albertel 5683:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5684:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5685:    my $uhome=&homeserver($uname,$udomain);
                   5686: 
1.133     albertel 5687:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5688:    my @pairs=split(/\&/,$rep);
1.273     albertel 5689:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5690:      return @pairs;
                   5691:    }
1.15      www      5692:    my %returnhash=();
1.42      www      5693:    my $i=0;
1.800     albertel 5694:    foreach my $item (@$storearr) {
                   5695:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5696:       $i++;
1.191     harris41 5697:    }
1.15      www      5698:    return %returnhash;
1.27      www      5699: }
                   5700: 
                   5701: # --------------------------------------------------------------- del interface
                   5702: 
                   5703: sub del {
1.133     albertel 5704:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5705:    my $items='';
1.800     albertel 5706:    foreach my $item (@$storearr) {
                   5707:        $items.=&escape($item).'&';
1.191     harris41 5708:    }
1.984     neumanie 5709: 
1.27      www      5710:    $items=~s/\&$//;
1.620     albertel 5711:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5712:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5713:    my $uhome=&homeserver($uname,$udomain);
                   5714:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5715: }
                   5716: 
                   5717: # -------------------------------------------------------------- dump interface
                   5718: 
1.1172.2.22  raeburn  5719: sub unserialize {
                   5720:     my ($rep, $escapedkeys) = @_;
                   5721: 
                   5722:     return {} if $rep =~ /^error/;
                   5723: 
                   5724:     my %returnhash=();
                   5725:     foreach my $item (split(/\&/,$rep)) {
                   5726:         my ($key, $value) = split(/=/, $item, 2);
                   5727:         $key = unescape($key) unless $escapedkeys;
                   5728:         next if $key =~ /^error: 2 /;
                   5729:         $returnhash{$key} = &thaw_unescape($value);
                   5730:     }
                   5731:     return \%returnhash;
                   5732: }
                   5733: 
                   5734: # see Lond::dump_with_regexp
                   5735: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5736: sub dump {
1.1172.2.22  raeburn  5737:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5738:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5739:     if (!$uname) { $uname=$env{'user.name'}; }
                   5740:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5741: 
1.1172.2.55  raeburn  5742:     if ($regexp) {
                   5743:         $regexp=&escape($regexp);
                   5744:     } else {
                   5745:         $regexp='.';
                   5746:     }
1.1172.2.22  raeburn  5747:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5748:         # user is hosted on this machine
1.1172.2.55  raeburn  5749:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5750:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5751:         return %{&unserialize($reply, $escapedkeys)};
                   5752:     }
1.1166    raeburn  5753:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5754:     my @pairs=split(/\&/,$rep);
                   5755:     my %returnhash=();
1.1098    foxr     5756:     if (!($rep =~ /^error/ )) {
                   5757: 	foreach my $item (@pairs) {
                   5758: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5759:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5760: 	    next if ($key =~ /^error: 2 /);
                   5761: 	    $returnhash{$key}=&thaw_unescape($value);
                   5762: 	}
1.755     albertel 5763:     }
                   5764:     return %returnhash;
1.407     www      5765: }
                   5766: 
1.1098    foxr     5767: 
1.717     albertel 5768: # --------------------------------------------------------- dumpstore interface
                   5769: 
                   5770: sub dumpstore {
                   5771:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5772:    # same as dump but keys must be escaped. They may contain colon separated
                   5773:    # lists of values that may themself contain colons (e.g. symbs).
                   5774:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5775: }
                   5776: 
1.407     www      5777: # -------------------------------------------------------------- keys interface
                   5778: 
                   5779: sub getkeys {
                   5780:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5781:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5782:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5783:    my $uhome=&homeserver($uname,$udomain);
                   5784:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5785:    my @keyarray=();
1.800     albertel 5786:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5787:       next if ($key =~ /^error: 2 /);
1.800     albertel 5788:       push(@keyarray,&unescape($key));
1.407     www      5789:    }
                   5790:    return @keyarray;
1.318     matthew  5791: }
                   5792: 
1.319     matthew  5793: # --------------------------------------------------------------- currentdump
                   5794: sub currentdump {
1.328     matthew  5795:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5796:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5797:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5798:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5799:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  5800:    my $rep;
                   5801: 
                   5802:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5803:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   5804:                    $courseid)));
                   5805:    } else {
                   5806:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5807:    }
                   5808: 
1.318     matthew  5809:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5810:    #
1.318     matthew  5811:    my %returnhash=();
1.319     matthew  5812:    #
                   5813:    if ($rep eq "unknown_cmd") { 
                   5814:        # an old lond will not know currentdump
                   5815:        # Do a dump and make it look like a currentdump
1.822     albertel 5816:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5817:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5818:        my %hash = @tmp;
                   5819:        @tmp=();
1.424     matthew  5820:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5821:    } else {
                   5822:        my @pairs=split(/\&/,$rep);
1.800     albertel 5823:        foreach my $pair (@pairs) {
                   5824:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5825:            my ($symb,$param) = split(/:/,$key);
                   5826:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5827:                                                         &thaw_unescape($value);
1.319     matthew  5828:        }
1.191     harris41 5829:    }
1.12      www      5830:    return %returnhash;
1.424     matthew  5831: }
                   5832: 
                   5833: sub convert_dump_to_currentdump{
                   5834:     my %hash = %{shift()};
                   5835:     my %returnhash;
                   5836:     # Code ripped from lond, essentially.  The only difference
                   5837:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5838:     # we might run in to problems with parameter names =~ /^v\./
                   5839:     while (my ($key,$value) = each(%hash)) {
                   5840:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5841: 	$symb  = &unescape($symb);
                   5842: 	$param = &unescape($param);
1.424     matthew  5843:         next if ($v eq 'version' || $symb eq 'keys');
                   5844:         next if (exists($returnhash{$symb}) &&
                   5845:                  exists($returnhash{$symb}->{$param}) &&
                   5846:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5847:         $returnhash{$symb}->{$param}=$value;
                   5848:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5849:     }
                   5850:     #
                   5851:     # Remove all of the keys in the hashes which keep track of
                   5852:     # the version of the parameter.
                   5853:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5854:         # use a foreach because we are going to delete from the hash.
                   5855:         foreach my $key (keys(%$param_hash)) {
                   5856:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5857:         }
                   5858:     }
                   5859:     return \%returnhash;
1.12      www      5860: }
                   5861: 
1.627     albertel 5862: # ------------------------------------------------------ critical inc interface
                   5863: 
                   5864: sub cinc {
                   5865:     return &inc(@_,'critical');
                   5866: }
                   5867: 
1.449     matthew  5868: # --------------------------------------------------------------- inc interface
                   5869: 
                   5870: sub inc {
1.627     albertel 5871:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5872:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5873:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5874:     my $uhome=&homeserver($uname,$udomain);
                   5875:     my $items='';
                   5876:     if (! ref($store)) {
                   5877:         # got a single value, so use that instead
                   5878:         $items = &escape($store).'=&';
                   5879:     } elsif (ref($store) eq 'SCALAR') {
                   5880:         $items = &escape($$store).'=&';        
                   5881:     } elsif (ref($store) eq 'ARRAY') {
                   5882:         $items = join('=&',map {&escape($_);} @{$store});
                   5883:     } elsif (ref($store) eq 'HASH') {
                   5884:         while (my($key,$value) = each(%{$store})) {
                   5885:             $items.= &escape($key).'='.&escape($value).'&';
                   5886:         }
                   5887:     }
                   5888:     $items=~s/\&$//;
1.627     albertel 5889:     if ($critical) {
                   5890: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5891:     } else {
                   5892: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5893:     }
1.449     matthew  5894: }
                   5895: 
1.12      www      5896: # --------------------------------------------------------------- put interface
                   5897: 
                   5898: sub put {
1.134     albertel 5899:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5900:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5901:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5902:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5903:    my $items='';
1.800     albertel 5904:    foreach my $item (keys(%$storehash)) {
                   5905:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5906:    }
1.12      www      5907:    $items=~s/\&$//;
1.134     albertel 5908:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5909: }
                   5910: 
1.631     albertel 5911: # ------------------------------------------------------------ newput interface
                   5912: 
                   5913: sub newput {
                   5914:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5915:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5916:    if (!$uname) { $uname=$env{'user.name'}; }
                   5917:    my $uhome=&homeserver($uname,$udomain);
                   5918:    my $items='';
                   5919:    foreach my $key (keys(%$storehash)) {
                   5920:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5921:    }
                   5922:    $items=~s/\&$//;
                   5923:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5924: }
                   5925: 
                   5926: # ---------------------------------------------------------  putstore interface
                   5927: 
1.524     raeburn  5928: sub putstore {
1.1172.2.59  raeburn  5929:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 5930:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5931:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5932:    my $uhome=&homeserver($uname,$udomain);
                   5933:    my $items='';
1.715     albertel 5934:    foreach my $key (keys(%$storehash)) {
                   5935:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5936:    }
1.715     albertel 5937:    $items=~s/\&$//;
1.716     albertel 5938:    my $esc_symb=&escape($symb);
                   5939:    my $esc_v=&escape($version);
1.715     albertel 5940:    my $reply =
1.716     albertel 5941:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5942: 	      $uhome);
1.1172.2.59  raeburn  5943:    if (($tolog) && ($reply eq 'ok')) {
                   5944:        my $namevalue='';
                   5945:        foreach my $key (keys(%{$storehash})) {
                   5946:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   5947:        }
                   5948:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   5949:                      '&host='.&escape($perlvar{'lonHostID'}).
                   5950:                      '&version='.$esc_v.
                   5951:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   5952:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   5953:    }
1.715     albertel 5954:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5955:        # gfall back to way things use to be done
1.715     albertel 5956:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5957: 			    $uname);
1.524     raeburn  5958:    }
1.715     albertel 5959:    return $reply;
                   5960: }
                   5961: 
                   5962: sub old_putstore {
1.716     albertel 5963:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5964:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5965:     if (!$uname) { $uname=$env{'user.name'}; }
                   5966:     my $uhome=&homeserver($uname,$udomain);
                   5967:     my %newstorehash;
1.800     albertel 5968:     foreach my $item (keys(%$storehash)) {
                   5969: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5970: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5971:     }
                   5972:     my $items='';
                   5973:     my %allitems = ();
1.800     albertel 5974:     foreach my $item (keys(%newstorehash)) {
                   5975: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5976: 	    my $key = $1.':keys:'.$2;
                   5977: 	    $allitems{$key} .= $3.':';
                   5978: 	}
1.800     albertel 5979: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5980:     }
1.800     albertel 5981:     foreach my $item (keys(%allitems)) {
                   5982: 	$allitems{$item} =~ s/\:$//;
                   5983: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5984:     }
                   5985:     $items=~s/\&$//;
                   5986:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5987: }
                   5988: 
1.47      www      5989: # ------------------------------------------------------ critical put interface
                   5990: 
                   5991: sub cput {
1.134     albertel 5992:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5993:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5994:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5995:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5996:    my $items='';
1.800     albertel 5997:    foreach my $item (keys(%$storehash)) {
                   5998:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5999:    }
1.47      www      6000:    $items=~s/\&$//;
1.134     albertel 6001:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6002: }
                   6003: 
                   6004: # -------------------------------------------------------------- eget interface
                   6005: 
                   6006: sub eget {
1.133     albertel 6007:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6008:    my $items='';
1.800     albertel 6009:    foreach my $item (@$storearr) {
                   6010:        $items.=&escape($item).'&';
1.191     harris41 6011:    }
1.12      www      6012:    $items=~s/\&$//;
1.620     albertel 6013:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6014:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6015:    my $uhome=&homeserver($uname,$udomain);
                   6016:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6017:    my @pairs=split(/\&/,$rep);
                   6018:    my %returnhash=();
1.42      www      6019:    my $i=0;
1.800     albertel 6020:    foreach my $item (@$storearr) {
                   6021:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6022:       $i++;
1.191     harris41 6023:    }
1.12      www      6024:    return %returnhash;
                   6025: }
                   6026: 
1.667     albertel 6027: # ------------------------------------------------------------ tmpput interface
                   6028: sub tmpput {
1.802     raeburn  6029:     my ($storehash,$server,$context)=@_;
1.667     albertel 6030:     my $items='';
1.800     albertel 6031:     foreach my $item (keys(%$storehash)) {
                   6032: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6033:     }
                   6034:     $items=~s/\&$//;
1.802     raeburn  6035:     if (defined($context)) {
                   6036:         $items .= ':'.&escape($context);
                   6037:     }
1.667     albertel 6038:     return &reply("tmpput:$items",$server);
                   6039: }
                   6040: 
                   6041: # ------------------------------------------------------------ tmpget interface
                   6042: sub tmpget {
1.688     albertel 6043:     my ($token,$server)=@_;
                   6044:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6045:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6046:     my %returnhash;
                   6047:     foreach my $item (split(/\&/,$rep)) {
                   6048: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6049:         next if ($key =~ /^error: 2 /);
1.667     albertel 6050: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6051:     }
                   6052:     return %returnhash;
                   6053: }
                   6054: 
1.1113    raeburn  6055: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6056: sub tmpdel {
                   6057:     my ($token,$server)=@_;
                   6058:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6059:     return &reply("tmpdel:$token",$server);
                   6060: }
                   6061: 
1.1172.2.13  raeburn  6062: # ------------------------------------------------------------ get_timebased_id
                   6063: 
                   6064: sub get_timebased_id {
                   6065:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6066:         $maxtries) = @_;
                   6067:     my ($newid,$error,$dellock);
                   6068:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6069:         return ('','ok','invalid call to get suffix');
                   6070:     }
                   6071: 
                   6072: # set defaults for any optional args for which values were not supplied
                   6073:     if ($who eq '') {
                   6074:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6075:     }
                   6076:     if (!$locktries) {
                   6077:         $locktries = 3;
                   6078:     }
                   6079:     if (!$maxtries) {
                   6080:         $maxtries = 10;
                   6081:     }
                   6082: 
                   6083:     if (($cdom eq '') || ($cnum eq '')) {
                   6084:         if ($env{'request.course.id'}) {
                   6085:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6086:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6087:         }
                   6088:         if (($cdom eq '') || ($cnum eq '')) {
                   6089:             return ('','ok','call to get suffix not in course context');
                   6090:         }
                   6091:     }
                   6092: 
                   6093: # construct locking item
                   6094:     my $lockhash = {
                   6095:                       $prefix."\0".'locked_'.$keyid => $who,
                   6096:                    };
                   6097:     my $tries = 0;
                   6098: 
                   6099: # attempt to get lock on nohist_$namespace file
                   6100:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6101:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6102:         $tries ++;
                   6103:         sleep 1;
                   6104:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6105:     }
                   6106: 
                   6107: # attempt to get unique identifier, based on current timestamp
                   6108:     if ($gotlock eq 'ok') {
                   6109:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6110:         my $id = time;
                   6111:         $newid = $id;
1.1172.2.56  raeburn  6112:         if ($idtype eq 'addcode') {
                   6113:             $newid .= &sixnum_code();
                   6114:         }
1.1172.2.13  raeburn  6115:         my $idtries = 0;
                   6116:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6117:             if ($idtype eq 'concat') {
                   6118:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6119:             } elsif ($idtype eq 'addcode') {
                   6120:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6121:             } else {
                   6122:                 $newid ++;
                   6123:             }
                   6124:             $idtries ++;
                   6125:         }
                   6126:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6127:             my %new_item =  (
                   6128:                               $prefix."\0".$newid => $who,
                   6129:                             );
                   6130:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6131:                                                  $cdom,$cnum);
                   6132:             if ($putresult ne 'ok') {
                   6133:                 undef($newid);
                   6134:                 $error = 'error saving new item: '.$putresult;
                   6135:             }
                   6136:         } else {
1.1172.2.56  raeburn  6137:              undef($newid);
1.1172.2.13  raeburn  6138:              $error = ('error: no unique suffix available for the new item ');
                   6139:         }
                   6140: #  remove lock
                   6141:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6142:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6143:     } else {
                   6144:         $error = "error: could not obtain lockfile\n";
                   6145:         $dellock = 'ok';
1.1172.2.58  raeburn  6146:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6147:             $dellock = 'nolock';
                   6148:         }
1.1172.2.13  raeburn  6149:     }
                   6150:     return ($newid,$dellock,$error);
                   6151: }
                   6152: 
1.1172.2.56  raeburn  6153: sub sixnum_code {
                   6154:     my $code;
                   6155:     for (0..6) {
                   6156:         $code .= int( rand(9) );
                   6157:     }
                   6158:     return $code;
                   6159: }
                   6160: 
1.765     albertel 6161: # -------------------------------------------------- portfolio access checking
                   6162: 
                   6163: sub portfolio_access {
1.766     albertel 6164:     my ($requrl) = @_;
1.765     albertel 6165:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   6166:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  6167:     if ($result) {
                   6168:         my %setters;
                   6169:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6170:             my ($startblock,$endblock) =
                   6171:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6172:             if ($startblock && $endblock) {
                   6173:                 return 'B';
                   6174:             }
                   6175:         } else {
                   6176:             my ($startblock,$endblock) =
                   6177:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6178:             if ($startblock && $endblock) {
                   6179:                 return 'B';
                   6180:             }
                   6181:         }
                   6182:     }
1.765     albertel 6183:     if ($result eq 'ok') {
1.766     albertel 6184:        return 'F';
1.765     albertel 6185:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6186:        return 'A';
1.765     albertel 6187:     }
1.766     albertel 6188:     return '';
1.765     albertel 6189: }
                   6190: 
                   6191: sub get_portfolio_access {
1.767     albertel 6192:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   6193: 
                   6194:     if (!ref($access_hash)) {
                   6195: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6196: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6197: 						   $file_name);
                   6198: 	$access_hash = $access_controls{$file_name};
                   6199:     }
                   6200: 
1.765     albertel 6201:     my ($public,$guest,@domains,@users,@courses,@groups);
                   6202:     my $now = time;
                   6203:     if (ref($access_hash) eq 'HASH') {
                   6204:         foreach my $key (keys(%{$access_hash})) {
                   6205:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6206:             if ($start > $now) {
                   6207:                 next;
                   6208:             }
                   6209:             if ($end && $end<$now) {
                   6210:                 next;
                   6211:             }
                   6212:             if ($scope eq 'public') {
                   6213:                 $public = $key;
                   6214:                 last;
                   6215:             } elsif ($scope eq 'guest') {
                   6216:                 $guest = $key;
                   6217:             } elsif ($scope eq 'domains') {
                   6218:                 push(@domains,$key);
                   6219:             } elsif ($scope eq 'users') {
                   6220:                 push(@users,$key);
                   6221:             } elsif ($scope eq 'course') {
                   6222:                 push(@courses,$key);
                   6223:             } elsif ($scope eq 'group') {
                   6224:                 push(@groups,$key);
                   6225:             }
                   6226:         }
                   6227:         if ($public) {
                   6228:             return 'ok';
                   6229:         }
                   6230:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6231:             if ($guest) {
                   6232:                 return $guest;
                   6233:             }
                   6234:         } else {
                   6235:             if (@domains > 0) {
                   6236:                 foreach my $domkey (@domains) {
                   6237:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6238:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6239:                             return 'ok';
                   6240:                         }
                   6241:                     }
                   6242:                 }
                   6243:             }
                   6244:             if (@users > 0) {
                   6245:                 foreach my $userkey (@users) {
1.865     raeburn  6246:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6247:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6248:                             if (ref($item) eq 'HASH') {
                   6249:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6250:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6251:                                     return 'ok';
                   6252:                                 }
                   6253:                             }
                   6254:                         }
                   6255:                     } 
1.765     albertel 6256:                 }
                   6257:             }
                   6258:             my %roleshash;
                   6259:             my @courses_and_groups = @courses;
                   6260:             push(@courses_and_groups,@groups); 
                   6261:             if (@courses_and_groups > 0) {
                   6262:                 my (%allgroups,%allroles); 
                   6263:                 my ($start,$end,$role,$sec,$group);
                   6264:                 foreach my $envkey (%env) {
1.1060    raeburn  6265:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6266:                         my $cid = $2.'_'.$3; 
                   6267:                         if ($1 eq 'gr') {
                   6268:                             $group = $4;
                   6269:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6270:                         } else {
                   6271:                             if ($4 eq '') {
                   6272:                                 $sec = 'none';
                   6273:                             } else {
                   6274:                                 $sec = $4;
                   6275:                             }
                   6276:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6277:                         }
1.811     albertel 6278:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6279:                         my $cid = $2.'_'.$3;
                   6280:                         if ($4 eq '') {
                   6281:                             $sec = 'none';
                   6282:                         } else {
                   6283:                             $sec = $4;
                   6284:                         }
                   6285:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6286:                     }
                   6287:                 }
                   6288:                 if (keys(%allroles) == 0) {
                   6289:                     return;
                   6290:                 }
                   6291:                 foreach my $key (@courses_and_groups) {
                   6292:                     my %content = %{$$access_hash{$key}};
                   6293:                     my $cnum = $content{'number'};
                   6294:                     my $cdom = $content{'domain'};
                   6295:                     my $cid = $cdom.'_'.$cnum;
                   6296:                     if (!exists($allroles{$cid})) {
                   6297:                         next;
                   6298:                     }    
                   6299:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6300:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6301:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6302:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6303:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6304:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6305:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6306:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6307:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6308:                                         if (grep/^all$/,@sections) {
                   6309:                                             return 'ok';
                   6310:                                         } else {
                   6311:                                             if (grep/^$sec$/,@sections) {
                   6312:                                                 return 'ok';
                   6313:                                             }
                   6314:                                         }
                   6315:                                     }
                   6316:                                 }
                   6317:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6318:                                     if (grep/^none$/,@groups) {
                   6319:                                         return 'ok';
                   6320:                                     }
                   6321:                                 } else {
                   6322:                                     if (grep/^all$/,@groups) {
                   6323:                                         return 'ok';
                   6324:                                     } 
                   6325:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6326:                                         if (grep/^$group$/,@groups) {
                   6327:                                             return 'ok';
                   6328:                                         }
                   6329:                                     }
                   6330:                                 } 
                   6331:                             }
                   6332:                         }
                   6333:                     }
                   6334:                 }
                   6335:             }
                   6336:             if ($guest) {
                   6337:                 return $guest;
                   6338:             }
                   6339:         }
                   6340:     }
                   6341:     return;
                   6342: }
                   6343: 
                   6344: sub course_group_datechecker {
                   6345:     my ($dates,$now,$status) = @_;
                   6346:     my ($start,$end) = split(/\./,$dates);
                   6347:     if (!$start && !$end) {
                   6348:         return 'ok';
                   6349:     }
                   6350:     if (grep/^active$/,@{$status}) {
                   6351:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6352:             return 'ok';
                   6353:         }
                   6354:     }
                   6355:     if (grep/^previous$/,@{$status}) {
                   6356:         if ($end > $now ) {
                   6357:             return 'ok';
                   6358:         }
                   6359:     }
                   6360:     if (grep/^future$/,@{$status}) {
                   6361:         if ($start > $now) {
                   6362:             return 'ok';
                   6363:         }
                   6364:     }
                   6365:     return; 
                   6366: }
                   6367: 
                   6368: sub parse_portfolio_url {
                   6369:     my ($url) = @_;
                   6370: 
                   6371:     my ($type,$udom,$unum,$group,$file_name);
                   6372:     
1.823     albertel 6373:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6374: 	$type = 1;
                   6375:         $udom = $1;
                   6376:         $unum = $2;
                   6377:         $file_name = $3;
1.823     albertel 6378:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6379: 	$type = 2;
                   6380:         $udom = $1;
                   6381:         $unum = $2;
                   6382:         $group = $3;
                   6383:         $file_name = $3.'/'.$4;
                   6384:     }
                   6385:     if (wantarray) {
                   6386: 	return ($type,$udom,$unum,$file_name,$group);
                   6387:     }
                   6388:     return $type;
                   6389: }
                   6390: 
                   6391: sub is_portfolio_url {
                   6392:     my ($url) = @_;
                   6393:     return scalar(&parse_portfolio_url($url));
                   6394: }
                   6395: 
1.798     raeburn  6396: sub is_portfolio_file {
                   6397:     my ($file) = @_;
1.820     raeburn  6398:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6399:         return 1;
                   6400:     }
                   6401:     return;
                   6402: }
                   6403: 
1.976     raeburn  6404: sub usertools_access {
1.1084    raeburn  6405:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6406:     my ($access,%tools);
                   6407:     if ($context eq '') {
                   6408:         $context = 'tools';
                   6409:     }
                   6410:     if ($context eq 'requestcourses') {
                   6411:         %tools = (
                   6412:                       official   => 1,
                   6413:                       unofficial => 1,
1.1006    raeburn  6414:                       community  => 1,
1.1172.2.37  raeburn  6415:                       textbook   => 1,
1.985     raeburn  6416:                  );
1.1172.2.9  raeburn  6417:     } elsif ($context eq 'requestauthor') {
                   6418:         %tools = (
                   6419:                       requestauthor => 1,
                   6420:                  );
1.985     raeburn  6421:     } else {
                   6422:         %tools = (
                   6423:                       aboutme   => 1,
                   6424:                       blog      => 1,
1.1172.2.6  raeburn  6425:                       webdav    => 1,
1.985     raeburn  6426:                       portfolio => 1,
                   6427:                  );
                   6428:     }
1.976     raeburn  6429:     return if (!defined($tools{$tool}));
                   6430: 
1.1172.2.35  raeburn  6431:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6432:         $udom = $env{'user.domain'};
                   6433:         $uname = $env{'user.name'};
                   6434:     }
                   6435: 
1.978     raeburn  6436:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6437:         if ($action ne 'reload') {
1.985     raeburn  6438:             if ($context eq 'requestcourses') {
                   6439:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6440:             } elsif ($context eq 'requestauthor') {
                   6441:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6442:             } else {
                   6443:                 return $env{'environment.availabletools.'.$tool};
                   6444:             }
                   6445:         }
1.976     raeburn  6446:     }
                   6447: 
1.1172.2.9  raeburn  6448:     my ($toolstatus,$inststatus,$envkey);
                   6449:     if ($context eq 'requestauthor') {
                   6450:         $envkey = $context;
                   6451:     } else {
                   6452:         $envkey = $context.'.'.$tool;
                   6453:     }
1.976     raeburn  6454: 
1.985     raeburn  6455:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6456:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6457:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6458:         $inststatus = $env{'environment.inststatus'};
                   6459:     } else {
1.1084    raeburn  6460:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6461:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6462:             $inststatus = $userenvref->{'inststatus'};
                   6463:         } else {
1.1172.2.9  raeburn  6464:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6465:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6466:             $inststatus = $userenv{'inststatus'};
                   6467:         }
1.976     raeburn  6468:     }
                   6469: 
                   6470:     if ($toolstatus ne '') {
                   6471:         if ($toolstatus) {
                   6472:             $access = 1;
                   6473:         } else {
                   6474:             $access = 0;
                   6475:         }
                   6476:         return $access;
                   6477:     }
                   6478: 
1.1084    raeburn  6479:     my ($is_adv,%domdef);
                   6480:     if (ref($is_advref) eq 'HASH') {
                   6481:         $is_adv = $is_advref->{'is_adv'};
                   6482:     } else {
                   6483:         $is_adv = &is_advanced_user($udom,$uname);
                   6484:     }
                   6485:     if (ref($domdefref) eq 'HASH') {
                   6486:         %domdef = %{$domdefref};
                   6487:     } else {
                   6488:         %domdef = &get_domain_defaults($udom);
                   6489:     }
1.976     raeburn  6490:     if (ref($domdef{$tool}) eq 'HASH') {
                   6491:         if ($is_adv) {
                   6492:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6493:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6494:                     $access = 1;
                   6495:                 } else {
                   6496:                     $access = 0;
                   6497:                 }
                   6498:                 return $access;
                   6499:             }
                   6500:         }
                   6501:         if ($inststatus ne '') {
                   6502:             my ($hasaccess,$hasnoaccess);
                   6503:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6504:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6505:                     if ($domdef{$tool}{$affiliation}) {
                   6506:                         $hasaccess = 1;
                   6507:                     } else {
                   6508:                         $hasnoaccess = 1;
                   6509:                     }
                   6510:                 }
                   6511:             }
                   6512:             if ($hasaccess || $hasnoaccess) {
                   6513:                 if ($hasaccess) {
                   6514:                     $access = 1;
                   6515:                 } elsif ($hasnoaccess) {
                   6516:                     $access = 0; 
                   6517:                 }
                   6518:                 return $access;
                   6519:             }
                   6520:         } else {
                   6521:             if ($domdef{$tool}{'default'} ne '') {
                   6522:                 if ($domdef{$tool}{'default'}) {
                   6523:                     $access = 1;
                   6524:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6525:                     $access = 0;
                   6526:                 }
                   6527:                 return $access;
                   6528:             }
                   6529:         }
                   6530:     } else {
1.1172.2.6  raeburn  6531:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6532:             $access = 1;
                   6533:         } else {
                   6534:             $access = 0;
                   6535:         }
1.976     raeburn  6536:         return $access;
                   6537:     }
                   6538: }
                   6539: 
1.1050    raeburn  6540: sub is_course_owner {
                   6541:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6542:     if (($udom eq '') || ($uname eq '')) {
                   6543:         $udom = $env{'user.domain'};
                   6544:         $uname = $env{'user.name'};
                   6545:     }
                   6546:     unless (($udom eq '') || ($uname eq '')) {
                   6547:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6548:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6549:                 return 1;
                   6550:             } else {
                   6551:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6552:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6553:                     return 1;
                   6554:                 }
                   6555:             }
                   6556:         }
                   6557:     }
                   6558:     return;
                   6559: }
                   6560: 
1.976     raeburn  6561: sub is_advanced_user {
                   6562:     my ($udom,$uname) = @_;
1.1085    raeburn  6563:     if ($udom ne '' && $uname ne '') {
                   6564:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6565:             if (wantarray) {
                   6566:                 return ($env{'user.adv'},$env{'user.author'});
                   6567:             } else {
                   6568:                 return $env{'user.adv'};
                   6569:             }
1.1085    raeburn  6570:         }
                   6571:     }
1.976     raeburn  6572:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6573:     my %allroles;
1.1128    raeburn  6574:     my ($is_adv,$is_author);
1.976     raeburn  6575:     foreach my $role (keys(%roleshash)) {
                   6576:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6577:         my $area = '/'.$tdomain.'/'.$trest;
                   6578:         if ($sec ne '') {
                   6579:             $area .= '/'.$sec;
                   6580:         }
                   6581:         if (($area ne '') && ($trole ne '')) {
                   6582:             my $spec=$trole.'.'.$area;
                   6583:             if ($trole =~ /^cr\//) {
                   6584:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6585:             } elsif ($trole ne 'gr') {
                   6586:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6587:             }
1.1128    raeburn  6588:             if ($trole eq 'au') {
                   6589:                 $is_author = 1;
                   6590:             }
1.976     raeburn  6591:         }
                   6592:     }
                   6593:     foreach my $role (keys(%allroles)) {
                   6594:         last if ($is_adv);
                   6595:         foreach my $item (split(/:/,$allroles{$role})) {
                   6596:             if ($item ne '') {
                   6597:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6598:                 if ($privilege eq 'adv') {
                   6599:                     $is_adv = 1;
                   6600:                     last;
                   6601:                 }
                   6602:             }
                   6603:         }
                   6604:     }
1.1128    raeburn  6605:     if (wantarray) {
                   6606:         return ($is_adv,$is_author);
                   6607:     }
1.976     raeburn  6608:     return $is_adv;
                   6609: }
1.798     raeburn  6610: 
1.1035    raeburn  6611: sub check_can_request {
1.1036    raeburn  6612:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6613:     my $canreq = 0;
                   6614:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6615:     my @options = ('approval','validate','autolimit');
                   6616:     my $optregex = join('|',@options);
                   6617:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6618:         foreach my $type (@{$types}) {
                   6619:             if (&usertools_access($env{'user.name'},
                   6620:                                   $env{'user.domain'},
                   6621:                                   $type,undef,'requestcourses')) {
                   6622:                 $canreq ++;
1.1036    raeburn  6623:                 if (ref($request_domains) eq 'HASH') {
                   6624:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6625:                 }
1.1035    raeburn  6626:                 if ($dom eq $env{'user.domain'}) {
                   6627:                     $can_request->{$type} = 1;
                   6628:                 }
                   6629:             }
                   6630:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6631:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6632:                 if (@curr > 0) {
1.1036    raeburn  6633:                     foreach my $item (@curr) {
                   6634:                         if (ref($request_domains) eq 'HASH') {
                   6635:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6636:                             if ($otherdom ne '') {
                   6637:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6638:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6639:                                         push(@{$request_domains->{$type}},$otherdom);
                   6640:                                     }
                   6641:                                 } else {
                   6642:                                     push(@{$request_domains->{$type}},$otherdom);
                   6643:                                 }
                   6644:                             }
                   6645:                         }
                   6646:                     }
                   6647:                     unless($dom eq $env{'user.domain'}) {
                   6648:                         $canreq ++;
1.1035    raeburn  6649:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6650:                             $can_request->{$type} = 1;
                   6651:                         }
                   6652:                     }
                   6653:                 }
                   6654:             }
                   6655:         }
                   6656:     }
                   6657:     return $canreq;
                   6658: }
                   6659: 
1.341     www      6660: # ---------------------------------------------- Custom access rule evaluation
                   6661: 
                   6662: sub customaccess {
                   6663:     my ($priv,$uri)=@_;
1.807     albertel 6664:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6665:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6666:     $udom = &LONCAPA::clean_domain($udom);
                   6667:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6668:     my $access=0;
1.800     albertel 6669:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6670: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6671: 	if ($type eq 'user') {
                   6672: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6673: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6674: 		if ($tdom) {
                   6675: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6676: 		}
1.896     albertel 6677: 		if ($tuname) {
                   6678: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6679: 		}
                   6680: 		$access=($effect eq 'allow');
                   6681: 		last;
                   6682: 	    }
                   6683: 	} else {
                   6684: 	    if ($role) {
                   6685: 		if ($role ne $urole) { next; }
                   6686: 	    }
                   6687: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6688: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6689: 		if ($tdom) {
                   6690: 		    if ($tdom ne $udom) { next; }
                   6691: 		}
                   6692: 		if ($tcrs) {
                   6693: 		    if ($tcrs ne $ucrs) { next; }
                   6694: 		}
                   6695: 		if ($tsec) {
                   6696: 		    if ($tsec ne $usec) { next; }
                   6697: 		}
                   6698: 		$access=($effect eq 'allow');
                   6699: 		last;
                   6700: 	    }
                   6701: 	    if ($realm eq '' && $role eq '') {
                   6702: 		$access=($effect eq 'allow');
                   6703: 	    }
1.402     bowersj2 6704: 	}
1.341     www      6705:     }
                   6706:     return $access;
                   6707: }
                   6708: 
1.103     harris41 6709: # ------------------------------------------------- Check for a user privilege
1.12      www      6710: 
                   6711: sub allowed {
1.1172.2.65  raeburn  6712:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6713:     my $ver_orguri=$uri;
1.439     www      6714:     $uri=&deversion($uri);
1.152     www      6715:     my $orguri=$uri;
1.52      www      6716:     $uri=&declutter($uri);
1.809     raeburn  6717: 
1.810     raeburn  6718:     if ($priv eq 'evb') {
                   6719: # Evade communication block restrictions for specified role in a course
                   6720:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6721:             return $1;
                   6722:         } else {
                   6723:             return;
                   6724:         }
                   6725:     }
                   6726: 
1.620     albertel 6727:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6728: # Free bre access to adm and meta resources
1.775     albertel 6729:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6730: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6731: 	&& ($priv eq 'bre')) {
1.14      www      6732: 	return 'F';
1.159     www      6733:     }
                   6734: 
1.545     banghart 6735: # Free bre access to user's own portfolio contents
1.714     raeburn  6736:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6737:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6738: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6739:         my %setters;
                   6740:         my ($startblock,$endblock) = 
                   6741:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6742:         if ($startblock && $endblock) {
                   6743:             return 'B';
                   6744:         } else {
                   6745:             return 'F';
                   6746:         }
1.545     banghart 6747:     }
                   6748: 
1.762     raeburn  6749: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6750:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6751:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6752:         if (exists($env{'request.course.id'})) {
                   6753:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6754:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6755:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6756:                 my $courseprivid=$env{'request.course.id'};
                   6757:                 $courseprivid=~s/\_/\//;
                   6758:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6759:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6760:                     return $1; 
1.762     raeburn  6761:                 } else {
                   6762:                     if ($env{'request.course.sec'}) {
                   6763:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6764:                     }
                   6765:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6766:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6767:                         return $2;
                   6768:                     }
1.714     raeburn  6769:                 }
                   6770:             }
                   6771:         }
                   6772:     }
                   6773: 
1.159     www      6774: # Free bre to public access
                   6775: 
                   6776:     if ($priv eq 'bre') {
1.238     www      6777:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6778: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6779:            return 'F'; 
                   6780:         }
1.238     www      6781:         if ($copyright eq 'priv') {
                   6782:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6783: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6784: 		return '';
                   6785:             }
                   6786:         }
                   6787:         if ($copyright eq 'domain') {
                   6788:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6789: 	    unless (($env{'user.domain'} eq $1) ||
                   6790:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6791: 		return '';
                   6792:             }
1.262     matthew  6793:         }
1.620     albertel 6794:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6795:             # Library role, so allow browsing of resources in this domain.
                   6796:             return 'F';
1.238     www      6797:         }
1.341     www      6798:         if ($copyright eq 'custom') {
                   6799: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6800:         }
1.14      www      6801:     }
1.264     matthew  6802:     # Domain coordinator is trying to create a course
1.620     albertel 6803:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6804:         # uri is the requested domain in this case.
                   6805:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6806:         # a role of dc for the domain in question.
1.620     albertel 6807:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6808:     }
1.29      www      6809: 
1.52      www      6810:     my $thisallowed='';
                   6811:     my $statecond=0;
                   6812:     my $courseprivid='';
                   6813: 
1.1039    raeburn  6814:     my $ownaccess;
1.1043    raeburn  6815:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6816:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6817:         if ($uri eq '') {
                   6818:             $ownaccess = 1;
                   6819:         } else {
                   6820:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6821:                 my $udom = $env{'user.domain'};
                   6822:                 my $uname = $env{'user.name'};
                   6823:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6824:                     $ownaccess = 1;
1.1040    raeburn  6825:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6826:                     unless ($uri =~ m{\.\./}) {
                   6827:                         $ownaccess = 1;
                   6828:                     }
                   6829:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6830:                     my $now = time;
                   6831:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6832:                         my $adom = $1;
                   6833:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6834:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6835:                                 my ($start,$end) = split('.',$env{$key});
                   6836:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6837:                                     $ownaccess = 1;
                   6838:                                     last;
                   6839:                                 }
                   6840:                             }
                   6841:                         }
                   6842:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6843:                         my $adom = $1;
                   6844:                         my $aname = $2;
1.1042    raeburn  6845:                         foreach my $role ('ca','aa') { 
                   6846:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6847:                                 my ($start,$end) =
                   6848:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6849:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6850:                                     $ownaccess = 1;
                   6851:                                     last;
                   6852:                                 }
1.1039    raeburn  6853:                             }
                   6854:                         }
                   6855:                     }
                   6856:                 }
                   6857:             }
                   6858:         }
                   6859:     }
                   6860: 
1.52      www      6861: # Course
                   6862: 
1.620     albertel 6863:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6864:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6865:             $thisallowed.=$1;
                   6866:         }
1.52      www      6867:     }
1.29      www      6868: 
1.52      www      6869: # Domain
                   6870: 
1.620     albertel 6871:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6872:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6873:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6874:             $thisallowed.=$1;
                   6875:         }
1.12      www      6876:     }
1.52      www      6877: 
1.1141    raeburn  6878: # User who is not author or co-author might still be able to edit
                   6879: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6880:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6881:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6882:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6883:             $thisallowed.=$1;
                   6884:         }
                   6885:     }
                   6886: 
1.52      www      6887: # Course: uri itself is a course
1.66      www      6888:     my $courseuri=$uri;
                   6889:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6890:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6891: 
1.620     albertel 6892:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6893:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6894:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6895:             $thisallowed.=$1;
                   6896:         }
1.12      www      6897:     }
1.29      www      6898: 
1.665     albertel 6899: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6900: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6901:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6902: 	$thisallowed='';
1.671     raeburn  6903:         my ($match)=&is_on_map($uri);
                   6904:         if ($match) {
                   6905:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6906:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  6907:                 my $value = $1;
                   6908:                 if ($noblockcheck) {
                   6909:                     $thisallowed.=$value;
1.1162    raeburn  6910:                 } else {
1.1172.2.65  raeburn  6911:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6912:                     if (@blockers > 0) {
                   6913:                         $thisallowed = 'B';
                   6914:                     } else {
                   6915:                         $thisallowed.=$value;
                   6916:                     }
1.1162    raeburn  6917:                 }
1.671     raeburn  6918:             }
                   6919:         } else {
1.705     albertel 6920:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6921:             if ($refuri) {
                   6922:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6923:                     $thisallowed='F';
1.671     raeburn  6924:                 } else {
                   6925:                     $refuri=&declutter($refuri);
                   6926:                     my ($match) = &is_on_map($refuri);
                   6927:                     if ($match) {
1.1172.2.65  raeburn  6928:                         if ($noblockcheck) {
1.1162    raeburn  6929:                             $thisallowed='F';
1.1172.2.65  raeburn  6930:                         } else {
                   6931:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6932:                             if (@blockers > 0) {
                   6933:                                 $thisallowed = 'B';
                   6934:                             } else {
                   6935:                                 $thisallowed='F';
                   6936:                             }
1.1162    raeburn  6937:                         }
1.671     raeburn  6938:                     }
1.669     raeburn  6939:                 }
1.671     raeburn  6940:             }
                   6941:         }
1.314     www      6942:     }
1.492     albertel 6943: 
1.766     albertel 6944:     if ($priv eq 'bre'
                   6945: 	&& $thisallowed ne 'F' 
                   6946: 	&& $thisallowed ne '2'
                   6947: 	&& &is_portfolio_url($uri)) {
                   6948: 	$thisallowed = &portfolio_access($uri);
                   6949:     }
                   6950:     
1.52      www      6951: # Full access at system, domain or course-wide level? Exit.
1.29      www      6952:     if ($thisallowed=~/F/) {
                   6953: 	return 'F';
                   6954:     }
                   6955: 
1.52      www      6956: # If this is generating or modifying users, exit with special codes
1.29      www      6957: 
1.643     www      6958:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6959: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6960: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6961: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6962: 	    unless ($auname) { return $thisallowed; }
                   6963: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6964: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6965: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6966: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6967: 	}
1.52      www      6968: 	return $thisallowed;
                   6969:     }
                   6970: #
1.103     harris41 6971: # Gathered so far: system, domain and course wide privileges
1.52      www      6972: #
                   6973: # Course: See if uri or referer is an individual resource that is part of 
                   6974: # the course
                   6975: 
1.620     albertel 6976:     if ($env{'request.course.id'}) {
1.232     www      6977: 
1.620     albertel 6978:        $courseprivid=$env{'request.course.id'};
                   6979:        if ($env{'request.course.sec'}) {
                   6980:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6981:        }
                   6982:        $courseprivid=~s/\_/\//;
                   6983:        my $checkreferer=1;
1.232     www      6984:        my ($match,$cond)=&is_on_map($uri);
                   6985:        if ($match) {
                   6986:            $statecond=$cond;
1.620     albertel 6987:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6988:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6989:                my $value = $1;
                   6990:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  6991:                    if ($noblockcheck) {
1.1162    raeburn  6992:                        $thisallowed.=$value;
1.1172.2.65  raeburn  6993:                    } else {
                   6994:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6995:                        if (@blockers > 0) {
                   6996:                            $thisallowed = 'B';
                   6997:                        } else {
                   6998:                            $thisallowed.=$value;
                   6999:                        }
1.1162    raeburn  7000:                    }
                   7001:                } else {
                   7002:                    $thisallowed.=$value;
                   7003:                }
1.52      www      7004:                $checkreferer=0;
                   7005:            }
1.29      www      7006:        }
1.83      www      7007:        
1.148     www      7008:        if ($checkreferer) {
1.620     albertel 7009: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7010:             unless ($refuri) {
1.800     albertel 7011:                 foreach my $key (keys(%env)) {
                   7012: 		    if ($key=~/^httpref\..*\*/) {
                   7013: 			my $pattern=$key;
1.156     www      7014:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7015:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7016:                         $pattern=~s/\//\\\//g;
1.152     www      7017:                         if ($orguri=~/$pattern/) {
1.800     albertel 7018: 			    $refuri=$env{$key};
1.148     www      7019:                         }
                   7020:                     }
1.191     harris41 7021:                 }
1.148     www      7022:             }
1.232     www      7023: 
1.148     www      7024:          if ($refuri) { 
1.152     www      7025: 	  $refuri=&declutter($refuri);
1.232     www      7026:           my ($match,$cond)=&is_on_map($refuri);
                   7027:             if ($match) {
                   7028:               my $refstatecond=$cond;
1.620     albertel 7029:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7030:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7031:                   my $value = $1;
                   7032:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7033:                       if ($noblockcheck) {
1.1162    raeburn  7034:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7035:                       } else {
                   7036:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7037:                           if (@blockers > 0) {
                   7038:                               $thisallowed = 'B';
                   7039:                           } else {
                   7040:                               $thisallowed.=$value;
                   7041:                           }
1.1162    raeburn  7042:                       }
                   7043:                   } else {
                   7044:                       $thisallowed.=$value;
                   7045:                   }
1.53      www      7046:                   $uri=$refuri;
                   7047:                   $statecond=$refstatecond;
1.52      www      7048:               }
                   7049:           }
1.148     www      7050:         }
1.29      www      7051:        }
1.52      www      7052:    }
1.29      www      7053: 
1.52      www      7054: #
1.103     harris41 7055: # Gathered now: all privileges that could apply, and condition number
1.52      www      7056: # 
                   7057: #
                   7058: # Full or no access?
                   7059: #
1.29      www      7060: 
1.52      www      7061:     if ($thisallowed=~/F/) {
                   7062: 	return 'F';
                   7063:     }
1.29      www      7064: 
1.52      www      7065:     unless ($thisallowed) {
                   7066:         return '';
                   7067:     }
1.29      www      7068: 
1.52      www      7069: # Restrictions exist, deal with them
                   7070: #
                   7071: #   C:according to course preferences
                   7072: #   R:according to resource settings
                   7073: #   L:unless locked
                   7074: #   X:according to user session state
                   7075: #
                   7076: 
                   7077: # Possibly locked functionality, check all courses
1.54      www      7078: # Locks might take effect only after 10 minutes cache expiration for other
                   7079: # courses, and 2 minutes for current course
1.52      www      7080: 
                   7081:     my $envkey;
                   7082:     if ($thisallowed=~/L/) {
1.1000    raeburn  7083:         foreach $envkey (keys(%env)) {
1.54      www      7084:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7085:                my $courseid=$2;
                   7086:                my $roleid=$1.'.'.$2;
1.92      www      7087:                $courseid=~s/^\///;
1.54      www      7088:                my $expiretime=600;
1.620     albertel 7089:                if ($env{'request.role'} eq $roleid) {
1.54      www      7090: 		  $expiretime=120;
                   7091:                }
                   7092: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7093:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7094:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7095: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7096:                }
1.620     albertel 7097:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7098:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7099: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7100:                        &log($env{'user.domain'},$env{'user.name'},
                   7101:                             $env{'user.home'},
1.57      www      7102:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7103:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7104:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7105: 		       return '';
                   7106:                    }
                   7107:                }
1.620     albertel 7108:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7109:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7110: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7111:                        &log($env{'user.domain'},$env{'user.name'},
                   7112:                             $env{'user.home'},
1.57      www      7113:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7114:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7115:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7116: 		       return '';
                   7117:                    }
                   7118:                }
                   7119: 	   }
1.29      www      7120:        }
1.52      www      7121:     }
                   7122:    
                   7123: #
                   7124: # Rest of the restrictions depend on selected course
                   7125: #
                   7126: 
1.620     albertel 7127:     unless ($env{'request.course.id'}) {
1.766     albertel 7128: 	if ($thisallowed eq 'A') {
                   7129: 	    return 'A';
1.814     raeburn  7130:         } elsif ($thisallowed eq 'B') {
                   7131:             return 'B';
1.766     albertel 7132: 	} else {
                   7133: 	    return '1';
                   7134: 	}
1.52      www      7135:     }
1.29      www      7136: 
1.52      www      7137: #
                   7138: # Now user is definitely in a course
                   7139: #
1.53      www      7140: 
                   7141: 
                   7142: # Course preferences
                   7143: 
                   7144:    if ($thisallowed=~/C/) {
1.620     albertel 7145:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7146:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7147:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7148: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7149: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7150: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7151: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7152: 			$env{'request.course.id'});
                   7153: 	   }
1.237     www      7154:            return '';
                   7155:        }
                   7156: 
1.620     albertel 7157:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7158: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7159: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7160: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7161: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7162: 			$env{'request.course.id'});
                   7163: 	   }
1.54      www      7164:            return '';
                   7165:        }
1.53      www      7166:    }
                   7167: 
                   7168: # Resource preferences
                   7169: 
                   7170:    if ($thisallowed=~/R/) {
1.620     albertel 7171:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7172:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7173: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7174: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7175: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7176: 	   }
                   7177: 	   return '';
1.54      www      7178:        }
1.53      www      7179:    }
1.30      www      7180: 
1.246     www      7181: # Restricted by state or randomout?
1.30      www      7182: 
1.52      www      7183:    if ($thisallowed=~/X/) {
1.620     albertel 7184:       if ($env{'acc.randomout'}) {
1.579     albertel 7185: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7186:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7187:             return ''; 
                   7188:          }
1.247     www      7189:       }
                   7190:       if (&condval($statecond)) {
1.52      www      7191: 	 return '2';
                   7192:       } else {
                   7193:          return '';
                   7194:       }
                   7195:    }
1.30      www      7196: 
1.766     albertel 7197:     if ($thisallowed eq 'A') {
                   7198: 	return 'A';
1.814     raeburn  7199:     } elsif ($thisallowed eq 'B') {
                   7200:         return 'B';
1.766     albertel 7201:     }
1.52      www      7202:    return 'F';
1.232     www      7203: }
1.1162    raeburn  7204: 
1.1172.2.13  raeburn  7205: # ------------------------------------------- Check construction space access
                   7206: 
                   7207: sub constructaccess {
                   7208:     my ($url,$setpriv)=@_;
                   7209: 
                   7210: # We do not allow editing of previous versions of files
                   7211:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7212: 
                   7213: # Get username and domain from URL
                   7214:     my ($ownername,$ownerdomain,$ownerhome);
                   7215: 
                   7216:     ($ownerdomain,$ownername) =
                   7217:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7218: 
                   7219: # The URL does not really point to any authorspace, forget it
                   7220:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7221: 
                   7222: # Now we need to see if the user has access to the authorspace of
                   7223: # $ownername at $ownerdomain
                   7224: 
                   7225:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7226: # Real author for this?
                   7227:        $ownerhome = $env{'user.home'};
                   7228:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7229:           return ($ownername,$ownerdomain,$ownerhome);
                   7230:        }
                   7231:     } else {
                   7232: # Co-author for this?
                   7233:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7234:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7235:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7236:             return ($ownername,$ownerdomain,$ownerhome);
                   7237:         }
                   7238:     }
                   7239: 
                   7240: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7241: # we might as well leave
                   7242:    unless ($setpriv) { return ''; }
                   7243: 
                   7244: # Backdoor access?
                   7245:     my $allowed=&allowed('eco',$ownerdomain);
                   7246: # Nope
                   7247:     unless ($allowed) { return ''; }
                   7248: # Looks like we may have access, but could be locked by the owner of the construction space
                   7249:     if ($allowed eq 'U') {
                   7250:         my %blocked=&get('environment',['domcoord.author'],
                   7251:                          $ownerdomain,$ownername);
                   7252: # Is blocked by owner
                   7253:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7254:     }
                   7255:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7256: # Grant temporary access
                   7257:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7258:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7259:         if (!$update) { $update = $then; }
                   7260:         my $refresh=$env{'user.refresh.time'};
                   7261:         if (!$refresh) { $refresh = $update; }
                   7262:         my $now = time;
                   7263:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7264:                            $now,'ca','constructaccess');
                   7265:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7266:         return($ownername,$ownerdomain,$ownerhome);
                   7267:     }
                   7268: # No business here
                   7269:     return '';
                   7270: }
                   7271: 
1.1172.2.66  raeburn  7272: # ----------------------------------------------------------- Content Blocking
                   7273: 
                   7274: {
                   7275: # Caches for faster Course Contents display where content blocking
                   7276: # is in operation (i.e., interval param set) for timed quiz.
                   7277: #
                   7278: # User for whom data are being temporarily cached.
                   7279: my $cacheduser='';
                   7280: # Cached blockers for this user (a hash of blocking items).
                   7281: my %cachedblockers=();
                   7282: # When the data were last cached.
                   7283: my $cachedlast='';
                   7284: 
                   7285: sub load_all_blockers {
                   7286:     my ($uname,$udom,$blocks)=@_;
                   7287:     if (($uname ne '') && ($udom ne '')) {
                   7288:         if (($cacheduser eq $uname.':'.$udom) &&
                   7289:             (abs($cachedlast-time)<5)) {
                   7290:             return;
                   7291:         }
                   7292:     }
                   7293:     $cachedlast=time;
                   7294:     $cacheduser=$uname.':'.$udom;
                   7295:     %cachedblockers = &get_commblock_resources($blocks);
                   7296: }
                   7297: 
1.1162    raeburn  7298: sub get_comm_blocks {
                   7299:     my ($cdom,$cnum) = @_;
                   7300:     if ($cdom eq '' || $cnum eq '') {
                   7301:         return unless ($env{'request.course.id'});
                   7302:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7303:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7304:     }
                   7305:     my %commblocks;
                   7306:     my $hashid=$cdom.'_'.$cnum;
                   7307:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7308:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7309:         %commblocks = %{$blocksref};
                   7310:     } else {
                   7311:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7312:         my $cachetime = 600;
                   7313:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7314:     }
                   7315:     return %commblocks;
                   7316: }
                   7317: 
1.1172.2.66  raeburn  7318: sub get_commblock_resources {
                   7319:     my ($blocks) = @_;
                   7320:     my %blockers = ();
                   7321:     return %blockers unless ($env{'request.course.id'});
                   7322:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7323:     my %commblocks;
                   7324:     if (ref($blocks) eq 'HASH') {
                   7325:         %commblocks = %{$blocks};
                   7326:     } else {
                   7327:         %commblocks = &get_comm_blocks();
                   7328:     }
1.1172.2.66  raeburn  7329:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7330:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7331:     return %blockers unless (ref($navmap));
                   7332:     my $now = time;
1.1162    raeburn  7333:     foreach my $block (keys(%commblocks)) {
                   7334:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7335:             my ($start,$end) = ($1,$2);
                   7336:             if ($start <= $now && $end >= $now) {
                   7337:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7338:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7339:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7340:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7341:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7342:                             }
                   7343:                         }
                   7344:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7345:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7346:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7347:                             }
                   7348:                         }
                   7349:                     }
                   7350:                 }
                   7351:             }
                   7352:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7353:             my $item = $1;
1.1163    raeburn  7354:             my @to_test;
1.1162    raeburn  7355:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7356:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7357:                     my @interval;
                   7358:                     my $type = 'map';
                   7359:                     if ($item eq 'course') {
                   7360:                         $type = 'course';
                   7361:                         @interval=&EXT("resource.0.interval");
                   7362:                     } else {
                   7363:                         if ($item =~ /___\d+___/) {
                   7364:                             $type = 'resource';
                   7365:                             @interval=&EXT("resource.0.interval",$item);
                   7366:                             if (ref($navmap)) {
                   7367:                                 my $res = $navmap->getBySymb($item);
                   7368:                                 push(@to_test,$res);
                   7369:                             }
1.1162    raeburn  7370:                         } else {
1.1172.2.66  raeburn  7371:                             my $mapsymb = &symbread($item,1);
                   7372:                             if ($mapsymb) {
                   7373:                                 if (ref($navmap)) {
                   7374:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7375:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7376:                                     foreach my $res (@to_test) {
                   7377:                                         my $symb = $res->symb();
                   7378:                                         next if ($symb eq $mapsymb);
                   7379:                                         if ($symb ne '') {
                   7380:                                             @interval=&EXT("resource.0.interval",$symb);
                   7381:                                             if ($interval[1] eq 'map') {
                   7382:                                                 last;
1.1162    raeburn  7383:                                             }
                   7384:                                         }
                   7385:                                     }
                   7386:                                 }
                   7387:                             }
                   7388:                         }
1.1172.2.66  raeburn  7389:                     }
                   7390:                     if ($interval[0] =~ /^\d+$/) {
                   7391:                         my $first_access;
                   7392:                         if ($type eq 'resource') {
                   7393:                             $first_access=&get_first_access($interval[1],$item);
                   7394:                         } elsif ($type eq 'map') {
                   7395:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7396:                         } else {
                   7397:                             $first_access=&get_first_access($interval[1]);
                   7398:                         }
                   7399:                         if ($first_access) {
                   7400:                             my $timesup = $first_access+$interval[0];
                   7401:                             if ($timesup > $now) {
                   7402:                                 my $activeblock;
                   7403:                                 foreach my $res (@to_test) {
                   7404:                                     if ($res->answerable()) {
                   7405:                                         $activeblock = 1;
                   7406:                                         last;
                   7407:                                     }
                   7408:                                 }
                   7409:                                 if ($activeblock) {
                   7410:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7411:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7412:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7413:                                          }
                   7414:                                     }
                   7415:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7416:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7417:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7418:                                         }
1.1162    raeburn  7419:                                     }
                   7420:                                 }
                   7421:                             }
                   7422:                         }
                   7423:                     }
                   7424:                 }
                   7425:             }
                   7426:         }
                   7427:     }
1.1172.2.66  raeburn  7428:     return %blockers;
1.1162    raeburn  7429: }
                   7430: 
1.1172.2.66  raeburn  7431: sub has_comm_blocking {
                   7432:     my ($priv,$symb,$uri,$blocks) = @_;
                   7433:     my @blockers;
                   7434:     return unless ($env{'request.course.id'});
                   7435:     return unless ($priv eq 'bre');
                   7436:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7437:     return if ($env{'request.state'} eq 'construct');
                   7438:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7439:     return unless (keys(%cachedblockers) > 0);
                   7440:     my (%possibles,@symbs);
                   7441:     if (!$symb) {
                   7442:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7443:     }
1.1172.2.66  raeburn  7444:     if ($symb) {
                   7445:         @symbs = ($symb);
                   7446:     } elsif (keys(%possibles)) {
                   7447:         @symbs = keys(%possibles);
                   7448:     }
                   7449:     my $noblock;
                   7450:     foreach my $symb (@symbs) {
                   7451:         last if ($noblock);
                   7452:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7453:         foreach my $block (keys(%cachedblockers)) {
                   7454:             if ($block =~ /^firstaccess____(.+)$/) {
                   7455:                 my $item = $1;
                   7456:                 if (($item eq $map) || ($item eq $symb)) {
                   7457:                     $noblock = 1;
                   7458:                     last;
                   7459:                 }
1.1162    raeburn  7460:             }
1.1172.2.66  raeburn  7461:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7462:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7463:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7464:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7465:                             push(@blockers,$block);
                   7466:                         }
                   7467:                     }
                   7468:                 }
                   7469:             }
                   7470:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7471:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7472:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7473:                         push(@blockers,$block);
                   7474:                     }
                   7475:                 }
1.1162    raeburn  7476:             }
                   7477:         }
                   7478:     }
1.1172.2.66  raeburn  7479:     return if ($noblock);
                   7480:     return @blockers;
                   7481: }
1.1162    raeburn  7482: }
                   7483: 
1.1172.2.66  raeburn  7484: # -------------------------------- Deversion and split uri into path an filename
                   7485: 
1.1133    foxr     7486: #
1.1172.2.66  raeburn  7487: #   Removes the version from a URI and
1.1133    foxr     7488: #   splits it in to its filename and path to the filename.
                   7489: #   Seems like File::Basename could have done this more clearly.
                   7490: #   Parameters:
                   7491: #      $uri   - input URI
                   7492: #   Returns:
                   7493: #     Two element list consisting of 
                   7494: #     $pathname  - the URI up to and excluding the trailing /
                   7495: #     $filename  - The part of the URI following the last /
                   7496: #  NOTE:
                   7497: #    Another realization of this is simply:
                   7498: #    use File::Basename;
                   7499: #    ...
                   7500: #    $uri = shift;
                   7501: #    $filename = basename($uri);
                   7502: #    $path     = dirname($uri);
                   7503: #    return ($filename, $path);
                   7504: #
                   7505: #     The implementation below is probably faster however.
                   7506: #
1.710     albertel 7507: sub split_uri_for_cond {
                   7508:     my $uri=&deversion(&declutter(shift));
                   7509:     my @uriparts=split(/\//,$uri);
                   7510:     my $filename=pop(@uriparts);
                   7511:     my $pathname=join('/',@uriparts);
                   7512:     return ($pathname,$filename);
                   7513: }
1.232     www      7514: # --------------------------------------------------- Is a resource on the map?
                   7515: 
                   7516: sub is_on_map {
1.710     albertel 7517:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7518:     #Trying to find the conditional for the file
1.620     albertel 7519:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7520: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7521:     if ($match) {
1.289     bowersj2 7522: 	return (1,$1);
                   7523:     } else {
1.434     www      7524: 	return (0,0);
1.289     bowersj2 7525:     }
1.12      www      7526: }
                   7527: 
1.427     www      7528: # --------------------------------------------------------- Get symb from alias
                   7529: 
                   7530: sub get_symb_from_alias {
                   7531:     my $symb=shift;
                   7532:     my ($map,$resid,$url)=&decode_symb($symb);
                   7533: # Already is a symb
                   7534:     if ($url) { return $symb; }
                   7535: # Must be an alias
                   7536:     my $aliassymb='';
                   7537:     my %bighash;
1.620     albertel 7538:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7539:                             &GDBM_READER(),0640)) {
                   7540:         my $rid=$bighash{'mapalias_'.$symb};
                   7541: 	if ($rid) {
                   7542: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7543: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7544: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7545: 	}
                   7546:         untie %bighash;
                   7547:     }
                   7548:     return $aliassymb;
                   7549: }
                   7550: 
1.12      www      7551: # ----------------------------------------------------------------- Define Role
                   7552: 
                   7553: sub definerole {
                   7554:   if (allowed('mcr','/')) {
                   7555:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7556:     foreach my $role (split(':',$sysrole)) {
                   7557: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7558:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7559:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7560: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7561:                return "refused:s:$crole&$cqual"; 
                   7562:             }
                   7563:         }
1.191     harris41 7564:     }
1.800     albertel 7565:     foreach my $role (split(':',$domrole)) {
                   7566: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7567:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7568:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7569: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7570:                return "refused:d:$crole&$cqual"; 
                   7571:             }
                   7572:         }
1.191     harris41 7573:     }
1.800     albertel 7574:     foreach my $role (split(':',$courole)) {
                   7575: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7576:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7577:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7578: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7579:                return "refused:c:$crole&$cqual"; 
                   7580:             }
                   7581:         }
1.191     harris41 7582:     }
1.620     albertel 7583:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7584:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7585: 	        "rolesdef_$rolename=".
                   7586:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7587:     return reply($command,$env{'user.home'});
1.12      www      7588:   } else {
                   7589:     return 'refused';
                   7590:   }
1.105     harris41 7591: }
                   7592: 
                   7593: # ---------------- Make a metadata query against the network of library servers
                   7594: 
                   7595: sub metadata_query {
1.1172.2.33  raeburn  7596:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7597:     my %rhash;
1.845     albertel 7598:     my %libserv = &all_library();
1.244     matthew  7599:     my @server_list = (defined($server_array) ? @$server_array
                   7600:                                               : keys(%libserv) );
                   7601:     for my $server (@server_list) {
1.1172.2.33  raeburn  7602:         my $domains = '';
                   7603:         if (ref($domains_hash) eq 'HASH') {
                   7604:             $domains = $domains_hash->{$server};    
                   7605:         }
1.118     harris41 7606: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  7607: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7608: 	    $rhash{$server}=$reply;
                   7609: 	}
                   7610: 	else {
                   7611: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  7612: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7613: 			     $server);
                   7614: 	    $rhash{$server}=$reply;
                   7615: 	}
1.112     harris41 7616:     }
1.118     harris41 7617:     return \%rhash;
1.240     www      7618: }
                   7619: 
                   7620: # ----------------------------------------- Send log queries and wait for reply
                   7621: 
                   7622: sub log_query {
                   7623:     my ($uname,$udom,$query,%filters)=@_;
                   7624:     my $uhome=&homeserver($uname,$udom);
                   7625:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7626:     my $uhost=&hostname($uhome);
1.800     albertel 7627:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7628:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7629:                        $uhome);
1.479     albertel 7630:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7631:     return get_query_reply($queryid);
                   7632: }
                   7633: 
1.818     raeburn  7634: # -------------------------- Update MySQL table for portfolio file
                   7635: 
                   7636: sub update_portfolio_table {
1.821     raeburn  7637:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7638:     if ($group ne '') {
                   7639:         $file_name =~s /^\Q$group\E//;
                   7640:     }
1.818     raeburn  7641:     my $homeserver = &homeserver($uname,$udom);
                   7642:     my $queryid=
1.821     raeburn  7643:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7644:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7645:     my $reply = &get_query_reply($queryid);
                   7646:     return $reply;
                   7647: }
                   7648: 
1.899     raeburn  7649: # -------------------------- Update MySQL allusers table
                   7650: 
                   7651: sub update_allusers_table {
                   7652:     my ($uname,$udom,$names) = @_;
                   7653:     my $homeserver = &homeserver($uname,$udom);
                   7654:     my $queryid=
                   7655:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7656:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7657:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7658:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7659:                'generation='.&escape($names->{'generation'}).'%%'.
                   7660:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7661:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7662:     return;
1.899     raeburn  7663: }
                   7664: 
1.508     raeburn  7665: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7666: 
                   7667: sub fetch_enrollment_query {
1.511     raeburn  7668:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7669:     my $homeserver;
1.547     raeburn  7670:     my $maxtries = 1;
1.508     raeburn  7671:     if ($context eq 'automated') {
                   7672:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7673:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7674:     } else {
                   7675:         $homeserver = &homeserver($cnum,$dom);
                   7676:     }
1.838     albertel 7677:     my $host=&hostname($homeserver);
1.506     raeburn  7678:     my $cmd = '';
1.1000    raeburn  7679:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7680:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7681:     }
                   7682:     $cmd =~ s/%%$//;
                   7683:     $cmd = &escape($cmd);
                   7684:     my $query = 'fetchenrollment';
1.620     albertel 7685:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7686:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7687:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7688:         return 'error: '.$queryid;
                   7689:     }
1.506     raeburn  7690:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7691:     my $tries = 1;
                   7692:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7693:         $reply = &get_query_reply($queryid);
                   7694:         $tries ++;
                   7695:     }
1.526     raeburn  7696:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7697:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7698:     } else {
1.901     albertel 7699:         my @responses = split(/:/,$reply);
1.515     raeburn  7700:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7701:             foreach my $line (@responses) {
                   7702:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7703:                 $$replyref{$key} = $value;
                   7704:             }
                   7705:         } else {
1.1117    foxr     7706:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7707:             foreach my $line (@responses) {
                   7708:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7709:                 $$replyref{$key} = $value;
                   7710:                 if ($value > 0) {
1.800     albertel 7711:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7712:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7713:                         my $destname = $pathname.'/'.$filename;
                   7714:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7715:                         if ($xml_classlist =~ /^error/) {
                   7716:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7717:                         } else {
1.506     raeburn  7718:                             if ( open(FILE,">$destname") ) {
                   7719:                                 print FILE &unescape($xml_classlist);
                   7720:                                 close(FILE);
1.526     raeburn  7721:                             } else {
                   7722:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7723:                             }
                   7724:                         }
                   7725:                     }
                   7726:                 }
                   7727:             }
                   7728:         }
                   7729:         return 'ok';
                   7730:     }
                   7731:     return 'error';
                   7732: }
                   7733: 
1.242     www      7734: sub get_query_reply {
                   7735:     my $queryid=shift;
1.1117    foxr     7736:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7737:     my $reply='';
                   7738:     for (1..100) {
                   7739: 	sleep 2;
                   7740:         if (-e $replyfile.'.end') {
1.448     albertel 7741: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7742: 		$reply = join('',<$fh>);
                   7743: 		close($fh);
1.240     www      7744: 	   } else { return 'error: reply_file_error'; }
1.242     www      7745:            return &unescape($reply);
                   7746: 	}
1.240     www      7747:     }
1.242     www      7748:     return 'timeout:'.$queryid;
1.240     www      7749: }
                   7750: 
                   7751: sub courselog_query {
1.241     www      7752: #
                   7753: # possible filters:
                   7754: # url: url or symb
                   7755: # username
                   7756: # domain
                   7757: # action: view, submit, grade
                   7758: # start: timestamp
                   7759: # end: timestamp
                   7760: #
1.240     www      7761:     my (%filters)=@_;
1.620     albertel 7762:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7763:     if ($filters{'url'}) {
                   7764: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7765:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7766:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7767:     }
1.620     albertel 7768:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7769:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7770:     return &log_query($cname,$cdom,'courselog',%filters);
                   7771: }
                   7772: 
                   7773: sub userlog_query {
1.858     raeburn  7774: #
                   7775: # possible filters:
                   7776: # action: log check role
                   7777: # start: timestamp
                   7778: # end: timestamp
                   7779: #
1.240     www      7780:     my ($uname,$udom,%filters)=@_;
                   7781:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7782: }
                   7783: 
1.506     raeburn  7784: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7785: 
                   7786: sub auto_run {
1.508     raeburn  7787:     my ($cnum,$cdom) = @_;
1.876     raeburn  7788:     my $response = 0;
                   7789:     my $settings;
                   7790:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7791:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7792:         $settings = $domconfig{'autoenroll'};
                   7793:         if ($settings->{'run'} eq '1') {
                   7794:             $response = 1;
                   7795:         }
                   7796:     } else {
1.934     raeburn  7797:         my $homeserver;
                   7798:         if (&is_course($cdom,$cnum)) {
                   7799:             $homeserver = &homeserver($cnum,$cdom);
                   7800:         } else {
                   7801:             $homeserver = &domain($cdom,'primary');
                   7802:         }
                   7803:         if ($homeserver ne 'no_host') {
                   7804:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7805:         }
1.876     raeburn  7806:     }
1.506     raeburn  7807:     return $response;
                   7808: }
1.776     albertel 7809: 
1.506     raeburn  7810: sub auto_get_sections {
1.508     raeburn  7811:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7812:     my $homeserver;
                   7813:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7814:         $homeserver = &homeserver($cnum,$cdom);
                   7815:     }
                   7816:     if (!defined($homeserver)) { 
                   7817:         if ($cdom =~ /^$match_domain$/) {
                   7818:             $homeserver = &domain($cdom,'primary');
                   7819:         }
                   7820:     }
                   7821:     my @secs;
                   7822:     if (defined($homeserver)) {
                   7823:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7824:         unless ($response eq 'refused') {
                   7825:             @secs = split(/:/,$response);
                   7826:         }
1.506     raeburn  7827:     }
                   7828:     return @secs;
                   7829: }
1.776     albertel 7830: 
1.506     raeburn  7831: sub auto_new_course {
1.1099    raeburn  7832:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7833:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7834:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7835:     return $response;
                   7836: }
1.776     albertel 7837: 
1.506     raeburn  7838: sub auto_validate_courseID {
1.508     raeburn  7839:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7840:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7841:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7842:     return $response;
                   7843: }
1.776     albertel 7844: 
1.1007    raeburn  7845: sub auto_validate_instcode {
1.1020    raeburn  7846:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7847:     my ($homeserver,$response);
                   7848:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7849:         $homeserver = &homeserver($cnum,$cdom);
                   7850:     }
                   7851:     if (!defined($homeserver)) {
                   7852:         if ($cdom =~ /^$match_domain$/) {
                   7853:             $homeserver = &domain($cdom,'primary');
                   7854:         }
                   7855:     }
1.1065    raeburn  7856:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7857:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7858:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7859:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7860: }
                   7861: 
1.506     raeburn  7862: sub auto_create_password {
1.873     raeburn  7863:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7864:     my ($homeserver,$response);
1.506     raeburn  7865:     my $create_passwd = 0;
                   7866:     my $authchk = '';
1.873     raeburn  7867:     if ($udom =~ /^$match_domain$/) {
                   7868:         $homeserver = &domain($udom,'primary');
                   7869:     }
                   7870:     if ($homeserver eq '') {
                   7871:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7872:             $homeserver = &homeserver($cnum,$cdom);
                   7873:         }
                   7874:     }
                   7875:     if ($homeserver eq '') {
                   7876:         $authchk = 'nodomain';
1.506     raeburn  7877:     } else {
1.873     raeburn  7878:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7879:         if ($response eq 'refused') {
                   7880:             $authchk = 'refused';
                   7881:         } else {
1.901     albertel 7882:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7883:         }
1.506     raeburn  7884:     }
                   7885:     return ($authparam,$create_passwd,$authchk);
                   7886: }
                   7887: 
1.706     raeburn  7888: sub auto_photo_permission {
                   7889:     my ($cnum,$cdom,$students) = @_;
                   7890:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7891:     my ($outcome,$perm_reqd,$conditions) = 
                   7892: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7893:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7894: 	return (undef,undef);
                   7895:     }
1.706     raeburn  7896:     return ($outcome,$perm_reqd,$conditions);
                   7897: }
                   7898: 
                   7899: sub auto_checkphotos {
                   7900:     my ($uname,$udom,$pid) = @_;
                   7901:     my $homeserver = &homeserver($uname,$udom);
                   7902:     my ($result,$resulttype);
                   7903:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7904: 				   &escape($uname).':'.&escape($pid),
                   7905: 				   $homeserver));
1.709     albertel 7906:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7907: 	return (undef,undef);
                   7908:     }
1.706     raeburn  7909:     if ($outcome) {
                   7910:         ($result,$resulttype) = split(/:/,$outcome);
                   7911:     } 
                   7912:     return ($result,$resulttype);
                   7913: }
                   7914: 
                   7915: sub auto_photochoice {
                   7916:     my ($cnum,$cdom) = @_;
                   7917:     my $homeserver = &homeserver($cnum,$cdom);
                   7918:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7919: 						       &escape($cdom),
                   7920: 						       $homeserver)));
1.709     albertel 7921:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7922: 	return (undef,undef);
                   7923:     }
1.706     raeburn  7924:     return ($update,$comment);
                   7925: }
                   7926: 
                   7927: sub auto_photoupdate {
                   7928:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7929:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7930:     my $host=&hostname($homeserver);
1.706     raeburn  7931:     my $cmd = '';
                   7932:     my $maxtries = 1;
1.800     albertel 7933:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7934:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7935:     }
                   7936:     $cmd =~ s/%%$//;
                   7937:     $cmd = &escape($cmd);
                   7938:     my $query = 'institutionalphotos';
                   7939:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7940:     unless ($queryid=~/^\Q$host\E\_/) {
                   7941:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7942:         return 'error: '.$queryid;
                   7943:     }
                   7944:     my $reply = &get_query_reply($queryid);
                   7945:     my $tries = 1;
                   7946:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7947:         $reply = &get_query_reply($queryid);
                   7948:         $tries ++;
                   7949:     }
                   7950:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7951:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7952:     } else {
                   7953:         my @responses = split(/:/,$reply);
                   7954:         my $outcome = shift(@responses); 
                   7955:         foreach my $item (@responses) {
                   7956:             my ($key,$value) = split(/=/,$item);
                   7957:             $$photo{$key} = $value;
                   7958:         }
                   7959:         return $outcome;
                   7960:     }
                   7961:     return 'error';
                   7962: }
                   7963: 
1.521     raeburn  7964: sub auto_instcode_format {
1.793     albertel 7965:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7966: 	$cat_order) = @_;
1.521     raeburn  7967:     my $courses = '';
1.772     raeburn  7968:     my @homeservers;
1.521     raeburn  7969:     if ($caller eq 'global') {
1.841     albertel 7970: 	my %servers = &get_servers($codedom,'library');
                   7971: 	foreach my $tryserver (keys(%servers)) {
                   7972: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7973: 		push(@homeservers,$tryserver);
                   7974: 	    }
1.584     raeburn  7975:         }
1.1022    raeburn  7976:     } elsif ($caller eq 'requests') {
                   7977:         if ($codedom =~ /^$match_domain$/) {
                   7978:             my $chome = &domain($codedom,'primary');
                   7979:             unless ($chome eq 'no_host') {
                   7980:                 push(@homeservers,$chome);
                   7981:             }
                   7982:         }
1.521     raeburn  7983:     } else {
1.772     raeburn  7984:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7985:     }
1.793     albertel 7986:     foreach my $code (keys(%{$instcodes})) {
                   7987:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7988:     }
                   7989:     chop($courses);
1.772     raeburn  7990:     my $ok_response = 0;
                   7991:     my $response;
                   7992:     while (@homeservers > 0 && $ok_response == 0) {
                   7993:         my $server = shift(@homeservers); 
                   7994:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7995:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7996:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7997: 		split(/:/,$response);
1.772     raeburn  7998:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7999:             push(@{$codetitles},&str2array($codetitles_str));
                   8000:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8001:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8002:             $ok_response = 1;
                   8003:         }
                   8004:     }
                   8005:     if ($ok_response) {
1.521     raeburn  8006:         return 'ok';
1.772     raeburn  8007:     } else {
                   8008:         return $response;
1.521     raeburn  8009:     }
                   8010: }
                   8011: 
1.792     raeburn  8012: sub auto_instcode_defaults {
                   8013:     my ($domain,$returnhash,$code_order) = @_;
                   8014:     my @homeservers;
1.841     albertel 8015: 
                   8016:     my %servers = &get_servers($domain,'library');
                   8017:     foreach my $tryserver (keys(%servers)) {
                   8018: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8019: 	    push(@homeservers,$tryserver);
                   8020: 	}
1.792     raeburn  8021:     }
1.841     albertel 8022: 
1.792     raeburn  8023:     my $response;
1.841     albertel 8024:     foreach my $server (@homeservers) {
1.792     raeburn  8025:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8026:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8027: 	
                   8028: 	foreach my $pair (split(/\&/,$response)) {
                   8029: 	    my ($name,$value)=split(/\=/,$pair);
                   8030: 	    if ($name eq 'code_order') {
                   8031: 		@{$code_order} = split(/\&/,&unescape($value));
                   8032: 	    } else {
                   8033: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8034: 	    }
                   8035: 	}
                   8036: 	return 'ok';
1.792     raeburn  8037:     }
1.841     albertel 8038: 
                   8039:     return $response;
1.1003    raeburn  8040: }
                   8041: 
                   8042: sub auto_possible_instcodes {
1.1007    raeburn  8043:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8044:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8045:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8046:         return;
                   8047:     }
1.1003    raeburn  8048:     my (@homeservers,$uhome);
                   8049:     if (defined(&domain($domain,'primary'))) {
                   8050:         $uhome=&domain($domain,'primary');
                   8051:         push(@homeservers,&domain($domain,'primary'));
                   8052:     } else {
                   8053:         my %servers = &get_servers($domain,'library');
                   8054:         foreach my $tryserver (keys(%servers)) {
                   8055:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8056:                 push(@homeservers,$tryserver);
                   8057:             }
                   8058:         }
                   8059:     }
                   8060:     my $response;
                   8061:     foreach my $server (@homeservers) {
                   8062:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8063:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8064:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8065:             split(':',$response);
                   8066:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8067:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8068:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8069:             my ($name,$value)=split('=',$item);
                   8070:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8071:         }
                   8072:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8073:             my ($name,$value)=split('=',$item);
                   8074:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8075:         }
                   8076:         return 'ok';
                   8077:     }
                   8078:     return $response;
                   8079: }
1.792     raeburn  8080: 
1.1010    raeburn  8081: sub auto_courserequest_checks {
                   8082:     my ($dom) = @_;
1.1020    raeburn  8083:     my ($homeserver,%validations);
                   8084:     if ($dom =~ /^$match_domain$/) {
                   8085:         $homeserver = &domain($dom,'primary');
                   8086:     }
                   8087:     unless ($homeserver eq 'no_host') {
                   8088:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8089:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8090:             my @items = split(/&/,$response);
                   8091:             foreach my $item (@items) {
                   8092:                 my ($key,$value) = split('=',$item);
                   8093:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8094:             }
                   8095:         }
                   8096:     }
1.1010    raeburn  8097:     return %validations; 
                   8098: }
                   8099: 
1.1020    raeburn  8100: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8101:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8102:     my ($homeserver,$response);
                   8103:     if ($dom =~ /^$match_domain$/) {
                   8104:         $homeserver = &domain($dom,'primary');
                   8105:     }
1.1172.2.43  raeburn  8106:     unless ($homeserver eq 'no_host') {
                   8107:         my $customdata;
                   8108:         if (ref($custominfo) eq 'HASH') {
                   8109:             $customdata = &freeze_escape($custominfo);
                   8110:         }
1.1020    raeburn  8111:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8112:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8113:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8114:                                     $customdata,$homeserver));
1.1020    raeburn  8115:     }
                   8116:     return $response;
                   8117: }
                   8118: 
1.777     albertel 8119: sub auto_validate_class_sec {
1.918     raeburn  8120:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8121:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8122:     my $ownerlist;
                   8123:     if (ref($owners) eq 'ARRAY') {
                   8124:         $ownerlist = join(',',@{$owners});
                   8125:     } else {
                   8126:         $ownerlist = $owners;
                   8127:     }
1.773     raeburn  8128:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8129:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8130:     return $response;
                   8131: }
                   8132: 
1.1172.2.38  raeburn  8133: sub auto_crsreq_update {
                   8134:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8135:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8136:     my ($homeserver,%crsreqresponse);
                   8137:     if ($cdom =~ /^$match_domain$/) {
                   8138:         $homeserver = &domain($cdom,'primary');
                   8139:     }
                   8140:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8141:         my $info;
                   8142:         if (ref($inbound) eq 'HASH') {
                   8143:             $info = &freeze_escape($inbound);
                   8144:         }
                   8145:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8146:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8147:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8148:                             &escape($title).':'.&escape($code).':'.
                   8149:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8150:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8151:             my @items = split(/&/,$response);
                   8152:             foreach my $item (@items) {
                   8153:                 my ($key,$value) = split('=',$item);
                   8154:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8155:             }
                   8156:         }
                   8157:     }
                   8158:     return \%crsreqresponse;
                   8159: }
                   8160: 
1.679     raeburn  8161: # ------------------------------------------------------- Course Group routines
                   8162: 
                   8163: sub get_coursegroups {
1.809     raeburn  8164:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8165:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8166: }
                   8167: 
1.679     raeburn  8168: sub modify_coursegroup {
                   8169:     my ($cdom,$cnum,$groupsettings) = @_;
                   8170:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8171: }
                   8172: 
1.809     raeburn  8173: sub toggle_coursegroup_status {
                   8174:     my ($cdom,$cnum,$group,$action) = @_;
                   8175:     my ($from_namespace,$to_namespace);
                   8176:     if ($action eq 'delete') {
                   8177:         $from_namespace = 'coursegroups';
                   8178:         $to_namespace = 'deleted_groups';
                   8179:     } else {
                   8180:         $from_namespace = 'deleted_groups';
                   8181:         $to_namespace = 'coursegroups';
                   8182:     }
                   8183:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8184:     if (my $tmp = &error(%curr_group)) {
                   8185:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8186:         return ('read error',$tmp);
                   8187:     } else {
                   8188:         my %savedsettings = %curr_group; 
1.809     raeburn  8189:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8190:         my $deloutcome;
                   8191:         if ($result eq 'ok') {
1.809     raeburn  8192:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8193:         } else {
                   8194:             return ('write error',$result);
                   8195:         }
                   8196:         if ($deloutcome eq 'ok') {
                   8197:             return 'ok';
                   8198:         } else {
                   8199:             return ('delete error',$deloutcome);
                   8200:         }
                   8201:     }
                   8202: }
                   8203: 
1.679     raeburn  8204: sub modify_group_roles {
1.957     raeburn  8205:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8206:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8207:     my $role = 'gr/'.&escape($userprivs);
                   8208:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8209:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8210:     if ($result eq 'ok') {
                   8211:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8212:     }
1.679     raeburn  8213:     return $result;
                   8214: }
                   8215: 
                   8216: sub modify_coursegroup_membership {
                   8217:     my ($cdom,$cnum,$membership) = @_;
                   8218:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8219:     return $result;
                   8220: }
                   8221: 
1.682     raeburn  8222: sub get_active_groups {
                   8223:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8224:     my $now = time;
                   8225:     my %groups = ();
                   8226:     foreach my $key (keys(%env)) {
1.811     albertel 8227:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8228:             my ($start,$end) = split(/\./,$env{$key});
                   8229:             if (($end!=0) && ($end<$now)) { next; }
                   8230:             if (($start!=0) && ($start>$now)) { next; }
                   8231:             if ($1 eq $cdom && $2 eq $cnum) {
                   8232:                 $groups{$3} = $env{$key} ;
                   8233:             }
                   8234:         }
                   8235:     }
                   8236:     return %groups;
                   8237: }
                   8238: 
1.683     raeburn  8239: sub get_group_membership {
                   8240:     my ($cdom,$cnum,$group) = @_;
                   8241:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8242: }
                   8243: 
                   8244: sub get_users_groups {
                   8245:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8246:     my @usersgroups;
1.683     raeburn  8247:     my $cachetime=1800;
                   8248: 
                   8249:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8250:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8251:     if (defined($cached)) {
1.734     albertel 8252:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8253:     } else {  
                   8254:         $grouplist = '';
1.816     raeburn  8255:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8256:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8257:         my $access_end = $env{'course.'.$courseid.
                   8258:                               '.default_enrollment_end_date'};
                   8259:         my $now = time;
                   8260:         foreach my $key (keys(%roleshash)) {
                   8261:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8262:                 my $group = $1;
                   8263:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8264:                     my $start = $2;
                   8265:                     my $end = $1;
                   8266:                     if ($start == -1) { next; } # deleted from group
                   8267:                     if (($start!=0) && ($start>$now)) { next; }
                   8268:                     if (($end!=0) && ($end<$now)) {
                   8269:                         if ($access_end && $access_end < $now) {
                   8270:                             if ($access_end - $end < 86400) {
                   8271:                                 push(@usersgroups,$group);
1.733     raeburn  8272:                             }
                   8273:                         }
1.817     raeburn  8274:                         next;
1.733     raeburn  8275:                     }
1.817     raeburn  8276:                     push(@usersgroups,$group);
1.683     raeburn  8277:                 }
                   8278:             }
                   8279:         }
1.817     raeburn  8280:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8281:         $grouplist = join(':',@usersgroups);
                   8282:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8283:     }
1.733     raeburn  8284:     return @usersgroups;
1.683     raeburn  8285: }
                   8286: 
                   8287: sub devalidate_getgroups_cache {
                   8288:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8289:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8290: 
1.683     raeburn  8291:     my $hashid="$udom:$uname:$courseid";
                   8292:     &devalidate_cache_new('getgroups',$hashid);
                   8293: }
                   8294: 
1.12      www      8295: # ------------------------------------------------------------------ Plain Text
                   8296: 
                   8297: sub plaintext {
1.988     raeburn  8298:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8299:     if ($short =~ m{^cr/}) {
1.758     albertel 8300: 	return (split('/',$short))[-1];
                   8301:     }
1.742     raeburn  8302:     if (!defined($cid)) {
                   8303:         $cid = $env{'request.course.id'};
                   8304:     }
                   8305:     my %rolenames = (
1.1008    raeburn  8306:                       Course    => 'std',
                   8307:                       Community => 'alt1',
1.742     raeburn  8308:                     );
1.1037    raeburn  8309:     if ($cid ne '') {
                   8310:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8311:             unless ($forcedefault) {
                   8312:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8313:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8314:                 return &Apache::lonlocal::mt($roletext);
                   8315:             }
                   8316:         }
                   8317:     }
                   8318:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8319:         (defined($rolenames{$type})) && 
                   8320:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8321:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8322:     } elsif ($cid ne '') {
                   8323:         my $crstype = $env{'course.'.$cid.'.type'};
                   8324:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8325:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8326:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8327:         }
1.742     raeburn  8328:     }
1.1037    raeburn  8329:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8330: }
                   8331: 
                   8332: # ----------------------------------------------------------------- Assign Role
                   8333: 
                   8334: sub assignrole {
1.957     raeburn  8335:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8336:         $context)=@_;
1.21      www      8337:     my $mrole;
                   8338:     if ($role =~ /^cr\//) {
1.393     www      8339:         my $cwosec=$url;
1.811     albertel 8340:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8341: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8342:            my $refused = 1;
                   8343:            if ($context eq 'requestcourses') {
                   8344:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8345:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8346:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8347:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8348:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8349:                            if ($crsenv{'internal.courseowner'} eq
                   8350:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8351:                                $refused = '';
                   8352:                            }
                   8353:                        }
                   8354:                    }
                   8355:                }
                   8356:            }
                   8357:            if ($refused) {
                   8358:                &logthis('Refused custom assignrole: '.
                   8359:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8360:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8361:                return 'refused';
                   8362:            }
1.104     www      8363:         }
1.21      www      8364:         $mrole='cr';
1.678     raeburn  8365:     } elsif ($role =~ /^gr\//) {
                   8366:         my $cwogrp=$url;
1.811     albertel 8367:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8368:         unless (&allowed('mdg',$cwogrp)) {
                   8369:             &logthis('Refused group assignrole: '.
                   8370:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8371:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8372:             return 'refused';
                   8373:         }
                   8374:         $mrole='gr';
1.21      www      8375:     } else {
1.82      www      8376:         my $cwosec=$url;
1.811     albertel 8377:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8378:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8379:             my $refused;
                   8380:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8381:                 if (!(&allowed('c'.$role,$url))) {
                   8382:                     $refused = 1;
                   8383:                 }
                   8384:             } else {
                   8385:                 $refused = 1;
                   8386:             }
1.947     raeburn  8387:             if ($refused) {
1.1045    raeburn  8388:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8389:                 if (!$selfenroll && $context eq 'course') {
                   8390:                     my %crsenv;
                   8391:                     if ($role eq 'cc' || $role eq 'co') {
                   8392:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8393:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8394:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8395:                                 if ($crsenv{'internal.courseowner'} eq 
                   8396:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8397:                                     $refused = '';
                   8398:                                 }
                   8399:                             }
                   8400:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8401:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8402:                                 if ($crsenv{'internal.courseowner'} eq 
                   8403:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8404:                                     $refused = '';
                   8405:                                 }
                   8406:                             }
                   8407:                         }
                   8408:                     }
                   8409:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8410:                     $refused = '';
1.1017    raeburn  8411:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8412:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8413:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8414:                         my $wrongcc;
                   8415:                         if ($cnum =~ /^$match_community$/) {
                   8416:                             $wrongcc = 1 if ($role eq 'cc');
                   8417:                         } else {
                   8418:                             $wrongcc = 1 if ($role eq 'co');
                   8419:                         }
                   8420:                         unless ($wrongcc) {
                   8421:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8422:                             if ($crsenv{'internal.courseowner'} eq 
                   8423:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8424:                                 $refused = '';
                   8425:                             }
1.1017    raeburn  8426:                         }
                   8427:                     }
1.1172.2.9  raeburn  8428:                 } elsif ($context eq 'requestauthor') {
                   8429:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8430:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8431:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8432:                             $refused = '';
                   8433:                         } else {
                   8434:                             my %domdefaults = &get_domain_defaults($udom);
                   8435:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8436:                                 my $checkbystatus;
                   8437:                                 if ($env{'user.adv'}) {
                   8438:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8439:                                     if ($disposition eq 'automatic') {
                   8440:                                         $refused = '';
                   8441:                                     } elsif ($disposition eq '') {
                   8442:                                         $checkbystatus = 1;
                   8443:                                     }
                   8444:                                 } else {
                   8445:                                     $checkbystatus = 1;
                   8446:                                 }
                   8447:                                 if ($checkbystatus) {
                   8448:                                     if ($env{'environment.inststatus'}) {
                   8449:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8450:                                         foreach my $type (@inststatuses) {
                   8451:                                             if (($type ne '') &&
                   8452:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8453:                                                 $refused = '';
                   8454:                                             }
                   8455:                                         }
                   8456:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8457:                                         $refused = '';
                   8458:                                     }
                   8459:                                 }
                   8460:                             }
                   8461:                         }
                   8462:                     }
1.1017    raeburn  8463:                 }
                   8464:                 if ($refused) {
1.947     raeburn  8465:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8466:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8467: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8468:                     return 'refused';
                   8469:                 }
1.932     raeburn  8470:             }
1.1131    raeburn  8471:         } elsif ($role eq 'au') {
                   8472:             if ($url ne '/'.$udom.'/') {
                   8473:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8474:                          ' to assign author role for '.$uname.':'.$udom.
                   8475:                          ' in domain: '.$url.' refused (wrong domain).');
                   8476:                 return 'refused';
                   8477:             }
1.104     www      8478:         }
1.21      www      8479:         $mrole=$role;
                   8480:     }
1.620     albertel 8481:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8482:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8483:     if ($end) { $command.='_'.$end; }
1.21      www      8484:     if ($start) {
                   8485: 	if ($end) { 
1.81      www      8486:            $command.='_'.$start; 
1.21      www      8487:         } else {
1.81      www      8488:            $command.='_0_'.$start;
1.21      www      8489:         }
                   8490:     }
1.739     raeburn  8491:     my $origstart = $start;
                   8492:     my $origend = $end;
1.957     raeburn  8493:     my $delflag;
1.357     www      8494: # actually delete
                   8495:     if ($deleteflag) {
1.373     www      8496: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8497: # modify command to delete the role
1.620     albertel 8498:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8499:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8500: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8501: # set start and finish to negative values for userrolelog
                   8502:            $start=-1;
                   8503:            $end=-1;
1.957     raeburn  8504:            $delflag = 1;
1.357     www      8505:         }
                   8506:     }
                   8507: # send command
1.349     www      8508:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8509: # log new user role if status is ok
1.349     www      8510:     if ($answer eq 'ok') {
1.663     raeburn  8511: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8512:         if (($role eq 'cc') || ($role eq 'in') ||
                   8513:             ($role eq 'ep') || ($role eq 'ad') ||
                   8514:             ($role eq 'ta') || ($role eq 'st') ||
                   8515:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8516:             ($role eq 'co')) {
1.1172.2.13  raeburn  8517: # for course roles, perform group memberships changes triggered by role change.
                   8518:             unless ($role =~ /^gr/) {
                   8519:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8520:                                                  $origstart,$selfenroll,$context);
                   8521:             }
1.1172.2.9  raeburn  8522:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8523:                            $selfenroll,$context);
                   8524:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8525:                  ($role eq 'au') || ($role eq 'dc')) {
                   8526:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8527:                            $context);
                   8528:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8529:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8530:                              $context);
                   8531:         }
1.1053    raeburn  8532:         if ($role eq 'cc') {
                   8533:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8534:         }
1.349     www      8535:     }
                   8536:     return $answer;
1.169     harris41 8537: }
                   8538: 
1.1053    raeburn  8539: sub autoupdate_coowners {
                   8540:     my ($url,$end,$start,$uname,$udom) = @_;
                   8541:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8542:     if (($cdom ne '') && ($cnum ne '')) {
                   8543:         my $now = time;
                   8544:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8545:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8546:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8547:             my $instcode = $coursehash{'internal.coursecode'};
                   8548:             if ($instcode ne '') {
1.1056    raeburn  8549:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8550:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8551:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8552:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8553:                         if ($result eq 'valid') {
                   8554:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8555:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8556:                                     push(@newcoowners,$coowner);
                   8557:                                 }
                   8558:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8559:                                     push(@newcoowners,$uname.':'.$udom);
                   8560:                                 }
                   8561:                                 @newcoowners = sort(@newcoowners);
                   8562:                             } else {
                   8563:                                 push(@newcoowners,$uname.':'.$udom);
                   8564:                             }
                   8565:                         } else {
                   8566:                             if ($coursehash{'internal.co-owners'}) {
                   8567:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8568:                                     unless ($coowner eq $uname.':'.$udom) {
                   8569:                                         push(@newcoowners,$coowner);
                   8570:                                     }
                   8571:                                 }
                   8572:                                 unless (@newcoowners > 0) {
                   8573:                                     $delcoowners = 1;
                   8574:                                     $coowners = '';
                   8575:                                 }
                   8576:                             }
                   8577:                         }
                   8578:                         if (@newcoowners || $delcoowners) {
                   8579:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8580:                                             $delcoowners,@newcoowners);
                   8581:                         }
                   8582:                     }
                   8583:                 }
                   8584:             }
                   8585:         }
                   8586:     }
                   8587: }
                   8588: 
                   8589: sub store_coowners {
                   8590:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8591:     my $cid = $cdom.'_'.$cnum;
                   8592:     my ($coowners,$delresult,$putresult);
                   8593:     if (@newcoowners) {
                   8594:         $coowners = join(',',@newcoowners);
                   8595:         my %coownershash = (
                   8596:                             'internal.co-owners' => $coowners,
                   8597:                            );
                   8598:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8599:         if ($putresult eq 'ok') {
                   8600:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8601:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8602:             }
                   8603:         }
                   8604:     }
                   8605:     if ($delcoowners) {
                   8606:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8607:         if ($delresult eq 'ok') {
                   8608:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8609:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8610:             }
                   8611:         }
                   8612:     }
                   8613:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8614:         my %crsinfo =
                   8615:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8616:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8617:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8618:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8619:         }
                   8620:     }
                   8621: }
                   8622: 
1.169     harris41 8623: # -------------------------------------------------- Modify user authentication
1.197     www      8624: # Overrides without validation
                   8625: 
1.169     harris41 8626: sub modifyuserauth {
                   8627:     my ($udom,$uname,$umode,$upass)=@_;
                   8628:     my $uhome=&homeserver($uname,$udom);
1.197     www      8629:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8630:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8631:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8632:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8633:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8634: 		     &escape($upass),$uhome);
1.620     albertel 8635:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8636:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8637:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8638:     &log($udom,,$uname,$uhome,
1.620     albertel 8639:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8640:                                      $env{'user.name'}.', '.$umode.
1.197     www      8641:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8642:     unless ($reply eq 'ok') {
1.197     www      8643:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8644: 	return 'error: '.$reply;
                   8645:     }   
1.170     harris41 8646:     return 'ok';
1.80      www      8647: }
                   8648: 
1.81      www      8649: # --------------------------------------------------------------- Modify a user
1.80      www      8650: 
1.81      www      8651: sub modifyuser {
1.206     matthew  8652:     my ($udom,    $uname, $uid,
                   8653:         $umode,   $upass, $first,
                   8654:         $middle,  $last,  $gene,
1.1058    raeburn  8655:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8656:     $udom= &LONCAPA::clean_domain($udom);
                   8657:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8658:     my $showcandelete = 'none';
                   8659:     if (ref($candelete) eq 'ARRAY') {
                   8660:         if (@{$candelete} > 0) {
                   8661:             $showcandelete = join(', ',@{$candelete});
                   8662:         }
                   8663:     }
1.81      www      8664:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8665:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8666: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8667:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8668:                                      ' desiredhome not specified'). 
1.620     albertel 8669:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8670:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8671:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8672:     my $newuser;
                   8673:     if ($uhome eq 'no_host') {
                   8674:         $newuser = 1;
                   8675:     }
1.80      www      8676: # ----------------------------------------------------------------- Create User
1.406     albertel 8677:     if (($uhome eq 'no_host') && 
                   8678: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8679:         my $unhome='';
1.844     albertel 8680:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8681:             $unhome = $desiredhome;
1.620     albertel 8682: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8683: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8684:         } else { # load balancing routine for determining $unhome
1.81      www      8685:             my $loadm=10000000;
1.841     albertel 8686: 	    my %servers = &get_servers($udom,'library');
                   8687: 	    foreach my $tryserver (keys(%servers)) {
                   8688: 		my $answer=reply('load',$tryserver);
                   8689: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8690: 		    $loadm=$answer;
                   8691: 		    $unhome=$tryserver;
                   8692: 		}
1.80      www      8693: 	    }
                   8694:         }
                   8695:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8696: 	    return 'error: unable to find a home server for '.$uname.
                   8697:                    ' in domain '.$udom;
1.80      www      8698:         }
                   8699:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8700:                          &escape($upass),$unhome);
                   8701: 	unless ($reply eq 'ok') {
                   8702:             return 'error: '.$reply;
                   8703:         }   
1.230     stredwic 8704:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8705:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8706: 	    return 'error: unable verify users home machine.';
1.80      www      8707:         }
1.209     matthew  8708:     }   # End of creation of new user
1.80      www      8709: # ---------------------------------------------------------------------- Add ID
                   8710:     if ($uid) {
                   8711:        $uid=~tr/A-Z/a-z/;
                   8712:        my %uidhash=&idrget($udom,$uname);
1.196     www      8713:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8714:          && (!$forceid)) {
1.80      www      8715: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8716: 	      return 'error: user id "'.$uid.'" does not match '.
                   8717:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8718:           }
                   8719:        } else {
                   8720: 	  &idput($udom,($uname => $uid));
                   8721:        }
                   8722:     }
                   8723: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8724:     my @tmp=&get('environment',
1.899     raeburn  8725: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8726:                     'permanentemail','inststatus'],
1.134     albertel 8727: 		   $udom,$uname);
1.1075    raeburn  8728:     my (%names,%oldnames);
1.313     matthew  8729:     if ($tmp[0] =~ m/^error:.*/) { 
                   8730:         %names=(); 
                   8731:     } else {
                   8732:         %names = @tmp;
1.1075    raeburn  8733:         %oldnames = %names;
1.313     matthew  8734:     }
1.388     www      8735: #
1.1058    raeburn  8736: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8737: # of users did not contain them), do not overwrite existing values
                   8738: # unless field is in $candelete array ref.  
                   8739: #
                   8740: 
                   8741:     my @fields = ('firstname','middlename','lastname','generation',
                   8742:                   'permanentemail','id');
                   8743:     my %newvalues;
                   8744:     if (ref($candelete) eq 'ARRAY') {
                   8745:         foreach my $field (@fields) {
                   8746:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8747:                 if ($field eq 'firstname') {
                   8748:                     $names{$field} = $first;
                   8749:                 } elsif ($field eq 'middlename') {
                   8750:                     $names{$field} = $middle;
                   8751:                 } elsif ($field eq 'lastname') {
                   8752:                     $names{$field} = $last;
                   8753:                 } elsif ($field eq 'generation') { 
                   8754:                     $names{$field} = $gene;
                   8755:                 } elsif ($field eq 'permanentemail') {
                   8756:                     $names{$field} = $email;
                   8757:                 } elsif ($field eq 'id') {
                   8758:                     $names{$field}  = $uid;
                   8759:                 }
                   8760:             }
                   8761:         }
                   8762:     }
1.388     www      8763:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8764:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8765:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8766:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8767:     if ($email) {
                   8768:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8769:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8770:     }
1.899     raeburn  8771:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8772:     if (defined($inststatus)) {
                   8773:         $names{'inststatus'} = '';
                   8774:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8775:         if (ref($usertypes) eq 'HASH') {
                   8776:             my @okstatuses; 
                   8777:             foreach my $item (split(/:/,$inststatus)) {
                   8778:                 if (defined($usertypes->{$item})) {
                   8779:                     push(@okstatuses,$item);  
                   8780:                 }
                   8781:             }
                   8782:             if (@okstatuses) {
                   8783:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8784:             }
                   8785:         }
                   8786:     }
1.1075    raeburn  8787:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8788:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8789:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8790:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8791:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8792:     } else {
                   8793:         $logmsg .= ' during self creation';
                   8794:     }
1.1075    raeburn  8795:     my $changed;
                   8796:     if ($newuser) {
                   8797:         $changed = 1;
                   8798:     } else {
                   8799:         foreach my $field (@fields) {
                   8800:             if ($names{$field} ne $oldnames{$field}) {
                   8801:                 $changed = 1;
                   8802:                 last;
                   8803:             }
                   8804:         }
                   8805:     }
                   8806:     unless ($changed) {
                   8807:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8808:         &logthis($logmsg);
                   8809:         return 'ok';
                   8810:     }
                   8811:     my $reply = &put('environment', \%names, $udom,$uname);
                   8812:     if ($reply ne 'ok') { 
                   8813:         return 'error: '.$reply;
                   8814:     }
1.1087    raeburn  8815:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8816:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8817:     }
1.1075    raeburn  8818:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8819:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8820:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8821:     &logthis($logmsg);
1.134     albertel 8822:     return 'ok';
1.80      www      8823: }
                   8824: 
1.81      www      8825: # -------------------------------------------------------------- Modify student
1.80      www      8826: 
1.81      www      8827: sub modifystudent {
                   8828:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8829:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8830:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8831:     if (!$cid) {
1.620     albertel 8832: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8833: 	    return 'not_in_class';
                   8834: 	}
1.80      www      8835:     }
                   8836: # --------------------------------------------------------------- Make the user
1.81      www      8837:     my $reply=&modifyuser
1.209     matthew  8838: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8839:          $desiredhome,$email,$inststatus);
1.80      www      8840:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8841:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  8842:     # student's environment
1.297     matthew  8843:     $uid = undef if (!$forceid);
1.455     albertel 8844:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8845: 					$gene,$usec,$end,$start,$type,$locktype,
                   8846:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8847:     return $reply;
                   8848: }
                   8849: 
                   8850: sub modify_student_enrollment {
1.1172.2.23  raeburn  8851:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8852:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8853:     my ($cdom,$cnum,$chome);
                   8854:     if (!$cid) {
1.620     albertel 8855: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8856: 	    return 'not_in_class';
                   8857: 	}
1.620     albertel 8858: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8859: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8860:     } else {
                   8861: 	($cdom,$cnum)=split(/_/,$cid);
                   8862:     }
1.620     albertel 8863:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8864:     if (!$chome) {
1.457     raeburn  8865: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8866:     }
1.455     albertel 8867:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8868:     # Make sure the user exists
1.81      www      8869:     my $uhome=&homeserver($uname,$udom);
                   8870:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8871: 	return 'error: no such user';
                   8872:     }
1.297     matthew  8873:     # Get student data if we were not given enough information
                   8874:     if (!defined($first)  || $first  eq '' || 
                   8875:         !defined($last)   || $last   eq '' || 
                   8876:         !defined($uid)    || $uid    eq '' || 
                   8877:         !defined($middle) || $middle eq '' || 
                   8878:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8879:         # They did not supply us with enough data to enroll the student, so
                   8880:         # we need to pick up more information.
1.297     matthew  8881:         my %tmp = &get('environment',
1.294     matthew  8882:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8883:                        ,$udom,$uname);
                   8884: 
1.800     albertel 8885:         #foreach my $key (keys(%tmp)) {
                   8886:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8887:         #}
1.294     matthew  8888:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8889:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8890:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8891:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8892:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8893:     }
1.556     albertel 8894:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8895:     my $user = "$uname:$udom";
                   8896:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8897:     my $reply=cput('classlist',
1.1148    raeburn  8898: 		   {$user => 
1.1172.2.19  raeburn  8899: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8900: 		   $cdom,$cnum);
1.1148    raeburn  8901:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8902:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8903:     } else { 
1.81      www      8904: 	return 'error: '.$reply;
                   8905:     }
1.297     matthew  8906:     # Add student role to user
1.83      www      8907:     my $uurl='/'.$cid;
1.81      www      8908:     $uurl=~s/\_/\//g;
                   8909:     if ($usec) {
                   8910: 	$uurl.='/'.$usec;
                   8911:     }
1.1148    raeburn  8912:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8913:                              $selfenroll,$context);
                   8914:     if ($result ne 'ok') {
                   8915:         if ($old_entry{$user} ne '') {
                   8916:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8917:         } else {
                   8918:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8919:         }
                   8920:     }
                   8921:     return $result; 
1.21      www      8922: }
                   8923: 
1.556     albertel 8924: sub format_name {
                   8925:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8926:     my $name;
                   8927:     if ($first ne 'lastname') {
                   8928: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8929:     } else {
                   8930: 	if ($lastname=~/\S/) {
                   8931: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8932: 	    $name=~s/\s+,/,/;
                   8933: 	} else {
                   8934: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8935: 	}
                   8936:     }
                   8937:     $name=~s/^\s+//;
                   8938:     $name=~s/\s+$//;
                   8939:     $name=~s/\s+/ /g;
                   8940:     return $name;
                   8941: }
                   8942: 
1.84      www      8943: # ------------------------------------------------- Write to course preferences
                   8944: 
                   8945: sub writecoursepref {
                   8946:     my ($courseid,%prefs)=@_;
                   8947:     $courseid=~s/^\///;
                   8948:     $courseid=~s/\_/\//g;
                   8949:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8950:     my $chome=homeserver($cnum,$cdomain);
                   8951:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8952: 	return 'error: no such course';
                   8953:     }
                   8954:     my $cstring='';
1.800     albertel 8955:     foreach my $pref (keys(%prefs)) {
                   8956: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8957:     }
1.84      www      8958:     $cstring=~s/\&$//;
                   8959:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8960: }
                   8961: 
                   8962: # ---------------------------------------------------------- Make/modify course
                   8963: 
                   8964: sub createcourse {
1.741     raeburn  8965:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8966:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8967:     $url=&declutter($url);
                   8968:     my $cid='';
1.1028    raeburn  8969:     if ($context eq 'requestcourses') {
                   8970:         my $can_create = 0;
                   8971:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8972:         if ($udom eq $ownerdom) {
                   8973:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8974:                                   $context)) {
                   8975:                 $can_create = 1;
                   8976:             }
                   8977:         } else {
                   8978:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8979:                                            $category);
                   8980:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8981:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8982:                 if (@curr > 0) {
                   8983:                     my @options = qw(approval validate autolimit);
                   8984:                     my $optregex = join('|',@options);
                   8985:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8986:                         $can_create = 1;
                   8987:                     }
                   8988:                 }
                   8989:             }
                   8990:         }
                   8991:         if ($can_create) {
                   8992:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8993:                 unless (&allowed('ccc',$udom)) {
                   8994:                     return 'refused'; 
                   8995:                 }
1.1017    raeburn  8996:             }
                   8997:         } else {
                   8998:             return 'refused';
                   8999:         }
1.1028    raeburn  9000:     } elsif (!&allowed('ccc',$udom)) {
                   9001:         return 'refused';
1.84      www      9002:     }
1.1011    raeburn  9003: # --------------------------------------------------------------- Get Unique ID
                   9004:     my $uname;
                   9005:     if ($cnum =~ /^$match_courseid$/) {
                   9006:         my $chome=&homeserver($cnum,$udom,'true');
                   9007:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9008:             $uname = $cnum;
                   9009:         } else {
1.1038    raeburn  9010:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9011:         }
                   9012:     } else {
1.1038    raeburn  9013:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9014:     }
                   9015:     return $uname if ($uname =~ /^error/);
                   9016: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9017:     if (!defined($course_server)) {
                   9018:         if (defined(&domain($udom,'primary'))) {
                   9019:             $course_server = &domain($udom,'primary');
                   9020:         } else {
                   9021:             $course_server = $env{'user.home'}; 
                   9022:         }
                   9023:     }
                   9024:     my %host_servers =
                   9025:         &Apache::lonnet::get_servers($udom,'library');
                   9026:     unless ($host_servers{$course_server}) {
                   9027:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9028:     }
1.84      www      9029: # ------------------------------------------------------------- Make the course
                   9030:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9031:                       $course_server);
1.84      www      9032:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9033:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9034:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9035: 	return 'error: no such course';
                   9036:     }
1.271     www      9037: # ----------------------------------------------------------------- Course made
1.516     raeburn  9038: # log existence
1.1029    raeburn  9039:     my $now = time;
1.918     raeburn  9040:     my $newcourse = {
                   9041:                     $udom.'_'.$uname => {
1.921     raeburn  9042:                                      description => $description,
                   9043:                                      inst_code   => $inst_code,
                   9044:                                      owner       => $course_owner,
                   9045:                                      type        => $crstype,
1.1029    raeburn  9046:                                      creator     => $env{'user.name'}.':'.
                   9047:                                                     $env{'user.domain'},
                   9048:                                      created     => $now,
                   9049:                                      context     => $context,
1.918     raeburn  9050:                                                 },
                   9051:                     };
1.921     raeburn  9052:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9053: # set toplevel url
1.271     www      9054:     my $topurl=$url;
                   9055:     unless ($nonstandard) {
                   9056: # ------------------------------------------ For standard courses, make top url
                   9057:         my $mapurl=&clutter($url);
1.278     www      9058:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9059:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9060: <map>
                   9061: <resource id="1" type="start"></resource>
                   9062: <resource id="2" src="$mapurl"></resource>
                   9063: <resource id="3" type="finish"></resource>
                   9064: <link index="1" from="1" to="2"></link>
                   9065: <link index="2" from="2" to="3"></link>
                   9066: </map>
                   9067: ENDINITMAP
                   9068:         $topurl=&declutter(
1.638     albertel 9069:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9070:                           );
                   9071:     }
                   9072: # ----------------------------------------------------------- Write preferences
1.84      www      9073:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9074:                      ('description'              => $description,
                   9075:                       'url'                      => $topurl,
                   9076:                       'internal.creator'         => $env{'user.name'}.':'.
                   9077:                                                     $env{'user.domain'},
                   9078:                       'internal.created'         => $now,
                   9079:                       'internal.creationcontext' => $context)
                   9080:                     );
1.84      www      9081:     return '/'.$udom.'/'.$uname;
                   9082: }
                   9083: 
1.1011    raeburn  9084: # ------------------------------------------------------------------- Create ID
                   9085: sub generate_coursenum {
1.1038    raeburn  9086:     my ($udom,$crstype) = @_;
1.1011    raeburn  9087:     my $domdesc = &domain($udom);
                   9088:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9089:     my $first;
                   9090:     if ($crstype eq 'Community') {
                   9091:         $first = '0';
                   9092:     } else {
                   9093:         $first = int(1+rand(9)); 
                   9094:     } 
                   9095:     my $uname=$first.
1.1011    raeburn  9096:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9097:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9098:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9099: # ----------------------------------------------- Make sure that does not exist
                   9100:     my $uhome=&homeserver($uname,$udom,'true');
                   9101:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9102:         if ($crstype eq 'Community') {
                   9103:             $first = '0';
                   9104:         } else {
                   9105:             $first = int(1+rand(9));
                   9106:         }
                   9107:         $uname=$first.
1.1011    raeburn  9108:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9109:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9110:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9111:         $uhome=&homeserver($uname,$udom,'true');
                   9112:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9113:             return 'error: unable to generate unique course-ID';
                   9114:         }
                   9115:     }
                   9116:     return $uname;
                   9117: }
                   9118: 
1.813     albertel 9119: sub is_course {
1.1167    droeschl 9120:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9121:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9122: 
                   9123:     return unless $cdom and $cnum;
                   9124: 
                   9125:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9126:         '.');
                   9127: 
1.1172.2.23  raeburn  9128:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9129:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9130: }
                   9131: 
1.1015    raeburn  9132: sub store_userdata {
                   9133:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9134:     my $result;
1.1016    raeburn  9135:     if ($datakey ne '') {
1.1013    raeburn  9136:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9137:             if ($udom eq '' || $uname eq '') {
                   9138:                 $udom = $env{'user.domain'};
                   9139:                 $uname = $env{'user.name'};
                   9140:             }
                   9141:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9142:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9143:                 $result = 'error: no_host';
                   9144:             } else {
                   9145:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9146:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9147: 
                   9148:                 my $namevalue='';
                   9149:                 foreach my $key (keys(%{$storehash})) {
                   9150:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9151:                 }
                   9152:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9153:                 unless ($namespace eq 'courserequests') {
                   9154:                     $datakey = &escape($datakey);
                   9155:                 }
1.1105    raeburn  9156:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9157:                                   $namevalue,$uhome);
1.1013    raeburn  9158:             }
                   9159:         } else {
                   9160:             $result = 'error: data to store was not a hash reference'; 
                   9161:         }
                   9162:     } else {
                   9163:         $result= 'error: invalid requestkey'; 
                   9164:     }
                   9165:     return $result;
                   9166: }
                   9167: 
1.21      www      9168: # ---------------------------------------------------------- Assign Custom Role
                   9169: 
                   9170: sub assigncustomrole {
1.957     raeburn  9171:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9172:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9173:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9174: }
                   9175: 
                   9176: # ----------------------------------------------------------------- Revoke Role
                   9177: 
                   9178: sub revokerole {
1.957     raeburn  9179:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9180:     my $now=time;
1.965     raeburn  9181:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9182: }
                   9183: 
                   9184: # ---------------------------------------------------------- Revoke Custom Role
                   9185: 
                   9186: sub revokecustomrole {
1.957     raeburn  9187:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9188:     my $now=time;
1.357     www      9189:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9190:            $deleteflag,$selfenroll,$context);
1.17      www      9191: }
                   9192: 
1.533     banghart 9193: # ------------------------------------------------------------ Disk usage
1.535     albertel 9194: sub diskusage {
1.955     raeburn  9195:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9196:     $directorypath =~ s/\/$//;
                   9197:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9198:                        .&escape($getpropath).':'.&escape($uname).':'
                   9199:                        .&escape($udom),homeserver($uname,$udom));
                   9200:     if ($listing eq 'unknown_cmd') {
                   9201:         if ($getpropath) {
                   9202:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9203:         }
                   9204:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9205:     }
1.514     albertel 9206:     return $listing;
1.512     banghart 9207: }
                   9208: 
1.566     banghart 9209: sub is_locked {
1.1096    raeburn  9210:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9211:     my @check;
                   9212:     my $is_locked;
1.1093    raeburn  9213:     push (@check,$file_name);
1.613     albertel 9214:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9215: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9216:     my ($tmp)=keys(%locked);
                   9217:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9218:     
1.566     banghart 9219:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9220:         $is_locked = 'false';
                   9221:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9222:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9223:                $is_locked = 'true';
1.1096    raeburn  9224:                if (ref($which) eq 'ARRAY') {
                   9225:                    push(@{$which},$entry);
                   9226:                } else {
                   9227:                    last;
                   9228:                }
1.745     raeburn  9229:            }
                   9230:        }
1.566     banghart 9231:     } else {
                   9232:         $is_locked = 'false';
                   9233:     }
1.1093    raeburn  9234:     return $is_locked;
1.566     banghart 9235: }
                   9236: 
1.759     albertel 9237: sub declutter_portfile {
                   9238:     my ($file) = @_;
1.833     albertel 9239:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9240:     return $file;
                   9241: }
                   9242: 
1.559     banghart 9243: # ------------------------------------------------------------- Mark as Read Only
                   9244: 
                   9245: sub mark_as_readonly {
                   9246:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9247:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9248:     my ($tmp)=keys(%current_permissions);
                   9249:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9250:     foreach my $file (@{$files}) {
1.759     albertel 9251: 	$file = &declutter_portfile($file);
1.561     banghart 9252:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9253:     }
1.613     albertel 9254:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9255:     return;
                   9256: }
                   9257: 
1.572     banghart 9258: # ------------------------------------------------------------Save Selected Files
                   9259: 
                   9260: sub save_selected_files {
                   9261:     my ($user, $path, @files) = @_;
                   9262:     my $filename = $user."savedfiles";
1.573     banghart 9263:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9264:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9265:     foreach my $file (@files) {
1.620     albertel 9266:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9267:     }
                   9268:     foreach my $file (@other_files) {
1.574     banghart 9269:         print (OUT $file."\n");
1.572     banghart 9270:     }
1.574     banghart 9271:     close (OUT);
1.572     banghart 9272:     return 'ok';
                   9273: }
                   9274: 
1.574     banghart 9275: sub clear_selected_files {
                   9276:     my ($user) = @_;
                   9277:     my $filename = $user."savedfiles";
1.1117    foxr     9278:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9279:     print (OUT undef);
                   9280:     close (OUT);
                   9281:     return ("ok");    
                   9282: }
                   9283: 
1.572     banghart 9284: sub files_in_path {
                   9285:     my ($user, $path) = @_;
                   9286:     my $filename = $user."savedfiles";
                   9287:     my %return_files;
1.1117    foxr     9288:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9289:     while (my $line_in = <IN>) {
1.574     banghart 9290:         chomp ($line_in);
                   9291:         my @paths_and_file = split (m!/!, $line_in);
                   9292:         my $file_part = pop (@paths_and_file);
                   9293:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9294:         $path_part.='/';
                   9295:         my $path_and_file = $path_part.$file_part;
                   9296:         if ($path_part eq $path) {
                   9297:             $return_files{$file_part}= 'selected';
                   9298:         }
                   9299:     }
1.574     banghart 9300:     close (IN);
                   9301:     return (\%return_files);
1.572     banghart 9302: }
                   9303: 
                   9304: # called in portfolio select mode, to show files selected NOT in current directory
                   9305: sub files_not_in_path {
                   9306:     my ($user, $path) = @_;
                   9307:     my $filename = $user."savedfiles";
                   9308:     my @return_files;
                   9309:     my $path_part;
1.1117    foxr     9310:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9311:     while (my $line = <IN>) {
1.572     banghart 9312:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9313:         my @paths_and_file = split(m|/|, $line);
                   9314:         my $file_part = pop(@paths_and_file);
                   9315:         chomp($file_part);
                   9316:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9317:         $path_part .= '/';
                   9318:         my $path_and_file = $path_part.$file_part;
                   9319:         if ($path_part ne $path) {
1.800     albertel 9320:             push(@return_files, ($path_and_file));
1.572     banghart 9321:         }
                   9322:     }
1.800     albertel 9323:     close(OUT);
1.574     banghart 9324:     return (@return_files);
1.572     banghart 9325: }
                   9326: 
1.745     raeburn  9327: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9328: 
1.745     raeburn  9329: sub get_portfile_permissions {
                   9330:     my ($domain,$user) = @_;
1.613     albertel 9331:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9332:     my ($tmp)=keys(%current_permissions);
                   9333:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9334:     return \%current_permissions;
                   9335: }
                   9336: 
                   9337: #---------------------------------------------Get portfolio file access controls
                   9338: 
1.749     raeburn  9339: sub get_access_controls {
1.745     raeburn  9340:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9341:     my %access;
                   9342:     my $real_file = $file;
                   9343:     $file =~ s/\.meta$//;
1.745     raeburn  9344:     if (defined($file)) {
1.749     raeburn  9345:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9346:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9347:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9348:             }
                   9349:         }
1.745     raeburn  9350:     } else {
1.749     raeburn  9351:         foreach my $key (keys(%{$current_permissions})) {
                   9352:             if ($key =~ /\0accesscontrol$/) {
                   9353:                 if (defined($group)) {
                   9354:                     if ($key !~ m-^\Q$group\E/-) {
                   9355:                         next;
                   9356:                     }
                   9357:                 }
                   9358:                 my ($fullpath) = split(/\0/,$key);
                   9359:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9360:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9361:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9362:                     }
                   9363:                 }
                   9364:             }
                   9365:         }
                   9366:     }
                   9367:     return %access;
                   9368: }
                   9369: 
                   9370: sub modify_access_controls {
                   9371:     my ($file_name,$changes,$domain,$user)=@_;
                   9372:     my ($outcome,$deloutcome);
                   9373:     my %store_permissions;
                   9374:     my %new_values;
                   9375:     my %new_control;
                   9376:     my %translation;
                   9377:     my @deletions = ();
                   9378:     my $now = time;
                   9379:     if (exists($$changes{'activate'})) {
                   9380:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9381:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9382:             my $numnew = scalar(@newitems);
                   9383:             for (my $i=0; $i<$numnew; $i++) {
                   9384:                 my $newkey = $newitems[$i];
                   9385:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9386:                 if ($newkey =~ /^\d+:/) { 
                   9387:                     $newkey =~ s/^(\d+)/$newid/;
                   9388:                     $translation{$1} = $newid;
                   9389:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9390:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9391:                     $translation{$1} = $newid;
                   9392:                 }
1.749     raeburn  9393:                 $new_values{$file_name."\0".$newkey} = 
                   9394:                                           $$changes{'activate'}{$newitems[$i]};
                   9395:                 $new_control{$newkey} = $now;
                   9396:             }
                   9397:         }
                   9398:     }
                   9399:     my %todelete;
                   9400:     my %changed_items;
                   9401:     foreach my $action ('delete','update') {
                   9402:         if (exists($$changes{$action})) {
                   9403:             if (ref($$changes{$action}) eq 'HASH') {
                   9404:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9405:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9406:                     if ($action eq 'delete') { 
                   9407:                         $todelete{$itemnum} = 1;
                   9408:                     } else {
                   9409:                         $changed_items{$itemnum} = $key;
                   9410:                     }
                   9411:                 }
1.745     raeburn  9412:             }
                   9413:         }
1.749     raeburn  9414:     }
                   9415:     # get lock on access controls for file.
                   9416:     my $lockhash = {
                   9417:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9418:                                                        ':'.$env{'user.domain'},
                   9419:                    }; 
                   9420:     my $tries = 0;
                   9421:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9422:    
                   9423:     while (($gotlock ne 'ok') && $tries <3) {
                   9424:         $tries ++;
                   9425:         sleep 1;
                   9426:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9427:     }
                   9428:     if ($gotlock eq 'ok') {
                   9429:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9430:         my ($tmp)=keys(%curr_permissions);
                   9431:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9432:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9433:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9434:             if (ref($curr_controls) eq 'HASH') {
                   9435:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9436:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9437:                     if (defined($todelete{$itemnum})) {
                   9438:                         push(@deletions,$file_name."\0".$control_item);
                   9439:                     } else {
                   9440:                         if (defined($changed_items{$itemnum})) {
                   9441:                             $new_control{$changed_items{$itemnum}} = $now;
                   9442:                             push(@deletions,$file_name."\0".$control_item);
                   9443:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9444:                         } else {
                   9445:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9446:                         }
                   9447:                     }
1.745     raeburn  9448:                 }
                   9449:             }
                   9450:         }
1.970     raeburn  9451:         my ($group);
                   9452:         if (&is_course($domain,$user)) {
                   9453:             ($group,my $file) = split(/\//,$file_name,2);
                   9454:         }
1.749     raeburn  9455:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9456:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9457:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9458:         #  remove lock
                   9459:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9460:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9461:         my $sqlresult =
1.970     raeburn  9462:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9463:                                     $group);
1.749     raeburn  9464:     } else {
                   9465:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9466:     }
1.749     raeburn  9467:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9468: }
                   9469: 
1.827     raeburn  9470: sub make_public_indefinitely {
                   9471:     my ($requrl) = @_;
                   9472:     my $now = time;
                   9473:     my $action = 'activate';
                   9474:     my $aclnum = 0;
                   9475:     if (&is_portfolio_url($requrl)) {
                   9476:         my (undef,$udom,$unum,$file_name,$group) =
                   9477:             &parse_portfolio_url($requrl);
                   9478:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9479:         my %access_controls = &get_access_controls($current_perms,
                   9480:                                                    $group,$file_name);
                   9481:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9482:             my ($num,$scope,$end,$start) = 
                   9483:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9484:             if ($scope eq 'public') {
                   9485:                 if ($start <= $now && $end == 0) {
                   9486:                     $action = 'none';
                   9487:                 } else {
                   9488:                     $action = 'update';
                   9489:                     $aclnum = $num;
                   9490:                 }
                   9491:                 last;
                   9492:             }
                   9493:         }
                   9494:         if ($action eq 'none') {
                   9495:              return 'ok';
                   9496:         } else {
                   9497:             my %changes;
                   9498:             my $newend = 0;
                   9499:             my $newstart = $now;
                   9500:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9501:             $changes{$action}{$newkey} = {
                   9502:                 type => 'public',
                   9503:                 time => {
                   9504:                     start => $newstart,
                   9505:                     end   => $newend,
                   9506:                 },
                   9507:             };
                   9508:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9509:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9510:             return $outcome;
                   9511:         }
                   9512:     } else {
                   9513:         return 'invalid';
                   9514:     }
                   9515: }
                   9516: 
1.745     raeburn  9517: #------------------------------------------------------Get Marked as Read Only
                   9518: 
                   9519: sub get_marked_as_readonly {
                   9520:     my ($domain,$user,$what,$group) = @_;
                   9521:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9522:     my @readonly_files;
1.629     banghart 9523:     my $cmp1=$what;
                   9524:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9525:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9526:         if (defined($group)) {
                   9527:             if ($file_name !~ m-^\Q$group\E/-) {
                   9528:                 next;
                   9529:             }
                   9530:         }
1.561     banghart 9531:         if (ref($value) eq "ARRAY"){
                   9532:             foreach my $stored_what (@{$value}) {
1.629     banghart 9533:                 my $cmp2=$stored_what;
1.759     albertel 9534:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9535:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9536:                 }
1.629     banghart 9537:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9538:                     push(@readonly_files, $file_name);
1.745     raeburn  9539:                     last;
1.563     banghart 9540:                 } elsif (!defined($what)) {
                   9541:                     push(@readonly_files, $file_name);
1.745     raeburn  9542:                     last;
1.561     banghart 9543:                 }
                   9544:             }
1.745     raeburn  9545:         }
1.561     banghart 9546:     }
                   9547:     return @readonly_files;
                   9548: }
1.577     banghart 9549: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9550: 
1.577     banghart 9551: sub get_marked_as_readonly_hash {
1.745     raeburn  9552:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9553:     my %readonly_files;
1.745     raeburn  9554:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9555:         if (defined($group)) {
                   9556:             if ($file_name !~ m-^\Q$group\E/-) {
                   9557:                 next;
                   9558:             }
                   9559:         }
1.577     banghart 9560:         if (ref($value) eq "ARRAY"){
                   9561:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9562:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9563:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9564:                         if ($lock_descriptor eq 'graded') {
                   9565:                             $readonly_files{$file_name} = 'graded';
                   9566:                         } elsif ($lock_descriptor eq 'handback') {
                   9567:                             $readonly_files{$file_name} = 'handback';
                   9568:                         } else {
                   9569:                             if (!exists($readonly_files{$file_name})) {
                   9570:                                 $readonly_files{$file_name} = 'locked';
                   9571:                             }
                   9572:                         }
1.745     raeburn  9573:                     }
1.750     banghart 9574:                 } 
1.577     banghart 9575:             }
                   9576:         } 
                   9577:     }
                   9578:     return %readonly_files;
                   9579: }
1.559     banghart 9580: # ------------------------------------------------------------ Unmark as Read Only
                   9581: 
                   9582: sub unmark_as_readonly {
1.629     banghart 9583:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9584:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9585:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9586:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9587:     my $symb_crs = $what;
                   9588:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9589:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9590:     my ($tmp)=keys(%current_permissions);
                   9591:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9592:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9593:     foreach my $file (@readonly_files) {
1.759     albertel 9594: 	my $clean_file = &declutter_portfile($file);
                   9595: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9596: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9597:         my @new_locks;
                   9598:         my @del_keys;
                   9599:         if (ref($current_locks) eq "ARRAY"){
                   9600:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9601:                 my $compare=$locker;
1.749     raeburn  9602:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9603:                     $compare=join('',@{$locker});
1.746     raeburn  9604:                     if ($compare ne $symb_crs) {
                   9605:                         push(@new_locks, $locker);
                   9606:                     }
1.563     banghart 9607:                 }
                   9608:             }
1.650     albertel 9609:             if (scalar(@new_locks) > 0) {
1.563     banghart 9610:                 $current_permissions{$file} = \@new_locks;
                   9611:             } else {
                   9612:                 push(@del_keys, $file);
1.613     albertel 9613:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9614:                 delete($current_permissions{$file});
1.563     banghart 9615:             }
                   9616:         }
1.561     banghart 9617:     }
1.613     albertel 9618:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9619:     return;
                   9620: }
1.512     banghart 9621: 
1.17      www      9622: # ------------------------------------------------------------ Directory lister
                   9623: 
                   9624: sub dirlist {
1.955     raeburn  9625:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9626:     $uri=~s/^\///;
                   9627:     $uri=~s/\/$//;
1.253     stredwic 9628:     my ($udom, $uname);
1.955     raeburn  9629:     if ($getuserdir) {
1.253     stredwic 9630:         $udom = $userdomain;
                   9631:         $uname = $username;
1.955     raeburn  9632:     } else {
                   9633:         (undef,$udom,$uname)=split(/\//,$uri);
                   9634:         if(defined($userdomain)) {
                   9635:             $udom = $userdomain;
                   9636:         }
                   9637:         if(defined($username)) {
                   9638:             $uname = $username;
                   9639:         }
1.253     stredwic 9640:     }
1.955     raeburn  9641:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9642: 
1.955     raeburn  9643:     $dirRoot = $perlvar{'lonDocRoot'};
                   9644:     if (defined($getpropath)) {
                   9645:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9646:         $dirRoot =~ s/\/$//;
1.955     raeburn  9647:     } elsif (defined($getuserdir)) {
                   9648:         my $subdir=$uname.'__';
                   9649:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9650:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9651:                    ."/$udom/$subdir/$uname";
                   9652:     } elsif (defined($alternateRoot)) {
                   9653:         $dirRoot = $alternateRoot;
1.751     banghart 9654:     }
1.253     stredwic 9655: 
                   9656:     if($udom) {
                   9657:         if($uname) {
1.1135    raeburn  9658:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9659:             if ($uhome eq 'no_host') {
                   9660:                 return ([],'no_host');
                   9661:             }
1.955     raeburn  9662:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9663:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9664:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9665:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9666:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9667:             } else {
                   9668:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9669:             }
1.605     matthew  9670:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9671:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9672:                 @listing_results = split(/:/,$listing);
                   9673:             } else {
                   9674:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9675:             }
1.1135    raeburn  9676:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9677:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9678:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9679:                 return ([],$listing);
                   9680:             } else {
                   9681:                 return (\@listing_results);
1.1135    raeburn  9682:             }
1.955     raeburn  9683:         } elsif(!$alternateRoot) {
1.1136    raeburn  9684:             my (%allusers,%listerror);
1.841     albertel 9685: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9686:  	    foreach my $tryserver (keys(%servers)) {
                   9687:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9688:                                   &escape($udom),$tryserver);
                   9689:                 if ($listing eq 'unknown_cmd') {
                   9690: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9691: 				      $udom, $tryserver);
                   9692:                 } else {
                   9693:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9694:                 }
1.841     albertel 9695: 		if ($listing eq 'unknown_cmd') {
                   9696: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9697: 				      $udom, $tryserver);
                   9698: 		    @listing_results = split(/:/,$listing);
                   9699: 		} else {
                   9700: 		    @listing_results =
                   9701: 			map { &unescape($_); } split(/:/,$listing);
                   9702: 		}
1.1136    raeburn  9703:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9704:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9705:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9706:                     $listerror{$tryserver} = $listing;
                   9707:                 } else {
1.841     albertel 9708: 		    foreach my $line (@listing_results) {
                   9709: 			my ($entry) = split(/&/,$line,2);
                   9710: 			$allusers{$entry} = 1;
                   9711: 		    }
                   9712: 		}
1.253     stredwic 9713:             }
1.1136    raeburn  9714:             my @alluserslist=();
1.800     albertel 9715:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9716:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9717:             }
1.1136    raeburn  9718:             return (\@alluserslist);
1.253     stredwic 9719:         } else {
1.1136    raeburn  9720:             return ([],'missing username');
1.253     stredwic 9721:         }
1.955     raeburn  9722:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9723:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9724:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9725:         return (\@all_domains);
1.955     raeburn  9726:     } else {
1.1136    raeburn  9727:         return ([],'missing domain');
1.275     stredwic 9728:     }
                   9729: }
                   9730: 
                   9731: # --------------------------------------------- GetFileTimestamp
                   9732: # This function utilizes dirlist and returns the date stamp for
                   9733: # when it was last modified.  It will also return an error of -1
                   9734: # if an error occurs
                   9735: 
                   9736: sub GetFileTimestamp {
1.955     raeburn  9737:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9738:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9739:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9740:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9741:                                     undef,$getuserdir);
                   9742:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9743:         return -1;
                   9744:     }
                   9745:     if (ref($fileref) eq 'ARRAY') {
                   9746:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9747:         # @stats contains first the filename, then the stat output
                   9748:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9749:     } else {
                   9750:         return -1;
1.253     stredwic 9751:     }
1.26      www      9752: }
                   9753: 
1.712     albertel 9754: sub stat_file {
                   9755:     my ($uri) = @_;
1.787     albertel 9756:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9757: 
1.955     raeburn  9758:     my ($udom,$uname,$file);
1.712     albertel 9759:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9760: 	($udom,$uname,$file) =
1.811     albertel 9761: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9762: 	$file = 'userfiles/'.$file;
                   9763:     }
                   9764:     if ($uri =~ m-^/res/-) {
                   9765: 	($udom,$uname) = 
1.807     albertel 9766: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9767: 	$file = $uri;
                   9768:     }
                   9769: 
                   9770:     if (!$udom || !$uname || !$file) {
                   9771: 	# unable to handle the uri
                   9772: 	return ();
                   9773:     }
1.956     raeburn  9774:     my $getpropath;
                   9775:     if ($file =~ /^userfiles\//) {
                   9776:         $getpropath = 1;
                   9777:     }
1.1136    raeburn  9778:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9779:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9780:         return ();
                   9781:     } else {
                   9782:         if (ref($listref) eq 'ARRAY') {
                   9783:             my @stats = split('&',$listref->[0]);
                   9784: 	    shift(@stats); #filename is first
                   9785: 	    return @stats;
                   9786:         }
1.712     albertel 9787:     }
                   9788:     return ();
                   9789: }
                   9790: 
1.26      www      9791: # -------------------------------------------------------- Value of a Condition
                   9792: 
1.713     albertel 9793: # gets the value of a specific preevaluated condition
                   9794: #    stored in the string  $env{user.state.<cid>}
                   9795: # or looks up a condition reference in the bighash and if if hasn't
                   9796: # already been evaluated recurses into docondval to get the value of
                   9797: # the condition, then memoizing it to 
                   9798: #   $env{user.state.<cid>.<condition>}
1.40      www      9799: sub directcondval {
                   9800:     my $number=shift;
1.620     albertel 9801:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9802: 	&Apache::lonuserstate::evalstate();
                   9803:     }
1.713     albertel 9804:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9805: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9806:     } elsif ($number =~ /^_/) {
                   9807: 	my $sub_condition;
                   9808: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9809: 		&GDBM_READER(),0640)) {
                   9810: 	    $sub_condition=$bighash{'conditions'.$number};
                   9811: 	    untie(%bighash);
                   9812: 	}
                   9813: 	my $value = &docondval($sub_condition);
1.949     raeburn  9814: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9815: 	return $value;
                   9816:     }
1.620     albertel 9817:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9818:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9819:     } else {
                   9820:        return 2;
                   9821:     }
                   9822: }
                   9823: 
1.713     albertel 9824: # get the collection of conditions for this resource
1.26      www      9825: sub condval {
                   9826:     my $condidx=shift;
1.54      www      9827:     my $allpathcond='';
1.713     albertel 9828:     foreach my $cond (split(/\|/,$condidx)) {
                   9829: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9830: 	    $allpathcond.=
                   9831: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9832: 	}
1.191     harris41 9833:     }
1.54      www      9834:     $allpathcond=~s/\|$//;
1.713     albertel 9835:     return &docondval($allpathcond);
                   9836: }
                   9837: 
                   9838: #evaluates an expression of conditions
                   9839: sub docondval {
                   9840:     my ($allpathcond) = @_;
                   9841:     my $result=0;
                   9842:     if ($env{'request.course.id'}
                   9843: 	&& defined($allpathcond)) {
                   9844: 	my $operand='|';
                   9845: 	my @stack;
                   9846: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9847: 	    if ($chunk eq '(') {
                   9848: 		push @stack,($operand,$result);
                   9849: 	    } elsif ($chunk eq ')') {
                   9850: 		my $before=pop @stack;
                   9851: 		if (pop @stack eq '&') {
                   9852: 		    $result=$result>$before?$before:$result;
                   9853: 		} else {
                   9854: 		    $result=$result>$before?$result:$before;
                   9855: 		}
                   9856: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9857: 		$operand=$chunk;
                   9858: 	    } else {
                   9859: 		my $new=directcondval($chunk);
                   9860: 		if ($operand eq '&') {
                   9861: 		    $result=$result>$new?$new:$result;
                   9862: 		} else {
                   9863: 		    $result=$result>$new?$result:$new;
                   9864: 		}
                   9865: 	    }
                   9866: 	}
1.26      www      9867:     }
                   9868:     return $result;
1.421     albertel 9869: }
                   9870: 
                   9871: # ---------------------------------------------------- Devalidate courseresdata
                   9872: 
                   9873: sub devalidatecourseresdata {
                   9874:     my ($coursenum,$coursedomain)=@_;
                   9875:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9876:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9877: }
                   9878: 
1.763     www      9879: 
1.200     www      9880: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9881: #
                   9882: #  Parameters:
                   9883: #      $coursenum    - Number of the course.
                   9884: #      $coursedomain - Domain at which the course was created.
                   9885: #  Returns:
                   9886: #     A hash of the course parameters along (I think) with timestamps
                   9887: #     and version info.
1.877     foxr     9888: 
1.624     albertel 9889: sub get_courseresdata {
                   9890:     my ($coursenum,$coursedomain)=@_;
1.200     www      9891:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9892:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9893:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9894:     my %dumpreply;
1.417     albertel 9895:     unless (defined($cached)) {
1.624     albertel 9896: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9897: 	$result=\%dumpreply;
1.251     albertel 9898: 	my ($tmp) = keys(%dumpreply);
                   9899: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9900: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9901: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9902: 	    return $tmp;
1.416     albertel 9903: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9904: 	    $result=undef;
1.599     albertel 9905: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9906: 	}
                   9907:     }
1.624     albertel 9908:     return $result;
                   9909: }
                   9910: 
1.633     albertel 9911: sub devalidateuserresdata {
                   9912:     my ($uname,$udom)=@_;
                   9913:     my $hashid="$udom:$uname";
                   9914:     &devalidate_cache_new('userres',$hashid);
                   9915: }
                   9916: 
1.624     albertel 9917: sub get_userresdata {
                   9918:     my ($uname,$udom)=@_;
                   9919:     #most student don\'t have any data set, check if there is some data
                   9920:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9921: 
                   9922:     my $hashid="$udom:$uname";
                   9923:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9924:     if (!defined($cached)) {
                   9925: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9926: 	$result=\%resourcedata;
                   9927: 	&do_cache_new('userres',$hashid,$result,600);
                   9928:     }
                   9929:     my ($tmp)=keys(%$result);
                   9930:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9931: 	return $result;
                   9932:     }
                   9933:     #error 2 occurs when the .db doesn't exist
                   9934:     if ($tmp!~/error: 2 /) {
1.672     albertel 9935: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9936: 		 " Trying to get resource data for ".
                   9937: 		 $uname." at ".$udom.": ".
                   9938: 		 $tmp."</font>");
                   9939:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9940: 	#&EXT_cache_set($udom,$uname);
                   9941: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9942: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9943:     }
                   9944:     return $tmp;
                   9945: }
1.879     foxr     9946: #----------------------------------------------- resdata - return resource data
                   9947: #  Purpose:
                   9948: #    Return resource data for either users or for a course.
                   9949: #  Parameters:
                   9950: #     $name      - Course/user name.
                   9951: #     $domain    - Name of the domain the user/course is registered on.
                   9952: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9953: #     @which     - Array of names of resources desired.
                   9954: #  Returns:
                   9955: #     The value of the first reasource in @which that is found in the
                   9956: #     resource hash.
                   9957: #  Exceptional Conditions:
                   9958: #     If the $type passed in is not valid (not the string 'course' or 
                   9959: #     'user', an undefined  reference is returned.
                   9960: #     If none of the resources are found, an undef is returned
1.624     albertel 9961: sub resdata {
                   9962:     my ($name,$domain,$type,@which)=@_;
                   9963:     my $result;
                   9964:     if ($type eq 'course') {
                   9965: 	$result=&get_courseresdata($name,$domain);
                   9966:     } elsif ($type eq 'user') {
                   9967: 	$result=&get_userresdata($name,$domain);
                   9968:     }
                   9969:     if (!ref($result)) { return $result; }    
1.251     albertel 9970:     foreach my $item (@which) {
1.927     albertel 9971: 	if (defined($result->{$item->[0]})) {
                   9972: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9973: 	}
1.250     albertel 9974:     }
1.291     albertel 9975:     return undef;
1.200     www      9976: }
                   9977: 
1.1172.2.31  raeburn  9978: sub get_numsuppfiles {
                   9979:     my ($cnum,$cdom,$ignorecache)=@_;
                   9980:     my $hashid=$cnum.':'.$cdom;
                   9981:     my ($suppcount,$cached);
                   9982:     unless ($ignorecache) {
                   9983:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9984:     }
                   9985:     unless (defined($cached)) {
                   9986:         my $chome=&homeserver($cnum,$cdom);
                   9987:         unless ($chome eq 'no_host') {
                   9988:             ($suppcount,my $errors) = (0,0);
                   9989:             my $suppmap = 'supplemental.sequence';
                   9990:             ($suppcount,$errors) =
                   9991:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9992:         }
                   9993:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9994:     }
                   9995:     return $suppcount;
                   9996: }
                   9997: 
1.379     matthew  9998: #
                   9999: # EXT resource caching routines
                   10000: #
                   10001: 
                   10002: sub clear_EXT_cache_status {
1.383     albertel 10003:     &delenv('cache.EXT.');
1.379     matthew  10004: }
                   10005: 
                   10006: sub EXT_cache_status {
                   10007:     my ($target_domain,$target_user) = @_;
1.383     albertel 10008:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10009:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10010:         # We know already the user has no data
                   10011:         return 1;
                   10012:     } else {
                   10013:         return 0;
                   10014:     }
                   10015: }
                   10016: 
                   10017: sub EXT_cache_set {
                   10018:     my ($target_domain,$target_user) = @_;
1.383     albertel 10019:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10020:     #&appenv({$cachename => time});
1.379     matthew  10021: }
                   10022: 
1.28      www      10023: # --------------------------------------------------------- Value of a Variable
1.58      www      10024: sub EXT {
1.715     albertel 10025: 
1.1172.2.28  raeburn  10026:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10027:     unless ($varname) { return ''; }
1.218     albertel 10028:     #get real user name/domain, courseid and symb
                   10029:     my $courseid;
1.359     albertel 10030:     my $publicuser;
1.427     www      10031:     if ($symbparm) {
                   10032: 	$symbparm=&get_symb_from_alias($symbparm);
                   10033:     }
1.218     albertel 10034:     if (!($uname && $udom)) {
1.790     albertel 10035:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10036:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10037:     } else {
1.620     albertel 10038: 	$courseid=$env{'request.course.id'};
1.218     albertel 10039:     }
1.48      www      10040:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10041:     my $rest;
1.320     albertel 10042:     if (defined($therest[0])) {
1.48      www      10043:        $rest=join('.',@therest);
                   10044:     } else {
                   10045:        $rest='';
                   10046:     }
1.320     albertel 10047: 
1.57      www      10048:     my $qualifierrest=$qualifier;
                   10049:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10050:     my $spacequalifierrest=$space;
                   10051:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10052:     if ($realm eq 'user') {
1.48      www      10053: # --------------------------------------------------------------- user.resource
                   10054: 	if ($space eq 'resource') {
1.651     albertel 10055: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10056: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10057: 		 &&
1.744     albertel 10058: 		 ($symbparm eq &symbread()) ) {	
                   10059: 		# if we are in the middle of processing the resource the
                   10060: 		# get the value we are planning on committing
                   10061:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10062:                     return $Apache::lonhomework::results{$qualifierrest};
                   10063:                 } else {
                   10064:                     return $Apache::lonhomework::history{$qualifierrest};
                   10065:                 }
1.335     albertel 10066: 	    } else {
1.359     albertel 10067: 		my %restored;
1.620     albertel 10068: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10069: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10070: 		} else {
                   10071: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10072: 		}
1.335     albertel 10073: 		return $restored{$qualifierrest};
                   10074: 	    }
1.48      www      10075: # ----------------------------------------------------------------- user.access
                   10076:         } elsif ($space eq 'access') {
1.218     albertel 10077: 	    # FIXME - not supporting calls for a specific user
1.48      www      10078:             return &allowed($qualifier,$rest);
                   10079: # ------------------------------------------ user.preferences, user.environment
                   10080:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10081: 	    if (($uname eq $env{'user.name'}) &&
                   10082: 		($udom eq $env{'user.domain'})) {
                   10083: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10084: 	    } else {
1.359     albertel 10085: 		my %returnhash;
                   10086: 		if (!$publicuser) {
                   10087: 		    %returnhash=&userenvironment($udom,$uname,
                   10088: 						 $qualifierrest);
                   10089: 		}
1.218     albertel 10090: 		return $returnhash{$qualifierrest};
                   10091: 	    }
1.48      www      10092: # ----------------------------------------------------------------- user.course
                   10093:         } elsif ($space eq 'course') {
1.218     albertel 10094: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10095:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10096: # ------------------------------------------------------------------- user.role
                   10097:         } elsif ($space eq 'role') {
1.218     albertel 10098: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10099:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10100:             if ($qualifier eq 'value') {
                   10101: 		return $role;
                   10102:             } elsif ($qualifier eq 'extent') {
                   10103:                 return $where;
                   10104:             }
                   10105: # ----------------------------------------------------------------- user.domain
                   10106:         } elsif ($space eq 'domain') {
1.218     albertel 10107:             return $udom;
1.48      www      10108: # ------------------------------------------------------------------- user.name
                   10109:         } elsif ($space eq 'name') {
1.218     albertel 10110:             return $uname;
1.48      www      10111: # ---------------------------------------------------- Any other user namespace
1.29      www      10112:         } else {
1.359     albertel 10113: 	    my %reply;
                   10114: 	    if (!$publicuser) {
                   10115: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10116: 	    }
                   10117: 	    return $reply{$qualifierrest};
1.48      www      10118:         }
1.236     www      10119:     } elsif ($realm eq 'query') {
                   10120: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10121:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10122: 						[$spacequalifierrest]);
1.620     albertel 10123: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10124:    } elsif ($realm eq 'request') {
1.48      www      10125: # ------------------------------------------------------------- request.browser
                   10126:         if ($space eq 'browser') {
1.1145    bisitz   10127:             return $env{'browser.'.$qualifier};
1.57      www      10128: # ------------------------------------------------------------ request.filename
                   10129:         } else {
1.620     albertel 10130:             return $env{'request.'.$spacequalifierrest};
1.29      www      10131:         }
1.28      www      10132:     } elsif ($realm eq 'course') {
1.48      www      10133: # ---------------------------------------------------------- course.description
1.620     albertel 10134:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10135:     } elsif ($realm eq 'resource') {
1.165     www      10136: 
1.620     albertel 10137: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10138: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10139: 	}
1.693     albertel 10140: 
1.1172.2.30  raeburn  10141:         if ($qualifier eq '') {
                   10142: 	    if ($space eq 'title') {
                   10143: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10144: 	        return &gettitle($symbparm);
                   10145: 	    }
1.693     albertel 10146: 	
1.1172.2.30  raeburn  10147: 	    if ($space eq 'map') {
                   10148: 	        my ($map) = &decode_symb($symbparm);
                   10149: 	        return &symbread($map);
                   10150: 	    }
                   10151:             if ($space eq 'maptitle') {
                   10152:                 my ($map) = &decode_symb($symbparm);
                   10153:                 return &gettitle($map);
                   10154:             }
                   10155: 	    if ($space eq 'filename') {
                   10156: 	        if ($symbparm) {
                   10157: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10158: 	        }
                   10159: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10160: 	    }
1.1172.2.30  raeburn  10161: 
                   10162:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10163:                 if ($space eq 'visibleparts') {
                   10164:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10165:                     my $item;
                   10166:                     if (ref($navmap)) {
                   10167:                         my $res = $navmap->getBySymb($symbparm);
                   10168:                         my $parts = $res->parts();
                   10169:                         if (ref($parts) eq 'ARRAY') {
                   10170:                             $item = join(',',@{$parts});
                   10171:                         }
                   10172:                         undef($navmap);
                   10173:                     }
                   10174:                     return $item;
                   10175:                 }
                   10176:             }
                   10177:         }
1.693     albertel 10178: 
                   10179: 	my ($section, $group, @groups);
1.593     albertel 10180: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10181:         if (($courseid eq '') && ($cid)) {
                   10182:             $courseid = $cid;
                   10183:         }
                   10184: 	if (($symbparm && $courseid) && 
                   10185: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10186: 
1.218     albertel 10187: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10188: 
1.60      www      10189: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10190: 	    my $symbp=$symbparm;
1.735     albertel 10191: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10192: 
                   10193: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10194: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10195: 
1.620     albertel 10196: 	    if (($env{'user.name'} eq $uname) &&
                   10197: 		($env{'user.domain'} eq $udom)) {
                   10198: 		$section=$env{'request.course.sec'};
1.733     raeburn  10199:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10200:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10201: 	    } else {
1.539     albertel 10202: 		if (! defined($usection)) {
1.551     albertel 10203: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10204: 		} else {
                   10205: 		    $section = $usection;
                   10206: 		}
1.733     raeburn  10207:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10208: 	    }
                   10209: 
                   10210: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10211: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10212: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10213: 
1.593     albertel 10214: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10215: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10216: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10217: 
1.60      www      10218: # ----------------------------------------------------------- first, check user
1.624     albertel 10219: 
                   10220: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10221: 				       ([$courselevelr,'resource'],
                   10222: 					[$courselevelm,'map'     ],
                   10223: 					[$courselevel, 'course'  ]));
1.931     albertel 10224: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10225: 
1.594     albertel 10226: # ------------------------------------------------ second, check some of course
1.684     raeburn  10227:             my $coursereply;
1.691     raeburn  10228:             if (@groups > 0) {
                   10229:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10230:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10231:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10232:             }
1.96      www      10233: 
1.684     raeburn  10234: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10235: 				  $env{'course.'.$courseid.'.domain'},
                   10236: 				  'course',
                   10237: 				  ([$seclevelr,   'resource'],
                   10238: 				   [$seclevelm,   'map'     ],
                   10239: 				   [$seclevel,    'course'  ],
                   10240: 				   [$courselevelr,'resource']));
                   10241: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10242: 
1.60      www      10243: # ------------------------------------------------------ third, check map parms
1.218     albertel 10244: 	    my %parmhash=();
                   10245: 	    my $thisparm='';
                   10246: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10247: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10248: 		    &GDBM_READER(),0640)) {
1.218     albertel 10249: 		$thisparm=$parmhash{$symbparm};
                   10250: 		untie(%parmhash);
                   10251: 	    }
1.927     albertel 10252: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10253: 	}
1.594     albertel 10254: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10255: 
1.218     albertel 10256: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10257: 	my $filename;
                   10258: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10259: 	if ($symbparm) {
1.409     www      10260: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10261: 	} else {
1.620     albertel 10262: 	    $filename=$env{'request.filename'};
1.282     albertel 10263: 	}
                   10264: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10265: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10266: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10267: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10268: 
1.927     albertel 10269: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10270: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10271: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10272: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10273: 				     $env{'course.'.$courseid.'.domain'},
                   10274: 				     'course',
1.927     albertel 10275: 				     ([$courselevelm,'map'   ],
                   10276: 				      [$courselevel, 'course']));
                   10277: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10278: 	}
1.145     www      10279: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10280: 	unless ($space eq '0') {
1.336     albertel 10281: 	    my @parts=split(/_/,$space);
                   10282: 	    my $id=pop(@parts);
                   10283: 	    my $part=join('_',@parts);
                   10284: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10285: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10286: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10287: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10288: 	}
1.395     albertel 10289: 	if ($recurse) { return undef; }
                   10290: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10291: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10292: # ---------------------------------------------------- Any other user namespace
                   10293:     } elsif ($realm eq 'environment') {
                   10294: # ----------------------------------------------------------------- environment
1.620     albertel 10295: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10296: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10297: 	} else {
1.770     albertel 10298: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10299: 		return '';
                   10300: 	    }
1.219     albertel 10301: 	    my %returnhash=&userenvironment($udom,$uname,
                   10302: 					    $spacequalifierrest);
                   10303: 	    return $returnhash{$spacequalifierrest};
                   10304: 	}
1.28      www      10305:     } elsif ($realm eq 'system') {
1.48      www      10306: # ----------------------------------------------------------------- system.time
                   10307: 	if ($space eq 'time') {
                   10308: 	    return time;
                   10309:         }
1.696     albertel 10310:     } elsif ($realm eq 'server') {
                   10311: # ----------------------------------------------------------------- system.time
                   10312: 	if ($space eq 'name') {
                   10313: 	    return $ENV{'SERVER_NAME'};
                   10314:         }
1.28      www      10315:     }
1.48      www      10316:     return '';
1.61      www      10317: }
                   10318: 
1.927     albertel 10319: sub get_reply {
                   10320:     my ($reply_value) = @_;
1.940     raeburn  10321:     if (ref($reply_value) eq 'ARRAY') {
                   10322:         if (wantarray) {
                   10323: 	    return @$reply_value;
                   10324:         }
                   10325:         return $reply_value->[0];
                   10326:     } else {
                   10327:         return $reply_value;
1.927     albertel 10328:     }
                   10329: }
                   10330: 
1.691     raeburn  10331: sub check_group_parms {
                   10332:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10333:     my @groupitems = ();
                   10334:     my $resultitem;
1.927     albertel 10335:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10336:     foreach my $group (@{$groups}) {
                   10337:         foreach my $level (@levels) {
1.927     albertel 10338:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10339:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10340:         }
                   10341:     }
                   10342:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10343:                             $env{'course.'.$courseid.'.domain'},
                   10344:                                      'course',@groupitems);
                   10345:     return $coursereply;
                   10346: }
                   10347: 
                   10348: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10349:     my ($courseid,@groups) = @_;
                   10350:     @groups = sort(@groups);
1.691     raeburn  10351:     return @groups;
                   10352: }
                   10353: 
1.395     albertel 10354: sub packages_tab_default {
                   10355:     my ($uri,$varname)=@_;
                   10356:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10357: 
                   10358:     my (@extension,@specifics,$do_default);
                   10359:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10360: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10361: 	if ($pack_type eq 'default') {
                   10362: 	    $do_default=1;
                   10363: 	} elsif ($pack_type eq 'extension') {
                   10364: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10365: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10366: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10367: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10368: 	}
                   10369:     }
                   10370:     # first look for a package that matches the requested part id
                   10371:     foreach my $package (@specifics) {
                   10372: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10373: 	next if ($pack_part ne $part);
                   10374: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10375: 	    return $packagetab{"$pack_type&$name&default"};
                   10376: 	}
                   10377:     }
                   10378:     # look for any possible matching non extension_ package
                   10379:     foreach my $package (@specifics) {
                   10380: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10381: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10382: 	    return $packagetab{"$pack_type&$name&default"};
                   10383: 	}
1.585     albertel 10384: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10385: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10386: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10387: 	}
                   10388:     }
1.738     albertel 10389:     # look for any posible extension_ match
                   10390:     foreach my $package (@extension) {
                   10391: 	my ($package,$pack_type)=@{$package};
                   10392: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10393: 	    return $packagetab{"$pack_type&$name&default"};
                   10394: 	}
                   10395: 	if (defined($packagetab{$package."&$name&default"})) {
                   10396: 	    return $packagetab{$package."&$name&default"};
                   10397: 	}
                   10398:     }
                   10399:     # look for a global default setting
                   10400:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10401: 	return $packagetab{"default&$name&default"};
                   10402:     }
1.395     albertel 10403:     return undef;
                   10404: }
                   10405: 
1.334     albertel 10406: sub add_prefix_and_part {
                   10407:     my ($prefix,$part)=@_;
                   10408:     my $keyroot;
                   10409:     if (defined($prefix) && $prefix !~ /^__/) {
                   10410: 	# prefix that has a part already
                   10411: 	$keyroot=$prefix;
                   10412:     } elsif (defined($prefix)) {
                   10413: 	# prefix that is missing a part
                   10414: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10415:     } else {
                   10416: 	# no prefix at all
                   10417: 	if (defined($part)) { $keyroot='_'.$part; }
                   10418:     }
                   10419:     return $keyroot;
                   10420: }
                   10421: 
1.71      www      10422: # ---------------------------------------------------------------- Get metadata
                   10423: 
1.599     albertel 10424: my %metaentry;
1.1070    www      10425: my %importedpartids;
1.71      www      10426: sub metadata {
1.176     www      10427:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10428:     $uri=&declutter($uri);
1.288     albertel 10429:     # if it is a non metadata possible uri return quickly
1.529     albertel 10430:     if (($uri eq '') || 
                   10431: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10432: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10433:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10434: 	return undef;
                   10435:     }
1.1172.2.49  raeburn  10436:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10437: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10438: 	return undef;
1.288     albertel 10439:     }
1.73      www      10440:     my $filename=$uri;
                   10441:     $uri=~s/\.meta$//;
1.172     www      10442: #
                   10443: # Is the metadata already cached?
1.177     www      10444: # Look at timestamp of caching
1.172     www      10445: # Everything is cached by the main uri, libraries are never directly cached
                   10446: #
1.428     albertel 10447:     if (!defined($liburi)) {
1.599     albertel 10448: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10449: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10450:     }
                   10451:     {
1.1069    www      10452: # Imported parts would go here
1.1070    www      10453:         my %importedids=();
                   10454:         my @origfileimportpartids=();
1.1069    www      10455:         my $importedparts=0;
1.172     www      10456: #
                   10457: # Is this a recursive call for a library?
                   10458: #
1.599     albertel 10459: #	if (! exists($metacache{$uri})) {
                   10460: #	    $metacache{$uri}={};
                   10461: #	}
1.924     albertel 10462: 	my $cachetime = 60*60;
1.171     www      10463:         if ($liburi) {
                   10464: 	    $liburi=&declutter($liburi);
                   10465:             $filename=$liburi;
1.401     bowersj2 10466:         } else {
1.599     albertel 10467: 	    &devalidate_cache_new('meta',$uri);
                   10468: 	    undef(%metaentry);
1.401     bowersj2 10469: 	}
1.140     www      10470:         my %metathesekeys=();
1.73      www      10471:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10472: 	my $metastring;
1.1140    www      10473: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10474: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10475: 	    $metastring = 
1.929     albertel 10476: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10477: 					  ('grade_target' => 'meta'));
                   10478: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10479: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10480:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10481: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10482: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10483: 	    $metastring=&getfile($file);
1.489     albertel 10484: 	}
1.208     albertel 10485:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10486:         my $token;
1.140     www      10487:         undef %metathesekeys;
1.71      www      10488:         while ($token=$parser->get_token) {
1.339     albertel 10489: 	    if ($token->[0] eq 'S') {
                   10490: 		if (defined($token->[2]->{'package'})) {
1.172     www      10491: #
                   10492: # This is a package - get package info
                   10493: #
1.339     albertel 10494: 		    my $package=$token->[2]->{'package'};
                   10495: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10496: 		    if (defined($token->[2]->{'id'})) { 
                   10497: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10498: 		    }
1.599     albertel 10499: 		    if ($metaentry{':packages'}) {
                   10500: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10501: 		    } else {
1.599     albertel 10502: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10503: 		    }
1.736     albertel 10504: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10505: 			my $part=$keyroot;
                   10506: 			$part=~s/^\_//;
1.736     albertel 10507: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10508: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10509: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10510: 			    # ignore package.tab specified default values
                   10511:                             # here &package_tab_default() will fetch those
                   10512: 			    if ($subp eq 'default') { next; }
1.736     albertel 10513: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10514: 			    my $unikey;
                   10515: 			    if ($pack =~ /_0$/) {
                   10516: 				$unikey='parameter_0_'.$name;
                   10517: 				$part=0;
                   10518: 			    } else {
                   10519: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10520: 			    }
1.339     albertel 10521: 			    if ($subp eq 'display') {
                   10522: 				$value.=' [Part: '.$part.']';
                   10523: 			    }
1.599     albertel 10524: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10525: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10526: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10527: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10528: 			    }
1.599     albertel 10529: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10530: 				$metaentry{':'.$unikey}=
                   10531: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10532: 			    }
1.339     albertel 10533: 			}
                   10534: 		    }
                   10535: 		} else {
1.172     www      10536: #
                   10537: # This is not a package - some other kind of start tag
1.339     albertel 10538: #
                   10539: 		    my $entry=$token->[1];
1.1068    www      10540: 		    my $unikey='';
1.175     www      10541: 
1.339     albertel 10542: 		    if ($entry eq 'import') {
1.175     www      10543: #
                   10544: # Importing a library here
1.339     albertel 10545: #
1.1067    www      10546:                         my $location=$parser->get_text('/import');
                   10547:                         my $dir=$filename;
                   10548:                         $dir=~s|[^/]*$||;
                   10549:                         $location=&filelocation($dir,$location);
1.1069    www      10550:                        
1.1068    www      10551:                         my $importmode=$token->[2]->{'importmode'};
                   10552:                         if ($importmode eq 'problem') {
1.1069    www      10553: # Import as problem/response
1.1068    www      10554:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10555:                         } elsif ($importmode eq 'part') {
                   10556: # Import as part(s)
1.1069    www      10557:                            $importedparts=1;
                   10558: # We need to get the original file and the imported file to get the part order correct
                   10559: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10560: # Load and inspect original file
1.1070    www      10561:                            if ($#origfileimportpartids<0) {
                   10562:                               undef(%importedpartids);
                   10563:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10564:                               my $origfile=&getfile($origfilelocation);
                   10565:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10566:                            }
                   10567: 
1.1069    www      10568: # Load and inspect imported file
                   10569:                            my $impfile=&getfile($location);
                   10570:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10571:                            if ($#impfilepartids>=0) {
                   10572: # This problem had parts
1.1070    www      10573:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10574:                            } else {
                   10575: # Importing by turning a single problem into a problem part
                   10576: # It gets the import-tags ID as part-ID
                   10577:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10578:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10579:                            }
1.1068    www      10580:                         } else {
                   10581: # Normal import
                   10582:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10583:                            if (defined($token->[2]->{'id'})) {
                   10584:                               $unikey.='_'.$token->[2]->{'id'};
                   10585:                            }
1.1067    www      10586:                         }
                   10587: 
1.339     albertel 10588: 			if ($depthcount<20) {
1.736     albertel 10589: 			    my $metadata = 
                   10590: 				&metadata($uri,'keys', $location,$unikey,
                   10591: 					  $depthcount+1);
                   10592: 			    foreach my $meta (split(',',$metadata)) {
                   10593: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10594: 				$metathesekeys{$meta}=1;
1.339     albertel 10595: 			    }
1.1068    www      10596: 			
                   10597:                         }
1.1067    www      10598: 		    } else {
                   10599: #
                   10600: # Not importing, some other kind of non-package, non-library start tag
                   10601: # 
                   10602:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10603:                         if (defined($token->[2]->{'id'})) {
                   10604:                             $unikey.='_'.$token->[2]->{'id'};
                   10605:                         }
1.339     albertel 10606: 			if (defined($token->[2]->{'name'})) { 
                   10607: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10608: 			}
                   10609: 			$metathesekeys{$unikey}=1;
1.736     albertel 10610: 			foreach my $param (@{$token->[3]}) {
                   10611: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10612: 				$token->[2]->{$param};
1.339     albertel 10613: 			}
                   10614: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10615: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10616: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10617: 		 # only ws inside the tag, and not in default, so use default
                   10618: 		 # as value
1.599     albertel 10619: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10620: 			} elsif ( $internaltext =~ /\S/ ) {
                   10621: 		  # something interesting inside the tag
                   10622: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10623: 			} else {
1.908     albertel 10624: 		  # no interesting values, don't set a default
1.339     albertel 10625: 			}
1.172     www      10626: # end of not-a-package not-a-library import
1.339     albertel 10627: 		    }
1.172     www      10628: # end of not-a-package start tag
1.339     albertel 10629: 		}
1.172     www      10630: # the next is the end of "start tag"
1.339     albertel 10631: 	    }
                   10632: 	}
1.483     albertel 10633: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10634: 	$extension = lc($extension);
                   10635: 	if ($extension eq 'htm') { $extension='html'; }
                   10636: 
1.737     albertel 10637: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10638: 	    #no specific packages #how's our extension
                   10639: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10640: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10641: 					 \%metathesekeys);
                   10642: 	}
1.883     albertel 10643: 
                   10644: 	if (!exists($metaentry{':packages'})
                   10645: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10646: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10647: 		#no specific packages well let's get default then
                   10648: 		if ($key!~/^default&/) { next; }
1.488     albertel 10649: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10650: 					     \%metathesekeys);
                   10651: 	    }
                   10652: 	}
1.338     www      10653: # are there custom rights to evaluate
1.599     albertel 10654: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10655: 
1.338     www      10656:     #
                   10657:     # Importing a rights file here
1.339     albertel 10658:     #
                   10659: 	    unless ($depthcount) {
1.599     albertel 10660: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10661: 		my $dir=$filename;
                   10662: 		$dir=~s|[^/]*$||;
                   10663: 		$location=&filelocation($dir,$location);
1.736     albertel 10664: 		my $rights_metadata =
                   10665: 		    &metadata($uri,'keys',$location,'_rights',
                   10666: 			      $depthcount+1);
                   10667: 		foreach my $rights (split(',',$rights_metadata)) {
                   10668: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10669: 		    $metathesekeys{$rights}=1;
1.339     albertel 10670: 		}
                   10671: 	    }
                   10672: 	}
1.737     albertel 10673: 	# uniqifiy package listing
                   10674: 	my %seen;
                   10675: 	my @uniq_packages =
                   10676: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10677: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10678: 
1.1070    www      10679:         if ($importedparts) {
                   10680: # We had imported parts and need to rebuild partorder
                   10681:            $metaentry{':partorder'}='';
                   10682:            $metathesekeys{'partorder'}=1;
                   10683:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10684:                if ($origfileimportpartids[$index] eq 'part') {
                   10685: # original part, part of the problem
                   10686:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10687:                } else {
                   10688: # we have imported parts at this position
                   10689:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10690:                }
                   10691:            }
                   10692:            $metaentry{':partorder'}=~s/^\,//;
                   10693:         }
                   10694: 
1.737     albertel 10695: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10696: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  10697: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 10698: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10699: # this is the end of "was not already recently cached
1.71      www      10700:     }
1.599     albertel 10701:     return $metaentry{':'.$what};
1.261     albertel 10702: }
                   10703: 
1.488     albertel 10704: sub metadata_create_package_def {
1.483     albertel 10705:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10706:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10707:     if ($subp eq 'default') { next; }
                   10708:     
1.599     albertel 10709:     if (defined($metaentry{':packages'})) {
                   10710: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10711:     } else {
1.599     albertel 10712: 	$metaentry{':packages'}=$package;
1.483     albertel 10713:     }
                   10714:     my $value=$packagetab{$key};
                   10715:     my $unikey;
                   10716:     $unikey='parameter_0_'.$name;
1.599     albertel 10717:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10718:     $$metathesekeys{$unikey}=1;
1.599     albertel 10719:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10720: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10721:     }
1.599     albertel 10722:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10723: 	$metaentry{':'.$unikey}=
                   10724: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10725:     }
                   10726: }
                   10727: 
1.261     albertel 10728: sub metadata_generate_part0 {
                   10729:     my ($metadata,$metacache,$uri) = @_;
                   10730:     my %allnames;
1.737     albertel 10731:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10732: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10733: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10734: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10735: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10736: 	    $allnames{$name}=$part;
                   10737: 	  }
                   10738: 	}
                   10739:     }
                   10740:     foreach my $name (keys(%allnames)) {
                   10741:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10742:       my $key=":parameter_0_$name";
1.261     albertel 10743:       $$metacache{"$key.part"}='0';
                   10744:       $$metacache{"$key.name"}=$name;
1.428     albertel 10745:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10746: 					   $allnames{$name}.'_'.$name.
                   10747: 					   '.type'};
1.428     albertel 10748:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10749: 			     '.display'};
1.644     www      10750:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10751:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10752:       $$metacache{"$key.display"}=$olddis;
                   10753:     }
1.71      www      10754: }
                   10755: 
1.764     albertel 10756: # ------------------------------------------------------ Devalidate title cache
                   10757: 
                   10758: sub devalidate_title_cache {
                   10759:     my ($url)=@_;
                   10760:     if (!$env{'request.course.id'}) { return; }
                   10761:     my $symb=&symbread($url);
                   10762:     if (!$symb) { return; }
                   10763:     my $key=$env{'request.course.id'}."\0".$symb;
                   10764:     &devalidate_cache_new('title',$key);
                   10765: }
                   10766: 
1.1014    droeschl 10767: # ------------------------------------------------- Get the title of a course
                   10768: 
                   10769: sub current_course_title {
                   10770:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10771: }
1.301     www      10772: # ------------------------------------------------- Get the title of a resource
                   10773: 
                   10774: sub gettitle {
                   10775:     my $urlsymb=shift;
                   10776:     my $symb=&symbread($urlsymb);
1.534     albertel 10777:     if ($symb) {
1.620     albertel 10778: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10779: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10780: 	if (defined($cached)) { 
                   10781: 	    return $result;
                   10782: 	}
1.534     albertel 10783: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10784: 	my $title='';
1.907     albertel 10785: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10786: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10787: 	} else {
                   10788: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10789: 		    &GDBM_READER(),0640)) {
                   10790: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10791: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10792: 		untie(%bighash);
                   10793: 	    }
1.534     albertel 10794: 	}
                   10795: 	$title=~s/\&colon\;/\:/gs;
                   10796: 	if ($title) {
1.1159    www      10797: # Remember both $symb and $title for dynamic metadata
                   10798:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10799:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10800: # Cache this title and then return it
1.599     albertel 10801: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10802: 	}
                   10803: 	$urlsymb=$url;
                   10804:     }
                   10805:     my $title=&metadata($urlsymb,'title');
                   10806:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10807:     return $title;
1.301     www      10808: }
1.613     albertel 10809: 
1.614     albertel 10810: sub get_slot {
                   10811:     my ($which,$cnum,$cdom)=@_;
                   10812:     if (!$cnum || !$cdom) {
1.790     albertel 10813: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10814: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10815: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10816:     }
1.703     albertel 10817:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10818:     my %slotinfo;
                   10819:     if (exists($remembered{$key})) {
                   10820: 	$slotinfo{$which} = $remembered{$key};
                   10821:     } else {
                   10822: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10823: 	&Apache::lonhomework::showhash(%slotinfo);
                   10824: 	my ($tmp)=keys(%slotinfo);
                   10825: 	if ($tmp=~/^error:/) { return (); }
                   10826: 	$remembered{$key} = $slotinfo{$which};
                   10827:     }
1.616     albertel 10828:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10829: 	return %{$slotinfo{$which}};
                   10830:     }
                   10831:     return $slotinfo{$which};
1.614     albertel 10832: }
1.1150    raeburn  10833: 
                   10834: sub get_reservable_slots {
                   10835:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10836:     my $now = time;
                   10837:     my $reservable_info;
                   10838:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10839:     if (exists($remembered{$key})) {
                   10840:         $reservable_info = $remembered{$key};
                   10841:     } else {
                   10842:         my %resv;
                   10843:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10844:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10845:         $reservable_info = \%resv;
                   10846:         $remembered{$key} = $reservable_info;
                   10847:     }
                   10848:     return $reservable_info;
                   10849: }
                   10850: 
                   10851: sub get_course_slots {
                   10852:     my ($cnum,$cdom) = @_;
                   10853:     my $hashid=$cnum.':'.$cdom;
                   10854:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10855:     if (defined($cached)) {
                   10856:         if (ref($result) eq 'HASH') {
                   10857:             return %{$result};
                   10858:         }
                   10859:     } else {
                   10860:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10861:         my ($tmp) = keys(%slots);
                   10862:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  10863:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10864:             return %slots;
                   10865:         }
                   10866:     }
                   10867:     return;
                   10868: }
                   10869: 
                   10870: sub devalidate_slots_cache {
                   10871:     my ($cnum,$cdom)=@_;
                   10872:     my $hashid=$cnum.':'.$cdom;
                   10873:     &devalidate_cache_new('allslots',$hashid);
                   10874: }
                   10875: 
1.1172.2.8  raeburn  10876: sub get_coursechange {
                   10877:     my ($cdom,$cnum) = @_;
                   10878:     if ($cdom eq '' || $cnum eq '') {
                   10879:         return unless ($env{'request.course.id'});
                   10880:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10881:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10882:     }
                   10883:     my $hashid=$cdom.'_'.$cnum;
                   10884:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10885:     if ((defined($cached)) && ($change ne '')) {
                   10886:         return $change;
                   10887:     } else {
                   10888:         my %crshash;
                   10889:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10890:         if ($crshash{'internal.contentchange'} eq '') {
                   10891:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10892:             if ($change eq '') {
                   10893:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10894:                 $change = $crshash{'internal.created'};
                   10895:             }
                   10896:         } else {
                   10897:             $change = $crshash{'internal.contentchange'};
                   10898:         }
                   10899:         my $cachetime = 600;
                   10900:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10901:     }
                   10902:     return $change;
                   10903: }
                   10904: 
                   10905: sub devalidate_coursechange_cache {
                   10906:     my ($cnum,$cdom)=@_;
                   10907:     my $hashid=$cnum.':'.$cdom;
                   10908:     &devalidate_cache_new('crschange',$hashid);
                   10909: }
                   10910: 
1.31      www      10911: # ------------------------------------------------- Update symbolic store links
                   10912: 
                   10913: sub symblist {
                   10914:     my ($mapname,%newhash)=@_;
1.438     www      10915:     $mapname=&deversion(&declutter($mapname));
1.31      www      10916:     my %hash;
1.620     albertel 10917:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10918:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10919:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10920: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10921: 		next if ($url eq 'last_known'
                   10922: 			 && $env{'form.no_update_last_known'});
                   10923: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10924: 						    $newhash{$url}->[1],
                   10925: 						    $newhash{$url}->[0]);
1.191     harris41 10926:             }
1.31      www      10927:             if (untie(%hash)) {
                   10928: 		return 'ok';
                   10929:             }
                   10930:         }
                   10931:     }
                   10932:     return 'error';
1.212     www      10933: }
                   10934: 
                   10935: # --------------------------------------------------------------- Verify a symb
                   10936: 
                   10937: sub symbverify {
1.1172.2.11  raeburn  10938:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10939:     my $thisfn=$thisurl;
1.439     www      10940:     $thisfn=&declutter($thisfn);
1.215     www      10941: # direct jump to resource in page or to a sequence - will construct own symbs
                   10942:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10943: # check URL part
1.409     www      10944:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10945: 
1.431     www      10946:     unless ($url eq $thisfn) { return 0; }
1.213     www      10947: 
1.216     www      10948:     $symb=&symbclean($symb);
1.510     www      10949:     $thisurl=&deversion($thisurl);
1.439     www      10950:     $thisfn=&deversion($thisfn);
1.213     www      10951: 
                   10952:     my %bighash;
                   10953:     my $okay=0;
1.431     www      10954: 
1.620     albertel 10955:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10956:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10957:         my $noclutter;
1.1032    raeburn  10958:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10959:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10960:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10961:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10962:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10963:                 $noclutter = 1;
                   10964:             }
                   10965:         }
                   10966:         my $ids;
                   10967:         if ($noclutter) {
                   10968:             $ids=$bighash{'ids_'.$thisurl};
                   10969:         } else {
                   10970:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10971:         }
1.1102    raeburn  10972:         unless ($ids) {
1.1172.2.13  raeburn  10973:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10974:             $ids=$bighash{$idkey};
1.216     www      10975:         }
                   10976:         if ($ids) {
                   10977: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10978:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10979:                 $symb =~ s/\?.+$//;
                   10980:             }
1.800     albertel 10981: 	    foreach my $id (split(/\,/,$ids)) {
                   10982: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10983:                if (
                   10984:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10985:    eq $symb) {
1.1172.2.11  raeburn  10986:                    if (ref($encstate)) {
                   10987:                        $$encstate = $bighash{'encrypted_'.$id};
                   10988:                    }
1.1172.2.13  raeburn  10989:                    if (($env{'request.role.adv'}) ||
                   10990:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10991:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10992:                        $okay=1;
                   10993:                        last;
                   10994:                    }
                   10995:                }
                   10996:            }
1.216     www      10997:         }
1.213     www      10998: 	untie(%bighash);
                   10999:     }
                   11000:     return $okay;
1.31      www      11001: }
                   11002: 
1.210     www      11003: # --------------------------------------------------------------- Clean-up symb
                   11004: 
                   11005: sub symbclean {
                   11006:     my $symb=shift;
1.568     albertel 11007:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11008: # remove version from map
                   11009:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11010: 
1.210     www      11011: # remove version from URL
                   11012:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11013: 
1.507     www      11014: # remove wrapper
                   11015: 
1.510     www      11016:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11017:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11018:     return $symb;
1.409     www      11019: }
                   11020: 
                   11021: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11022: 
                   11023: sub encode_symb {
                   11024:     my ($map,$resid,$url)=@_;
                   11025:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11026: }
1.409     www      11027: 
                   11028: sub decode_symb {
1.568     albertel 11029:     my $symb=shift;
                   11030:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11031:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11032:     return (&fixversion($map),$resid,&fixversion($url));
                   11033: }
                   11034: 
                   11035: sub fixversion {
                   11036:     my $fn=shift;
1.609     banghart 11037:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11038:     my %bighash;
                   11039:     my $uri=&clutter($fn);
1.620     albertel 11040:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11041: # is this cached?
1.599     albertel 11042:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11043:     if (defined($cached)) { return $result; }
                   11044: # unfortunately not cached, or expired
1.620     albertel 11045:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11046: 	    &GDBM_READER(),0640)) {
                   11047:  	if ($bighash{'version_'.$uri}) {
                   11048:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11049:  	    unless (($version eq 'mostrecent') || 
                   11050: 		    ($version==&getversion($uri))) {
1.440     www      11051:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11052:  	    }
                   11053:  	}
                   11054:  	untie %bighash;
1.413     www      11055:     }
1.599     albertel 11056:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11057: }
                   11058: 
                   11059: sub deversion {
                   11060:     my $url=shift;
                   11061:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11062:     return $url;
1.210     www      11063: }
                   11064: 
1.31      www      11065: # ------------------------------------------------------ Return symb list entry
                   11066: 
                   11067: sub symbread {
1.1172.2.66  raeburn  11068:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11069:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11070:     if (defined($env{$cache_str})) {
                   11071:         if ($ignorecachednull) {
                   11072:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11073:         } else {
                   11074:             return $env{$cache_str};
                   11075:         }
                   11076:     }
1.242     www      11077: # no filename provided? try from environment
1.1172.2.54  raeburn  11078:     unless ($thisfn) {
1.620     albertel 11079:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11080:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11081:         }
                   11082:         $thisfn=$env{'request.filename'};
1.44      www      11083:     }
1.569     albertel 11084:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11085: # is that filename actually a symb? Verify, clean, and return
                   11086:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11087: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11088: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11089: 	}
1.242     www      11090:     }
1.44      www      11091:     $thisfn=declutter($thisfn);
1.31      www      11092:     my %hash;
1.37      www      11093:     my %bighash;
                   11094:     my $syval='';
1.620     albertel 11095:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11096:         my $targetfn = $thisfn;
1.609     banghart 11097:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11098:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11099:         }
1.687     albertel 11100: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11101: 	    $targetfn=$1;
                   11102: 	}
1.620     albertel 11103:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11104:                       &GDBM_READER(),0640)) {
1.481     raeburn  11105: 	    $syval=$hash{$targetfn};
1.37      www      11106:             untie(%hash);
                   11107:         }
                   11108: # ---------------------------------------------------------- There was an entry
                   11109:         if ($syval) {
1.601     albertel 11110: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11111: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11112: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11113: 		    #return $env{$cache_str}='';
1.601     albertel 11114: 		#}    
                   11115: 		#$syval.=$1;
                   11116: 	    #}
1.37      www      11117:         } else {
                   11118: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11119:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11120:                             &GDBM_READER(),0640)) {
1.37      www      11121: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11122:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11123:               unless ($ids) { 
                   11124:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11125:               }
                   11126:               unless ($ids) {
                   11127: # alias?
                   11128: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11129:               }
1.37      www      11130:               if ($ids) {
                   11131: # ------------------------------------------------------------------- Has ID(s)
                   11132:                  my @possibilities=split(/\,/,$ids);
1.39      www      11133:                  if ($#possibilities==0) {
                   11134: # ----------------------------------------------- There is only one possibility
1.37      www      11135: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11136: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11137: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11138:                      if (ref($possibles) eq 'HASH') {
                   11139:                          $possibles->{$syval} = 1;
                   11140:                      }
                   11141:                      if ($checkforblock) {
                   11142:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11143:                          if (@blockers) {
                   11144:                              $syval = '';
                   11145:                              return;
                   11146:                          }
                   11147:                      }
                   11148:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11149: # ------------------------------------------ There is more than one possibility
                   11150:                      my $realpossible=0;
1.800     albertel 11151:                      foreach my $id (@possibilities) {
                   11152: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11153:                          my $canaccess;
                   11154:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11155:                              $canaccess = 1;
                   11156:                          } else {
                   11157:                              $canaccess = &allowed('bre',$file);
                   11158:                          }
                   11159:                          if ($canaccess) {
                   11160:          		     my ($mapid,$resid)=split(/\./,$id);
                   11161:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11162:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11163:                                                              $resid,$thisfn);
                   11164:                                  if (ref($possibles) eq 'HASH') {
                   11165:                                      $possibles->{$syval} = 1;
                   11166:                                  }
                   11167:                                  if ($checkforblock) {
                   11168:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11169:                                      unless (@blockers > 0) {
                   11170:                                          $syval = $poss_syval;
                   11171:                                          $realpossible++;
                   11172:                                      }
                   11173:                                  } else {
                   11174:                                      $syval = $poss_syval;
                   11175:                                      $realpossible++;
                   11176:                                  }
                   11177:                              }
1.39      www      11178: 			 }
1.191     harris41 11179:                      }
1.39      www      11180: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11181:                  } else {
                   11182:                      $syval='';
1.37      www      11183:                  }
                   11184: 	      }
1.1172.2.66  raeburn  11185:               untie(%bighash);
1.481     raeburn  11186:            }
1.31      www      11187:         }
1.62      www      11188:         if ($syval) {
1.620     albertel 11189: 	    return $env{$cache_str}=$syval;
1.62      www      11190:         }
1.31      www      11191:     }
1.949     raeburn  11192:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11193:     return $env{$cache_str}='';
1.31      www      11194: }
                   11195: 
                   11196: # ---------------------------------------------------------- Return random seed
                   11197: 
1.32      www      11198: sub numval {
                   11199:     my $txt=shift;
                   11200:     $txt=~tr/A-J/0-9/;
                   11201:     $txt=~tr/a-j/0-9/;
                   11202:     $txt=~tr/K-T/0-9/;
                   11203:     $txt=~tr/k-t/0-9/;
                   11204:     $txt=~tr/U-Z/0-5/;
                   11205:     $txt=~tr/u-z/0-5/;
                   11206:     $txt=~s/\D//g;
1.564     albertel 11207:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11208:     return int($txt);
1.368     albertel 11209: }
                   11210: 
1.484     albertel 11211: sub numval2 {
                   11212:     my $txt=shift;
                   11213:     $txt=~tr/A-J/0-9/;
                   11214:     $txt=~tr/a-j/0-9/;
                   11215:     $txt=~tr/K-T/0-9/;
                   11216:     $txt=~tr/k-t/0-9/;
                   11217:     $txt=~tr/U-Z/0-5/;
                   11218:     $txt=~tr/u-z/0-5/;
                   11219:     $txt=~s/\D//g;
                   11220:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11221:     my $total;
                   11222:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11223:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11224:     return int($total);
                   11225: }
                   11226: 
1.575     albertel 11227: sub numval3 {
                   11228:     use integer;
                   11229:     my $txt=shift;
                   11230:     $txt=~tr/A-J/0-9/;
                   11231:     $txt=~tr/a-j/0-9/;
                   11232:     $txt=~tr/K-T/0-9/;
                   11233:     $txt=~tr/k-t/0-9/;
                   11234:     $txt=~tr/U-Z/0-5/;
                   11235:     $txt=~tr/u-z/0-5/;
                   11236:     $txt=~s/\D//g;
                   11237:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11238:     my $total;
                   11239:     foreach my $val (@txts) { $total+=$val; }
                   11240:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11241:     return $total;
                   11242: }
                   11243: 
1.675     albertel 11244: sub digest {
                   11245:     my ($data)=@_;
                   11246:     my $digest=&Digest::MD5::md5($data);
                   11247:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11248:     my ($e,$f);
                   11249:     {
                   11250:         use integer;
                   11251:         $e=($a+$b);
                   11252:         $f=($c+$d);
                   11253:         if ($_64bit) {
                   11254:             $e=(($e<<32)>>32);
                   11255:             $f=(($f<<32)>>32);
                   11256:         }
                   11257:     }
                   11258:     if (wantarray) {
                   11259: 	return ($e,$f);
                   11260:     } else {
                   11261: 	my $g;
                   11262: 	{
                   11263: 	    use integer;
                   11264: 	    $g=($e+$f);
                   11265: 	    if ($_64bit) {
                   11266: 		$g=(($g<<32)>>32);
                   11267: 	    }
                   11268: 	}
                   11269: 	return $g;
                   11270:     }
                   11271: }
                   11272: 
1.368     albertel 11273: sub latest_rnd_algorithm_id {
1.675     albertel 11274:     return '64bit5';
1.366     albertel 11275: }
1.32      www      11276: 
1.503     albertel 11277: sub get_rand_alg {
                   11278:     my ($courseid)=@_;
1.790     albertel 11279:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11280:     if ($courseid) {
1.620     albertel 11281: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11282:     }
                   11283:     return &latest_rnd_algorithm_id();
                   11284: }
                   11285: 
1.562     albertel 11286: sub validCODE {
                   11287:     my ($CODE)=@_;
                   11288:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11289:     return 0;
                   11290: }
                   11291: 
1.491     albertel 11292: sub getCODE {
1.620     albertel 11293:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11294:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11295: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11296: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11297: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11298:     }
                   11299:     return undef;
                   11300: }
1.1133    foxr     11301: #
                   11302: #  Determines the random seed for a specific context:
                   11303: #
                   11304: # parameters:
                   11305: #   symb      - in course context the symb for the seed.
                   11306: #   course_id - The course id of the form domain_coursenum.
                   11307: #   domain    - Domain for the user.
                   11308: #   course    - Course for the user.
                   11309: #   cenv      - environment of the course.
                   11310: #
                   11311: # NOTE:
                   11312: #   All parameters are picked out of the environment if missing
                   11313: #   or not defined.
                   11314: #   If a symb cannot be determined the current time is used instead.
                   11315: #
                   11316: #  For a given well defined symb, courside, domain, username,
                   11317: #  and course environment, the seed is reproducible.
                   11318: #
1.31      www      11319: sub rndseed {
1.1133    foxr     11320:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11321:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11322:     if (!defined($symb)) {
1.366     albertel 11323: 	unless ($symb=$wsymb) { return time; }
                   11324:     }
1.1146    foxr     11325:     if (!defined $courseid) { 
                   11326: 	$courseid=$wcourseid; 
                   11327:     }
                   11328:     if (!defined $domain) { $domain=$wdomain; }
                   11329:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11330: 
                   11331:     my $which;
                   11332:     if (defined($cenv->{'rndseed'})) {
                   11333: 	$which = $cenv->{'rndseed'};
                   11334:     } else {
                   11335: 	$which =&get_rand_alg($courseid);
                   11336:     }
1.491     albertel 11337:     if (defined(&getCODE())) {
1.675     albertel 11338: 	if ($which eq '64bit5') {
                   11339: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11340: 	} elsif ($which eq '64bit4') {
1.575     albertel 11341: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11342: 	} else {
                   11343: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11344: 	}
1.675     albertel 11345:     } elsif ($which eq '64bit5') {
                   11346: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11347:     } elsif ($which eq '64bit4') {
                   11348: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11349:     } elsif ($which eq '64bit3') {
                   11350: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11351:     } elsif ($which eq '64bit2') {
                   11352: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11353:     } elsif ($which eq '64bit') {
                   11354: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11355:     }
                   11356:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11357: }
                   11358: 
                   11359: sub rndseed_32bit {
                   11360:     my ($symb,$courseid,$domain,$username)=@_;
                   11361:     {
                   11362: 	use integer;
                   11363: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11364: 	my $symbseed=numval($symb) << 22;
                   11365: 	my $namechck=unpack("%32C*",$username) << 17;
                   11366: 	my $nameseed=numval($username) << 12;
                   11367: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11368: 	my $courseseed=unpack("%32C*",$courseid);
                   11369: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11370: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11371: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11372: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11373: 	return $num;
                   11374:     }
                   11375: }
                   11376: 
                   11377: sub rndseed_64bit {
                   11378:     my ($symb,$courseid,$domain,$username)=@_;
                   11379:     {
                   11380: 	use integer;
                   11381: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11382: 	my $symbseed=numval($symb) << 10;
                   11383: 	my $namechck=unpack("%32S*",$username);
                   11384: 	
                   11385: 	my $nameseed=numval($username) << 21;
                   11386: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11387: 	my $courseseed=unpack("%32S*",$courseid);
                   11388: 	
                   11389: 	my $num1=$symbchck+$symbseed+$namechck;
                   11390: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11391: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11392: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11393: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11394: 	return "$num1,$num2";
1.155     albertel 11395:     }
1.366     albertel 11396: }
                   11397: 
1.443     albertel 11398: sub rndseed_64bit2 {
                   11399:     my ($symb,$courseid,$domain,$username)=@_;
                   11400:     {
                   11401: 	use integer;
                   11402: 	# strings need to be an even # of cahracters long, it it is odd the
                   11403:         # last characters gets thrown away
                   11404: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11405: 	my $symbseed=numval($symb) << 10;
                   11406: 	my $namechck=unpack("%32S*",$username.' ');
                   11407: 	
                   11408: 	my $nameseed=numval($username) << 21;
1.501     albertel 11409: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11410: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11411: 	
                   11412: 	my $num1=$symbchck+$symbseed+$namechck;
                   11413: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11414: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11415: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11416: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11417: 	return "$num1,$num2";
                   11418:     }
                   11419: }
                   11420: 
                   11421: sub rndseed_64bit3 {
                   11422:     my ($symb,$courseid,$domain,$username)=@_;
                   11423:     {
                   11424: 	use integer;
                   11425: 	# strings need to be an even # of cahracters long, it it is odd the
                   11426:         # last characters gets thrown away
                   11427: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11428: 	my $symbseed=numval2($symb) << 10;
                   11429: 	my $namechck=unpack("%32S*",$username.' ');
                   11430: 	
                   11431: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11432: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11433: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11434: 	
                   11435: 	my $num1=$symbchck+$symbseed+$namechck;
                   11436: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11437: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11438: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11439: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11440: 	
1.503     albertel 11441: 	return "$num1:$num2";
1.443     albertel 11442:     }
                   11443: }
                   11444: 
1.575     albertel 11445: sub rndseed_64bit4 {
                   11446:     my ($symb,$courseid,$domain,$username)=@_;
                   11447:     {
                   11448: 	use integer;
                   11449: 	# strings need to be an even # of cahracters long, it it is odd the
                   11450:         # last characters gets thrown away
                   11451: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11452: 	my $symbseed=numval3($symb) << 10;
                   11453: 	my $namechck=unpack("%32S*",$username.' ');
                   11454: 	
                   11455: 	my $nameseed=numval3($username) << 21;
                   11456: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11457: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11458: 	
                   11459: 	my $num1=$symbchck+$symbseed+$namechck;
                   11460: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11461: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11462: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11463: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11464: 	
1.575     albertel 11465: 	return "$num1:$num2";
                   11466:     }
                   11467: }
                   11468: 
1.675     albertel 11469: sub rndseed_64bit5 {
                   11470:     my ($symb,$courseid,$domain,$username)=@_;
                   11471:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11472:     return "$num1:$num2";
                   11473: }
                   11474: 
1.366     albertel 11475: sub rndseed_CODE_64bit {
                   11476:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11477:     {
1.366     albertel 11478: 	use integer;
1.443     albertel 11479: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11480: 	my $symbseed=numval2($symb);
1.491     albertel 11481: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11482: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11483: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11484: 	my $num1=$symbseed+$CODEchck;
                   11485: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11486: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11487: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11488: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11489: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11490: 	return "$num1:$num2";
1.366     albertel 11491:     }
                   11492: }
                   11493: 
1.575     albertel 11494: sub rndseed_CODE_64bit4 {
                   11495:     my ($symb,$courseid,$domain,$username)=@_;
                   11496:     {
                   11497: 	use integer;
                   11498: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11499: 	my $symbseed=numval3($symb);
                   11500: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11501: 	my $CODEseed=numval3(&getCODE());
                   11502: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11503: 	my $num1=$symbseed+$CODEchck;
                   11504: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11505: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11506: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11507: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11508: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11509: 	return "$num1:$num2";
                   11510:     }
                   11511: }
                   11512: 
1.675     albertel 11513: sub rndseed_CODE_64bit5 {
                   11514:     my ($symb,$courseid,$domain,$username)=@_;
                   11515:     my $code = &getCODE();
                   11516:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11517:     return "$num1:$num2";
                   11518: }
                   11519: 
1.366     albertel 11520: sub setup_random_from_rndseed {
                   11521:     my ($rndseed)=@_;
1.503     albertel 11522:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  11523: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11524:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11525:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11526:         } else {
                   11527:             &Math::Random::random_set_seed($num1,$num2);
                   11528:         }
1.366     albertel 11529:     } else {
                   11530: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11531:     }
1.36      albertel 11532: }
                   11533: 
1.474     albertel 11534: sub latest_receipt_algorithm_id {
1.835     albertel 11535:     return 'receipt3';
1.474     albertel 11536: }
                   11537: 
1.480     www      11538: sub recunique {
                   11539:     my $fucourseid=shift;
                   11540:     my $unique;
1.835     albertel 11541:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11542: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11543: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11544:     } else {
                   11545: 	$unique=$perlvar{'lonReceipt'};
                   11546:     }
                   11547:     return unpack("%32C*",$unique);
                   11548: }
                   11549: 
                   11550: sub recprefix {
                   11551:     my $fucourseid=shift;
                   11552:     my $prefix;
1.835     albertel 11553:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11554: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11555: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11556:     } else {
                   11557: 	$prefix=$perlvar{'lonHostID'};
                   11558:     }
                   11559:     return unpack("%32C*",$prefix);
                   11560: }
                   11561: 
1.76      www      11562: sub ireceipt {
1.474     albertel 11563:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11564: 
                   11565:     my $return =&recprefix($fucourseid).'-';
                   11566: 
                   11567:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11568: 	$env{'request.state'} eq 'construct') {
                   11569: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11570: 	return $return;
                   11571:     }
                   11572: 
1.76      www      11573:     my $cuname=unpack("%32C*",$funame);
                   11574:     my $cudom=unpack("%32C*",$fudom);
                   11575:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11576:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11577:     my $cunique=&recunique($fucourseid);
1.474     albertel 11578:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11579:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11580: 
1.790     albertel 11581: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11582: 			       
                   11583: 	$return.= ($cunique%$cuname+
                   11584: 		   $cunique%$cudom+
                   11585: 		   $cusymb%$cuname+
                   11586: 		   $cusymb%$cudom+
                   11587: 		   $cucourseid%$cuname+
                   11588: 		   $cucourseid%$cudom+
                   11589: 		   $cpart%$cuname+
                   11590: 		   $cpart%$cudom);
                   11591:     } else {
                   11592: 	$return.= ($cunique%$cuname+
                   11593: 		   $cunique%$cudom+
                   11594: 		   $cusymb%$cuname+
                   11595: 		   $cusymb%$cudom+
                   11596: 		   $cucourseid%$cuname+
                   11597: 		   $cucourseid%$cudom);
                   11598:     }
                   11599:     return $return;
1.76      www      11600: }
                   11601: 
                   11602: sub receipt {
1.474     albertel 11603:     my ($part)=@_;
1.790     albertel 11604:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11605:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11606: }
1.260     ng       11607: 
1.790     albertel 11608: sub whichuser {
                   11609:     my ($passedsymb)=@_;
                   11610:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11611:     if (defined($env{'form.grade_symb'})) {
                   11612: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11613: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11614: 	if (!$allowed &&
                   11615: 	    exists($env{'request.course.sec'}) &&
                   11616: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11617: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11618: 			      '/'.$env{'request.course.sec'});
                   11619: 	}
                   11620: 	if ($allowed) {
                   11621: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11622: 	    $courseid=$tmp_courseid;
                   11623: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11624: 	    ($name)=&get_env_multiple('form.grade_username');
                   11625: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11626: 	}
                   11627:     }
                   11628:     if (!$passedsymb) {
                   11629: 	$symb=&symbread();
                   11630:     } else {
                   11631: 	$symb=$passedsymb;
                   11632:     }
                   11633:     $courseid=$env{'request.course.id'};
                   11634:     $domain=$env{'user.domain'};
                   11635:     $name=$env{'user.name'};
                   11636:     if ($name eq 'public' && $domain eq 'public') {
                   11637: 	if (!defined($env{'form.username'})) {
                   11638: 	    $env{'form.username'}.=time.rand(10000000);
                   11639: 	}
                   11640: 	$name.=$env{'form.username'};
                   11641:     }
                   11642:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11643: 
                   11644: }
                   11645: 
1.36      albertel 11646: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11647: # returns either the contents of the file or 
                   11648: # -1 if the file doesn't exist
1.481     raeburn  11649: #
                   11650: # if the target is a file that was uploaded via DOCS, 
                   11651: # a check will be made to see if a current copy exists on the local server,
                   11652: # if it does this will be served, otherwise a copy will be retrieved from
                   11653: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11654: # the local server.   
1.472     albertel 11655: 
1.36      albertel 11656: sub getfile {
1.538     albertel 11657:     my ($file) = @_;
1.609     banghart 11658:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11659:     &repcopy($file);
                   11660:     return &readfile($file);
                   11661: }
                   11662: 
                   11663: sub repcopy_userfile {
                   11664:     my ($file)=@_;
1.1142    raeburn  11665:     my $londocroot = $perlvar{'lonDocRoot'};
                   11666:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11667:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11668:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11669: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11670:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11671:     if (-e "$file") {
1.828     www      11672: # we already have a local copy, check it out
1.538     albertel 11673: 	my @fileinfo = stat($file);
1.828     www      11674: 	my $rtncode;
                   11675: 	my $info;
1.538     albertel 11676: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11677: 	if ($lwpresp ne 'ok') {
1.828     www      11678: # there is no such file anymore, even though we had a local copy
1.482     albertel 11679: 	    if ($rtncode eq '404') {
1.538     albertel 11680: 		unlink($file);
1.482     albertel 11681: 	    }
                   11682: 	    return -1;
                   11683: 	}
                   11684: 	if ($info < $fileinfo[9]) {
1.828     www      11685: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11686: 	    return 'ok';
1.828     www      11687: 	} else {
                   11688: # the file is outdated, get rid of it
                   11689: 	    unlink($file);
1.482     albertel 11690: 	}
1.828     www      11691:     }
                   11692: # one way or the other, at this point, we don't have the file
                   11693: # construct the correct path for the file
                   11694:     my @parts = ($cdom,$cnum); 
                   11695:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11696: 	push @parts, split(/\//,$1);
                   11697:     }
                   11698:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11699:     foreach my $part (@parts) {
                   11700: 	$path .= '/'.$part;
                   11701: 	if (!-e $path) {
                   11702: 	    mkdir($path,0770);
1.482     albertel 11703: 	}
                   11704:     }
1.828     www      11705: # now the path exists for sure
                   11706: # get a user agent
                   11707:     my $ua=new LWP::UserAgent;
                   11708:     my $transferfile=$file.'.in.transfer';
                   11709: # FIXME: this should flock
                   11710:     if (-e $transferfile) { return 'ok'; }
                   11711:     my $request;
                   11712:     $uri=~s/^\///;
1.980     raeburn  11713:     my $homeserver = &homeserver($cnum,$cdom);
                   11714:     my $protocol = $protocol{$homeserver};
                   11715:     $protocol = 'http' if ($protocol ne 'https');
                   11716:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11717:     my $response=$ua->request($request,$transferfile);
                   11718: # did it work?
                   11719:     if ($response->is_error()) {
                   11720: 	unlink($transferfile);
                   11721: 	&logthis("Userfile repcopy failed for $uri");
                   11722: 	return -1;
                   11723:     }
                   11724: # worked, rename the transfer file
                   11725:     rename($transferfile,$file);
1.607     raeburn  11726:     return 'ok';
1.481     raeburn  11727: }
                   11728: 
1.517     albertel 11729: sub tokenwrapper {
                   11730:     my $uri=shift;
1.980     raeburn  11731:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11732:     $uri=~s|^/||;
1.620     albertel 11733:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11734:     my $token=$1;
1.552     albertel 11735:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11736:     if ($udom && $uname && $file) {
                   11737: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11738:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11739:         my $homeserver = &homeserver($uname,$udom);
                   11740:         my $protocol = $protocol{$homeserver};
                   11741:         $protocol = 'http' if ($protocol ne 'https');
                   11742:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11743:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11744:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11745:     } else {
                   11746:         return '/adm/notfound.html';
                   11747:     }
                   11748: }
                   11749: 
1.828     www      11750: # call with reqtype HEAD: get last modification time
                   11751: # call with reqtype GET: get the file contents
                   11752: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11753: #
1.481     raeburn  11754: sub getuploaded {
                   11755:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11756:     $uri=~s/^\///;
1.980     raeburn  11757:     my $homeserver = &homeserver($cnum,$cdom);
                   11758:     my $protocol = $protocol{$homeserver};
                   11759:     $protocol = 'http' if ($protocol ne 'https');
                   11760:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11761:     my $ua=new LWP::UserAgent;
                   11762:     my $request=new HTTP::Request($reqtype,$uri);
                   11763:     my $response=$ua->request($request);
                   11764:     $$rtncode = $response->code;
1.482     albertel 11765:     if (! $response->is_success()) {
                   11766: 	return 'failed';
                   11767:     }      
                   11768:     if ($reqtype eq 'HEAD') {
1.486     www      11769: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11770:     } elsif ($reqtype eq 'GET') {
                   11771: 	$$info = $response->content;
1.472     albertel 11772:     }
1.482     albertel 11773:     return 'ok';
1.36      albertel 11774: }
                   11775: 
1.481     raeburn  11776: sub readfile {
                   11777:     my $file = shift;
                   11778:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11779:     my $fh;
                   11780:     open($fh,"<$file");
                   11781:     my $a='';
1.800     albertel 11782:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11783:     return $a;
                   11784: }
                   11785: 
1.36      albertel 11786: sub filelocation {
1.590     banghart 11787:     my ($dir,$file) = @_;
                   11788:     my $location;
                   11789:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11790: 
                   11791:     if ($file =~ m-^/adm/-) {
                   11792: 	$file=~s-^/adm/wrapper/-/-;
                   11793: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11794:     }
1.882     albertel 11795: 
1.1139    www      11796:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11797:         $location = $file;
1.609     banghart 11798:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11799:         my ($udom,$uname,$filename)=
1.811     albertel 11800:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11801:         my $home=&homeserver($uname,$udom);
                   11802:         my $is_me=0;
                   11803:         my @ids=&current_machine_ids();
                   11804:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11805:         if ($is_me) {
1.1117    foxr     11806:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11807:         } else {
                   11808:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11809:   	      $udom.'/'.$uname.'/'.$filename;
                   11810:         }
1.882     albertel 11811:     } elsif ($file =~ m-^/adm/-) {
                   11812: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11813:     } else {
                   11814:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11815:         $file=~s:^/(res|priv)/:/:;
                   11816:         my $space=$1;
1.590     banghart 11817:         if ( !( $file =~ m:^/:) ) {
                   11818:             $location = $dir. '/'.$file;
                   11819:         } else {
1.1142    raeburn  11820:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11821:         }
1.59      albertel 11822:     }
1.590     banghart 11823:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11824:     while ($location=~m{/\.\./}) {
                   11825: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11826: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11827: 	} else {
                   11828: 	    $location=~ s{/\.\./}{/}g;
                   11829: 	}
                   11830:     } #remove dir/..
1.590     banghart 11831:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11832:     return $location;
1.46      www      11833: }
1.36      albertel 11834: 
1.46      www      11835: sub hreflocation {
                   11836:     my ($dir,$file)=@_;
1.980     raeburn  11837:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11838: 	$file=filelocation($dir,$file);
1.700     albertel 11839:     } elsif ($file=~m-^/adm/-) {
                   11840: 	$file=~s-^/adm/wrapper/-/-;
                   11841: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11842:     }
                   11843:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11844: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11845:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11846: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11847: 	        {/uploaded/$1/$2/}x;
1.46      www      11848:     }
1.913     albertel 11849:     if ($file=~ m{^/userfiles/}) {
                   11850: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11851:     }
1.462     albertel 11852:     return $file;
1.465     albertel 11853: }
                   11854: 
1.1139    www      11855: 
                   11856: 
                   11857: 
                   11858: 
1.465     albertel 11859: sub current_machine_domains {
1.853     albertel 11860:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11861: }
                   11862: 
                   11863: sub machine_domains {
                   11864:     my ($hostname) = @_;
1.465     albertel 11865:     my @domains;
1.838     albertel 11866:     my %hostname = &all_hostnames();
1.465     albertel 11867:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11868: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11869: 	if ($hostname eq $name) {
1.844     albertel 11870: 	    push(@domains,&host_domain($id));
1.465     albertel 11871: 	}
                   11872:     }
                   11873:     return @domains;
                   11874: }
                   11875: 
                   11876: sub current_machine_ids {
1.853     albertel 11877:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11878: }
                   11879: 
                   11880: sub machine_ids {
                   11881:     my ($hostname) = @_;
                   11882:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11883:     my @ids;
1.888     albertel 11884:     my %name_to_host = &all_names();
1.889     albertel 11885:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11886: 	return @{ $name_to_host{$hostname} };
                   11887:     }
                   11888:     return;
1.31      www      11889: }
                   11890: 
1.824     raeburn  11891: sub additional_machine_domains {
                   11892:     my @domains;
                   11893:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11894:     while( my $line = <$fh>) {
                   11895:         $line =~ s/\s//g;
                   11896:         push(@domains,$line);
                   11897:     }
                   11898:     return @domains;
                   11899: }
                   11900: 
                   11901: sub default_login_domain {
                   11902:     my $domain = $perlvar{'lonDefDomain'};
                   11903:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11904:     foreach my $posdom (&current_machine_domains(),
                   11905:                         &additional_machine_domains()) {
                   11906:         if (lc($posdom) eq lc($testdomain)) {
                   11907:             $domain=$posdom;
                   11908:             last;
                   11909:         }
                   11910:     }
                   11911:     return $domain;
                   11912: }
                   11913: 
1.31      www      11914: # ------------------------------------------------------------- Declutters URLs
                   11915: 
                   11916: sub declutter {
                   11917:     my $thisfn=shift;
1.569     albertel 11918:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  11919:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   11920:         $thisfn=~s{^/home/httpd/html}{};
                   11921:     }
1.31      www      11922:     $thisfn=~s/^\///;
1.697     albertel 11923:     $thisfn=~s|^adm/wrapper/||;
                   11924:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11925:     $thisfn=~s/^res\///;
1.1172    bisitz   11926:     $thisfn=~s/^priv\///;
1.1032    raeburn  11927:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11928:         $thisfn=~s/\?.+$//;
                   11929:     }
1.268     www      11930:     return $thisfn;
                   11931: }
                   11932: 
                   11933: # ------------------------------------------------------------- Clutter up URLs
                   11934: 
                   11935: sub clutter {
                   11936:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11937:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11938: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11939:        $thisfn='/res'.$thisfn; 
                   11940:     }
1.1031    raeburn  11941:     if ($thisfn !~m|^/adm|) {
                   11942: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11943: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11944: 	} else {
                   11945: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11946: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11947: 	    if ($embstyle eq 'ssi'
                   11948: 		|| ($embstyle eq 'hdn')
                   11949: 		|| ($embstyle eq 'rat')
                   11950: 		|| ($embstyle eq 'prv')
                   11951: 		|| ($embstyle eq 'ign')) {
                   11952: 		#do nothing with these
                   11953: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11954: 		|| ($embstyle eq 'emb')
                   11955: 		|| ($embstyle eq 'wrp')) {
                   11956: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11957: 	    } elsif ($embstyle eq 'unk'
                   11958: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11959: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11960: 	    } else {
1.718     www      11961: #		&logthis("Got a blank emb style");
1.695     albertel 11962: 	    }
1.694     albertel 11963: 	}
                   11964:     }
1.31      www      11965:     return $thisfn;
1.12      www      11966: }
                   11967: 
1.787     albertel 11968: sub clutter_with_no_wrapper {
                   11969:     my $uri = &clutter(shift);
                   11970:     if ($uri =~ m-^/adm/-) {
                   11971: 	$uri =~ s-^/adm/wrapper/-/-;
                   11972: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11973:     }
                   11974:     return $uri;
                   11975: }
                   11976: 
1.557     albertel 11977: sub freeze_escape {
                   11978:     my ($value)=@_;
                   11979:     if (ref($value)) {
                   11980: 	$value=&nfreeze($value);
                   11981: 	return '__FROZEN__'.&escape($value);
                   11982:     }
                   11983:     return &escape($value);
                   11984: }
                   11985: 
1.11      www      11986: 
1.557     albertel 11987: sub thaw_unescape {
                   11988:     my ($value)=@_;
                   11989:     if ($value =~ /^__FROZEN__/) {
                   11990: 	substr($value,0,10,undef);
                   11991: 	$value=&unescape($value);
                   11992: 	return &thaw($value);
                   11993:     }
                   11994:     return &unescape($value);
                   11995: }
                   11996: 
1.436     albertel 11997: sub correct_line_ends {
                   11998:     my ($result)=@_;
                   11999:     $$result =~s/\r\n/\n/mg;
                   12000:     $$result =~s/\r/\n/mg;
1.415     albertel 12001: }
1.1       albertel 12002: # ================================================================ Main Program
                   12003: 
1.184     www      12004: sub goodbye {
1.204     albertel 12005:    &logthis("Starting Shut down");
1.443     albertel 12006: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12007:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12008: #converted
1.599     albertel 12009: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12010:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12011: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12012: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12013: #1.1 only
1.870     albertel 12014: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12015: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12016: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12017: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12018:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12019:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12020:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12021:    &flushcourselogs();
                   12022:    &logthis("Shutting down");
                   12023: }
                   12024: 
1.852     albertel 12025: sub get_dns {
1.1172.2.17  raeburn  12026:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12027:     if (!$ignore_cache) {
                   12028: 	my ($content,$cached)=
                   12029: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12030: 	if ($cached) {
1.1172.2.17  raeburn  12031: 	    &$func($content,$hashref);
1.869     albertel 12032: 	    return;
                   12033: 	}
                   12034:     }
                   12035: 
                   12036:     my %alldns;
1.852     albertel 12037:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12038:     foreach my $dns (<$config>) {
                   12039: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12040:         my $line = $1;
                   12041:         my ($host,$protocol) = split(/:/,$line);
                   12042:         if ($protocol ne 'https') {
                   12043:             $protocol = 'http';
                   12044:         }
                   12045: 	$alldns{$host} = $protocol;
1.869     albertel 12046:     }
                   12047:     while (%alldns) {
1.1172.2.52  raeburn  12048: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12049: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12050:         $ua->timeout(30);
1.979     raeburn  12051: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12052: 	my $response=$ua->request($request);
1.979     raeburn  12053:         delete($alldns{$dns});
1.852     albertel 12054: 	next if ($response->is_error());
                   12055: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12056:         unless ($nocache) {
1.1172.2.23  raeburn  12057: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12058:         }
                   12059: 	&$func(\@content,$hashref);
1.869     albertel 12060: 	return;
1.852     albertel 12061:     }
                   12062:     close($config);
1.871     albertel 12063:     my $which = (split('/',$url))[3];
                   12064:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12065:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12066:     my @content = <$config>;
1.1172.2.17  raeburn  12067:     &$func(\@content,$hashref);
                   12068:     return;
                   12069: }
                   12070: 
                   12071: # ------------------------------------------------------Get DNS checksums file
                   12072: sub parse_dns_checksums_tab {
                   12073:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12074:     my $lonhost = $perlvar{'lonHostID'};
                   12075:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12076:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12077:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12078:     my $webconfdir = '/etc/httpd/conf';
                   12079:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12080:         $webconfdir = '/etc/apache2';
                   12081:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12082:         if ($1 >= 10) {
                   12083:             $webconfdir = '/etc/apache2';
                   12084:         }
                   12085:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12086:         if ($1 >= 10.0) {
                   12087:             $webconfdir = '/etc/apache2';
                   12088:         }
                   12089:     }
1.1172.2.17  raeburn  12090:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12091:     my (%chksum,%revnum);
                   12092:     if (ref($lines) eq 'ARRAY') {
                   12093:         chomp(@{$lines});
1.1172.2.34  raeburn  12094:         my $version = shift(@{$lines});
                   12095:         if ($version eq $release) {
1.1172.2.17  raeburn  12096:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12097:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12098:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12099:                     if ($webconfdir eq '/etc/apache2') {
                   12100:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12101:                     }
                   12102:                 }
1.1172.2.34  raeburn  12103:                 $chksum{$file} = $shasum;
                   12104:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12105:             }
                   12106:             if (ref($hashref) eq 'HASH') {
                   12107:                 %{$hashref} = (
                   12108:                                 sums     => \%chksum,
                   12109:                                 versions => \%revnum,
                   12110:                               );
                   12111:             }
                   12112:         }
                   12113:     }
1.869     albertel 12114:     return;
1.852     albertel 12115: }
1.1172.2.17  raeburn  12116: 
                   12117: sub fetch_dns_checksums {
                   12118:     my %checksums;
1.1172.2.34  raeburn  12119:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12120:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12121:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12122:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12123:              \%checksums);
                   12124:     return \%checksums;
                   12125: }
                   12126: 
1.327     albertel 12127: # ------------------------------------------------------------ Read domain file
                   12128: {
1.852     albertel 12129:     my $loaded;
1.846     albertel 12130:     my %domain;
                   12131: 
1.852     albertel 12132:     sub parse_domain_tab {
                   12133: 	my ($lines) = @_;
                   12134: 	foreach my $line (@$lines) {
                   12135: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12136: 
1.846     albertel 12137: 	    chomp($line);
1.852     albertel 12138: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12139: 	    my %this_domain;
                   12140: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12141: 			       'lang_def', 'city', 'longi', 'lati',
                   12142: 			       'primary') {
                   12143: 		$this_domain{$field} = shift(@elements);
                   12144: 	    }
                   12145: 	    $domain{$name} = \%this_domain;
1.852     albertel 12146: 	}
                   12147:     }
1.864     albertel 12148: 
                   12149:     sub reset_domain_info {
                   12150: 	undef($loaded);
                   12151: 	undef(%domain);
                   12152:     }
                   12153: 
1.852     albertel 12154:     sub load_domain_tab {
1.869     albertel 12155: 	my ($ignore_cache) = @_;
                   12156: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 12157: 	my $fh;
                   12158: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12159: 	    my @lines = <$fh>;
                   12160: 	    &parse_domain_tab(\@lines);
1.448     albertel 12161: 	}
1.852     albertel 12162: 	close($fh);
                   12163: 	$loaded = 1;
1.327     albertel 12164:     }
1.846     albertel 12165: 
                   12166:     sub domain {
1.852     albertel 12167: 	&load_domain_tab() if (!$loaded);
                   12168: 
1.846     albertel 12169: 	my ($name,$what) = @_;
                   12170: 	return if ( !exists($domain{$name}) );
                   12171: 
                   12172: 	if (!$what) {
                   12173: 	    return $domain{$name}{'description'};
                   12174: 	}
                   12175: 	return $domain{$name}{$what};
                   12176:     }
1.974     raeburn  12177: 
                   12178:     sub domain_info {
                   12179:         &load_domain_tab() if (!$loaded);
                   12180:         return %domain;
                   12181:     }
                   12182: 
1.327     albertel 12183: }
                   12184: 
                   12185: 
1.1       albertel 12186: # ------------------------------------------------------------- Read hosts file
                   12187: {
1.838     albertel 12188:     my %hostname;
1.844     albertel 12189:     my %hostdom;
1.845     albertel 12190:     my %libserv;
1.852     albertel 12191:     my $loaded;
1.888     albertel 12192:     my %name_to_host;
1.1074    raeburn  12193:     my %internetdom;
1.1107    raeburn  12194:     my %LC_dns_serv;
1.852     albertel 12195: 
                   12196:     sub parse_hosts_tab {
                   12197: 	my ($file) = @_;
                   12198: 	foreach my $configline (@$file) {
                   12199: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12200:             chomp($configline);
                   12201: 	    if ($configline =~ /^\^/) {
                   12202:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12203:                     $LC_dns_serv{$1} = 1;
                   12204:                 }
                   12205:                 next;
                   12206:             }
1.1074    raeburn  12207: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12208: 	    $name=~s/\s//g;
                   12209: 	    if ($id && $domain && $role && $name) {
                   12210: 		$hostname{$id}=$name;
1.888     albertel 12211: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12212: 		$hostdom{$id}=$domain;
                   12213: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12214:                 if (defined($protocol)) {
                   12215:                     if ($protocol eq 'https') {
                   12216:                         $protocol{$id} = $protocol;
                   12217:                     } else {
                   12218:                         $protocol{$id} = 'http'; 
                   12219:                     }
1.968     raeburn  12220:                 } else {
1.969     raeburn  12221:                     $protocol{$id} = 'http';
1.968     raeburn  12222:                 }
1.1074    raeburn  12223:                 if (defined($intdom)) {
                   12224:                     $internetdom{$id} = $intdom;
                   12225:                 }
1.852     albertel 12226: 	    }
                   12227: 	}
                   12228:     }
1.864     albertel 12229:     
                   12230:     sub reset_hosts_info {
1.897     albertel 12231: 	&purge_remembered();
1.864     albertel 12232: 	&reset_domain_info();
                   12233: 	&reset_hosts_ip_info();
1.892     albertel 12234: 	undef(%name_to_host);
1.864     albertel 12235: 	undef(%hostname);
                   12236: 	undef(%hostdom);
                   12237: 	undef(%libserv);
                   12238: 	undef($loaded);
                   12239:     }
1.1       albertel 12240: 
1.852     albertel 12241:     sub load_hosts_tab {
1.869     albertel 12242: 	my ($ignore_cache) = @_;
                   12243: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 12244: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12245: 	my @config = <$config>;
                   12246: 	&parse_hosts_tab(\@config);
                   12247: 	close($config);
                   12248: 	$loaded=1;
1.1       albertel 12249:     }
1.852     albertel 12250: 
1.838     albertel 12251:     sub hostname {
1.852     albertel 12252: 	&load_hosts_tab() if (!$loaded);
                   12253: 
1.838     albertel 12254: 	my ($lonid) = @_;
                   12255: 	return $hostname{$lonid};
                   12256:     }
1.845     albertel 12257: 
1.838     albertel 12258:     sub all_hostnames {
1.852     albertel 12259: 	&load_hosts_tab() if (!$loaded);
                   12260: 
1.838     albertel 12261: 	return %hostname;
                   12262:     }
1.845     albertel 12263: 
1.888     albertel 12264:     sub all_names {
                   12265: 	&load_hosts_tab() if (!$loaded);
                   12266: 
                   12267: 	return %name_to_host;
                   12268:     }
                   12269: 
1.974     raeburn  12270:     sub all_host_domain {
                   12271:         &load_hosts_tab() if (!$loaded);
                   12272:         return %hostdom;
                   12273:     }
                   12274: 
1.845     albertel 12275:     sub is_library {
1.852     albertel 12276: 	&load_hosts_tab() if (!$loaded);
                   12277: 
1.845     albertel 12278: 	return exists($libserv{$_[0]});
                   12279:     }
                   12280: 
                   12281:     sub all_library {
1.852     albertel 12282: 	&load_hosts_tab() if (!$loaded);
                   12283: 
1.845     albertel 12284: 	return %libserv;
                   12285:     }
                   12286: 
1.1062    droeschl 12287:     sub unique_library {
                   12288: 	#2x reverse removes all hostnames that appear more than once
                   12289:         my %unique = reverse &all_library();
                   12290:         return reverse %unique;
                   12291:     }
                   12292: 
1.841     albertel 12293:     sub get_servers {
1.852     albertel 12294: 	&load_hosts_tab() if (!$loaded);
                   12295: 
1.841     albertel 12296: 	my ($domain,$type) = @_;
                   12297: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12298: 	                                          : %hostname;
                   12299: 	my %result;
1.842     albertel 12300: 	if (ref($domain) eq 'ARRAY') {
                   12301: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12302: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12303: 		    $result{$host} = $hostname;
                   12304: 		}
                   12305: 	    }
                   12306: 	} else {
                   12307: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12308: 		if ($hostdom{$host} eq $domain) {
                   12309: 		    $result{$host} = $hostname;
                   12310: 		}
1.841     albertel 12311: 	    }
                   12312: 	}
                   12313: 	return %result;
                   12314:     }
1.845     albertel 12315: 
1.1062    droeschl 12316:     sub get_unique_servers {
                   12317:         my %unique = reverse &get_servers(@_);
                   12318: 	return reverse %unique;
                   12319:     }
                   12320: 
1.844     albertel 12321:     sub host_domain {
1.852     albertel 12322: 	&load_hosts_tab() if (!$loaded);
                   12323: 
1.844     albertel 12324: 	my ($lonid) = @_;
                   12325: 	return $hostdom{$lonid};
                   12326:     }
                   12327: 
1.841     albertel 12328:     sub all_domains {
1.852     albertel 12329: 	&load_hosts_tab() if (!$loaded);
                   12330: 
1.841     albertel 12331: 	my %seen;
                   12332: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12333: 	return @uniq;
                   12334:     }
1.1074    raeburn  12335: 
                   12336:     sub internet_dom {
                   12337:         &load_hosts_tab() if (!$loaded);
                   12338: 
                   12339:         my ($lonid) = @_;
                   12340:         return $internetdom{$lonid};
                   12341:     }
1.1107    raeburn  12342: 
                   12343:     sub is_LC_dns {
                   12344:         &load_hosts_tab() if (!$loaded);
                   12345: 
                   12346:         my ($hostname) = @_;
                   12347:         return exists($LC_dns_serv{$hostname});
                   12348:     }
                   12349: 
1.1       albertel 12350: }
                   12351: 
1.847     albertel 12352: { 
                   12353:     my %iphost;
1.856     albertel 12354:     my %name_to_ip;
                   12355:     my %lonid_to_ip;
1.869     albertel 12356: 
1.847     albertel 12357:     sub get_hosts_from_ip {
                   12358: 	my ($ip) = @_;
                   12359: 	my %iphosts = &get_iphost();
                   12360: 	if (ref($iphosts{$ip})) {
                   12361: 	    return @{$iphosts{$ip}};
                   12362: 	}
                   12363: 	return;
1.839     albertel 12364:     }
1.864     albertel 12365:     
                   12366:     sub reset_hosts_ip_info {
                   12367: 	undef(%iphost);
                   12368: 	undef(%name_to_ip);
                   12369: 	undef(%lonid_to_ip);
                   12370:     }
1.856     albertel 12371: 
                   12372:     sub get_host_ip {
                   12373: 	my ($lonid) = @_;
                   12374: 	if (exists($lonid_to_ip{$lonid})) {
                   12375: 	    return $lonid_to_ip{$lonid};
                   12376: 	}
                   12377: 	my $name=&hostname($lonid);
                   12378:    	my $ip = gethostbyname($name);
                   12379: 	return if (!$ip || length($ip) ne 4);
                   12380: 	$ip=inet_ntoa($ip);
                   12381: 	$name_to_ip{$name}   = $ip;
                   12382: 	$lonid_to_ip{$lonid} = $ip;
                   12383: 	return $ip;
                   12384:     }
1.847     albertel 12385:     
                   12386:     sub get_iphost {
1.869     albertel 12387: 	my ($ignore_cache) = @_;
1.894     albertel 12388: 
1.869     albertel 12389: 	if (!$ignore_cache) {
                   12390: 	    if (%iphost) {
                   12391: 		return %iphost;
                   12392: 	    }
                   12393: 	    my ($ip_info,$cached)=
                   12394: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12395: 	    if ($cached) {
                   12396: 		%iphost      = %{$ip_info->[0]};
                   12397: 		%name_to_ip  = %{$ip_info->[1]};
                   12398: 		%lonid_to_ip = %{$ip_info->[2]};
                   12399: 		return %iphost;
                   12400: 	    }
                   12401: 	}
1.894     albertel 12402: 
                   12403: 	# get yesterday's info for fallback
                   12404: 	my %old_name_to_ip;
                   12405: 	my ($ip_info,$cached)=
                   12406: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12407: 	if ($cached) {
                   12408: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12409: 	}
                   12410: 
1.888     albertel 12411: 	my %name_to_host = &all_names();
                   12412: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12413: 	    my $ip;
                   12414: 	    if (!exists($name_to_ip{$name})) {
                   12415: 		$ip = gethostbyname($name);
                   12416: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12417: 		    if (defined($old_name_to_ip{$name})) {
                   12418: 			$ip = $old_name_to_ip{$name};
                   12419: 			&logthis("Can't find $name defaulting to old $ip");
                   12420: 		    } else {
                   12421: 			&logthis("Name $name no IP found");
                   12422: 			next;
                   12423: 		    }
                   12424: 		} else {
                   12425: 		    $ip=inet_ntoa($ip);
1.847     albertel 12426: 		}
                   12427: 		$name_to_ip{$name} = $ip;
                   12428: 	    } else {
                   12429: 		$ip = $name_to_ip{$name};
1.653     albertel 12430: 	    }
1.888     albertel 12431: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12432: 		$lonid_to_ip{$id} = $ip;
                   12433: 	    }
                   12434: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12435: 	}
1.1172.2.23  raeburn  12436: 	&do_cache_new('iphost','iphost',
                   12437: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12438: 		      48*60*60);
1.869     albertel 12439: 
1.847     albertel 12440: 	return %iphost;
1.598     albertel 12441:     }
                   12442: 
1.992     raeburn  12443:     #
                   12444:     #  Given a DNS returns the loncapa host name for that DNS 
                   12445:     # 
                   12446:     sub host_from_dns {
                   12447:         my ($dns) = @_;
                   12448:         my @hosts;
                   12449:         my $ip;
                   12450: 
1.993     raeburn  12451:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12452:             $ip = $name_to_ip{$dns};
                   12453:         }
                   12454:         if (!$ip) {
                   12455:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12456:             if (length($ip) == 4) { 
                   12457: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12458:             }
                   12459:         }
                   12460:         if ($ip) {
                   12461: 	    @hosts = get_hosts_from_ip($ip);
                   12462: 	    return $hosts[0];
                   12463:         }
                   12464:         return undef;
1.986     foxr     12465:     }
1.992     raeburn  12466: 
1.1074    raeburn  12467:     sub get_internet_names {
                   12468:         my ($lonid) = @_;
                   12469:         return if ($lonid eq '');
                   12470:         my ($idnref,$cached)=
                   12471:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12472:         if ($cached) {
                   12473:             return $idnref;
                   12474:         }
                   12475:         my $ip = &get_host_ip($lonid);
                   12476:         my @hosts = &get_hosts_from_ip($ip);
                   12477:         my %iphost = &get_iphost();
                   12478:         my (@idns,%seen);
                   12479:         foreach my $id (@hosts) {
                   12480:             my $dom = &host_domain($id);
                   12481:             my $prim_id = &domain($dom,'primary');
                   12482:             my $prim_ip = &get_host_ip($prim_id);
                   12483:             next if ($seen{$prim_ip});
                   12484:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12485:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12486:                     my $intdom = &internet_dom($id);
                   12487:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12488:                         push(@idns,$intdom);
                   12489:                     }
                   12490:                 }
                   12491:             }
                   12492:             $seen{$prim_ip} = 1;
                   12493:         }
1.1172.2.23  raeburn  12494:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12495:     }
                   12496: 
1.986     foxr     12497: }
                   12498: 
1.1079    raeburn  12499: sub all_loncaparevs {
1.1172.2.39  raeburn  12500:     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  12501: }
                   12502: 
1.1172.2.27  raeburn  12503: # ------------------------------------------------------- Read loncaparev table
                   12504: {
                   12505:     sub load_loncaparevs {
                   12506:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12507:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12508:                 while (my $configline=<$config>) {
                   12509:                     chomp($configline);
                   12510:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12511:                     $loncaparevs{$hostid}=$loncaparev;
                   12512:                 }
                   12513:                 close($config);
                   12514:             }
                   12515:         }
                   12516:     }
                   12517: }
                   12518: 
                   12519: # ----------------------------------------------------- Read serverhostID table
                   12520: {
                   12521:     sub load_serverhomeIDs {
                   12522:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12523:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12524:                 while (my $configline=<$config>) {
                   12525:                     chomp($configline);
                   12526:                     my ($name,$id)=split(/:/,$configline);
                   12527:                     $serverhomeIDs{$name}=$id;
                   12528:                 }
                   12529:                 close($config);
                   12530:             }
                   12531:         }
                   12532:     }
                   12533: }
                   12534: 
                   12535: 
1.862     albertel 12536: BEGIN {
                   12537: 
                   12538: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12539:     unless ($readit) {
                   12540: {
                   12541:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12542:     %perlvar = (%perlvar,%{$configvars});
                   12543: }
                   12544: 
                   12545: 
1.1       albertel 12546: # ------------------------------------------------------ Read spare server file
                   12547: {
1.448     albertel 12548:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12549: 
                   12550:     while (my $configline=<$config>) {
                   12551:        chomp($configline);
1.284     matthew  12552:        if ($configline) {
1.784     albertel 12553: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12554: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12555: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12556:        }
                   12557:     }
1.448     albertel 12558:     close($config);
1.1       albertel 12559: }
1.11      www      12560: # ------------------------------------------------------------ Read permissions
                   12561: {
1.448     albertel 12562:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12563: 
                   12564:     while (my $configline=<$config>) {
1.448     albertel 12565: 	chomp($configline);
                   12566: 	if ($configline) {
                   12567: 	    my ($role,$perm)=split(/ /,$configline);
                   12568: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12569: 	}
1.11      www      12570:     }
1.448     albertel 12571:     close($config);
1.11      www      12572: }
                   12573: 
                   12574: # -------------------------------------------- Read plain texts for permissions
                   12575: {
1.448     albertel 12576:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12577: 
                   12578:     while (my $configline=<$config>) {
1.448     albertel 12579: 	chomp($configline);
                   12580: 	if ($configline) {
1.742     raeburn  12581: 	    my ($short,@plain)=split(/:/,$configline);
                   12582:             %{$prp{$short}} = ();
                   12583: 	    if (@plain > 0) {
                   12584:                 $prp{$short}{'std'} = $plain[0];
                   12585:                 for (my $i=1; $i<@plain; $i++) {
                   12586:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12587:                 }
                   12588:             }
1.448     albertel 12589: 	}
1.135     www      12590:     }
1.448     albertel 12591:     close($config);
1.135     www      12592: }
                   12593: 
                   12594: # ---------------------------------------------------------- Read package table
                   12595: {
1.448     albertel 12596:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12597: 
                   12598:     while (my $configline=<$config>) {
1.483     albertel 12599: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12600: 	chomp($configline);
                   12601: 	my ($short,$plain)=split(/:/,$configline);
                   12602: 	my ($pack,$name)=split(/\&/,$short);
                   12603: 	if ($plain ne '') {
                   12604: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12605: 	    $packagetab{$short}=$plain; 
                   12606: 	}
1.11      www      12607:     }
1.448     albertel 12608:     close($config);
1.329     matthew  12609: }
                   12610: 
1.1172.2.27  raeburn  12611: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12612: 
1.1172.2.27  raeburn  12613: &load_loncaparevs();
                   12614: 
                   12615: # ------------------------------------------------------- Read serverhostID table
                   12616: 
                   12617: &load_serverhomeIDs();
1.1074    raeburn  12618: 
1.1172.2.27  raeburn  12619: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12620: {
                   12621:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12622:     if (-e $file) {
                   12623:         my $parser = HTML::LCParser->new($file);
                   12624:         while (my $token = $parser->get_token()) {
                   12625:             if ($token->[0] eq 'S') {
                   12626:                 my $item = $token->[1];
                   12627:                 my $name = $token->[2]{'name'};
                   12628:                 my $value = $token->[2]{'value'};
                   12629:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12630:                     my $release = $parser->get_text();
                   12631:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12632:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12633:                 }
                   12634:             }
                   12635:         }
                   12636:     }
1.1073    raeburn  12637: }
                   12638: 
1.1138    raeburn  12639: # ---------------------------------------------------------- Read managers table
                   12640: {
                   12641:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12642:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12643:             while (my $configline=<$config>) {
                   12644:                 chomp($configline);
                   12645:                 next if ($configline =~ /^\#/);
                   12646:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12647:                     $managerstab{$configline} = 1;
                   12648:                 }
                   12649:             }
                   12650:             close($config);
                   12651:         }
                   12652:     }
                   12653: }
                   12654: 
1.329     matthew  12655: # ------------- set up temporary directory
                   12656: {
1.1117    foxr     12657:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12658: 
1.11      www      12659: }
                   12660: 
1.794     albertel 12661: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12662: 				'compress_threshold'=> 20_000,
                   12663:  			        });
1.185     www      12664: 
1.281     www      12665: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12666: $dumpcount=0;
1.958     www      12667: $locknum=0;
1.22      www      12668: 
1.163     harris41 12669: &logtouch();
1.672     albertel 12670: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12671: $readit=1;
1.564     albertel 12672:     {
                   12673: 	use integer;
                   12674: 	my $test=(2**32)+1;
1.568     albertel 12675: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12676: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12677:     }
1.195     www      12678: }
1.1       albertel 12679: }
1.179     www      12680: 
1.1       albertel 12681: 1;
1.191     harris41 12682: __END__
                   12683: 
1.243     albertel 12684: =pod
                   12685: 
1.191     harris41 12686: =head1 NAME
                   12687: 
1.243     albertel 12688: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12689: 
                   12690: =head1 SYNOPSIS
                   12691: 
1.243     albertel 12692: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12693: 
                   12694:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12695: 
1.243     albertel 12696: Common parameters:
                   12697: 
                   12698: =over 4
                   12699: 
                   12700: =item *
                   12701: 
                   12702: $uname : an internal username (if $cname expecting a course Id specifically)
                   12703: 
                   12704: =item *
                   12705: 
                   12706: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12707: 
                   12708: =item *
                   12709: 
                   12710: $symb : a resource instance identifier
                   12711: 
                   12712: =item *
                   12713: 
                   12714: $namespace : the name of a .db file that contains the data needed or
                   12715: being set.
                   12716: 
                   12717: =back
                   12718: 
1.394     bowersj2 12719: =head1 OVERVIEW
1.191     harris41 12720: 
1.394     bowersj2 12721: lonnet provides subroutines which interact with the
                   12722: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12723: about classes, users, and resources.
1.243     albertel 12724: 
                   12725: For many of these objects you can also use this to store data about
                   12726: them or modify them in various ways.
1.191     harris41 12727: 
1.394     bowersj2 12728: =head2 Symbs
1.191     harris41 12729: 
1.394     bowersj2 12730: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12731: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12732: map, the resource number of the resource in the map, and the URL of
                   12733: the resource itself. The latter is somewhat redundant, but might help
                   12734: if maps change.
                   12735: 
                   12736: An example is
                   12737: 
                   12738:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12739: 
                   12740: The respective map entry is
                   12741: 
                   12742:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12743:   title="Problem 2">
                   12744:  </resource>
                   12745: 
                   12746: Symbs are used by the random number generator, as well as to store and
                   12747: restore data specific to a certain instance of for example a problem.
                   12748: 
                   12749: =head2 Storing And Retrieving Data
                   12750: 
                   12751: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12752: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12753: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12754: is is the non-critical message twin of cstore. These functions are for
                   12755: handlers to store a perl hash to a user's permanent data space in an
                   12756: easy manner, and to retrieve it again on another call. It is expected
                   12757: that a handler would use this once at the beginning to retrieve data,
                   12758: and then again once at the end to send only the new data back.
                   12759: 
                   12760: The data is stored in the user's data directory on the user's
                   12761: homeserver under the ID of the course.
                   12762: 
                   12763: The hash that is returned by restore will have all of the previous
                   12764: value for all of the elements of the hash.
                   12765: 
                   12766: Example:
                   12767: 
                   12768:  #creating a hash
                   12769:  my %hash;
                   12770:  $hash{'foo'}='bar';
                   12771: 
                   12772:  #storing it
                   12773:  &Apache::lonnet::cstore(\%hash);
                   12774: 
                   12775:  #changing a value
                   12776:  $hash{'foo'}='notbar';
                   12777: 
                   12778:  #adding a new value
                   12779:  $hash{'bar'}='foo';
                   12780:  &Apache::lonnet::cstore(\%hash);
                   12781: 
                   12782:  #retrieving the hash
                   12783:  my %history=&Apache::lonnet::restore();
                   12784: 
                   12785:  #print the hash
                   12786:  foreach my $key (sort(keys(%history))) {
                   12787:    print("\%history{$key} = $history{$key}");
                   12788:  }
                   12789: 
                   12790: Will print out:
1.191     harris41 12791: 
1.394     bowersj2 12792:  %history{1:foo} = bar
                   12793:  %history{1:keys} = foo:timestamp
                   12794:  %history{1:timestamp} = 990455579
                   12795:  %history{2:bar} = foo
                   12796:  %history{2:foo} = notbar
                   12797:  %history{2:keys} = foo:bar:timestamp
                   12798:  %history{2:timestamp} = 990455580
                   12799:  %history{bar} = foo
                   12800:  %history{foo} = notbar
                   12801:  %history{timestamp} = 990455580
                   12802:  %history{version} = 2
                   12803: 
                   12804: Note that the special hash entries C<keys>, C<version> and
                   12805: C<timestamp> were added to the hash. C<version> will be equal to the
                   12806: total number of versions of the data that have been stored. The
                   12807: C<timestamp> attribute will be the UNIX time the hash was
                   12808: stored. C<keys> is available in every historical section to list which
                   12809: keys were added or changed at a specific historical revision of a
                   12810: hash.
                   12811: 
                   12812: B<Warning>: do not store the hash that restore returns directly. This
                   12813: will cause a mess since it will restore the historical keys as if the
                   12814: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12815: 
1.394     bowersj2 12816: Calling convention:
1.191     harris41 12817: 
1.1172.2.27  raeburn  12818:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  12819:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 12820: 
1.394     bowersj2 12821: For more detailed information, see lonnet specific documentation.
1.191     harris41 12822: 
1.394     bowersj2 12823: =head1 RETURN MESSAGES
1.191     harris41 12824: 
1.394     bowersj2 12825: =over 4
1.191     harris41 12826: 
1.394     bowersj2 12827: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12828: 
1.394     bowersj2 12829: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12830: when the connection is brought back up
1.191     harris41 12831: 
1.394     bowersj2 12832: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12833: for later delivery
1.191     harris41 12834: 
1.967     bisitz   12835: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12836: 
1.394     bowersj2 12837: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12838: that was requested
1.191     harris41 12839: 
1.243     albertel 12840: =back
1.191     harris41 12841: 
1.243     albertel 12842: =head1 PUBLIC SUBROUTINES
1.191     harris41 12843: 
1.243     albertel 12844: =head2 Session Environment Functions
1.191     harris41 12845: 
1.243     albertel 12846: =over 4
1.191     harris41 12847: 
1.394     bowersj2 12848: =item * 
                   12849: X<appenv()>
1.949     raeburn  12850: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12851: the user envirnoment file, and will be restored for each access this
1.620     albertel 12852: user makes during this session, also modifies the %env for the current
1.949     raeburn  12853: process. Optional rolesarrayref - if defined contains a reference to an array
                   12854: of roles which are exempt from the restriction on modifying user.role entries 
                   12855: in the user's environment.db and in %env.    
1.191     harris41 12856: 
                   12857: =item *
1.394     bowersj2 12858: X<delenv()>
1.987     raeburn  12859: B<delenv($delthis,$regexp)>: removes all items from the session
                   12860: environment file that begin with $delthis. If the 
                   12861: optional second arg - $regexp - is true, $delthis is treated as a 
                   12862: regular expression, otherwise \Q$delthis\E is used. 
                   12863: The values are also deleted from the current processes %env.
1.191     harris41 12864: 
1.795     albertel 12865: =item * get_env_multiple($name) 
                   12866: 
                   12867: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12868: values may be defined and end up as an array ref.
                   12869: 
                   12870: returns an array of values
                   12871: 
1.243     albertel 12872: =back
                   12873: 
                   12874: =head2 User Information
1.191     harris41 12875: 
1.243     albertel 12876: =over 4
1.191     harris41 12877: 
                   12878: =item *
1.394     bowersj2 12879: X<queryauthenticate()>
                   12880: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12881: authentication scheme
                   12882: 
                   12883: =item *
1.394     bowersj2 12884: X<authenticate()>
1.1073    raeburn  12885: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12886: authenticate user from domain's lib servers (first use the current
                   12887: one). C<$upass> should be the users password.
1.1073    raeburn  12888: $checkdefauth is optional (value is 1 if a check should be made to
                   12889:    authenticate user using default authentication method, and allow
                   12890:    account creation if username does not have account in the domain).
                   12891: $clientcancheckhost is optional (value is 1 if checking whether the
                   12892:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12893: 
                   12894: =item *
1.394     bowersj2 12895: X<homeserver()>
                   12896: B<homeserver($uname,$udom)>: find the server which has
                   12897: the user's directory and files (there must be only one), this caches
                   12898: the answer, and also caches if there is a borken connection.
1.191     harris41 12899: 
                   12900: =item *
1.394     bowersj2 12901: X<idget()>
                   12902: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12903: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12904: username, and only 1 username per ID in a specific domain) (returns
                   12905: hash: id=>name,id=>name)
1.191     harris41 12906: 
                   12907: =item *
1.394     bowersj2 12908: X<idrget()>
                   12909: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12910: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12911: 
                   12912: =item *
1.394     bowersj2 12913: X<idput()>
                   12914: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12915: 
                   12916: =item *
1.394     bowersj2 12917: X<rolesinit()>
1.1169    droeschl 12918: B<rolesinit($udom,$username)>: get user privileges.
                   12919: returns user role, first access and timer interval hashes
1.243     albertel 12920: 
                   12921: =item *
1.1171    droeschl 12922: X<privileged()>
                   12923: B<privileged($username,$domain)>: returns a true if user has a
                   12924: privileged and active role (i.e. su or dc), false otherwise.
                   12925: 
                   12926: =item *
1.551     albertel 12927: X<getsection()>
                   12928: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12929: course $cname, return section name/number or '' for "not in course"
                   12930: and '-1' for "no section"
                   12931: 
                   12932: =item *
1.394     bowersj2 12933: X<userenvironment()>
                   12934: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12935: passed in @what from the requested user's environment, returns a hash
                   12936: 
1.858     raeburn  12937: =item * 
                   12938: X<userlog_query()>
1.859     albertel 12939: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12940: activity.log file. %filters defines filters applied when parsing the
                   12941: log file. These can be start or end timestamps, or the type of action
                   12942: - log to look for Login or Logout events, check for Checkin or
                   12943: Checkout, role for role selection. The response is in the form
                   12944: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12945: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12946: 
1.243     albertel 12947: =back
                   12948: 
                   12949: =head2 User Roles
                   12950: 
                   12951: =over 4
                   12952: 
                   12953: =item *
                   12954: 
1.1172.2.65  raeburn  12955: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   12956: returns codes for allowed actions.
                   12957: 
                   12958: The first argument is required, all others are optional.
                   12959: 
                   12960: $priv is the privilege being checked.
                   12961: $uri contains additional information about what is being checked for access (e.g.,
                   12962: URL, course ID etc.).
                   12963: $symb is the unique resource instance identifier in a course; if needed,
                   12964: but not provided, it will be retrieved via a call to &symbread().
                   12965: $role is the role for which a priv is being checked (only used if priv is evb).
                   12966: $clientip is the user's IP address (only used when checking for access to portfolio
                   12967: files).
                   12968: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   12969: prevents recursive calls to &allowed.
                   12970: 
1.243     albertel 12971:  F: full access
                   12972:  U,I,K: authentication modes (cxx only)
                   12973:  '': forbidden
                   12974:  1: user needs to choose course
                   12975:  2: browse allowed
1.766     albertel 12976:  A: passphrase authentication needed
1.1172.2.65  raeburn  12977:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 12978: 
                   12979: =item *
                   12980: 
1.1172.2.13  raeburn  12981: constructaccess($url,$setpriv) : check for access to construction space URL
                   12982: 
                   12983: See if the owner domain and name in the URL match those in the
                   12984: expected environment.  If so, return three element list
                   12985: ($ownername,$ownerdomain,$ownerhome).
                   12986: 
                   12987: Otherwise return the null string.
                   12988: 
                   12989: If second argument 'setpriv' is true, it assigns the privileges,
                   12990: and returns the same three element list, unless the owner has
                   12991: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12992: in which case the null string is returned.
                   12993: 
                   12994: =item *
                   12995: 
1.243     albertel 12996: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12997: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12998: and course level
                   12999: 
                   13000: =item *
                   13001: 
1.988     raeburn  13002: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13003: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13004: $type is Course (default) or Community.
1.988     raeburn  13005: If $forcedefault evaluates to true, text returned will be default 
                   13006: text for $type. Otherwise, if this is a course, the text returned 
                   13007: will be a custom name for the role (if defined in the course's 
                   13008: environment).  If no custom name is defined the default is returned.
                   13009:    
1.832     raeburn  13010: =item *
                   13011: 
1.1172.2.23  raeburn  13012: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13013: All arguments are optional. Returns a hash of a roles, either for
                   13014: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13015: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13016: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13017: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13018: For each key, value is set to colon-separated start and end times for
                   13019: the role.  If no username and domain are specified, will default to
1.934     raeburn  13020: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13021: of role statuses (active, future or previous), roles 
                   13022: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13023: to restrict the list of roles reported. If no array ref is 
                   13024: provided for types, will default to return only active roles.
1.834     albertel 13025: 
1.1172.2.13  raeburn  13026: =item *
                   13027: 
                   13028: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13029: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13030: 
                   13031: Additional optional arguments are: $type (if role checking is to be restricted
                   13032: to certain user status types -- previous (expired roles), active (currently
                   13033: available roles) or future (roles available in the future), and
                   13034: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13035: have active Domain Coordinator role in course's domain or in additional
                   13036: domains (specified in 'Domains to check for privileged users' in course
                   13037: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13038: 
                   13039: =item *
                   13040: 
                   13041: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13042: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13043: $possdomains and $possroles are optional array refs -- to domains to check and
                   13044: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13045: users' roles.db to check for a dc or su role in any domain. This can be
                   13046: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13047: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13048: this then allows &privileged_by_domain() to be used, which caches the identity
                   13049: of privileged users, eliminating the need for repeated calls to &dump().
                   13050: 
                   13051: =item *
                   13052: 
                   13053: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13054: where the outer hash keys are domains specified in the $possdomains array ref,
                   13055: next inner hash keys are privileged roles specified in the $roles array ref,
                   13056: and the innermost hash contains key = value pairs for username:domain = end:start
                   13057: for active or future "privileged" users with that role in that domain. To avoid
                   13058: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13059: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13060: 
1.243     albertel 13061: =back
                   13062: 
                   13063: =head2 User Modification
                   13064: 
                   13065: =over 4
                   13066: 
                   13067: =item *
                   13068: 
1.957     raeburn  13069: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13070: user for the level given by URL.  Optional start and end dates (leave empty
                   13071: string or zero for "no date")
1.191     harris41 13072: 
                   13073: =item *
                   13074: 
1.243     albertel 13075: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13076: change a users, password, possible return values are: ok,
                   13077: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13078: refused
1.191     harris41 13079: 
                   13080: =item *
                   13081: 
1.243     albertel 13082: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13083: 
                   13084: =item *
                   13085: 
1.1058    raeburn  13086: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13087:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13088: 
                   13089: will update user information (firstname,middlename,lastname,generation,
                   13090: permanentemail), and if forceid is true, student/employee ID also.
                   13091: A user's institutional affiliation(s) can also be updated.
                   13092: User information fields will not be overwritten with empty entries 
                   13093: unless the field is included in the $candelete array reference.
                   13094: This array is included when a single user is modified via "Manage Users",
                   13095: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13096: 
                   13097: =item *
                   13098: 
1.286     matthew  13099: modifystudent
                   13100: 
1.957     raeburn  13101: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13102: The course id is resolved based on the current user's environment.  
                   13103: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13104: associated with a course.
                   13105: 
1.297     matthew  13106: This call is essentially a wrapper for lonnet::modifyuser and
                   13107: lonnet::modify_student_enrollment
1.286     matthew  13108: 
                   13109: Inputs: 
                   13110: 
                   13111: =over 4
                   13112: 
1.957     raeburn  13113: =item B<$udom> Student's loncapa domain
1.286     matthew  13114: 
1.957     raeburn  13115: =item B<$uname> Student's loncapa login name
1.286     matthew  13116: 
1.964     bisitz   13117: =item B<$uid> Student/Employee ID
1.286     matthew  13118: 
1.957     raeburn  13119: =item B<$umode> Student's authentication mode
1.286     matthew  13120: 
1.957     raeburn  13121: =item B<$upass> Student's password
1.286     matthew  13122: 
1.957     raeburn  13123: =item B<$first> Student's first name
1.286     matthew  13124: 
1.957     raeburn  13125: =item B<$middle> Student's middle name
1.286     matthew  13126: 
1.957     raeburn  13127: =item B<$last> Student's last name
1.286     matthew  13128: 
1.957     raeburn  13129: =item B<$gene> Student's generation
1.286     matthew  13130: 
1.957     raeburn  13131: =item B<$usec> Student's section in course
1.286     matthew  13132: 
                   13133: =item B<$end> Unix time of the roles expiration
                   13134: 
                   13135: =item B<$start> Unix time of the roles start date
                   13136: 
                   13137: =item B<$forceid> If defined, allow $uid to be changed
                   13138: 
                   13139: =item B<$desiredhome> server to use as home server for student
                   13140: 
1.957     raeburn  13141: =item B<$email> Student's permanent e-mail address
                   13142: 
                   13143: =item B<$type> Type of enrollment (auto or manual)
                   13144: 
1.963     raeburn  13145: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13146: 
                   13147: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13148: 
1.963     raeburn  13149: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13150: 
1.963     raeburn  13151: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13152: 
1.1172.2.19  raeburn  13153: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13154: 
                   13155: =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  13156: 
1.286     matthew  13157: =back
1.297     matthew  13158: 
                   13159: =item *
                   13160: 
                   13161: modify_student_enrollment
                   13162: 
1.1172.2.31  raeburn  13163: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13164: 'role.request.course' must be defined for this function to proceed.
                   13165: 
                   13166: Inputs:
                   13167: 
                   13168: =over 4
                   13169: 
1.1172.2.31  raeburn  13170: =item $udom, student's domain
1.297     matthew  13171: 
1.1172.2.31  raeburn  13172: =item $uname, student's name
1.297     matthew  13173: 
1.1172.2.31  raeburn  13174: =item $uid, student's user id
1.297     matthew  13175: 
1.1172.2.31  raeburn  13176: =item $first, student's first name
1.297     matthew  13177: 
                   13178: =item $middle
                   13179: 
                   13180: =item $last
                   13181: 
                   13182: =item $gene
                   13183: 
                   13184: =item $usec
                   13185: 
                   13186: =item $end
                   13187: 
                   13188: =item $start
                   13189: 
1.957     raeburn  13190: =item $type
                   13191: 
                   13192: =item $locktype
                   13193: 
                   13194: =item $cid
                   13195: 
                   13196: =item $selfenroll
                   13197: 
                   13198: =item $context
                   13199: 
1.1172.2.19  raeburn  13200: =item $credits, number of credits student will earn from this class
                   13201: 
1.297     matthew  13202: =back
                   13203: 
1.191     harris41 13204: 
                   13205: =item *
                   13206: 
1.243     albertel 13207: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13208: custom role; give a custom role to a user for the level given by URL.  Specify
                   13209: name and domain of role author, and role name
1.191     harris41 13210: 
                   13211: =item *
                   13212: 
1.243     albertel 13213: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13214: 
                   13215: =item *
                   13216: 
1.243     albertel 13217: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13218: 
                   13219: =back
                   13220: 
                   13221: =head2 Course Infomation
                   13222: 
                   13223: =over 4
1.191     harris41 13224: 
                   13225: =item *
                   13226: 
1.1118    foxr     13227: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13228: specified course id, including all environment settings for the
                   13229: course, the description of the course will be in the hash under the
                   13230: key 'description'
1.191     harris41 13231: 
1.1118    foxr     13232: $options is an optional parameter that if supplied is a hash reference that controls
                   13233: what how this function works.  It has the following key/values:
                   13234: 
                   13235: =over 4
                   13236: 
                   13237: =item freshen_cache
                   13238: 
                   13239: If defined, and the environment cache for the course is valid, it is 
                   13240: returned in the returned hash.
                   13241: 
                   13242: =item one_time
                   13243: 
                   13244: If defined, the last cache time is set to _now_
                   13245: 
                   13246: =item user
                   13247: 
                   13248: If defined, the supplied username is used instead of the current user.
                   13249: 
                   13250: 
                   13251: =back
                   13252: 
1.191     harris41 13253: =item *
                   13254: 
1.624     albertel 13255: resdata($name,$domain,$type,@which) : request for current parameter
                   13256: setting for a specific $type, where $type is either 'course' or 'user',
                   13257: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  13258: answers for 10 minutes.
1.243     albertel 13259: 
1.877     foxr     13260: =item *
                   13261: 
                   13262: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13263: data base, returning a hash that is keyed by the resource name and has
                   13264: values that are the resource value.  I believe that the timestamps and
                   13265: versions are also returned.
                   13266: 
1.1172.2.31  raeburn  13267: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13268: supplemental content area. This routine caches the number of files for
                   13269: 10 minutes.
                   13270: 
1.243     albertel 13271: =back
                   13272: 
                   13273: =head2 Course Modification
                   13274: 
                   13275: =over 4
1.191     harris41 13276: 
                   13277: =item *
                   13278: 
1.243     albertel 13279: writecoursepref($courseid,%prefs) : write preferences (environment
                   13280: database) for a course
1.191     harris41 13281: 
                   13282: =item *
                   13283: 
1.1011    raeburn  13284: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13285: 
                   13286: =item *
                   13287: 
1.1038    raeburn  13288: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13289: 
1.1167    droeschl 13290: =item *
                   13291: 
                   13292: is_course($courseid), is_course($cdom, $cnum)
                   13293: 
                   13294: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13295: two component version $cdom, $cnum. It checks if the specified course exists.
                   13296: 
                   13297: Returns:
                   13298:     undef if the course doesn't exist, otherwise
                   13299:     in scalar context the combined courseid.
                   13300:     in list context the two components of the course identifier, domain and 
                   13301:     courseid.    
                   13302: 
1.243     albertel 13303: =back
                   13304: 
                   13305: =head2 Resource Subroutines
                   13306: 
                   13307: =over 4
1.191     harris41 13308: 
                   13309: =item *
                   13310: 
1.243     albertel 13311: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13312: 
                   13313: =item *
                   13314: 
1.243     albertel 13315: repcopy($filename) : subscribes to the requested file, and attempts to
                   13316: replicate from the owning library server, Might return
1.607     raeburn  13317: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13318: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13319: resource. Expects the local filesystem pathname
                   13320: (/home/httpd/html/res/....)
                   13321: 
                   13322: =back
                   13323: 
                   13324: =head2 Resource Information
                   13325: 
                   13326: =over 4
1.191     harris41 13327: 
                   13328: =item *
                   13329: 
1.1172.2.28  raeburn  13330: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13331: and returns the value of a variety of different possible values,
                   13332: $varname should be a request string, and the other parameters can be
                   13333: used to specify who and what one is asking about. Ordinarily, $cid 
                   13334: does not need to be specified, as it is retrived from 
                   13335: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13336: within lonuserstate::loadmap() when initializing a course, before
                   13337: $env{'request.course.id'} has been set, so it needs to be provided
                   13338: in that one case.
1.243     albertel 13339: 
                   13340: Possible values for $varname are environment.lastname (or other item
                   13341: from the envirnment hash), user.name (or someother aspect about the
                   13342: user), resource.0.maxtries (or some other part and parameter of a
                   13343: resource)
1.204     albertel 13344: 
                   13345: =item *
                   13346: 
1.243     albertel 13347: directcondval($number) : get current value of a condition; reads from a state
                   13348: string
1.204     albertel 13349: 
                   13350: =item *
                   13351: 
1.243     albertel 13352: condval($condidx) : value of condition index based on state
1.204     albertel 13353: 
                   13354: =item *
                   13355: 
1.243     albertel 13356: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13357: resource's metadata, $what should be either a specific key, or either
                   13358: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13359: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13360: 
                   13361: this function automatically caches all requests
1.191     harris41 13362: 
                   13363: =item *
                   13364: 
1.243     albertel 13365: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13366: network of library servers; returns file handle of where SQL and regex results
                   13367: will be stored for query
1.191     harris41 13368: 
                   13369: =item *
                   13370: 
1.1172.2.66  raeburn  13371: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   13372: return symbolic list entry (all arguments optional).
                   13373: 
                   13374: Args: filename is the filename (including path) for the file for which a symb
                   13375: is required; donotrecurse, if true will prevent calls to allowed() being made
                   13376: to check access status if more than one resource was found in the bighash
                   13377: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   13378: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   13379: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13380: cause possible symbs to be checked to determine if they are subject to content
                   13381: blocking, if so they will not be included as possible symbs; possibles is a
                   13382: ref to a hash, which, as a side effect, will be populated with all possible
                   13383: symbs (content blocking not tested).
                   13384: 
1.243     albertel 13385: returns the data handle
1.191     harris41 13386: 
                   13387: =item *
                   13388: 
1.1172.2.17  raeburn  13389: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13390: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13391: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13392: on failure, user must be in a course, as it assumes the existence of
                   13393: the course initial hash, and uses $env('request.course.id'}.  The third
                   13394: arg is an optional reference to a scalar.  If this arg is passed in the
                   13395: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13396: encrypted; otherwise it will be null.
1.243     albertel 13397: 
1.191     harris41 13398: =item *
                   13399: 
1.243     albertel 13400: symbclean($symb) : removes versions numbers from a symb, returns the
                   13401: cleaned symb
1.191     harris41 13402: 
                   13403: =item *
                   13404: 
1.243     albertel 13405: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13406: course map, user must be in a course for it to work.
1.191     harris41 13407: 
                   13408: =item *
                   13409: 
1.243     albertel 13410: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13411: 
                   13412: =item *
                   13413: 
1.243     albertel 13414: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13415: a random seed, all arguments are optional, if they aren't sent it uses the
                   13416: environment to derive them. Note: if symb isn't sent and it can't get one
                   13417: from &symbread it will use the current time as its return value
1.191     harris41 13418: 
                   13419: =item *
                   13420: 
1.243     albertel 13421: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13422: unfakeable, receipt
1.191     harris41 13423: 
                   13424: =item *
                   13425: 
1.620     albertel 13426: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13427: 
                   13428: =item *
                   13429: 
1.243     albertel 13430: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13431: 
                   13432: =item *
                   13433: 
1.243     albertel 13434: 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 13435: 
                   13436: =item *
                   13437: 
1.243     albertel 13438: 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 13439: 
                   13440: =item *
                   13441: 
1.243     albertel 13442: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13443: 
                   13444: =item *
                   13445: 
1.243     albertel 13446: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13447: forcing spreadsheet to reevaluate the resource scores next time.
                   13448: 
1.1172.2.13  raeburn  13449: =item *
                   13450: 
                   13451: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13452: when viewing in course context.
                   13453: 
                   13454:  input: six args -- filename (decluttered), course number, course domain,
                   13455:                     url, symb (if registered) and group (if this is a
                   13456:                     group item -- e.g., bulletin board, group page etc.).
                   13457: 
                   13458:  output: array of five scalars --
                   13459:          $cfile -- url for file editing if editable on current server
                   13460:          $home -- homeserver of resource (i.e., for author if published,
                   13461:                                           or course if uploaded.).
                   13462:          $switchserver --  1 if server switch will be needed.
                   13463:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13464:          $forceview -- 1 if icon/link should be to go to view mode
                   13465: 
                   13466: =item *
                   13467: 
                   13468: is_course_upload($file,$cnum,$cdom)
                   13469: 
                   13470: Used in course context to determine if current file was uploaded to
                   13471: the course (i.e., would be found in /userfiles/docs on the course's
                   13472: homeserver.
                   13473: 
                   13474:   input: 3 args -- filename (decluttered), course number and course domain.
                   13475:   output: boolean -- 1 if file was uploaded.
                   13476: 
1.243     albertel 13477: =back
                   13478: 
                   13479: =head2 Storing/Retreiving Data
                   13480: 
                   13481: =over 4
1.191     harris41 13482: 
                   13483: =item *
                   13484: 
1.1172.2.64  raeburn  13485: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   13486: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13487: the remaining args aren't required and if they aren't passed or are '' they will
                   13488: be derived from the env (with the exception of $laststore, which is an
                   13489: optional arg used when a user's submission is stored in grading).
                   13490: $laststore is $version=$timestamp, where $version is the most recent version
                   13491: number retrieved for the corresponding $symb in the $namespace db file, and
                   13492: $timestamp is the timestamp for that transaction (UNIX time).
                   13493: $laststore is currently only passed when cstore() is called by
                   13494: structuretags::finalize_storage().
1.191     harris41 13495: 
                   13496: =item *
                   13497: 
1.1172.2.64  raeburn  13498: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   13499: but uses critical subroutine
1.191     harris41 13500: 
                   13501: =item *
                   13502: 
1.243     albertel 13503: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13504: all args are optional
1.191     harris41 13505: 
                   13506: =item *
                   13507: 
1.717     albertel 13508: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13509: dumps the complete (or key matching regexp) namespace into a hash
                   13510: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13511: normally &store()ed into
                   13512: 
                   13513: $range should be either an integer '100' (give me the first 100
                   13514:                                            matching records)
                   13515:               or be  two integers sperated by a - with no spaces
                   13516:                  '30-50' (give me the 30th through the 50th matching
                   13517:                           records)
                   13518: 
                   13519: 
                   13520: =item *
                   13521: 
1.1172.2.59  raeburn  13522: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 13523: replaces a &store() version of data with a replacement set of data
                   13524: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  13525: reference. If $tolog is true, the transaction is logged in the courselog
                   13526: with an action=PUTSTORE.
1.717     albertel 13527: 
                   13528: =item *
                   13529: 
1.243     albertel 13530: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13531: works very similar to store/cstore, but all data is stored in a
                   13532: temporary location and can be reset using tmpreset, $storehash should
                   13533: be a hash reference, returns nothing on success
1.191     harris41 13534: 
                   13535: =item *
                   13536: 
1.243     albertel 13537: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13538: similar to restore, but all data is stored in a temporary location and
                   13539: can be reset using tmpreset. Returns a hash of values on success,
                   13540: error string otherwise.
1.191     harris41 13541: 
                   13542: =item *
                   13543: 
1.243     albertel 13544: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13545: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13546: 
                   13547: =item *
                   13548: 
1.243     albertel 13549: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13550: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13551: 
                   13552: =item *
                   13553: 
1.243     albertel 13554: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13555: namesp ($udom and $uname are optional)
1.191     harris41 13556: 
                   13557: =item *
                   13558: 
1.702     albertel 13559: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13560: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13561: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13562: 
1.702     albertel 13563: $range should be either an integer '100' (give me the first 100
                   13564:                                            matching records)
                   13565:               or be  two integers sperated by a - with no spaces
                   13566:                  '30-50' (give me the 30th through the 50th matching
                   13567:                           records)
1.449     matthew  13568: =item *
                   13569: 
                   13570: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13571: $store can be a scalar, an array reference, or if the amount to be 
                   13572: incremented is > 1, a hash reference.
                   13573: 
                   13574: ($udom and $uname are optional)
1.191     harris41 13575: 
                   13576: =item *
                   13577: 
1.243     albertel 13578: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13579: ($udom and $uname are optional)
1.191     harris41 13580: 
                   13581: =item *
                   13582: 
1.243     albertel 13583: cput($namespace,$storehash,$udom,$uname) : critical put
                   13584: ($udom and $uname are optional)
1.191     harris41 13585: 
                   13586: =item *
                   13587: 
1.748     albertel 13588: newput($namespace,$storehash,$udom,$uname) :
                   13589: 
                   13590: Attempts to store the items in the $storehash, but only if they don't
                   13591: currently exist, if this succeeds you can be certain that you have 
                   13592: successfully created a new key value pair in the $namespace db.
                   13593: 
                   13594: 
                   13595: Args:
                   13596:  $namespace: name of database to store values to
                   13597:  $storehash: hashref to store to the db
                   13598:  $udom: (optional) domain of user containing the db
                   13599:  $uname: (optional) name of user caontaining the db
                   13600: 
                   13601: Returns:
                   13602:  'ok' -> succeeded in storing all keys of $storehash
                   13603:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13604:                         least <key> already existed in the db (other
                   13605:                         requested keys may also already exist)
1.967     bisitz   13606:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13607:  'con_lost' -> unable to contact request server
                   13608:  'refused' -> action was not allowed by remote machine
                   13609: 
                   13610: 
                   13611: =item *
                   13612: 
1.243     albertel 13613: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13614: reference filled in from namesp (encrypts the return communication)
                   13615: ($udom and $uname are optional)
1.191     harris41 13616: 
                   13617: =item *
                   13618: 
1.243     albertel 13619: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13620: critical subroutine
                   13621: 
1.806     raeburn  13622: =item *
                   13623: 
1.860     raeburn  13624: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13625: array reference filled in from namespace found in domain level on either
                   13626: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13627: 
                   13628: =item *
                   13629: 
1.860     raeburn  13630: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13631: domain level either on specified domain server ($uhome) or primary domain 
                   13632: server ($udom and $uhome are optional)
1.806     raeburn  13633: 
1.943     raeburn  13634: =item * 
                   13635: 
1.1172.2.35  raeburn  13636: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   13637: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13638: the target domain.
                   13639: 
                   13640: May also include additional key => value pairs for the following groups:
                   13641: 
                   13642: =over
                   13643: 
                   13644: =item
                   13645: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13646: 
                   13647: =over
                   13648: 
                   13649: =item defaultquota, authorquota
                   13650: 
                   13651: =back
                   13652: 
                   13653: =item
                   13654: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13655: portfolio for users).
                   13656: 
                   13657: =over
                   13658: 
                   13659: =item
                   13660: aboutme, blog, webdav, portfolio
                   13661: 
                   13662: =back
                   13663: 
                   13664: =item
                   13665: requestcourses: ability to request courses, and how requests are processed.
                   13666: 
                   13667: =over
                   13668: 
                   13669: =item
1.1172.2.37  raeburn  13670: official, unofficial, community, textbook
1.1172.2.35  raeburn  13671: 
                   13672: =back
                   13673: 
                   13674: =item
                   13675: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13676: 
                   13677: =over
                   13678: 
                   13679: =item
1.1172.2.44  raeburn  13680: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  13681: 
                   13682: =back
                   13683: 
                   13684: =item
                   13685: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13686: for course's uploaded content.
                   13687: 
                   13688: =over
                   13689: 
                   13690: =item
1.1172.2.37  raeburn  13691: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35  raeburn  13692: 
                   13693: =back
                   13694: 
                   13695: =item
                   13696: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13697: on your servers.
                   13698: 
                   13699: =over
                   13700: 
                   13701: =item
                   13702: remotesessions, hostedsessions
                   13703: 
                   13704: =back
                   13705: 
                   13706: =back
                   13707: 
                   13708: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13709: utility to create a configuration.db file on a domain's primary library server
                   13710: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13711: -- corresponding values are authentication type (internal, krb4, krb5,
                   13712: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   13713: will be available. Values are retrieved from cache (if current), unless the
                   13714: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13715: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13716: 
                   13717: Typical usage:
1.943     raeburn  13718: 
1.1172.2.35  raeburn  13719: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13720: 
1.243     albertel 13721: =back
                   13722: 
                   13723: =head2 Network Status Functions
                   13724: 
                   13725: =over 4
1.191     harris41 13726: 
                   13727: =item *
                   13728: 
1.1137    raeburn  13729: dirlist() : return directory list based on URI (first arg).
                   13730: 
                   13731: Inputs: 1 required, 5 optional.
                   13732: 
                   13733: =over
                   13734: 
                   13735: =item 
                   13736: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13737: 
                   13738: =item
                   13739: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13740: 
                   13741: =item
                   13742: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13743: 
                   13744: =item
                   13745: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13746: 
                   13747: =item
                   13748: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13749: 
                   13750: =item 
                   13751: $alternateRoot - path to prepend in place of path from $uri.
                   13752: 
                   13753: =back
                   13754: 
                   13755: Returns: Array of up to two items.
                   13756: 
                   13757: =over
                   13758: 
                   13759: a reference to an array of files/subdirectories
                   13760: 
                   13761: =over
                   13762: 
                   13763: Each element in the array of files/subdirectories is a & separated list of
                   13764: item name and the result of running stat on the item.  If dirlist was requested
                   13765: for a file instead of a directory, the item name will be ''. For a directory 
                   13766: listing, if the item is a metadata file, the element will end &N&M 
                   13767: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13768: default copyright set (1).  
                   13769: 
                   13770: =back
                   13771: 
                   13772: a scalar containing error condition (if encountered).
                   13773: 
                   13774: =over
                   13775: 
                   13776: =item 
                   13777: no_host (no homeserver identified for $username:$domain).
                   13778: 
                   13779: =item 
                   13780: no_such_host (server contacted for listing not identified as valid host).
                   13781: 
                   13782: =item 
                   13783: con_lost (connection to remote server failed).
                   13784: 
                   13785: =item 
                   13786: refused (invalid $username:$domain received on lond side).
                   13787: 
                   13788: =item 
                   13789: no_such_dir (directory at specified path on lond side does not exist). 
                   13790: 
                   13791: =item 
                   13792: empty (directory at specified path on lond side is empty).
                   13793: 
                   13794: =over
                   13795: 
                   13796: This is currently not encountered because the &ls3, &ls2, 
                   13797: &ls (_handler) routines on the lond side do not filter out
                   13798: . and .. from a directory listing. 
                   13799: 
                   13800: =back
                   13801: 
                   13802: =back
                   13803: 
                   13804: =back
1.191     harris41 13805: 
                   13806: =item *
                   13807: 
1.243     albertel 13808: spareserver() : find server with least workload from spare.tab
                   13809: 
1.986     foxr     13810: 
                   13811: =item *
                   13812: 
                   13813: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13814: if there is no corresponding loncapa host.
                   13815: 
1.243     albertel 13816: =back
                   13817: 
1.986     foxr     13818: 
1.243     albertel 13819: =head2 Apache Request
                   13820: 
                   13821: =over 4
1.191     harris41 13822: 
                   13823: =item *
                   13824: 
1.243     albertel 13825: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13826: localhost, posts hash
                   13827: 
                   13828: =back
                   13829: 
                   13830: =head2 Data to String to Data
                   13831: 
                   13832: =over 4
1.191     harris41 13833: 
                   13834: =item *
                   13835: 
1.243     albertel 13836: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13837: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13838: 
                   13839: =item *
                   13840: 
1.243     albertel 13841: hashref2str($hashref) : convert a hashref into a string complete with
                   13842: escaping and '=' and '&' separators, supports elements that are
                   13843: arrayrefs and hashrefs
1.191     harris41 13844: 
                   13845: =item *
                   13846: 
1.243     albertel 13847: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13848: with escaping and '&' separators, supports elements that are arrayrefs
                   13849: and hashrefs
1.191     harris41 13850: 
                   13851: =item *
                   13852: 
1.243     albertel 13853: str2hash($string) : convert string to hash using unescaping and
                   13854: splitting on '=' and '&', supports elements that are arrayrefs and
                   13855: hashrefs
1.191     harris41 13856: 
                   13857: =item *
                   13858: 
1.243     albertel 13859: str2array($string) : convert string to hash using unescaping and
                   13860: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13861: 
                   13862: =back
                   13863: 
                   13864: =head2 Logging Routines
                   13865: 
                   13866: 
                   13867: These routines allow one to make log messages in the lonnet.log and
                   13868: lonnet.perm logfiles.
1.191     harris41 13869: 
1.1119    foxr     13870: =over 4
                   13871: 
1.191     harris41 13872: =item *
                   13873: 
1.243     albertel 13874: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13875: 
                   13876: =item *
                   13877: 
1.243     albertel 13878: logthis() : append message to the normal lonnet.log file, it gets
                   13879: preiodically rolled over and deleted.
1.191     harris41 13880: 
                   13881: =item *
                   13882: 
1.243     albertel 13883: logperm() : append a permanent message to lonnet.perm.log, this log
                   13884: file never gets deleted by any automated portion of the system, only
                   13885: messages of critical importance should go in here.
                   13886: 
1.1119    foxr     13887: 
1.243     albertel 13888: =back
                   13889: 
                   13890: =head2 General File Helper Routines
                   13891: 
                   13892: =over 4
1.191     harris41 13893: 
                   13894: =item *
                   13895: 
1.481     raeburn  13896: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13897: (a) files in /uploaded
                   13898:   (i) If a local copy of the file exists - 
                   13899:       compares modification date of local copy with last-modified date for 
                   13900:       definitive version stored on home server for course. If local copy is 
                   13901:       stale, requests a new version from the home server and stores it. 
                   13902:       If the original has been removed from the home server, then local copy 
                   13903:       is unlinked.
                   13904:   (ii) If local copy does not exist -
                   13905:       requests the file from the home server and stores it. 
                   13906:   
                   13907:   If $caller is 'uploadrep':  
                   13908:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13909:     for request for files originally uploaded via DOCS. 
                   13910:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13911:   
                   13912:   Otherwise:
                   13913:      This indicates a call from the content generation phase of the request.
                   13914:      -  returns the entire contents of the file or -1.
                   13915:      
                   13916: (b) files in /res
                   13917:    - returns the entire contents of a file or -1; 
                   13918:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13919: 
1.712     albertel 13920: 
                   13921: =item *
                   13922: 
                   13923: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13924:                   reference
                   13925: 
                   13926: returns either a stat() list of data about the file or an empty list
                   13927: if the file doesn't exist or couldn't find out about it (connection
                   13928: problems or user unknown)
                   13929: 
1.191     harris41 13930: =item *
                   13931: 
1.243     albertel 13932: filelocation($dir,$file) : returns file system location of a file
                   13933: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13934: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13935: and a file of ../bob will become /a/bob)
1.191     harris41 13936: 
                   13937: =item *
                   13938: 
                   13939: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13940: filelocation except for hrefs
                   13941: 
                   13942: =item *
                   13943: 
1.1172.2.49  raeburn  13944: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   13945: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 13946: 
1.243     albertel 13947: =back
                   13948: 
1.608     albertel 13949: =head2 Usererfile file routines (/uploaded*)
                   13950: 
                   13951: =over 4
                   13952: 
                   13953: =item *
                   13954: 
                   13955: userfileupload(): main rotine for putting a file in a user or course's
                   13956:                   filespace, arguments are,
                   13957: 
1.620     albertel 13958:  formname - required - this is the name of the element in $env where the
1.608     albertel 13959:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13960:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13961:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13962:  context - if coursedoc, store the file in the course of the active role
                   13963:              of the current user; 
                   13964:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13965:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13966:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13967:          if undefined, it will be placed in "unknown"
                   13968: 
                   13969:  (This routine calls clean_filename() to remove any dangerous
                   13970:  characters from the filename, and then calls finuserfileupload() to
                   13971:  complete the transaction)
                   13972: 
                   13973:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13974:  and /adm/notfound.html if unsuccessful
                   13975: 
                   13976: =item *
                   13977: 
                   13978: clean_filename(): routine for cleaing a filename up for storage in
                   13979:                  userfile space, argument is:
                   13980: 
                   13981:  filename - proposed filename
                   13982: 
                   13983: returns: the new clean filename
                   13984: 
                   13985: =item *
                   13986: 
1.1090    raeburn  13987: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13988: userspace, probably shouldn't be called directly
                   13989: 
                   13990:   docuname: username or courseid of destination for the file
                   13991:   docudom: domain of user/course of destination for the file
                   13992:   formname: same as for userfileupload()
1.1090    raeburn  13993:   fname: filename (including subdirectories) for the file
                   13994:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13995:   allfiles: reference to hash used to store objects found by parser
                   13996:   codebase: reference to hash used for codebases of java objects found by parser
                   13997:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13998:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13999:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14000:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14001:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14002:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14003:   mimetype: reference to scalar to accommodate mime type determined
                   14004:             from File::MMagic if $parser = parse.
1.608     albertel 14005: 
                   14006:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14007:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14008:  was 'overwrite').
                   14009:  
1.608     albertel 14010: 
                   14011: =item *
                   14012: 
                   14013: renameuserfile(): renames an existing userfile to a new name
                   14014: 
                   14015:   Args:
                   14016:    docuname: username or courseid of destination for the file
                   14017:    docudom: domain of user/course of destination for the file
                   14018:    old: current file name (including any subdirs under userfiles)
                   14019:    new: desired file name (including any subdirs under userfiles)
                   14020: 
                   14021: =item *
                   14022: 
                   14023: mkdiruserfile(): creates a directory is a userfiles dir
                   14024: 
                   14025:   Args:
                   14026:    docuname: username or courseid of destination for the file
                   14027:    docudom: domain of user/course of destination for the file
                   14028:    dir: dir to create (including any subdirs under userfiles)
                   14029: 
                   14030: =item *
                   14031: 
                   14032: removeuserfile(): removes a file that exists in userfiles
                   14033: 
                   14034:   Args:
                   14035:    docuname: username or courseid of destination for the file
                   14036:    docudom: domain of user/course of destination for the file
                   14037:    fname: filname to delete (including any subdirs under userfiles)
                   14038: 
                   14039: =item *
                   14040: 
                   14041: removeuploadedurl(): convience function for removeuserfile()
                   14042: 
                   14043:   Args:
                   14044:    url:  a full /uploaded/... url to delete
                   14045: 
1.747     albertel 14046: =item * 
                   14047: 
                   14048: get_portfile_permissions():
                   14049:   Args:
                   14050:     domain: domain of user or course contain the portfolio files
                   14051:     user: name of user or num of course contain the portfolio files
                   14052:   Returns:
                   14053:     hashref of a dump of the proper file_permissions.db
                   14054:    
                   14055: 
                   14056: =item * 
                   14057: 
                   14058: get_access_controls():
                   14059: 
                   14060: Args:
                   14061:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14062:   group: (optional) the group you want the files associated with
                   14063:   file: (optional) the file you want access info on
                   14064: 
                   14065: Returns:
1.749     raeburn  14066:     a hash (keys are file names) of hashes containing
                   14067:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14068:         values are XML containing access control settings (see below) 
1.747     albertel 14069: 
                   14070: Internal notes:
                   14071: 
1.749     raeburn  14072:  access controls are stored in file_permissions.db as key=value pairs.
                   14073:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14074:         where scope -> public,guest,course,group,domains or users.
                   14075:               end -> UNIX time for end of access (0 -> no end date)
                   14076:               start -> UNIX time for start of access
                   14077: 
                   14078:     value -> XML description of access control
                   14079:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14080:             <start></start>
                   14081:             <end></end>
                   14082: 
                   14083:             <password></password>  for scope type = guest
                   14084: 
                   14085:             <domain></domain>     for scope type = course or group
                   14086:             <number></number>
                   14087:             <roles id="">
                   14088:              <role></role>
                   14089:              <access></access>
                   14090:              <section></section>
                   14091:              <group></group>
                   14092:             </roles>
                   14093: 
                   14094:             <dom></dom>         for scope type = domains
                   14095: 
                   14096:             <users>             for scope type = users
                   14097:              <user>
                   14098:               <uname></uname>
                   14099:               <udom></udom>
                   14100:              </user>
                   14101:             </users>
                   14102:            </scope> 
                   14103:               
                   14104:  Access data is also aggregated for each file in an additional key=value pair:
                   14105:  key -> path to file/file_name\0accesscontrol 
                   14106:  value -> reference to hash
                   14107:           hash contains key = value pairs
                   14108:           where key = uniqueID:scope_end_start
                   14109:                 value = UNIX time record was last updated
                   14110: 
                   14111:           Used to improve speed of look-ups of access controls for each file.  
                   14112:  
                   14113:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14114: 
1.1172.2.13  raeburn  14115: =item *
                   14116: 
1.749     raeburn  14117: modify_access_controls():
                   14118: 
                   14119: Modifies access controls for a portfolio file
                   14120: Args
                   14121: 1. file name
                   14122: 2. reference to hash of required changes,
                   14123: 3. domain
                   14124: 4. username
                   14125:   where domain,username are the domain of the portfolio owner 
                   14126:   (either a user or a course) 
                   14127: 
                   14128: Returns:
                   14129: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14130: 2. result of deletions ('ok' or 'error', with error message).
                   14131: 3. reference to hash of any new or updated access controls.
                   14132: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14133:    key = integer (inbound ID)
1.1172.2.13  raeburn  14134:    value = uniqueID
                   14135: 
                   14136: =item *
                   14137: 
                   14138: get_timebased_id():
                   14139: 
                   14140: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14141: course via the Course Editor (e.g., folders, composite pages,
                   14142: group bulletin boards).
                   14143: 
                   14144: Args: (first three required; six others optional)
                   14145: 
                   14146: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14147:    docssequence, or name of group
                   14148: 
                   14149: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14150:    e.g., num, boardids
                   14151: 
                   14152: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14153:    file will be named nohist_namespace.db
                   14154: 
                   14155: 4. cdom: domain of course; default is current course domain from %env
                   14156: 
                   14157: 5. cnum: course number; default is current course number from %env
                   14158: 
                   14159: 6. idtype: set to concat if an additional digit is to be appended to the
                   14160:    unix timestamp to form the suffix, if the plain timestamp is already
                   14161:    in use.  Default is to not do this, but simply increment the unix
                   14162:    timestamp by 1 until a unique key is obtained.
                   14163: 
                   14164: 7. who: holder of locking key; defaults to user:domain for user.
                   14165: 
                   14166: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14167:    retrying); default is 3.
                   14168: 
                   14169: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14170: 
                   14171: Returns:
                   14172: 
                   14173: 1. suffix obtained (numeric)
                   14174: 
                   14175: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14176: 
                   14177: 3. error: contains (localized) error message if an error occurred.
                   14178: 
1.747     albertel 14179: 
1.608     albertel 14180: =back
                   14181: 
1.243     albertel 14182: =head2 HTTP Helper Routines
                   14183: 
                   14184: =over 4
                   14185: 
1.191     harris41 14186: =item *
                   14187: 
                   14188: escape() : unpack non-word characters into CGI-compatible hex codes
                   14189: 
                   14190: =item *
                   14191: 
                   14192: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14193: 
1.243     albertel 14194: =back
                   14195: 
                   14196: =head1 PRIVATE SUBROUTINES
                   14197: 
                   14198: =head2 Underlying communication routines (Shouldn't call)
                   14199: 
                   14200: =over 4
                   14201: 
                   14202: =item *
                   14203: 
                   14204: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14205: 
                   14206: =item *
                   14207: 
                   14208: reply() : uses subreply to send a message to remote machine, logs all failures
                   14209: 
                   14210: =item *
                   14211: 
                   14212: critical() : passes a critical message to another server; if cannot
                   14213: get through then place message in connection buffer directory and
                   14214: returns con_delayed, if incapable of saving message, returns
                   14215: con_failed
                   14216: 
                   14217: =item *
                   14218: 
                   14219: reconlonc() : tries to reconnect lonc client processes.
                   14220: 
                   14221: =back
                   14222: 
                   14223: =head2 Resource Access Logging
                   14224: 
                   14225: =over 4
                   14226: 
                   14227: =item *
                   14228: 
                   14229: flushcourselogs() : flush (save) buffer logs and access logs
                   14230: 
                   14231: =item *
                   14232: 
                   14233: courselog($what) : save message for course in hash
                   14234: 
                   14235: =item *
                   14236: 
                   14237: courseacclog($what) : save message for course using &courselog().  Perform
                   14238: special processing for specific resource types (problems, exams, quizzes, etc).
                   14239: 
1.191     harris41 14240: =item *
                   14241: 
                   14242: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14243: as a PerlChildExitHandler
1.243     albertel 14244: 
                   14245: =back
                   14246: 
                   14247: =head2 Other
                   14248: 
                   14249: =over 4
                   14250: 
                   14251: =item *
                   14252: 
                   14253: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14254: 
                   14255: =back
                   14256: 
                   14257: =cut
1.877     foxr     14258: 

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