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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.68! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.67 2015/05/22 17:58:00 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,
1.1172.2.68! raeburn  4274:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
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.68! raeburn  4297:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
        !          4298:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4299:                 } else {
                   4300:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4301:                              $sincefilter.':'.&escape($descfilter).':'.
                   4302:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4303:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4304:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4305:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4306:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4307:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4308:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68! raeburn  4309:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
        !          4310:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4311:                 }
                   4312: 
1.918     raeburn  4313:                 my @pairs=split(/\&/,$rep);
                   4314:                 foreach my $item (@pairs) {
                   4315:                     my ($key,$value)=split(/\=/,$item,2);
                   4316:                     $key = &unescape($key);
                   4317:                     next if ($key =~ /^error: 2 /);
                   4318:                     my $result = &thaw_unescape($value);
                   4319:                     if (ref($result) eq 'HASH') {
                   4320:                         $returnhash{$key}=$result;
                   4321:                     } else {
1.921     raeburn  4322:                         my @responses = split(/:/,$value);
                   4323:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4324:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4325:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4326:                         }
1.1008    raeburn  4327:                     }
1.353     www      4328:                 }
                   4329:             }
                   4330:         }
                   4331:     }
                   4332:     return %returnhash;
                   4333: }
                   4334: 
1.1055    raeburn  4335: sub courselastaccess {
                   4336:     my ($cdom,$cnum,$hostidref) = @_;
                   4337:     my %returnhash;
                   4338:     if ($cdom && $cnum) {
                   4339:         my $chome = &homeserver($cnum,$cdom);
                   4340:         if ($chome ne 'no_host') {
                   4341:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4342:             &extract_lastaccess(\%returnhash,$rep);
                   4343:         }
                   4344:     } else {
                   4345:         if (!$cdom) { $cdom=''; }
                   4346:         my %libserv = &all_library();
                   4347:         foreach my $tryserver (keys(%libserv)) {
                   4348:             if (ref($hostidref) eq 'ARRAY') {
                   4349:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4350:             } 
                   4351:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4352:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4353:                 &extract_lastaccess(\%returnhash,$rep);
                   4354:             }
                   4355:         }
                   4356:     }
                   4357:     return %returnhash;
                   4358: }
                   4359: 
                   4360: sub extract_lastaccess {
                   4361:     my ($returnhash,$rep) = @_;
                   4362:     if (ref($returnhash) eq 'HASH') {
                   4363:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4364:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4365:                  $rep eq '') {
                   4366:             my @pairs=split(/\&/,$rep);
                   4367:             foreach my $item (@pairs) {
                   4368:                 my ($key,$value)=split(/\=/,$item,2);
                   4369:                 $key = &unescape($key);
                   4370:                 next if ($key =~ /^error: 2 /);
                   4371:                 $returnhash->{$key} = &thaw_unescape($value);
                   4372:             }
                   4373:         }
                   4374:     }
                   4375:     return;
                   4376: }
                   4377: 
1.658     raeburn  4378: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4379: 
                   4380: sub dcmailput {
1.685     raeburn  4381:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4382:     my $status = &Apache::lonnet::critical(
1.740     www      4383:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4384:        &escape($message),$server);
1.662     raeburn  4385:     return $status;
                   4386: }
                   4387: 
1.658     raeburn  4388: sub dcmaildump {
                   4389:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4390:     my %returnhash=();
1.846     albertel 4391: 
                   4392:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4393:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4394:                                                          &escape($enddate).':';
                   4395: 	my @esc_senders=map { &escape($_)} @$senders;
                   4396: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4397: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4398:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4399:             if (($key) && ($value)) {
                   4400:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4401:             }
                   4402:         }
                   4403:     }
                   4404:     return %returnhash;
                   4405: }
1.662     raeburn  4406: # ---------------------------------------------------------- Domain roles
                   4407: 
                   4408: sub get_domain_roles {
                   4409:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4410:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4411:         $startdate = '.';
                   4412:     }
1.1018    raeburn  4413:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4414:         $enddate = '.';
                   4415:     }
1.922     raeburn  4416:     my $rolelist;
                   4417:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4418:         $rolelist = join('&',@{$roles});
1.922     raeburn  4419:     }
1.662     raeburn  4420:     my %personnel = ();
1.841     albertel 4421: 
                   4422:     my %servers = &get_servers($dom,'library');
                   4423:     foreach my $tryserver (keys(%servers)) {
                   4424: 	%{$personnel{$tryserver}}=();
                   4425: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4426: 					    &escape($startdate).':'.
                   4427: 					    &escape($enddate).':'.
                   4428: 					    &escape($rolelist), $tryserver))) {
                   4429: 	    my ($key,$value) = split(/\=/,$line,2);
                   4430: 	    if (($key) && ($value)) {
                   4431: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4432: 	    }
                   4433: 	}
1.662     raeburn  4434:     }
                   4435:     return %personnel;
                   4436: }
1.658     raeburn  4437: 
1.1057    www      4438: # ----------------------------------------------------------- Interval timing 
1.149     www      4439: 
1.1153    www      4440: {
                   4441: # Caches needed for speedup of navmaps
                   4442: # We don't want to cache this for very long at all (5 seconds at most)
                   4443: # 
                   4444: # The user for whom we cache
                   4445: my $cachedkey='';
                   4446: # The cached times for this user
                   4447: my %cachedtimes=();
                   4448: # When this was last done
1.1172.2.66  raeburn  4449: my $cachedtime='';
1.1153    www      4450: 
                   4451: sub load_all_first_access {
1.1154    raeburn  4452:     my ($uname,$udom)=@_;
1.1156    www      4453:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4454:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4455:         return;
                   4456:     }
                   4457:     $cachedtime=time;
                   4458:     $cachedkey=$uname.':'.$udom;
                   4459:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4460: }
                   4461: 
1.504     albertel 4462: sub get_first_access {
1.1162    raeburn  4463:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4464:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4465:     if ($argsymb) { $symb=$argsymb; }
                   4466:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4467:     if ($argmap) { $map = $argmap; }
1.926     albertel 4468:     if ($type eq 'course') {
                   4469: 	$res='course';
                   4470:     } elsif ($type eq 'map') {
1.588     albertel 4471: 	$res=&symbread($map);
                   4472:     } else {
                   4473: 	$res=$symb;
                   4474:     }
1.1153    www      4475:     &load_all_first_access($uname,$udom);
                   4476:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4477: }
                   4478: 
                   4479: sub set_first_access {
1.1162    raeburn  4480:     my ($type,$interval)=@_;
1.790     albertel 4481:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4482:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4483:     if ($type eq 'course') {
                   4484: 	$res='course';
                   4485:     } elsif ($type eq 'map') {
1.588     albertel 4486: 	$res=&symbread($map);
                   4487:     } else {
                   4488: 	$res=$symb;
                   4489:     }
1.1153    www      4490:     $cachedkey='';
1.1162    raeburn  4491:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4492:     if (!$firstaccess) {
1.1162    raeburn  4493:         my $start = time;
                   4494: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4495:                           $udom,$uname);
                   4496:         if ($putres eq 'ok') {
                   4497:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4498:                  $udom,$uname); 
                   4499:             &appenv(
                   4500:                      {
                   4501:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4502:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4503:                      }
                   4504:                   );
                   4505:         }
                   4506:         return $putres;
1.505     albertel 4507:     }
                   4508:     return 'already_set';
1.504     albertel 4509: }
1.1153    www      4510: }
1.1172.2.32  raeburn  4511: 
                   4512: sub checkout {
                   4513:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4514:     my $now=time;
                   4515:     my $lonhost=$perlvar{'lonHostID'};
                   4516:     my $infostr=&escape(
                   4517:                  'CHECKOUTTOKEN&'.
                   4518:                  $tuname.'&'.
                   4519:                  $tudom.'&'.
                   4520:                  $tcrsid.'&'.
                   4521:                  $symb.'&'.
                   4522:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4523:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4524:     if ($token=~/^error\:/) {
                   4525:         &logthis("<font color=\"blue\">WARNING: ".
                   4526:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4527:                  "</font>");
                   4528:         return '';
                   4529:     }
                   4530: 
                   4531:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4532:     $token=~tr/a-z/A-Z/;
                   4533: 
                   4534:     my %infohash=('resource.0.outtoken' => $token,
                   4535:                   'resource.0.checkouttime' => $now,
                   4536:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4537: 
                   4538:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4539:        return '';
                   4540:     } else {
                   4541:         &logthis("<font color=\"blue\">WARNING: ".
                   4542:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4543:                  "</font>");
                   4544:     }
                   4545: 
                   4546:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4547:                          &escape('Checkout '.$infostr.' - '.
                   4548:                                                  $token)) ne 'ok') {
                   4549:         return '';
                   4550:     } else {
                   4551:         &logthis("<font color=\"blue\">WARNING: ".
                   4552:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4553:                  "</font>");
                   4554:     }
                   4555:     return $token;
                   4556: }
                   4557: 
                   4558: # ------------------------------------------------------------ Check in an item
                   4559: 
                   4560: sub checkin {
                   4561:     my $token=shift;
                   4562:     my $now=time;
                   4563:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4564:     $lonhost=~tr/A-Z/a-z/;
                   4565:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4566:     $dtoken=~s/\W/\_/g;
                   4567:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4568:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4569: 
                   4570:     unless (($tuname) && ($tudom)) {
                   4571:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4572:         return '';
                   4573:     }
                   4574: 
                   4575:     unless (&allowed('mgr',$tcrsid)) {
                   4576:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4577:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4578:         return '';
                   4579:     }
                   4580: 
                   4581:     my %infohash=('resource.0.intoken' => $token,
                   4582:                   'resource.0.checkintime' => $now,
                   4583:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4584: 
                   4585:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4586:        return '';
                   4587:     }
                   4588: 
                   4589:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4590:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4591:         return '';
                   4592:     }
                   4593: 
                   4594:     return ($symb,$tuname,$tudom,$tcrsid);
                   4595: }
                   4596: 
1.110     www      4597: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4598: 
                   4599: sub expirespread {
                   4600:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4601:     my $cid=$env{'request.course.id'}; 
1.110     www      4602:     if ($cid) {
                   4603:        my $now=time;
                   4604:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4605:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4606:                             $env{'course.'.$cid.'.num'}.
1.110     www      4607: 	        	    ':nohist_expirationdates:'.
                   4608:                             &escape($key).'='.$now,
1.620     albertel 4609:                             $env{'course.'.$cid.'.home'})
1.110     www      4610:     }
                   4611:     return 'ok';
1.14      www      4612: }
                   4613: 
1.109     www      4614: # ----------------------------------------------------- Devalidate Spreadsheets
                   4615: 
                   4616: sub devalidate {
1.325     www      4617:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4618:     my $cid=$env{'request.course.id'}; 
1.109     www      4619:     if ($cid) {
1.391     matthew  4620:         # delete the stored spreadsheets for
                   4621:         # - the student level sheet of this user in course's homespace
                   4622:         # - the assessment level sheet for this resource 
                   4623:         #   for this user in user's homespace
1.553     albertel 4624: 	# - current conditional state info
1.325     www      4625: 	my $key=$uname.':'.$udom.':';
1.109     www      4626:         my $status=
1.299     matthew  4627: 	    &del('nohist_calculatedsheets',
1.391     matthew  4628: 		 [$key.'studentcalc:'],
1.620     albertel 4629: 		 $env{'course.'.$cid.'.domain'},
                   4630: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4631: 		.' '.
                   4632: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4633: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4634:         unless ($status eq 'ok ok') {
                   4635:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4636:                     $uname.' at '.$udom.' for '.
1.109     www      4637: 		    $symb.': '.$status);
1.133     albertel 4638:         }
1.553     albertel 4639: 	&delenv('user.state.'.$cid);
1.109     www      4640:     }
                   4641: }
                   4642: 
1.265     albertel 4643: sub get_scalar {
                   4644:     my ($string,$end) = @_;
                   4645:     my $value;
                   4646:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4647: 	$value = $1;
                   4648:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4649: 	$value = $1;
                   4650:     }
                   4651:     return &unescape($value);
                   4652: }
                   4653: 
                   4654: sub array2str {
                   4655:   my (@array) = @_;
                   4656:   my $result=&arrayref2str(\@array);
                   4657:   $result=~s/^__ARRAY_REF__//;
                   4658:   $result=~s/__END_ARRAY_REF__$//;
                   4659:   return $result;
                   4660: }
                   4661: 
1.204     albertel 4662: sub arrayref2str {
                   4663:   my ($arrayref) = @_;
1.265     albertel 4664:   my $result='__ARRAY_REF__';
1.204     albertel 4665:   foreach my $elem (@$arrayref) {
1.265     albertel 4666:     if(ref($elem) eq 'ARRAY') {
                   4667:       $result.=&arrayref2str($elem).'&';
                   4668:     } elsif(ref($elem) eq 'HASH') {
                   4669:       $result.=&hashref2str($elem).'&';
                   4670:     } elsif(ref($elem)) {
                   4671:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4672:     } else {
                   4673:       $result.=&escape($elem).'&';
                   4674:     }
                   4675:   }
                   4676:   $result=~s/\&$//;
1.265     albertel 4677:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4678:   return $result;
                   4679: }
                   4680: 
1.168     albertel 4681: sub hash2str {
1.204     albertel 4682:   my (%hash) = @_;
                   4683:   my $result=&hashref2str(\%hash);
1.265     albertel 4684:   $result=~s/^__HASH_REF__//;
                   4685:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4686:   return $result;
                   4687: }
                   4688: 
                   4689: sub hashref2str {
                   4690:   my ($hashref)=@_;
1.265     albertel 4691:   my $result='__HASH_REF__';
1.800     albertel 4692:   foreach my $key (sort(keys(%$hashref))) {
                   4693:     if (ref($key) eq 'ARRAY') {
                   4694:       $result.=&arrayref2str($key).'=';
                   4695:     } elsif (ref($key) eq 'HASH') {
                   4696:       $result.=&hashref2str($key).'=';
                   4697:     } elsif (ref($key)) {
1.265     albertel 4698:       $result.='=';
1.800     albertel 4699:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4700:     } else {
1.1132    raeburn  4701: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4702:     }
                   4703: 
1.800     albertel 4704:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4705:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4706:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4707:       $result.=&hashref2str($hashref->{$key}).'&';
                   4708:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4709:        $result.='&';
1.800     albertel 4710:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4711:     } else {
1.800     albertel 4712:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4713:     }
                   4714:   }
1.168     albertel 4715:   $result=~s/\&$//;
1.265     albertel 4716:   $result .= '__END_HASH_REF__';
1.168     albertel 4717:   return $result;
                   4718: }
                   4719: 
                   4720: sub str2hash {
1.265     albertel 4721:     my ($string)=@_;
                   4722:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4723:     return %$hash;
                   4724: }
                   4725: 
                   4726: sub str2hashref {
1.168     albertel 4727:   my ($string) = @_;
1.265     albertel 4728: 
                   4729:   my %hash;
                   4730: 
                   4731:   if($string !~ /^__HASH_REF__/) {
                   4732:       if (! ($string eq '' || !defined($string))) {
                   4733: 	  $hash{'error'}='Not hash reference';
                   4734:       }
                   4735:       return (\%hash, $string);
                   4736:   }
                   4737: 
                   4738:   $string =~ s/^__HASH_REF__//;
                   4739: 
                   4740:   while($string !~ /^__END_HASH_REF__/) {
                   4741:       #key
                   4742:       my $key='';
                   4743:       if($string =~ /^__HASH_REF__/) {
                   4744:           ($key, $string)=&str2hashref($string);
                   4745:           if(defined($key->{'error'})) {
                   4746:               $hash{'error'}='Bad data';
                   4747:               return (\%hash, $string);
                   4748:           }
                   4749:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4750:           ($key, $string)=&str2arrayref($string);
                   4751:           if($key->[0] eq 'Array reference error') {
                   4752:               $hash{'error'}='Bad data';
                   4753:               return (\%hash, $string);
                   4754:           }
                   4755:       } else {
                   4756:           $string =~ s/^(.*?)=//;
1.267     albertel 4757: 	  $key=&unescape($1);
1.265     albertel 4758:       }
                   4759:       $string =~ s/^=//;
                   4760: 
                   4761:       #value
                   4762:       my $value='';
                   4763:       if($string =~ /^__HASH_REF__/) {
                   4764:           ($value, $string)=&str2hashref($string);
                   4765:           if(defined($value->{'error'})) {
                   4766:               $hash{'error'}='Bad data';
                   4767:               return (\%hash, $string);
                   4768:           }
                   4769:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4770:           ($value, $string)=&str2arrayref($string);
                   4771:           if($value->[0] eq 'Array reference error') {
                   4772:               $hash{'error'}='Bad data';
                   4773:               return (\%hash, $string);
                   4774:           }
                   4775:       } else {
                   4776: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4777:       }
                   4778:       $string =~ s/^&//;
                   4779: 
                   4780:       $hash{$key}=$value;
1.204     albertel 4781:   }
1.265     albertel 4782: 
                   4783:   $string =~ s/^__END_HASH_REF__//;
                   4784: 
                   4785:   return (\%hash, $string);
1.204     albertel 4786: }
                   4787: 
                   4788: sub str2array {
1.265     albertel 4789:     my ($string)=@_;
                   4790:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4791:     return @$array;
                   4792: }
                   4793: 
                   4794: sub str2arrayref {
1.204     albertel 4795:   my ($string) = @_;
1.265     albertel 4796:   my @array;
                   4797: 
                   4798:   if($string !~ /^__ARRAY_REF__/) {
                   4799:       if (! ($string eq '' || !defined($string))) {
                   4800: 	  $array[0]='Array reference error';
                   4801:       }
                   4802:       return (\@array, $string);
                   4803:   }
                   4804: 
                   4805:   $string =~ s/^__ARRAY_REF__//;
                   4806: 
                   4807:   while($string !~ /^__END_ARRAY_REF__/) {
                   4808:       my $value='';
                   4809:       if($string =~ /^__HASH_REF__/) {
                   4810:           ($value, $string)=&str2hashref($string);
                   4811:           if(defined($value->{'error'})) {
                   4812:               $array[0] ='Array reference error';
                   4813:               return (\@array, $string);
                   4814:           }
                   4815:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4816:           ($value, $string)=&str2arrayref($string);
                   4817:           if($value->[0] eq 'Array reference error') {
                   4818:               $array[0] ='Array reference error';
                   4819:               return (\@array, $string);
                   4820:           }
                   4821:       } else {
                   4822: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4823:       }
                   4824:       $string =~ s/^&//;
                   4825: 
                   4826:       push(@array, $value);
1.191     harris41 4827:   }
1.265     albertel 4828: 
                   4829:   $string =~ s/^__END_ARRAY_REF__//;
                   4830: 
                   4831:   return (\@array, $string);
1.168     albertel 4832: }
                   4833: 
1.167     albertel 4834: # -------------------------------------------------------------------Temp Store
                   4835: 
1.168     albertel 4836: sub tmpreset {
                   4837:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4838:   if (!$symb) {
                   4839:     $symb=&symbread();
1.620     albertel 4840:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4841:   }
                   4842:   $symb=escape($symb);
                   4843: 
1.620     albertel 4844:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4845:   $namespace=~s/\//\_/g;
                   4846:   $namespace=~s/\W//g;
                   4847: 
1.620     albertel 4848:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4849:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4850:   if ($domain eq 'public' && $stuname eq 'public') {
                   4851:       $stuname=$ENV{'REMOTE_ADDR'};
                   4852:   }
1.1117    foxr     4853:   my $path=LONCAPA::tempdir();
1.168     albertel 4854:   my %hash;
                   4855:   if (tie(%hash,'GDBM_File',
                   4856: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4857: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4858:     foreach my $key (keys(%hash)) {
1.180     albertel 4859:       if ($key=~ /:$symb/) {
1.168     albertel 4860: 	delete($hash{$key});
                   4861:       }
                   4862:     }
                   4863:   }
                   4864: }
                   4865: 
1.167     albertel 4866: sub tmpstore {
1.168     albertel 4867:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4868: 
                   4869:   if (!$symb) {
                   4870:     $symb=&symbread();
1.620     albertel 4871:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4872:   }
                   4873:   $symb=escape($symb);
                   4874: 
                   4875:   if (!$namespace) {
                   4876:     # I don't think we would ever want to store this for a course.
                   4877:     # it seems this will only be used if we don't have a course.
1.620     albertel 4878:     #$namespace=$env{'request.course.id'};
1.168     albertel 4879:     #if (!$namespace) {
1.620     albertel 4880:       $namespace=$env{'request.state'};
1.168     albertel 4881:     #}
                   4882:   }
                   4883:   $namespace=~s/\//\_/g;
                   4884:   $namespace=~s/\W//g;
1.620     albertel 4885:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4886:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4887:   if ($domain eq 'public' && $stuname eq 'public') {
                   4888:       $stuname=$ENV{'REMOTE_ADDR'};
                   4889:   }
1.168     albertel 4890:   my $now=time;
                   4891:   my %hash;
1.1117    foxr     4892:   my $path=LONCAPA::tempdir();
1.168     albertel 4893:   if (tie(%hash,'GDBM_File',
                   4894: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4895: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4896:     $hash{"version:$symb"}++;
                   4897:     my $version=$hash{"version:$symb"};
                   4898:     my $allkeys=''; 
                   4899:     foreach my $key (keys(%$storehash)) {
                   4900:       $allkeys.=$key.':';
1.591     albertel 4901:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4902:     }
                   4903:     $hash{"$version:$symb:timestamp"}=$now;
                   4904:     $allkeys.='timestamp';
                   4905:     $hash{"$version:keys:$symb"}=$allkeys;
                   4906:     if (untie(%hash)) {
                   4907:       return 'ok';
                   4908:     } else {
                   4909:       return "error:$!";
                   4910:     }
                   4911:   } else {
                   4912:     return "error:$!";
                   4913:   }
                   4914: }
1.167     albertel 4915: 
1.168     albertel 4916: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4917: 
1.168     albertel 4918: sub tmprestore {
                   4919:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4920: 
1.168     albertel 4921:   if (!$symb) {
                   4922:     $symb=&symbread();
1.620     albertel 4923:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4924:   }
                   4925:   $symb=escape($symb);
                   4926: 
1.620     albertel 4927:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4928: 
1.620     albertel 4929:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4930:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4931:   if ($domain eq 'public' && $stuname eq 'public') {
                   4932:       $stuname=$ENV{'REMOTE_ADDR'};
                   4933:   }
1.168     albertel 4934:   my %returnhash;
                   4935:   $namespace=~s/\//\_/g;
                   4936:   $namespace=~s/\W//g;
                   4937:   my %hash;
1.1117    foxr     4938:   my $path=LONCAPA::tempdir();
1.168     albertel 4939:   if (tie(%hash,'GDBM_File',
                   4940: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4941: 	  &GDBM_READER(),0640)) {
1.168     albertel 4942:     my $version=$hash{"version:$symb"};
                   4943:     $returnhash{'version'}=$version;
                   4944:     my $scope;
                   4945:     for ($scope=1;$scope<=$version;$scope++) {
                   4946:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4947:       my @keys=split(/:/,$vkeys);
                   4948:       my $key;
                   4949:       $returnhash{"$scope:keys"}=$vkeys;
                   4950:       foreach $key (@keys) {
1.591     albertel 4951: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4952: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4953:       }
                   4954:     }
1.168     albertel 4955:     if (!(untie(%hash))) {
                   4956:       return "error:$!";
                   4957:     }
                   4958:   } else {
                   4959:     return "error:$!";
                   4960:   }
                   4961:   return %returnhash;
1.167     albertel 4962: }
                   4963: 
1.9       www      4964: # ----------------------------------------------------------------------- Store
                   4965: 
                   4966: sub store {
1.1172.2.64  raeburn  4967:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      4968:     my $home='';
                   4969: 
1.168     albertel 4970:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4971: 
1.213     www      4972:     $symb=&symbclean($symb);
1.122     albertel 4973:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4974: 
1.620     albertel 4975:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4976:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4977: 
                   4978:     &devalidate($symb,$stuname,$domain);
1.109     www      4979: 
                   4980:     $symb=escape($symb);
1.187     www      4981:     if (!$namespace) { 
1.620     albertel 4982:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4983:           return ''; 
                   4984:        } 
                   4985:     }
1.620     albertel 4986:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4987: 
                   4988:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4989:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4990: 
1.12      www      4991:     my $namevalue='';
1.800     albertel 4992:     foreach my $key (keys(%$storehash)) {
                   4993:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4994:     }
1.12      www      4995:     $namevalue=~s/\&$//;
1.187     www      4996:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  4997:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      4998: }
                   4999: 
1.47      www      5000: # -------------------------------------------------------------- Critical Store
                   5001: 
                   5002: sub cstore {
1.1172.2.64  raeburn  5003:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5004:     my $home='';
                   5005: 
1.168     albertel 5006:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5007: 
1.213     www      5008:     $symb=&symbclean($symb);
1.122     albertel 5009:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5010: 
1.620     albertel 5011:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5012:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5013: 
                   5014:     &devalidate($symb,$stuname,$domain);
1.109     www      5015: 
                   5016:     $symb=escape($symb);
1.187     www      5017:     if (!$namespace) { 
1.620     albertel 5018:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5019:           return ''; 
                   5020:        } 
                   5021:     }
1.620     albertel 5022:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5023: 
                   5024:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5025:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5026: 
1.47      www      5027:     my $namevalue='';
1.800     albertel 5028:     foreach my $key (keys(%$storehash)) {
                   5029:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5030:     }
1.47      www      5031:     $namevalue=~s/\&$//;
1.187     www      5032:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5033:     return critical
1.1172.2.64  raeburn  5034:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5035: }
                   5036: 
1.9       www      5037: # --------------------------------------------------------------------- Restore
                   5038: 
                   5039: sub restore {
1.124     www      5040:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5041:     my $home='';
                   5042: 
1.168     albertel 5043:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5044: 
1.122     albertel 5045:     if (!$symb) {
1.1172.2.26  raeburn  5046:         return if ($namespace eq 'courserequests');
                   5047:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5048:     } else {
1.1172.2.26  raeburn  5049:         unless ($namespace eq 'courserequests') {
                   5050:             $symb=&escape(&symbclean($symb));
                   5051:         }
1.122     albertel 5052:     }
1.188     www      5053:     if (!$namespace) { 
1.620     albertel 5054:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5055:           return ''; 
                   5056:        } 
                   5057:     }
1.620     albertel 5058:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5059:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5060:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5061:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5062: 
1.12      www      5063:     my %returnhash=();
1.800     albertel 5064:     foreach my $line (split(/\&/,$answer)) {
                   5065: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5066:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5067:     }
1.75      www      5068:     my $version;
                   5069:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5070:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5071:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5072:        }
1.75      www      5073:     }
1.13      www      5074:     return %returnhash;
1.34      www      5075: }
                   5076: 
                   5077: # ---------------------------------------------------------- Course Description
1.1118    foxr     5078: #
                   5079: #  
1.34      www      5080: 
                   5081: sub coursedescription {
1.731     albertel 5082:     my ($courseid,$args)=@_;
1.34      www      5083:     $courseid=~s/^\///;
1.49      www      5084:     $courseid=~s/\_/\//g;
1.34      www      5085:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5086:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5087:     my $normalid=$cdomain.'_'.$cnum;
                   5088:     # need to always cache even if we get errors otherwise we keep 
                   5089:     # trying and trying and trying to get the course description.
                   5090:     my %envhash=();
                   5091:     my %returnhash=();
1.731     albertel 5092:     
                   5093:     my $expiretime=600;
                   5094:     if ($env{'request.course.id'} eq $normalid) {
                   5095: 	$expiretime=120;
                   5096:     }
                   5097: 
                   5098:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5099:     if (!$args->{'freshen_cache'}
                   5100: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5101: 	foreach my $key (keys(%env)) {
                   5102: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5103: 	    my ($setting) = $1;
                   5104: 	    $returnhash{$setting} = $env{$key};
                   5105: 	}
                   5106: 	return %returnhash;
                   5107:     }
                   5108: 
1.1118    foxr     5109:     # get the data again
                   5110: 
1.731     albertel 5111:     if (!$args->{'one_time'}) {
                   5112: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5113:     }
1.811     albertel 5114: 
1.34      www      5115:     if ($chome ne 'no_host') {
1.302     albertel 5116:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5117:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5118: 	   my $username = $env{'user.name'}; # Defult username
                   5119: 	   if(defined $args->{'user'}) {
                   5120: 	       $username = $args->{'user'};
                   5121: 	   }
1.129     albertel 5122:            $returnhash{'home'}= $chome;
                   5123: 	   $returnhash{'domain'} = $cdomain;
                   5124: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5125:            if (!defined($returnhash{'type'})) {
                   5126:                $returnhash{'type'} = 'Course';
                   5127:            }
1.130     albertel 5128:            while (my ($name,$value) = each %returnhash) {
1.53      www      5129:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5130:            }
1.270     www      5131:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5132:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5133: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5134:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5135:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5136:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5137:        }
                   5138:     }
1.731     albertel 5139:     if (!$args->{'one_time'}) {
1.949     raeburn  5140: 	&appenv(\%envhash);
1.731     albertel 5141:     }
1.302     albertel 5142:     return %returnhash;
1.461     www      5143: }
                   5144: 
1.1080    raeburn  5145: sub update_released_required {
                   5146:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5147:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5148:         $cid = $env{'request.course.id'};
                   5149:         $cdom = $env{'course.'.$cid.'.domain'};
                   5150:         $cnum = $env{'course.'.$cid.'.num'};
                   5151:         $chome = $env{'course.'.$cid.'.home'};
                   5152:     }
                   5153:     if ($needsrelease) {
                   5154:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5155:         my $needsupdate;
                   5156:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5157:             $needsupdate = 1;
                   5158:         } else {
                   5159:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5160:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5161:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5162:                 $needsupdate = 1;
                   5163:             }
                   5164:         }
                   5165:         if ($needsupdate) {
                   5166:             my %needshash = (
                   5167:                              'internal.releaserequired' => $needsrelease,
                   5168:                             );
                   5169:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5170:             if ($putresult eq 'ok') {
                   5171:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5172:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5173:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5174:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5175:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5176:                 }
                   5177:             }
                   5178:         }
                   5179:     }
                   5180:     return;
                   5181: }
                   5182: 
1.461     www      5183: # -------------------------------------------------See if a user is privileged
                   5184: 
                   5185: sub privileged {
1.1172.2.23  raeburn  5186:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5187:     my $now = time;
1.1172.2.23  raeburn  5188:     my $roles;
                   5189:     if (ref($possroles) eq 'ARRAY') {
                   5190:         $roles = $possroles;
                   5191:     } else {
                   5192:         $roles = ['dc','su'];
                   5193:     }
                   5194:     if (ref($possdomains) eq 'ARRAY') {
                   5195:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5196:         foreach my $dom (@{$possdomains}) {
                   5197:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5198:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5199:                 foreach my $role (@{$roles}) {
                   5200:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5201:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5202:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5203:                             return 1 unless (($end && $end < $now) ||
                   5204:                                              ($start && $start > $now));
                   5205:                         }
                   5206:                     }
                   5207:                 }
                   5208:             }
                   5209:         }
                   5210:     } else {
                   5211:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5212:         my $now = time;
1.1170    droeschl 5213: 
1.1172.2.58  raeburn  5214:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5215:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5216:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5217:                 return 1 unless ($tend && $tend < $now)
                   5218:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5219:             }
1.1172.2.23  raeburn  5220:         }
                   5221:     }
1.461     www      5222:     return 0;
1.9       www      5223: }
1.1       albertel 5224: 
1.1172.2.23  raeburn  5225: sub privileged_by_domain {
                   5226:     my ($domains,$roles) = @_;
                   5227:     my %privileged = ();
                   5228:     my $cachetime = 60*60*24;
                   5229:     my $now = time;
                   5230:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5231:         return %privileged;
                   5232:     }
                   5233:     foreach my $dom (@{$domains}) {
                   5234:         next if (ref($privileged{$dom}) eq 'HASH');
                   5235:         my $needroles;
                   5236:         foreach my $role (@{$roles}) {
                   5237:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5238:             if (defined($cached)) {
                   5239:                 if (ref($result) eq 'HASH') {
                   5240:                     $privileged{$dom}{$role} = $result;
                   5241:                 }
                   5242:             } else {
                   5243:                 $needroles = 1;
                   5244:             }
                   5245:         }
                   5246:         if ($needroles) {
                   5247:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5248:             $privileged{$dom} = {};
                   5249:             foreach my $server (keys(%dompersonnel)) {
                   5250:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5251:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5252:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5253:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5254:                         next if ($end && $end < $now);
                   5255:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5256:                             $dompersonnel{$server}{$item};
                   5257:                     }
                   5258:                 }
                   5259:             }
                   5260:             if (ref($privileged{$dom}) eq 'HASH') {
                   5261:                 foreach my $role (@{$roles}) {
                   5262:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5263:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5264:                     } else {
                   5265:                         my %hash = ();
                   5266:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5267:                     }
                   5268:                 }
                   5269:             }
                   5270:         }
                   5271:     }
                   5272:     return %privileged;
                   5273: }
                   5274: 
1.103     harris41 5275: # -------------------------------------------------------- Get user privileges
1.11      www      5276: 
                   5277: sub rolesinit {
1.1169    droeschl 5278:     my ($domain, $username) = @_;
                   5279:     my %userroles = ('user.login.time' => time);
                   5280:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5281: 
                   5282:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5283:     # also, blocking can be triggered by an activating timer
                   5284:     # it's saved in the user's %env.
                   5285:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5286:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5287:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5288:         %timerintchk, %timerintenv);
                   5289: 
1.1162    raeburn  5290:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5291:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5292:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5293:     }
1.1169    droeschl 5294: 
1.1162    raeburn  5295:     foreach my $key (keys(%timerinterval)) {
                   5296:         my ($cid,$rest) = split(/\0/,$key);
                   5297:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5298:     }
1.1169    droeschl 5299: 
1.11      www      5300:     my %allroles=();
1.1162    raeburn  5301:     my %allgroups=();
1.11      www      5302: 
1.1172.2.58  raeburn  5303:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5304:         my $role = $rolesdump{$area};
                   5305:         $area =~ s/\_\w\w$//;
                   5306: 
                   5307:         my ($trole, $tend, $tstart, $group_privs);
                   5308: 
                   5309:         if ($role =~ /^cr/) {
                   5310:         # Custom role, defined by a user 
                   5311:         # e.g., user.role.cr/msu/smith/mynewrole
                   5312:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5313:                 $trole = $1;
                   5314:                 ($tend, $tstart) = split('_', $2);
                   5315:             } else {
                   5316:                 $trole = $role;
                   5317:             }
                   5318:         } elsif ($role =~ m|^gr/|) {
                   5319:         # Role of member in a group, defined within a course/community
                   5320:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5321:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5322:             next if $tstart eq '-1';
                   5323:             ($trole, $group_privs) = split(/\//, $trole);
                   5324:             $group_privs = &unescape($group_privs);
                   5325:         } else {
                   5326:         # Just a normal role, defined in roles.tab
                   5327:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5328:         }
                   5329: 
                   5330:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5331:                  $username);
                   5332:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5333: 
                   5334:         # role expired or not available yet?
                   5335:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5336:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5337: 
                   5338:         next if $area eq '' or $trole eq '';
                   5339: 
                   5340:         my $spec = "$trole.$area";
                   5341:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5342: 
                   5343:         if ($trole =~ /^cr\//) {
                   5344:         # Custom role, defined by a user
                   5345:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5346:         } elsif ($trole eq 'gr') {
                   5347:         # Role of a member in a group, defined within a course/community
                   5348:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5349:             next;
                   5350:         } else {
                   5351:         # Normal role, defined in roles.tab
                   5352:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5353:         }
                   5354: 
                   5355:         my $cid = $tdomain.'_'.$trest;
                   5356:         unless ($firstaccchk{$cid}) {
                   5357:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5358:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5359:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5360:                         $coursetimerstarts{$cid}{$item}; 
                   5361:                 }
                   5362:             }
                   5363:             $firstaccchk{$cid} = 1;
                   5364:         }
                   5365:         unless ($timerintchk{$cid}) {
                   5366:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5367:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5368:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5369:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5370:                 }
1.12      www      5371:             }
1.1169    droeschl 5372:             $timerintchk{$cid} = 1;
1.191     harris41 5373:         }
1.11      www      5374:     }
1.1169    droeschl 5375: 
                   5376:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5377:         \%allroles, \%allgroups);
                   5378:     $env{'user.adv'} = $userroles{'user.adv'};
                   5379: 
1.1162    raeburn  5380:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5381: }
                   5382: 
1.567     raeburn  5383: sub set_arearole {
1.1172.2.19  raeburn  5384:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5385:     unless ($nolog) {
1.567     raeburn  5386: # log the associated role with the area
1.1172.2.19  raeburn  5387:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5388:     }
1.743     albertel 5389:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5390: }
                   5391: 
                   5392: sub custom_roleprivs {
                   5393:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5394:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5395:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5396:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5397:         my ($rdummy,$roledef)=
                   5398:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5399:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5400:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5401:             if (defined($syspriv)) {
1.1043    raeburn  5402:                 if ($trest =~ /^$match_community$/) {
                   5403:                     $syspriv =~ s/bre\&S//; 
                   5404:                 }
1.567     raeburn  5405:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5406:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5407:             }
                   5408:             if ($tdomain ne '') {
                   5409:                 if (defined($dompriv)) {
                   5410:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5411:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5412:                 }
                   5413:                 if (($trest ne '') && (defined($coursepriv))) {
                   5414:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5415:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5416:                 }
                   5417:             }
                   5418:         }
                   5419:     }
                   5420: }
                   5421: 
1.678     raeburn  5422: sub group_roleprivs {
                   5423:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5424:     my $access = 1;
                   5425:     my $now = time;
                   5426:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5427:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5428:     if ($access) {
1.811     albertel 5429:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5430:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5431:     }
                   5432: }
1.567     raeburn  5433: 
                   5434: sub standard_roleprivs {
                   5435:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5436:     if (defined($pr{$trole.':s'})) {
                   5437:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5438:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5439:     }
                   5440:     if ($tdomain ne '') {
                   5441:         if (defined($pr{$trole.':d'})) {
                   5442:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5443:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5444:         }
                   5445:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5446:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5447:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5448:         }
                   5449:     }
                   5450: }
                   5451: 
                   5452: sub set_userprivs {
1.1064    raeburn  5453:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5454:     my $author=0;
                   5455:     my $adv=0;
1.678     raeburn  5456:     my %grouproles = ();
                   5457:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5458:         my @groupkeys; 
1.1000    raeburn  5459:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5460:             push(@groupkeys,$role);
                   5461:         }
                   5462:         if (ref($groups_roles) eq 'HASH') {
                   5463:             foreach my $key (keys(%{$groups_roles})) {
                   5464:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5465:                     push(@groupkeys,$key);
                   5466:                 }
                   5467:             }
                   5468:         }
                   5469:         if (@groupkeys > 0) {
                   5470:             foreach my $role (@groupkeys) {
                   5471:                 my ($trole,$area,$sec,$extendedarea);
                   5472:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5473:                     $trole = $1;
                   5474:                     $area = $2;
                   5475:                     $sec = $3;
                   5476:                     $extendedarea = $area.$sec;
                   5477:                     if (exists($$allgroups{$area})) {
                   5478:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5479:                             my $spec = $trole.'.'.$extendedarea;
                   5480:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5481:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5482:                         }
1.678     raeburn  5483:                     }
                   5484:                 }
                   5485:             }
                   5486:         }
                   5487:     }
1.800     albertel 5488:     foreach my $group (keys(%grouproles)) {
                   5489:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5490:     }
1.800     albertel 5491:     foreach my $role (keys(%{$allroles})) {
                   5492:         my %thesepriv;
1.941     raeburn  5493:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5494:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5495:             if ($item ne '') {
                   5496:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5497:                 if ($restrictions eq '') {
                   5498:                     $thesepriv{$privilege}='F';
                   5499:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5500:                     $thesepriv{$privilege}.=$restrictions;
                   5501:                 }
                   5502:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5503:             }
                   5504:         }
                   5505:         my $thesestr='';
1.1104    raeburn  5506:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5507: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5508: 	}
                   5509:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5510:     }
                   5511:     return ($author,$adv);
                   5512: }
                   5513: 
1.994     raeburn  5514: sub role_status {
1.1104    raeburn  5515:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5516:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5517:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5518:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5519:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5520:             $$where = '/'.$two;
1.994     raeburn  5521:             $$trolecode=$$role.'.'.$$where;
                   5522:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5523:             $$tstatus='is';
1.1104    raeburn  5524:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5525:                 $$tstatus='future';
1.1034    raeburn  5526:                 if ($$tstart<$now) {
                   5527:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5528:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5529:                             my (%allroles,%allgroups,$group_privs,
                   5530:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5531:                             my %userroles = (
                   5532:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5533:                             );
1.1064    raeburn  5534:                             @rolecodes = ('cm'); 
1.1002    raeburn  5535:                             my $spec=$$role.'.'.$$where;
                   5536:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5537:                             if ($$role =~ /^cr\//) {
                   5538:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5539:                                 push(@rolecodes,'cr');
1.1002    raeburn  5540:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5541:                                 push(@rolecodes,$$role);
1.1002    raeburn  5542:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5543:                                                     $env{'user.name'});
1.1064    raeburn  5544:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5545:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5546:                                 $group_privs = &unescape($group_privs);
                   5547:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5548:                                 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  5549:                                 &get_groups_roles($tdomain,$trest,
                   5550:                                                   \%course_roles,\@rolecodes,
                   5551:                                                   \%groups_roles);
1.1002    raeburn  5552:                             } else {
1.1064    raeburn  5553:                                 push(@rolecodes,$$role);
1.1002    raeburn  5554:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5555:                             }
1.1064    raeburn  5556:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5557:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5558:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5559:                         }
                   5560:                     }
1.1034    raeburn  5561:                     $$tstatus = 'is';
1.1002    raeburn  5562:                 }
1.994     raeburn  5563:             }
                   5564:             if ($$tend) {
1.1104    raeburn  5565:                 if ($$tend<$update) {
1.994     raeburn  5566:                     $$tstatus='expired';
                   5567:                 } elsif ($$tend<$now) {
                   5568:                     $$tstatus='will_not';
                   5569:                 }
                   5570:             }
                   5571:         }
                   5572:     }
                   5573: }
                   5574: 
1.1104    raeburn  5575: sub get_groups_roles {
                   5576:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5577:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5578:                   (ref($rolecodes) eq 'ARRAY') && 
                   5579:                   (ref($groups_roles) eq 'HASH')); 
                   5580:     if (keys(%{$cdom_courseroles}) > 0) {
                   5581:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5582:         if ($cdom ne '' && $cnum ne '') {
                   5583:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5584:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5585:                     my $crsrole = $1;
                   5586:                     my $crssec = $2;
                   5587:                     if ($crsrole =~ /^cr/) {
                   5588:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5589:                             push(@{$rolecodes},'cr');
                   5590:                         }
                   5591:                     } else {
                   5592:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5593:                             push(@{$rolecodes},$crsrole);
                   5594:                         }
                   5595:                     }
                   5596:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5597:                     if ($crssec ne '') {
                   5598:                         $rolekey .= "/$crssec";
                   5599:                     }
                   5600:                     $rolekey .= './';
                   5601:                     $groups_roles->{$rolekey} = $rolecodes;
                   5602:                 }
                   5603:             }
                   5604:         }
                   5605:     }
                   5606:     return;
                   5607: }
                   5608: 
                   5609: sub delete_env_groupprivs {
                   5610:     my ($where,$courseroles,$possroles) = @_;
                   5611:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5612:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5613:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5614:         %{$courseroles->{$udom}} =
                   5615:             &get_my_roles('','','userroles',['active'],
                   5616:                           $possroles,[$udom],1);
                   5617:     }
                   5618:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5619:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5620:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5621:             my $area = '/'.$cdom.'/'.$cnum;
                   5622:             my $privkey = "user.priv.$crsrole.$area";
                   5623:             if ($crssec ne '') {
                   5624:                 $privkey .= '/'.$crssec;
                   5625:             }
                   5626:             $privkey .= ".$area/$group";
                   5627:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5628:         }
                   5629:     }
                   5630:     return;
                   5631: }
                   5632: 
1.994     raeburn  5633: sub check_adhoc_privs {
1.1104    raeburn  5634:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5635:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5636:     my $setprivs;
1.994     raeburn  5637:     if ($env{$cckey}) {
                   5638:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5639:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5640:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5641:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5642:             $setprivs = 1;
1.994     raeburn  5643:         }
                   5644:     } else {
1.1088    raeburn  5645:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5646:         $setprivs = 1;
1.994     raeburn  5647:     }
1.1172.2.9  raeburn  5648:     return $setprivs;
1.994     raeburn  5649: }
                   5650: 
                   5651: sub set_adhoc_privileges {
                   5652: # role can be cc or ca
1.1088    raeburn  5653:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5654:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5655:     my $spec = $role.'.'.$area;
                   5656:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5657:                                   $env{'user.name'},1);
1.994     raeburn  5658:     my %ccrole = ();
                   5659:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5660:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5661:     &appenv(\%userroles,[$role,'cm']);
                   5662:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5663:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5664:         &appenv( {'request.role'        => $spec,
                   5665:                   'request.role.domain' => $dcdom,
                   5666:                   'request.course.sec'  => ''
                   5667:                  }
                   5668:                );
                   5669:         my $tadv=0;
                   5670:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5671:         &appenv({'request.role.adv'    => $tadv});
                   5672:     }
1.994     raeburn  5673: }
                   5674: 
1.12      www      5675: # --------------------------------------------------------------- get interface
                   5676: 
                   5677: sub get {
1.131     albertel 5678:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5679:    my $items='';
1.800     albertel 5680:    foreach my $item (@$storearr) {
                   5681:        $items.=&escape($item).'&';
1.191     harris41 5682:    }
1.12      www      5683:    $items=~s/\&$//;
1.620     albertel 5684:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5685:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5686:    my $uhome=&homeserver($uname,$udomain);
                   5687: 
1.133     albertel 5688:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5689:    my @pairs=split(/\&/,$rep);
1.273     albertel 5690:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5691:      return @pairs;
                   5692:    }
1.15      www      5693:    my %returnhash=();
1.42      www      5694:    my $i=0;
1.800     albertel 5695:    foreach my $item (@$storearr) {
                   5696:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5697:       $i++;
1.191     harris41 5698:    }
1.15      www      5699:    return %returnhash;
1.27      www      5700: }
                   5701: 
                   5702: # --------------------------------------------------------------- del interface
                   5703: 
                   5704: sub del {
1.133     albertel 5705:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5706:    my $items='';
1.800     albertel 5707:    foreach my $item (@$storearr) {
                   5708:        $items.=&escape($item).'&';
1.191     harris41 5709:    }
1.984     neumanie 5710: 
1.27      www      5711:    $items=~s/\&$//;
1.620     albertel 5712:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5713:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5714:    my $uhome=&homeserver($uname,$udomain);
                   5715:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5716: }
                   5717: 
                   5718: # -------------------------------------------------------------- dump interface
                   5719: 
1.1172.2.22  raeburn  5720: sub unserialize {
                   5721:     my ($rep, $escapedkeys) = @_;
                   5722: 
                   5723:     return {} if $rep =~ /^error/;
                   5724: 
                   5725:     my %returnhash=();
                   5726:     foreach my $item (split(/\&/,$rep)) {
                   5727:         my ($key, $value) = split(/=/, $item, 2);
                   5728:         $key = unescape($key) unless $escapedkeys;
                   5729:         next if $key =~ /^error: 2 /;
                   5730:         $returnhash{$key} = &thaw_unescape($value);
                   5731:     }
                   5732:     return \%returnhash;
                   5733: }
                   5734: 
                   5735: # see Lond::dump_with_regexp
                   5736: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5737: sub dump {
1.1172.2.22  raeburn  5738:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5739:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5740:     if (!$uname) { $uname=$env{'user.name'}; }
                   5741:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5742: 
1.1172.2.55  raeburn  5743:     if ($regexp) {
                   5744:         $regexp=&escape($regexp);
                   5745:     } else {
                   5746:         $regexp='.';
                   5747:     }
1.1172.2.22  raeburn  5748:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5749:         # user is hosted on this machine
1.1172.2.55  raeburn  5750:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5751:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5752:         return %{&unserialize($reply, $escapedkeys)};
                   5753:     }
1.1166    raeburn  5754:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5755:     my @pairs=split(/\&/,$rep);
                   5756:     my %returnhash=();
1.1098    foxr     5757:     if (!($rep =~ /^error/ )) {
                   5758: 	foreach my $item (@pairs) {
                   5759: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5760:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5761: 	    next if ($key =~ /^error: 2 /);
                   5762: 	    $returnhash{$key}=&thaw_unescape($value);
                   5763: 	}
1.755     albertel 5764:     }
                   5765:     return %returnhash;
1.407     www      5766: }
                   5767: 
1.1098    foxr     5768: 
1.717     albertel 5769: # --------------------------------------------------------- dumpstore interface
                   5770: 
                   5771: sub dumpstore {
                   5772:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5773:    # same as dump but keys must be escaped. They may contain colon separated
                   5774:    # lists of values that may themself contain colons (e.g. symbs).
                   5775:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5776: }
                   5777: 
1.407     www      5778: # -------------------------------------------------------------- keys interface
                   5779: 
                   5780: sub getkeys {
                   5781:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5782:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5783:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5784:    my $uhome=&homeserver($uname,$udomain);
                   5785:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5786:    my @keyarray=();
1.800     albertel 5787:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5788:       next if ($key =~ /^error: 2 /);
1.800     albertel 5789:       push(@keyarray,&unescape($key));
1.407     www      5790:    }
                   5791:    return @keyarray;
1.318     matthew  5792: }
                   5793: 
1.319     matthew  5794: # --------------------------------------------------------------- currentdump
                   5795: sub currentdump {
1.328     matthew  5796:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5797:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5798:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5799:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5800:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  5801:    my $rep;
                   5802: 
                   5803:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5804:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   5805:                    $courseid)));
                   5806:    } else {
                   5807:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5808:    }
                   5809: 
1.318     matthew  5810:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5811:    #
1.318     matthew  5812:    my %returnhash=();
1.319     matthew  5813:    #
                   5814:    if ($rep eq "unknown_cmd") { 
                   5815:        # an old lond will not know currentdump
                   5816:        # Do a dump and make it look like a currentdump
1.822     albertel 5817:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5818:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5819:        my %hash = @tmp;
                   5820:        @tmp=();
1.424     matthew  5821:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5822:    } else {
                   5823:        my @pairs=split(/\&/,$rep);
1.800     albertel 5824:        foreach my $pair (@pairs) {
                   5825:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5826:            my ($symb,$param) = split(/:/,$key);
                   5827:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5828:                                                         &thaw_unescape($value);
1.319     matthew  5829:        }
1.191     harris41 5830:    }
1.12      www      5831:    return %returnhash;
1.424     matthew  5832: }
                   5833: 
                   5834: sub convert_dump_to_currentdump{
                   5835:     my %hash = %{shift()};
                   5836:     my %returnhash;
                   5837:     # Code ripped from lond, essentially.  The only difference
                   5838:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5839:     # we might run in to problems with parameter names =~ /^v\./
                   5840:     while (my ($key,$value) = each(%hash)) {
                   5841:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5842: 	$symb  = &unescape($symb);
                   5843: 	$param = &unescape($param);
1.424     matthew  5844:         next if ($v eq 'version' || $symb eq 'keys');
                   5845:         next if (exists($returnhash{$symb}) &&
                   5846:                  exists($returnhash{$symb}->{$param}) &&
                   5847:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5848:         $returnhash{$symb}->{$param}=$value;
                   5849:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5850:     }
                   5851:     #
                   5852:     # Remove all of the keys in the hashes which keep track of
                   5853:     # the version of the parameter.
                   5854:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5855:         # use a foreach because we are going to delete from the hash.
                   5856:         foreach my $key (keys(%$param_hash)) {
                   5857:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5858:         }
                   5859:     }
                   5860:     return \%returnhash;
1.12      www      5861: }
                   5862: 
1.627     albertel 5863: # ------------------------------------------------------ critical inc interface
                   5864: 
                   5865: sub cinc {
                   5866:     return &inc(@_,'critical');
                   5867: }
                   5868: 
1.449     matthew  5869: # --------------------------------------------------------------- inc interface
                   5870: 
                   5871: sub inc {
1.627     albertel 5872:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5873:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5874:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5875:     my $uhome=&homeserver($uname,$udomain);
                   5876:     my $items='';
                   5877:     if (! ref($store)) {
                   5878:         # got a single value, so use that instead
                   5879:         $items = &escape($store).'=&';
                   5880:     } elsif (ref($store) eq 'SCALAR') {
                   5881:         $items = &escape($$store).'=&';        
                   5882:     } elsif (ref($store) eq 'ARRAY') {
                   5883:         $items = join('=&',map {&escape($_);} @{$store});
                   5884:     } elsif (ref($store) eq 'HASH') {
                   5885:         while (my($key,$value) = each(%{$store})) {
                   5886:             $items.= &escape($key).'='.&escape($value).'&';
                   5887:         }
                   5888:     }
                   5889:     $items=~s/\&$//;
1.627     albertel 5890:     if ($critical) {
                   5891: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5892:     } else {
                   5893: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5894:     }
1.449     matthew  5895: }
                   5896: 
1.12      www      5897: # --------------------------------------------------------------- put interface
                   5898: 
                   5899: sub put {
1.134     albertel 5900:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5901:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5902:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5903:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5904:    my $items='';
1.800     albertel 5905:    foreach my $item (keys(%$storehash)) {
                   5906:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5907:    }
1.12      www      5908:    $items=~s/\&$//;
1.134     albertel 5909:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5910: }
                   5911: 
1.631     albertel 5912: # ------------------------------------------------------------ newput interface
                   5913: 
                   5914: sub newput {
                   5915:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5916:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5917:    if (!$uname) { $uname=$env{'user.name'}; }
                   5918:    my $uhome=&homeserver($uname,$udomain);
                   5919:    my $items='';
                   5920:    foreach my $key (keys(%$storehash)) {
                   5921:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5922:    }
                   5923:    $items=~s/\&$//;
                   5924:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5925: }
                   5926: 
                   5927: # ---------------------------------------------------------  putstore interface
                   5928: 
1.524     raeburn  5929: sub putstore {
1.1172.2.59  raeburn  5930:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 5931:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5932:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5933:    my $uhome=&homeserver($uname,$udomain);
                   5934:    my $items='';
1.715     albertel 5935:    foreach my $key (keys(%$storehash)) {
                   5936:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5937:    }
1.715     albertel 5938:    $items=~s/\&$//;
1.716     albertel 5939:    my $esc_symb=&escape($symb);
                   5940:    my $esc_v=&escape($version);
1.715     albertel 5941:    my $reply =
1.716     albertel 5942:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5943: 	      $uhome);
1.1172.2.59  raeburn  5944:    if (($tolog) && ($reply eq 'ok')) {
                   5945:        my $namevalue='';
                   5946:        foreach my $key (keys(%{$storehash})) {
                   5947:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   5948:        }
                   5949:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   5950:                      '&host='.&escape($perlvar{'lonHostID'}).
                   5951:                      '&version='.$esc_v.
                   5952:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   5953:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   5954:    }
1.715     albertel 5955:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5956:        # gfall back to way things use to be done
1.715     albertel 5957:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5958: 			    $uname);
1.524     raeburn  5959:    }
1.715     albertel 5960:    return $reply;
                   5961: }
                   5962: 
                   5963: sub old_putstore {
1.716     albertel 5964:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5965:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5966:     if (!$uname) { $uname=$env{'user.name'}; }
                   5967:     my $uhome=&homeserver($uname,$udomain);
                   5968:     my %newstorehash;
1.800     albertel 5969:     foreach my $item (keys(%$storehash)) {
                   5970: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5971: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5972:     }
                   5973:     my $items='';
                   5974:     my %allitems = ();
1.800     albertel 5975:     foreach my $item (keys(%newstorehash)) {
                   5976: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5977: 	    my $key = $1.':keys:'.$2;
                   5978: 	    $allitems{$key} .= $3.':';
                   5979: 	}
1.800     albertel 5980: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5981:     }
1.800     albertel 5982:     foreach my $item (keys(%allitems)) {
                   5983: 	$allitems{$item} =~ s/\:$//;
                   5984: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5985:     }
                   5986:     $items=~s/\&$//;
                   5987:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5988: }
                   5989: 
1.47      www      5990: # ------------------------------------------------------ critical put interface
                   5991: 
                   5992: sub cput {
1.134     albertel 5993:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5994:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5995:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5996:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5997:    my $items='';
1.800     albertel 5998:    foreach my $item (keys(%$storehash)) {
                   5999:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6000:    }
1.47      www      6001:    $items=~s/\&$//;
1.134     albertel 6002:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6003: }
                   6004: 
                   6005: # -------------------------------------------------------------- eget interface
                   6006: 
                   6007: sub eget {
1.133     albertel 6008:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6009:    my $items='';
1.800     albertel 6010:    foreach my $item (@$storearr) {
                   6011:        $items.=&escape($item).'&';
1.191     harris41 6012:    }
1.12      www      6013:    $items=~s/\&$//;
1.620     albertel 6014:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6015:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6016:    my $uhome=&homeserver($uname,$udomain);
                   6017:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6018:    my @pairs=split(/\&/,$rep);
                   6019:    my %returnhash=();
1.42      www      6020:    my $i=0;
1.800     albertel 6021:    foreach my $item (@$storearr) {
                   6022:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6023:       $i++;
1.191     harris41 6024:    }
1.12      www      6025:    return %returnhash;
                   6026: }
                   6027: 
1.667     albertel 6028: # ------------------------------------------------------------ tmpput interface
                   6029: sub tmpput {
1.802     raeburn  6030:     my ($storehash,$server,$context)=@_;
1.667     albertel 6031:     my $items='';
1.800     albertel 6032:     foreach my $item (keys(%$storehash)) {
                   6033: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6034:     }
                   6035:     $items=~s/\&$//;
1.802     raeburn  6036:     if (defined($context)) {
                   6037:         $items .= ':'.&escape($context);
                   6038:     }
1.667     albertel 6039:     return &reply("tmpput:$items",$server);
                   6040: }
                   6041: 
                   6042: # ------------------------------------------------------------ tmpget interface
                   6043: sub tmpget {
1.688     albertel 6044:     my ($token,$server)=@_;
                   6045:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6046:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6047:     my %returnhash;
                   6048:     foreach my $item (split(/\&/,$rep)) {
                   6049: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6050:         next if ($key =~ /^error: 2 /);
1.667     albertel 6051: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6052:     }
                   6053:     return %returnhash;
                   6054: }
                   6055: 
1.1113    raeburn  6056: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6057: sub tmpdel {
                   6058:     my ($token,$server)=@_;
                   6059:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6060:     return &reply("tmpdel:$token",$server);
                   6061: }
                   6062: 
1.1172.2.13  raeburn  6063: # ------------------------------------------------------------ get_timebased_id
                   6064: 
                   6065: sub get_timebased_id {
                   6066:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6067:         $maxtries) = @_;
                   6068:     my ($newid,$error,$dellock);
                   6069:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6070:         return ('','ok','invalid call to get suffix');
                   6071:     }
                   6072: 
                   6073: # set defaults for any optional args for which values were not supplied
                   6074:     if ($who eq '') {
                   6075:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6076:     }
                   6077:     if (!$locktries) {
                   6078:         $locktries = 3;
                   6079:     }
                   6080:     if (!$maxtries) {
                   6081:         $maxtries = 10;
                   6082:     }
                   6083: 
                   6084:     if (($cdom eq '') || ($cnum eq '')) {
                   6085:         if ($env{'request.course.id'}) {
                   6086:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6087:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6088:         }
                   6089:         if (($cdom eq '') || ($cnum eq '')) {
                   6090:             return ('','ok','call to get suffix not in course context');
                   6091:         }
                   6092:     }
                   6093: 
                   6094: # construct locking item
                   6095:     my $lockhash = {
                   6096:                       $prefix."\0".'locked_'.$keyid => $who,
                   6097:                    };
                   6098:     my $tries = 0;
                   6099: 
                   6100: # attempt to get lock on nohist_$namespace file
                   6101:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6102:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6103:         $tries ++;
                   6104:         sleep 1;
                   6105:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6106:     }
                   6107: 
                   6108: # attempt to get unique identifier, based on current timestamp
                   6109:     if ($gotlock eq 'ok') {
                   6110:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6111:         my $id = time;
                   6112:         $newid = $id;
1.1172.2.56  raeburn  6113:         if ($idtype eq 'addcode') {
                   6114:             $newid .= &sixnum_code();
                   6115:         }
1.1172.2.13  raeburn  6116:         my $idtries = 0;
                   6117:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6118:             if ($idtype eq 'concat') {
                   6119:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6120:             } elsif ($idtype eq 'addcode') {
                   6121:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6122:             } else {
                   6123:                 $newid ++;
                   6124:             }
                   6125:             $idtries ++;
                   6126:         }
                   6127:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6128:             my %new_item =  (
                   6129:                               $prefix."\0".$newid => $who,
                   6130:                             );
                   6131:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6132:                                                  $cdom,$cnum);
                   6133:             if ($putresult ne 'ok') {
                   6134:                 undef($newid);
                   6135:                 $error = 'error saving new item: '.$putresult;
                   6136:             }
                   6137:         } else {
1.1172.2.56  raeburn  6138:              undef($newid);
1.1172.2.13  raeburn  6139:              $error = ('error: no unique suffix available for the new item ');
                   6140:         }
                   6141: #  remove lock
                   6142:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6143:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6144:     } else {
                   6145:         $error = "error: could not obtain lockfile\n";
                   6146:         $dellock = 'ok';
1.1172.2.58  raeburn  6147:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6148:             $dellock = 'nolock';
                   6149:         }
1.1172.2.13  raeburn  6150:     }
                   6151:     return ($newid,$dellock,$error);
                   6152: }
                   6153: 
1.1172.2.56  raeburn  6154: sub sixnum_code {
                   6155:     my $code;
                   6156:     for (0..6) {
                   6157:         $code .= int( rand(9) );
                   6158:     }
                   6159:     return $code;
                   6160: }
                   6161: 
1.765     albertel 6162: # -------------------------------------------------- portfolio access checking
                   6163: 
                   6164: sub portfolio_access {
1.766     albertel 6165:     my ($requrl) = @_;
1.765     albertel 6166:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   6167:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  6168:     if ($result) {
                   6169:         my %setters;
                   6170:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6171:             my ($startblock,$endblock) =
                   6172:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6173:             if ($startblock && $endblock) {
                   6174:                 return 'B';
                   6175:             }
                   6176:         } else {
                   6177:             my ($startblock,$endblock) =
                   6178:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6179:             if ($startblock && $endblock) {
                   6180:                 return 'B';
                   6181:             }
                   6182:         }
                   6183:     }
1.765     albertel 6184:     if ($result eq 'ok') {
1.766     albertel 6185:        return 'F';
1.765     albertel 6186:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6187:        return 'A';
1.765     albertel 6188:     }
1.766     albertel 6189:     return '';
1.765     albertel 6190: }
                   6191: 
                   6192: sub get_portfolio_access {
1.767     albertel 6193:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   6194: 
                   6195:     if (!ref($access_hash)) {
                   6196: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6197: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6198: 						   $file_name);
                   6199: 	$access_hash = $access_controls{$file_name};
                   6200:     }
                   6201: 
1.765     albertel 6202:     my ($public,$guest,@domains,@users,@courses,@groups);
                   6203:     my $now = time;
                   6204:     if (ref($access_hash) eq 'HASH') {
                   6205:         foreach my $key (keys(%{$access_hash})) {
                   6206:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6207:             if ($start > $now) {
                   6208:                 next;
                   6209:             }
                   6210:             if ($end && $end<$now) {
                   6211:                 next;
                   6212:             }
                   6213:             if ($scope eq 'public') {
                   6214:                 $public = $key;
                   6215:                 last;
                   6216:             } elsif ($scope eq 'guest') {
                   6217:                 $guest = $key;
                   6218:             } elsif ($scope eq 'domains') {
                   6219:                 push(@domains,$key);
                   6220:             } elsif ($scope eq 'users') {
                   6221:                 push(@users,$key);
                   6222:             } elsif ($scope eq 'course') {
                   6223:                 push(@courses,$key);
                   6224:             } elsif ($scope eq 'group') {
                   6225:                 push(@groups,$key);
                   6226:             }
                   6227:         }
                   6228:         if ($public) {
                   6229:             return 'ok';
                   6230:         }
                   6231:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6232:             if ($guest) {
                   6233:                 return $guest;
                   6234:             }
                   6235:         } else {
                   6236:             if (@domains > 0) {
                   6237:                 foreach my $domkey (@domains) {
                   6238:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6239:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6240:                             return 'ok';
                   6241:                         }
                   6242:                     }
                   6243:                 }
                   6244:             }
                   6245:             if (@users > 0) {
                   6246:                 foreach my $userkey (@users) {
1.865     raeburn  6247:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6248:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6249:                             if (ref($item) eq 'HASH') {
                   6250:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6251:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6252:                                     return 'ok';
                   6253:                                 }
                   6254:                             }
                   6255:                         }
                   6256:                     } 
1.765     albertel 6257:                 }
                   6258:             }
                   6259:             my %roleshash;
                   6260:             my @courses_and_groups = @courses;
                   6261:             push(@courses_and_groups,@groups); 
                   6262:             if (@courses_and_groups > 0) {
                   6263:                 my (%allgroups,%allroles); 
                   6264:                 my ($start,$end,$role,$sec,$group);
                   6265:                 foreach my $envkey (%env) {
1.1060    raeburn  6266:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6267:                         my $cid = $2.'_'.$3; 
                   6268:                         if ($1 eq 'gr') {
                   6269:                             $group = $4;
                   6270:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6271:                         } else {
                   6272:                             if ($4 eq '') {
                   6273:                                 $sec = 'none';
                   6274:                             } else {
                   6275:                                 $sec = $4;
                   6276:                             }
                   6277:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6278:                         }
1.811     albertel 6279:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6280:                         my $cid = $2.'_'.$3;
                   6281:                         if ($4 eq '') {
                   6282:                             $sec = 'none';
                   6283:                         } else {
                   6284:                             $sec = $4;
                   6285:                         }
                   6286:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6287:                     }
                   6288:                 }
                   6289:                 if (keys(%allroles) == 0) {
                   6290:                     return;
                   6291:                 }
                   6292:                 foreach my $key (@courses_and_groups) {
                   6293:                     my %content = %{$$access_hash{$key}};
                   6294:                     my $cnum = $content{'number'};
                   6295:                     my $cdom = $content{'domain'};
                   6296:                     my $cid = $cdom.'_'.$cnum;
                   6297:                     if (!exists($allroles{$cid})) {
                   6298:                         next;
                   6299:                     }    
                   6300:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6301:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6302:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6303:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6304:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6305:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6306:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6307:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6308:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6309:                                         if (grep/^all$/,@sections) {
                   6310:                                             return 'ok';
                   6311:                                         } else {
                   6312:                                             if (grep/^$sec$/,@sections) {
                   6313:                                                 return 'ok';
                   6314:                                             }
                   6315:                                         }
                   6316:                                     }
                   6317:                                 }
                   6318:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6319:                                     if (grep/^none$/,@groups) {
                   6320:                                         return 'ok';
                   6321:                                     }
                   6322:                                 } else {
                   6323:                                     if (grep/^all$/,@groups) {
                   6324:                                         return 'ok';
                   6325:                                     } 
                   6326:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6327:                                         if (grep/^$group$/,@groups) {
                   6328:                                             return 'ok';
                   6329:                                         }
                   6330:                                     }
                   6331:                                 } 
                   6332:                             }
                   6333:                         }
                   6334:                     }
                   6335:                 }
                   6336:             }
                   6337:             if ($guest) {
                   6338:                 return $guest;
                   6339:             }
                   6340:         }
                   6341:     }
                   6342:     return;
                   6343: }
                   6344: 
                   6345: sub course_group_datechecker {
                   6346:     my ($dates,$now,$status) = @_;
                   6347:     my ($start,$end) = split(/\./,$dates);
                   6348:     if (!$start && !$end) {
                   6349:         return 'ok';
                   6350:     }
                   6351:     if (grep/^active$/,@{$status}) {
                   6352:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6353:             return 'ok';
                   6354:         }
                   6355:     }
                   6356:     if (grep/^previous$/,@{$status}) {
                   6357:         if ($end > $now ) {
                   6358:             return 'ok';
                   6359:         }
                   6360:     }
                   6361:     if (grep/^future$/,@{$status}) {
                   6362:         if ($start > $now) {
                   6363:             return 'ok';
                   6364:         }
                   6365:     }
                   6366:     return; 
                   6367: }
                   6368: 
                   6369: sub parse_portfolio_url {
                   6370:     my ($url) = @_;
                   6371: 
                   6372:     my ($type,$udom,$unum,$group,$file_name);
                   6373:     
1.823     albertel 6374:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6375: 	$type = 1;
                   6376:         $udom = $1;
                   6377:         $unum = $2;
                   6378:         $file_name = $3;
1.823     albertel 6379:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6380: 	$type = 2;
                   6381:         $udom = $1;
                   6382:         $unum = $2;
                   6383:         $group = $3;
                   6384:         $file_name = $3.'/'.$4;
                   6385:     }
                   6386:     if (wantarray) {
                   6387: 	return ($type,$udom,$unum,$file_name,$group);
                   6388:     }
                   6389:     return $type;
                   6390: }
                   6391: 
                   6392: sub is_portfolio_url {
                   6393:     my ($url) = @_;
                   6394:     return scalar(&parse_portfolio_url($url));
                   6395: }
                   6396: 
1.798     raeburn  6397: sub is_portfolio_file {
                   6398:     my ($file) = @_;
1.820     raeburn  6399:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6400:         return 1;
                   6401:     }
                   6402:     return;
                   6403: }
                   6404: 
1.976     raeburn  6405: sub usertools_access {
1.1084    raeburn  6406:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6407:     my ($access,%tools);
                   6408:     if ($context eq '') {
                   6409:         $context = 'tools';
                   6410:     }
                   6411:     if ($context eq 'requestcourses') {
                   6412:         %tools = (
                   6413:                       official   => 1,
                   6414:                       unofficial => 1,
1.1006    raeburn  6415:                       community  => 1,
1.1172.2.37  raeburn  6416:                       textbook   => 1,
1.985     raeburn  6417:                  );
1.1172.2.9  raeburn  6418:     } elsif ($context eq 'requestauthor') {
                   6419:         %tools = (
                   6420:                       requestauthor => 1,
                   6421:                  );
1.985     raeburn  6422:     } else {
                   6423:         %tools = (
                   6424:                       aboutme   => 1,
                   6425:                       blog      => 1,
1.1172.2.6  raeburn  6426:                       webdav    => 1,
1.985     raeburn  6427:                       portfolio => 1,
                   6428:                  );
                   6429:     }
1.976     raeburn  6430:     return if (!defined($tools{$tool}));
                   6431: 
1.1172.2.35  raeburn  6432:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6433:         $udom = $env{'user.domain'};
                   6434:         $uname = $env{'user.name'};
                   6435:     }
                   6436: 
1.978     raeburn  6437:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6438:         if ($action ne 'reload') {
1.985     raeburn  6439:             if ($context eq 'requestcourses') {
                   6440:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6441:             } elsif ($context eq 'requestauthor') {
                   6442:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6443:             } else {
                   6444:                 return $env{'environment.availabletools.'.$tool};
                   6445:             }
                   6446:         }
1.976     raeburn  6447:     }
                   6448: 
1.1172.2.9  raeburn  6449:     my ($toolstatus,$inststatus,$envkey);
                   6450:     if ($context eq 'requestauthor') {
                   6451:         $envkey = $context;
                   6452:     } else {
                   6453:         $envkey = $context.'.'.$tool;
                   6454:     }
1.976     raeburn  6455: 
1.985     raeburn  6456:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6457:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6458:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6459:         $inststatus = $env{'environment.inststatus'};
                   6460:     } else {
1.1084    raeburn  6461:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6462:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6463:             $inststatus = $userenvref->{'inststatus'};
                   6464:         } else {
1.1172.2.9  raeburn  6465:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6466:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6467:             $inststatus = $userenv{'inststatus'};
                   6468:         }
1.976     raeburn  6469:     }
                   6470: 
                   6471:     if ($toolstatus ne '') {
                   6472:         if ($toolstatus) {
                   6473:             $access = 1;
                   6474:         } else {
                   6475:             $access = 0;
                   6476:         }
                   6477:         return $access;
                   6478:     }
                   6479: 
1.1084    raeburn  6480:     my ($is_adv,%domdef);
                   6481:     if (ref($is_advref) eq 'HASH') {
                   6482:         $is_adv = $is_advref->{'is_adv'};
                   6483:     } else {
                   6484:         $is_adv = &is_advanced_user($udom,$uname);
                   6485:     }
                   6486:     if (ref($domdefref) eq 'HASH') {
                   6487:         %domdef = %{$domdefref};
                   6488:     } else {
                   6489:         %domdef = &get_domain_defaults($udom);
                   6490:     }
1.976     raeburn  6491:     if (ref($domdef{$tool}) eq 'HASH') {
                   6492:         if ($is_adv) {
                   6493:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6494:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6495:                     $access = 1;
                   6496:                 } else {
                   6497:                     $access = 0;
                   6498:                 }
                   6499:                 return $access;
                   6500:             }
                   6501:         }
                   6502:         if ($inststatus ne '') {
                   6503:             my ($hasaccess,$hasnoaccess);
                   6504:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6505:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6506:                     if ($domdef{$tool}{$affiliation}) {
                   6507:                         $hasaccess = 1;
                   6508:                     } else {
                   6509:                         $hasnoaccess = 1;
                   6510:                     }
                   6511:                 }
                   6512:             }
                   6513:             if ($hasaccess || $hasnoaccess) {
                   6514:                 if ($hasaccess) {
                   6515:                     $access = 1;
                   6516:                 } elsif ($hasnoaccess) {
                   6517:                     $access = 0; 
                   6518:                 }
                   6519:                 return $access;
                   6520:             }
                   6521:         } else {
                   6522:             if ($domdef{$tool}{'default'} ne '') {
                   6523:                 if ($domdef{$tool}{'default'}) {
                   6524:                     $access = 1;
                   6525:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6526:                     $access = 0;
                   6527:                 }
                   6528:                 return $access;
                   6529:             }
                   6530:         }
                   6531:     } else {
1.1172.2.6  raeburn  6532:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6533:             $access = 1;
                   6534:         } else {
                   6535:             $access = 0;
                   6536:         }
1.976     raeburn  6537:         return $access;
                   6538:     }
                   6539: }
                   6540: 
1.1050    raeburn  6541: sub is_course_owner {
                   6542:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6543:     if (($udom eq '') || ($uname eq '')) {
                   6544:         $udom = $env{'user.domain'};
                   6545:         $uname = $env{'user.name'};
                   6546:     }
                   6547:     unless (($udom eq '') || ($uname eq '')) {
                   6548:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6549:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6550:                 return 1;
                   6551:             } else {
                   6552:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6553:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6554:                     return 1;
                   6555:                 }
                   6556:             }
                   6557:         }
                   6558:     }
                   6559:     return;
                   6560: }
                   6561: 
1.976     raeburn  6562: sub is_advanced_user {
                   6563:     my ($udom,$uname) = @_;
1.1085    raeburn  6564:     if ($udom ne '' && $uname ne '') {
                   6565:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6566:             if (wantarray) {
                   6567:                 return ($env{'user.adv'},$env{'user.author'});
                   6568:             } else {
                   6569:                 return $env{'user.adv'};
                   6570:             }
1.1085    raeburn  6571:         }
                   6572:     }
1.976     raeburn  6573:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6574:     my %allroles;
1.1128    raeburn  6575:     my ($is_adv,$is_author);
1.976     raeburn  6576:     foreach my $role (keys(%roleshash)) {
                   6577:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6578:         my $area = '/'.$tdomain.'/'.$trest;
                   6579:         if ($sec ne '') {
                   6580:             $area .= '/'.$sec;
                   6581:         }
                   6582:         if (($area ne '') && ($trole ne '')) {
                   6583:             my $spec=$trole.'.'.$area;
                   6584:             if ($trole =~ /^cr\//) {
                   6585:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6586:             } elsif ($trole ne 'gr') {
                   6587:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6588:             }
1.1128    raeburn  6589:             if ($trole eq 'au') {
                   6590:                 $is_author = 1;
                   6591:             }
1.976     raeburn  6592:         }
                   6593:     }
                   6594:     foreach my $role (keys(%allroles)) {
                   6595:         last if ($is_adv);
                   6596:         foreach my $item (split(/:/,$allroles{$role})) {
                   6597:             if ($item ne '') {
                   6598:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6599:                 if ($privilege eq 'adv') {
                   6600:                     $is_adv = 1;
                   6601:                     last;
                   6602:                 }
                   6603:             }
                   6604:         }
                   6605:     }
1.1128    raeburn  6606:     if (wantarray) {
                   6607:         return ($is_adv,$is_author);
                   6608:     }
1.976     raeburn  6609:     return $is_adv;
                   6610: }
1.798     raeburn  6611: 
1.1035    raeburn  6612: sub check_can_request {
1.1036    raeburn  6613:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6614:     my $canreq = 0;
                   6615:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6616:     my @options = ('approval','validate','autolimit');
                   6617:     my $optregex = join('|',@options);
                   6618:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6619:         foreach my $type (@{$types}) {
                   6620:             if (&usertools_access($env{'user.name'},
                   6621:                                   $env{'user.domain'},
                   6622:                                   $type,undef,'requestcourses')) {
                   6623:                 $canreq ++;
1.1036    raeburn  6624:                 if (ref($request_domains) eq 'HASH') {
                   6625:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6626:                 }
1.1035    raeburn  6627:                 if ($dom eq $env{'user.domain'}) {
                   6628:                     $can_request->{$type} = 1;
                   6629:                 }
                   6630:             }
                   6631:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6632:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6633:                 if (@curr > 0) {
1.1036    raeburn  6634:                     foreach my $item (@curr) {
                   6635:                         if (ref($request_domains) eq 'HASH') {
                   6636:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6637:                             if ($otherdom ne '') {
                   6638:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6639:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6640:                                         push(@{$request_domains->{$type}},$otherdom);
                   6641:                                     }
                   6642:                                 } else {
                   6643:                                     push(@{$request_domains->{$type}},$otherdom);
                   6644:                                 }
                   6645:                             }
                   6646:                         }
                   6647:                     }
                   6648:                     unless($dom eq $env{'user.domain'}) {
                   6649:                         $canreq ++;
1.1035    raeburn  6650:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6651:                             $can_request->{$type} = 1;
                   6652:                         }
                   6653:                     }
                   6654:                 }
                   6655:             }
                   6656:         }
                   6657:     }
                   6658:     return $canreq;
                   6659: }
                   6660: 
1.341     www      6661: # ---------------------------------------------- Custom access rule evaluation
                   6662: 
                   6663: sub customaccess {
                   6664:     my ($priv,$uri)=@_;
1.807     albertel 6665:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6666:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6667:     $udom = &LONCAPA::clean_domain($udom);
                   6668:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6669:     my $access=0;
1.800     albertel 6670:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6671: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6672: 	if ($type eq 'user') {
                   6673: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6674: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6675: 		if ($tdom) {
                   6676: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6677: 		}
1.896     albertel 6678: 		if ($tuname) {
                   6679: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6680: 		}
                   6681: 		$access=($effect eq 'allow');
                   6682: 		last;
                   6683: 	    }
                   6684: 	} else {
                   6685: 	    if ($role) {
                   6686: 		if ($role ne $urole) { next; }
                   6687: 	    }
                   6688: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6689: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6690: 		if ($tdom) {
                   6691: 		    if ($tdom ne $udom) { next; }
                   6692: 		}
                   6693: 		if ($tcrs) {
                   6694: 		    if ($tcrs ne $ucrs) { next; }
                   6695: 		}
                   6696: 		if ($tsec) {
                   6697: 		    if ($tsec ne $usec) { next; }
                   6698: 		}
                   6699: 		$access=($effect eq 'allow');
                   6700: 		last;
                   6701: 	    }
                   6702: 	    if ($realm eq '' && $role eq '') {
                   6703: 		$access=($effect eq 'allow');
                   6704: 	    }
1.402     bowersj2 6705: 	}
1.341     www      6706:     }
                   6707:     return $access;
                   6708: }
                   6709: 
1.103     harris41 6710: # ------------------------------------------------- Check for a user privilege
1.12      www      6711: 
                   6712: sub allowed {
1.1172.2.65  raeburn  6713:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6714:     my $ver_orguri=$uri;
1.439     www      6715:     $uri=&deversion($uri);
1.152     www      6716:     my $orguri=$uri;
1.52      www      6717:     $uri=&declutter($uri);
1.809     raeburn  6718: 
1.810     raeburn  6719:     if ($priv eq 'evb') {
                   6720: # Evade communication block restrictions for specified role in a course
                   6721:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6722:             return $1;
                   6723:         } else {
                   6724:             return;
                   6725:         }
                   6726:     }
                   6727: 
1.620     albertel 6728:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6729: # Free bre access to adm and meta resources
1.775     albertel 6730:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6731: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6732: 	&& ($priv eq 'bre')) {
1.14      www      6733: 	return 'F';
1.159     www      6734:     }
                   6735: 
1.545     banghart 6736: # Free bre access to user's own portfolio contents
1.714     raeburn  6737:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6738:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6739: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6740:         my %setters;
                   6741:         my ($startblock,$endblock) = 
                   6742:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6743:         if ($startblock && $endblock) {
                   6744:             return 'B';
                   6745:         } else {
                   6746:             return 'F';
                   6747:         }
1.545     banghart 6748:     }
                   6749: 
1.762     raeburn  6750: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6751:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6752:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6753:         if (exists($env{'request.course.id'})) {
                   6754:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6755:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6756:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6757:                 my $courseprivid=$env{'request.course.id'};
                   6758:                 $courseprivid=~s/\_/\//;
                   6759:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6760:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6761:                     return $1; 
1.762     raeburn  6762:                 } else {
                   6763:                     if ($env{'request.course.sec'}) {
                   6764:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6765:                     }
                   6766:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6767:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6768:                         return $2;
                   6769:                     }
1.714     raeburn  6770:                 }
                   6771:             }
                   6772:         }
                   6773:     }
                   6774: 
1.159     www      6775: # Free bre to public access
                   6776: 
                   6777:     if ($priv eq 'bre') {
1.238     www      6778:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6779: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6780:            return 'F'; 
                   6781:         }
1.238     www      6782:         if ($copyright eq 'priv') {
                   6783:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6784: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6785: 		return '';
                   6786:             }
                   6787:         }
                   6788:         if ($copyright eq 'domain') {
                   6789:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6790: 	    unless (($env{'user.domain'} eq $1) ||
                   6791:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6792: 		return '';
                   6793:             }
1.262     matthew  6794:         }
1.620     albertel 6795:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6796:             # Library role, so allow browsing of resources in this domain.
                   6797:             return 'F';
1.238     www      6798:         }
1.341     www      6799:         if ($copyright eq 'custom') {
                   6800: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6801:         }
1.14      www      6802:     }
1.264     matthew  6803:     # Domain coordinator is trying to create a course
1.620     albertel 6804:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6805:         # uri is the requested domain in this case.
                   6806:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6807:         # a role of dc for the domain in question.
1.620     albertel 6808:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6809:     }
1.29      www      6810: 
1.52      www      6811:     my $thisallowed='';
                   6812:     my $statecond=0;
                   6813:     my $courseprivid='';
                   6814: 
1.1039    raeburn  6815:     my $ownaccess;
1.1043    raeburn  6816:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6817:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6818:         if ($uri eq '') {
                   6819:             $ownaccess = 1;
                   6820:         } else {
                   6821:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6822:                 my $udom = $env{'user.domain'};
                   6823:                 my $uname = $env{'user.name'};
                   6824:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6825:                     $ownaccess = 1;
1.1040    raeburn  6826:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6827:                     unless ($uri =~ m{\.\./}) {
                   6828:                         $ownaccess = 1;
                   6829:                     }
                   6830:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6831:                     my $now = time;
                   6832:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6833:                         my $adom = $1;
                   6834:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6835:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6836:                                 my ($start,$end) = split('.',$env{$key});
                   6837:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6838:                                     $ownaccess = 1;
                   6839:                                     last;
                   6840:                                 }
                   6841:                             }
                   6842:                         }
                   6843:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6844:                         my $adom = $1;
                   6845:                         my $aname = $2;
1.1042    raeburn  6846:                         foreach my $role ('ca','aa') { 
                   6847:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6848:                                 my ($start,$end) =
                   6849:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6850:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6851:                                     $ownaccess = 1;
                   6852:                                     last;
                   6853:                                 }
1.1039    raeburn  6854:                             }
                   6855:                         }
                   6856:                     }
                   6857:                 }
                   6858:             }
                   6859:         }
                   6860:     }
                   6861: 
1.52      www      6862: # Course
                   6863: 
1.620     albertel 6864:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6865:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6866:             $thisallowed.=$1;
                   6867:         }
1.52      www      6868:     }
1.29      www      6869: 
1.52      www      6870: # Domain
                   6871: 
1.620     albertel 6872:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6873:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6874:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6875:             $thisallowed.=$1;
                   6876:         }
1.12      www      6877:     }
1.52      www      6878: 
1.1141    raeburn  6879: # User who is not author or co-author might still be able to edit
                   6880: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6881:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6882:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6883:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6884:             $thisallowed.=$1;
                   6885:         }
                   6886:     }
                   6887: 
1.52      www      6888: # Course: uri itself is a course
1.66      www      6889:     my $courseuri=$uri;
                   6890:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6891:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6892: 
1.620     albertel 6893:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6894:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6895:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6896:             $thisallowed.=$1;
                   6897:         }
1.12      www      6898:     }
1.29      www      6899: 
1.665     albertel 6900: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6901: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6902:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6903: 	$thisallowed='';
1.671     raeburn  6904:         my ($match)=&is_on_map($uri);
                   6905:         if ($match) {
                   6906:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6907:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  6908:                 my $value = $1;
                   6909:                 if ($noblockcheck) {
                   6910:                     $thisallowed.=$value;
1.1162    raeburn  6911:                 } else {
1.1172.2.65  raeburn  6912:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6913:                     if (@blockers > 0) {
                   6914:                         $thisallowed = 'B';
                   6915:                     } else {
                   6916:                         $thisallowed.=$value;
                   6917:                     }
1.1162    raeburn  6918:                 }
1.671     raeburn  6919:             }
                   6920:         } else {
1.705     albertel 6921:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6922:             if ($refuri) {
                   6923:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6924:                     $thisallowed='F';
1.671     raeburn  6925:                 } else {
                   6926:                     $refuri=&declutter($refuri);
                   6927:                     my ($match) = &is_on_map($refuri);
                   6928:                     if ($match) {
1.1172.2.65  raeburn  6929:                         if ($noblockcheck) {
1.1162    raeburn  6930:                             $thisallowed='F';
1.1172.2.65  raeburn  6931:                         } else {
                   6932:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6933:                             if (@blockers > 0) {
                   6934:                                 $thisallowed = 'B';
                   6935:                             } else {
                   6936:                                 $thisallowed='F';
                   6937:                             }
1.1162    raeburn  6938:                         }
1.671     raeburn  6939:                     }
1.669     raeburn  6940:                 }
1.671     raeburn  6941:             }
                   6942:         }
1.314     www      6943:     }
1.492     albertel 6944: 
1.766     albertel 6945:     if ($priv eq 'bre'
                   6946: 	&& $thisallowed ne 'F' 
                   6947: 	&& $thisallowed ne '2'
                   6948: 	&& &is_portfolio_url($uri)) {
                   6949: 	$thisallowed = &portfolio_access($uri);
                   6950:     }
                   6951:     
1.52      www      6952: # Full access at system, domain or course-wide level? Exit.
1.29      www      6953:     if ($thisallowed=~/F/) {
                   6954: 	return 'F';
                   6955:     }
                   6956: 
1.52      www      6957: # If this is generating or modifying users, exit with special codes
1.29      www      6958: 
1.643     www      6959:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6960: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6961: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6962: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6963: 	    unless ($auname) { return $thisallowed; }
                   6964: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6965: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6966: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6967: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6968: 	}
1.52      www      6969: 	return $thisallowed;
                   6970:     }
                   6971: #
1.103     harris41 6972: # Gathered so far: system, domain and course wide privileges
1.52      www      6973: #
                   6974: # Course: See if uri or referer is an individual resource that is part of 
                   6975: # the course
                   6976: 
1.620     albertel 6977:     if ($env{'request.course.id'}) {
1.232     www      6978: 
1.620     albertel 6979:        $courseprivid=$env{'request.course.id'};
                   6980:        if ($env{'request.course.sec'}) {
                   6981:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6982:        }
                   6983:        $courseprivid=~s/\_/\//;
                   6984:        my $checkreferer=1;
1.232     www      6985:        my ($match,$cond)=&is_on_map($uri);
                   6986:        if ($match) {
                   6987:            $statecond=$cond;
1.620     albertel 6988:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6989:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6990:                my $value = $1;
                   6991:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  6992:                    if ($noblockcheck) {
1.1162    raeburn  6993:                        $thisallowed.=$value;
1.1172.2.65  raeburn  6994:                    } else {
                   6995:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6996:                        if (@blockers > 0) {
                   6997:                            $thisallowed = 'B';
                   6998:                        } else {
                   6999:                            $thisallowed.=$value;
                   7000:                        }
1.1162    raeburn  7001:                    }
                   7002:                } else {
                   7003:                    $thisallowed.=$value;
                   7004:                }
1.52      www      7005:                $checkreferer=0;
                   7006:            }
1.29      www      7007:        }
1.83      www      7008:        
1.148     www      7009:        if ($checkreferer) {
1.620     albertel 7010: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7011:             unless ($refuri) {
1.800     albertel 7012:                 foreach my $key (keys(%env)) {
                   7013: 		    if ($key=~/^httpref\..*\*/) {
                   7014: 			my $pattern=$key;
1.156     www      7015:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7016:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7017:                         $pattern=~s/\//\\\//g;
1.152     www      7018:                         if ($orguri=~/$pattern/) {
1.800     albertel 7019: 			    $refuri=$env{$key};
1.148     www      7020:                         }
                   7021:                     }
1.191     harris41 7022:                 }
1.148     www      7023:             }
1.232     www      7024: 
1.148     www      7025:          if ($refuri) { 
1.152     www      7026: 	  $refuri=&declutter($refuri);
1.232     www      7027:           my ($match,$cond)=&is_on_map($refuri);
                   7028:             if ($match) {
                   7029:               my $refstatecond=$cond;
1.620     albertel 7030:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7031:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7032:                   my $value = $1;
                   7033:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7034:                       if ($noblockcheck) {
1.1162    raeburn  7035:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7036:                       } else {
                   7037:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7038:                           if (@blockers > 0) {
                   7039:                               $thisallowed = 'B';
                   7040:                           } else {
                   7041:                               $thisallowed.=$value;
                   7042:                           }
1.1162    raeburn  7043:                       }
                   7044:                   } else {
                   7045:                       $thisallowed.=$value;
                   7046:                   }
1.53      www      7047:                   $uri=$refuri;
                   7048:                   $statecond=$refstatecond;
1.52      www      7049:               }
                   7050:           }
1.148     www      7051:         }
1.29      www      7052:        }
1.52      www      7053:    }
1.29      www      7054: 
1.52      www      7055: #
1.103     harris41 7056: # Gathered now: all privileges that could apply, and condition number
1.52      www      7057: # 
                   7058: #
                   7059: # Full or no access?
                   7060: #
1.29      www      7061: 
1.52      www      7062:     if ($thisallowed=~/F/) {
                   7063: 	return 'F';
                   7064:     }
1.29      www      7065: 
1.52      www      7066:     unless ($thisallowed) {
                   7067:         return '';
                   7068:     }
1.29      www      7069: 
1.52      www      7070: # Restrictions exist, deal with them
                   7071: #
                   7072: #   C:according to course preferences
                   7073: #   R:according to resource settings
                   7074: #   L:unless locked
                   7075: #   X:according to user session state
                   7076: #
                   7077: 
                   7078: # Possibly locked functionality, check all courses
1.54      www      7079: # Locks might take effect only after 10 minutes cache expiration for other
                   7080: # courses, and 2 minutes for current course
1.52      www      7081: 
                   7082:     my $envkey;
                   7083:     if ($thisallowed=~/L/) {
1.1000    raeburn  7084:         foreach $envkey (keys(%env)) {
1.54      www      7085:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7086:                my $courseid=$2;
                   7087:                my $roleid=$1.'.'.$2;
1.92      www      7088:                $courseid=~s/^\///;
1.54      www      7089:                my $expiretime=600;
1.620     albertel 7090:                if ($env{'request.role'} eq $roleid) {
1.54      www      7091: 		  $expiretime=120;
                   7092:                }
                   7093: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7094:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7095:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7096: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7097:                }
1.620     albertel 7098:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7099:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7100: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7101:                        &log($env{'user.domain'},$env{'user.name'},
                   7102:                             $env{'user.home'},
1.57      www      7103:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7104:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7105:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7106: 		       return '';
                   7107:                    }
                   7108:                }
1.620     albertel 7109:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7110:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7111: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7112:                        &log($env{'user.domain'},$env{'user.name'},
                   7113:                             $env{'user.home'},
1.57      www      7114:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7115:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7116:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7117: 		       return '';
                   7118:                    }
                   7119:                }
                   7120: 	   }
1.29      www      7121:        }
1.52      www      7122:     }
                   7123:    
                   7124: #
                   7125: # Rest of the restrictions depend on selected course
                   7126: #
                   7127: 
1.620     albertel 7128:     unless ($env{'request.course.id'}) {
1.766     albertel 7129: 	if ($thisallowed eq 'A') {
                   7130: 	    return 'A';
1.814     raeburn  7131:         } elsif ($thisallowed eq 'B') {
                   7132:             return 'B';
1.766     albertel 7133: 	} else {
                   7134: 	    return '1';
                   7135: 	}
1.52      www      7136:     }
1.29      www      7137: 
1.52      www      7138: #
                   7139: # Now user is definitely in a course
                   7140: #
1.53      www      7141: 
                   7142: 
                   7143: # Course preferences
                   7144: 
                   7145:    if ($thisallowed=~/C/) {
1.620     albertel 7146:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7147:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7148:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7149: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7150: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7151: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7152: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7153: 			$env{'request.course.id'});
                   7154: 	   }
1.237     www      7155:            return '';
                   7156:        }
                   7157: 
1.620     albertel 7158:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7159: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7160: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7161: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7162: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7163: 			$env{'request.course.id'});
                   7164: 	   }
1.54      www      7165:            return '';
                   7166:        }
1.53      www      7167:    }
                   7168: 
                   7169: # Resource preferences
                   7170: 
                   7171:    if ($thisallowed=~/R/) {
1.620     albertel 7172:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7173:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7174: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7175: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7176: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7177: 	   }
                   7178: 	   return '';
1.54      www      7179:        }
1.53      www      7180:    }
1.30      www      7181: 
1.246     www      7182: # Restricted by state or randomout?
1.30      www      7183: 
1.52      www      7184:    if ($thisallowed=~/X/) {
1.620     albertel 7185:       if ($env{'acc.randomout'}) {
1.579     albertel 7186: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7187:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7188:             return ''; 
                   7189:          }
1.247     www      7190:       }
                   7191:       if (&condval($statecond)) {
1.52      www      7192: 	 return '2';
                   7193:       } else {
                   7194:          return '';
                   7195:       }
                   7196:    }
1.30      www      7197: 
1.766     albertel 7198:     if ($thisallowed eq 'A') {
                   7199: 	return 'A';
1.814     raeburn  7200:     } elsif ($thisallowed eq 'B') {
                   7201:         return 'B';
1.766     albertel 7202:     }
1.52      www      7203:    return 'F';
1.232     www      7204: }
1.1162    raeburn  7205: 
1.1172.2.13  raeburn  7206: # ------------------------------------------- Check construction space access
                   7207: 
                   7208: sub constructaccess {
                   7209:     my ($url,$setpriv)=@_;
                   7210: 
                   7211: # We do not allow editing of previous versions of files
                   7212:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7213: 
                   7214: # Get username and domain from URL
                   7215:     my ($ownername,$ownerdomain,$ownerhome);
                   7216: 
                   7217:     ($ownerdomain,$ownername) =
                   7218:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7219: 
                   7220: # The URL does not really point to any authorspace, forget it
                   7221:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7222: 
                   7223: # Now we need to see if the user has access to the authorspace of
                   7224: # $ownername at $ownerdomain
                   7225: 
                   7226:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7227: # Real author for this?
                   7228:        $ownerhome = $env{'user.home'};
                   7229:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7230:           return ($ownername,$ownerdomain,$ownerhome);
                   7231:        }
                   7232:     } else {
                   7233: # Co-author for this?
                   7234:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7235:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7236:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7237:             return ($ownername,$ownerdomain,$ownerhome);
                   7238:         }
                   7239:     }
                   7240: 
                   7241: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7242: # we might as well leave
                   7243:    unless ($setpriv) { return ''; }
                   7244: 
                   7245: # Backdoor access?
                   7246:     my $allowed=&allowed('eco',$ownerdomain);
                   7247: # Nope
                   7248:     unless ($allowed) { return ''; }
                   7249: # Looks like we may have access, but could be locked by the owner of the construction space
                   7250:     if ($allowed eq 'U') {
                   7251:         my %blocked=&get('environment',['domcoord.author'],
                   7252:                          $ownerdomain,$ownername);
                   7253: # Is blocked by owner
                   7254:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7255:     }
                   7256:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7257: # Grant temporary access
                   7258:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7259:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7260:         if (!$update) { $update = $then; }
                   7261:         my $refresh=$env{'user.refresh.time'};
                   7262:         if (!$refresh) { $refresh = $update; }
                   7263:         my $now = time;
                   7264:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7265:                            $now,'ca','constructaccess');
                   7266:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7267:         return($ownername,$ownerdomain,$ownerhome);
                   7268:     }
                   7269: # No business here
                   7270:     return '';
                   7271: }
                   7272: 
1.1172.2.66  raeburn  7273: # ----------------------------------------------------------- Content Blocking
                   7274: 
                   7275: {
                   7276: # Caches for faster Course Contents display where content blocking
                   7277: # is in operation (i.e., interval param set) for timed quiz.
                   7278: #
                   7279: # User for whom data are being temporarily cached.
                   7280: my $cacheduser='';
                   7281: # Cached blockers for this user (a hash of blocking items).
                   7282: my %cachedblockers=();
                   7283: # When the data were last cached.
                   7284: my $cachedlast='';
                   7285: 
                   7286: sub load_all_blockers {
                   7287:     my ($uname,$udom,$blocks)=@_;
                   7288:     if (($uname ne '') && ($udom ne '')) {
                   7289:         if (($cacheduser eq $uname.':'.$udom) &&
                   7290:             (abs($cachedlast-time)<5)) {
                   7291:             return;
                   7292:         }
                   7293:     }
                   7294:     $cachedlast=time;
                   7295:     $cacheduser=$uname.':'.$udom;
                   7296:     %cachedblockers = &get_commblock_resources($blocks);
                   7297: }
                   7298: 
1.1162    raeburn  7299: sub get_comm_blocks {
                   7300:     my ($cdom,$cnum) = @_;
                   7301:     if ($cdom eq '' || $cnum eq '') {
                   7302:         return unless ($env{'request.course.id'});
                   7303:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7304:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7305:     }
                   7306:     my %commblocks;
                   7307:     my $hashid=$cdom.'_'.$cnum;
                   7308:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7309:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7310:         %commblocks = %{$blocksref};
                   7311:     } else {
                   7312:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7313:         my $cachetime = 600;
                   7314:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7315:     }
                   7316:     return %commblocks;
                   7317: }
                   7318: 
1.1172.2.66  raeburn  7319: sub get_commblock_resources {
                   7320:     my ($blocks) = @_;
                   7321:     my %blockers = ();
                   7322:     return %blockers unless ($env{'request.course.id'});
                   7323:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7324:     my %commblocks;
                   7325:     if (ref($blocks) eq 'HASH') {
                   7326:         %commblocks = %{$blocks};
                   7327:     } else {
                   7328:         %commblocks = &get_comm_blocks();
                   7329:     }
1.1172.2.66  raeburn  7330:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7331:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7332:     return %blockers unless (ref($navmap));
                   7333:     my $now = time;
1.1162    raeburn  7334:     foreach my $block (keys(%commblocks)) {
                   7335:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7336:             my ($start,$end) = ($1,$2);
                   7337:             if ($start <= $now && $end >= $now) {
                   7338:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7339:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7340:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7341:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7342:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7343:                             }
                   7344:                         }
                   7345:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7346:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7347:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7348:                             }
                   7349:                         }
                   7350:                     }
                   7351:                 }
                   7352:             }
                   7353:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7354:             my $item = $1;
1.1163    raeburn  7355:             my @to_test;
1.1162    raeburn  7356:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7357:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7358:                     my @interval;
                   7359:                     my $type = 'map';
                   7360:                     if ($item eq 'course') {
                   7361:                         $type = 'course';
                   7362:                         @interval=&EXT("resource.0.interval");
                   7363:                     } else {
                   7364:                         if ($item =~ /___\d+___/) {
                   7365:                             $type = 'resource';
                   7366:                             @interval=&EXT("resource.0.interval",$item);
                   7367:                             if (ref($navmap)) {
                   7368:                                 my $res = $navmap->getBySymb($item);
                   7369:                                 push(@to_test,$res);
                   7370:                             }
1.1162    raeburn  7371:                         } else {
1.1172.2.66  raeburn  7372:                             my $mapsymb = &symbread($item,1);
                   7373:                             if ($mapsymb) {
                   7374:                                 if (ref($navmap)) {
                   7375:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7376:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7377:                                     foreach my $res (@to_test) {
                   7378:                                         my $symb = $res->symb();
                   7379:                                         next if ($symb eq $mapsymb);
                   7380:                                         if ($symb ne '') {
                   7381:                                             @interval=&EXT("resource.0.interval",$symb);
                   7382:                                             if ($interval[1] eq 'map') {
                   7383:                                                 last;
1.1162    raeburn  7384:                                             }
                   7385:                                         }
                   7386:                                     }
                   7387:                                 }
                   7388:                             }
                   7389:                         }
1.1172.2.66  raeburn  7390:                     }
                   7391:                     if ($interval[0] =~ /^\d+$/) {
                   7392:                         my $first_access;
                   7393:                         if ($type eq 'resource') {
                   7394:                             $first_access=&get_first_access($interval[1],$item);
                   7395:                         } elsif ($type eq 'map') {
                   7396:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7397:                         } else {
                   7398:                             $first_access=&get_first_access($interval[1]);
                   7399:                         }
                   7400:                         if ($first_access) {
                   7401:                             my $timesup = $first_access+$interval[0];
                   7402:                             if ($timesup > $now) {
                   7403:                                 my $activeblock;
                   7404:                                 foreach my $res (@to_test) {
                   7405:                                     if ($res->answerable()) {
                   7406:                                         $activeblock = 1;
                   7407:                                         last;
                   7408:                                     }
                   7409:                                 }
                   7410:                                 if ($activeblock) {
                   7411:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7412:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7413:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7414:                                          }
                   7415:                                     }
                   7416:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7417:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7418:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7419:                                         }
1.1162    raeburn  7420:                                     }
                   7421:                                 }
                   7422:                             }
                   7423:                         }
                   7424:                     }
                   7425:                 }
                   7426:             }
                   7427:         }
                   7428:     }
1.1172.2.66  raeburn  7429:     return %blockers;
1.1162    raeburn  7430: }
                   7431: 
1.1172.2.66  raeburn  7432: sub has_comm_blocking {
                   7433:     my ($priv,$symb,$uri,$blocks) = @_;
                   7434:     my @blockers;
                   7435:     return unless ($env{'request.course.id'});
                   7436:     return unless ($priv eq 'bre');
                   7437:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7438:     return if ($env{'request.state'} eq 'construct');
                   7439:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7440:     return unless (keys(%cachedblockers) > 0);
                   7441:     my (%possibles,@symbs);
                   7442:     if (!$symb) {
                   7443:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7444:     }
1.1172.2.66  raeburn  7445:     if ($symb) {
                   7446:         @symbs = ($symb);
                   7447:     } elsif (keys(%possibles)) {
                   7448:         @symbs = keys(%possibles);
                   7449:     }
                   7450:     my $noblock;
                   7451:     foreach my $symb (@symbs) {
                   7452:         last if ($noblock);
                   7453:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7454:         foreach my $block (keys(%cachedblockers)) {
                   7455:             if ($block =~ /^firstaccess____(.+)$/) {
                   7456:                 my $item = $1;
                   7457:                 if (($item eq $map) || ($item eq $symb)) {
                   7458:                     $noblock = 1;
                   7459:                     last;
                   7460:                 }
1.1162    raeburn  7461:             }
1.1172.2.66  raeburn  7462:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7463:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7464:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7465:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7466:                             push(@blockers,$block);
                   7467:                         }
                   7468:                     }
                   7469:                 }
                   7470:             }
                   7471:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7472:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7473:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7474:                         push(@blockers,$block);
                   7475:                     }
                   7476:                 }
1.1162    raeburn  7477:             }
                   7478:         }
                   7479:     }
1.1172.2.66  raeburn  7480:     return if ($noblock);
                   7481:     return @blockers;
                   7482: }
1.1162    raeburn  7483: }
                   7484: 
1.1172.2.66  raeburn  7485: # -------------------------------- Deversion and split uri into path an filename
                   7486: 
1.1133    foxr     7487: #
1.1172.2.66  raeburn  7488: #   Removes the version from a URI and
1.1133    foxr     7489: #   splits it in to its filename and path to the filename.
                   7490: #   Seems like File::Basename could have done this more clearly.
                   7491: #   Parameters:
                   7492: #      $uri   - input URI
                   7493: #   Returns:
                   7494: #     Two element list consisting of 
                   7495: #     $pathname  - the URI up to and excluding the trailing /
                   7496: #     $filename  - The part of the URI following the last /
                   7497: #  NOTE:
                   7498: #    Another realization of this is simply:
                   7499: #    use File::Basename;
                   7500: #    ...
                   7501: #    $uri = shift;
                   7502: #    $filename = basename($uri);
                   7503: #    $path     = dirname($uri);
                   7504: #    return ($filename, $path);
                   7505: #
                   7506: #     The implementation below is probably faster however.
                   7507: #
1.710     albertel 7508: sub split_uri_for_cond {
                   7509:     my $uri=&deversion(&declutter(shift));
                   7510:     my @uriparts=split(/\//,$uri);
                   7511:     my $filename=pop(@uriparts);
                   7512:     my $pathname=join('/',@uriparts);
                   7513:     return ($pathname,$filename);
                   7514: }
1.232     www      7515: # --------------------------------------------------- Is a resource on the map?
                   7516: 
                   7517: sub is_on_map {
1.710     albertel 7518:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7519:     #Trying to find the conditional for the file
1.620     albertel 7520:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7521: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7522:     if ($match) {
1.289     bowersj2 7523: 	return (1,$1);
                   7524:     } else {
1.434     www      7525: 	return (0,0);
1.289     bowersj2 7526:     }
1.12      www      7527: }
                   7528: 
1.427     www      7529: # --------------------------------------------------------- Get symb from alias
                   7530: 
                   7531: sub get_symb_from_alias {
                   7532:     my $symb=shift;
                   7533:     my ($map,$resid,$url)=&decode_symb($symb);
                   7534: # Already is a symb
                   7535:     if ($url) { return $symb; }
                   7536: # Must be an alias
                   7537:     my $aliassymb='';
                   7538:     my %bighash;
1.620     albertel 7539:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7540:                             &GDBM_READER(),0640)) {
                   7541:         my $rid=$bighash{'mapalias_'.$symb};
                   7542: 	if ($rid) {
                   7543: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7544: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7545: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7546: 	}
                   7547:         untie %bighash;
                   7548:     }
                   7549:     return $aliassymb;
                   7550: }
                   7551: 
1.12      www      7552: # ----------------------------------------------------------------- Define Role
                   7553: 
                   7554: sub definerole {
                   7555:   if (allowed('mcr','/')) {
                   7556:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7557:     foreach my $role (split(':',$sysrole)) {
                   7558: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7559:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7560:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7561: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7562:                return "refused:s:$crole&$cqual"; 
                   7563:             }
                   7564:         }
1.191     harris41 7565:     }
1.800     albertel 7566:     foreach my $role (split(':',$domrole)) {
                   7567: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7568:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7569:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7570: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7571:                return "refused:d:$crole&$cqual"; 
                   7572:             }
                   7573:         }
1.191     harris41 7574:     }
1.800     albertel 7575:     foreach my $role (split(':',$courole)) {
                   7576: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7577:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7578:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7579: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7580:                return "refused:c:$crole&$cqual"; 
                   7581:             }
                   7582:         }
1.191     harris41 7583:     }
1.620     albertel 7584:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7585:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7586: 	        "rolesdef_$rolename=".
                   7587:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7588:     return reply($command,$env{'user.home'});
1.12      www      7589:   } else {
                   7590:     return 'refused';
                   7591:   }
1.105     harris41 7592: }
                   7593: 
                   7594: # ---------------- Make a metadata query against the network of library servers
                   7595: 
                   7596: sub metadata_query {
1.1172.2.33  raeburn  7597:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7598:     my %rhash;
1.845     albertel 7599:     my %libserv = &all_library();
1.244     matthew  7600:     my @server_list = (defined($server_array) ? @$server_array
                   7601:                                               : keys(%libserv) );
                   7602:     for my $server (@server_list) {
1.1172.2.33  raeburn  7603:         my $domains = '';
                   7604:         if (ref($domains_hash) eq 'HASH') {
                   7605:             $domains = $domains_hash->{$server};    
                   7606:         }
1.118     harris41 7607: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  7608: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7609: 	    $rhash{$server}=$reply;
                   7610: 	}
                   7611: 	else {
                   7612: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  7613: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7614: 			     $server);
                   7615: 	    $rhash{$server}=$reply;
                   7616: 	}
1.112     harris41 7617:     }
1.118     harris41 7618:     return \%rhash;
1.240     www      7619: }
                   7620: 
                   7621: # ----------------------------------------- Send log queries and wait for reply
                   7622: 
                   7623: sub log_query {
                   7624:     my ($uname,$udom,$query,%filters)=@_;
                   7625:     my $uhome=&homeserver($uname,$udom);
                   7626:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7627:     my $uhost=&hostname($uhome);
1.800     albertel 7628:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7629:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7630:                        $uhome);
1.479     albertel 7631:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7632:     return get_query_reply($queryid);
                   7633: }
                   7634: 
1.818     raeburn  7635: # -------------------------- Update MySQL table for portfolio file
                   7636: 
                   7637: sub update_portfolio_table {
1.821     raeburn  7638:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7639:     if ($group ne '') {
                   7640:         $file_name =~s /^\Q$group\E//;
                   7641:     }
1.818     raeburn  7642:     my $homeserver = &homeserver($uname,$udom);
                   7643:     my $queryid=
1.821     raeburn  7644:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7645:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7646:     my $reply = &get_query_reply($queryid);
                   7647:     return $reply;
                   7648: }
                   7649: 
1.899     raeburn  7650: # -------------------------- Update MySQL allusers table
                   7651: 
                   7652: sub update_allusers_table {
                   7653:     my ($uname,$udom,$names) = @_;
                   7654:     my $homeserver = &homeserver($uname,$udom);
                   7655:     my $queryid=
                   7656:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7657:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7658:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7659:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7660:                'generation='.&escape($names->{'generation'}).'%%'.
                   7661:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7662:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7663:     return;
1.899     raeburn  7664: }
                   7665: 
1.508     raeburn  7666: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7667: 
                   7668: sub fetch_enrollment_query {
1.511     raeburn  7669:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7670:     my $homeserver;
1.547     raeburn  7671:     my $maxtries = 1;
1.508     raeburn  7672:     if ($context eq 'automated') {
                   7673:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7674:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7675:     } else {
                   7676:         $homeserver = &homeserver($cnum,$dom);
                   7677:     }
1.838     albertel 7678:     my $host=&hostname($homeserver);
1.506     raeburn  7679:     my $cmd = '';
1.1000    raeburn  7680:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7681:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7682:     }
                   7683:     $cmd =~ s/%%$//;
                   7684:     $cmd = &escape($cmd);
                   7685:     my $query = 'fetchenrollment';
1.620     albertel 7686:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7687:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7688:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7689:         return 'error: '.$queryid;
                   7690:     }
1.506     raeburn  7691:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7692:     my $tries = 1;
                   7693:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7694:         $reply = &get_query_reply($queryid);
                   7695:         $tries ++;
                   7696:     }
1.526     raeburn  7697:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7698:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7699:     } else {
1.901     albertel 7700:         my @responses = split(/:/,$reply);
1.515     raeburn  7701:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7702:             foreach my $line (@responses) {
                   7703:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7704:                 $$replyref{$key} = $value;
                   7705:             }
                   7706:         } else {
1.1117    foxr     7707:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7708:             foreach my $line (@responses) {
                   7709:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7710:                 $$replyref{$key} = $value;
                   7711:                 if ($value > 0) {
1.800     albertel 7712:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7713:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7714:                         my $destname = $pathname.'/'.$filename;
                   7715:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7716:                         if ($xml_classlist =~ /^error/) {
                   7717:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7718:                         } else {
1.506     raeburn  7719:                             if ( open(FILE,">$destname") ) {
                   7720:                                 print FILE &unescape($xml_classlist);
                   7721:                                 close(FILE);
1.526     raeburn  7722:                             } else {
                   7723:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7724:                             }
                   7725:                         }
                   7726:                     }
                   7727:                 }
                   7728:             }
                   7729:         }
                   7730:         return 'ok';
                   7731:     }
                   7732:     return 'error';
                   7733: }
                   7734: 
1.242     www      7735: sub get_query_reply {
                   7736:     my $queryid=shift;
1.1117    foxr     7737:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7738:     my $reply='';
                   7739:     for (1..100) {
                   7740: 	sleep 2;
                   7741:         if (-e $replyfile.'.end') {
1.448     albertel 7742: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7743: 		$reply = join('',<$fh>);
                   7744: 		close($fh);
1.240     www      7745: 	   } else { return 'error: reply_file_error'; }
1.242     www      7746:            return &unescape($reply);
                   7747: 	}
1.240     www      7748:     }
1.242     www      7749:     return 'timeout:'.$queryid;
1.240     www      7750: }
                   7751: 
                   7752: sub courselog_query {
1.241     www      7753: #
                   7754: # possible filters:
                   7755: # url: url or symb
                   7756: # username
                   7757: # domain
                   7758: # action: view, submit, grade
                   7759: # start: timestamp
                   7760: # end: timestamp
                   7761: #
1.240     www      7762:     my (%filters)=@_;
1.620     albertel 7763:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7764:     if ($filters{'url'}) {
                   7765: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7766:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7767:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7768:     }
1.620     albertel 7769:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7770:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7771:     return &log_query($cname,$cdom,'courselog',%filters);
                   7772: }
                   7773: 
                   7774: sub userlog_query {
1.858     raeburn  7775: #
                   7776: # possible filters:
                   7777: # action: log check role
                   7778: # start: timestamp
                   7779: # end: timestamp
                   7780: #
1.240     www      7781:     my ($uname,$udom,%filters)=@_;
                   7782:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7783: }
                   7784: 
1.506     raeburn  7785: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7786: 
                   7787: sub auto_run {
1.508     raeburn  7788:     my ($cnum,$cdom) = @_;
1.876     raeburn  7789:     my $response = 0;
                   7790:     my $settings;
                   7791:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7792:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7793:         $settings = $domconfig{'autoenroll'};
                   7794:         if ($settings->{'run'} eq '1') {
                   7795:             $response = 1;
                   7796:         }
                   7797:     } else {
1.934     raeburn  7798:         my $homeserver;
                   7799:         if (&is_course($cdom,$cnum)) {
                   7800:             $homeserver = &homeserver($cnum,$cdom);
                   7801:         } else {
                   7802:             $homeserver = &domain($cdom,'primary');
                   7803:         }
                   7804:         if ($homeserver ne 'no_host') {
                   7805:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7806:         }
1.876     raeburn  7807:     }
1.506     raeburn  7808:     return $response;
                   7809: }
1.776     albertel 7810: 
1.506     raeburn  7811: sub auto_get_sections {
1.508     raeburn  7812:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7813:     my $homeserver;
                   7814:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7815:         $homeserver = &homeserver($cnum,$cdom);
                   7816:     }
                   7817:     if (!defined($homeserver)) { 
                   7818:         if ($cdom =~ /^$match_domain$/) {
                   7819:             $homeserver = &domain($cdom,'primary');
                   7820:         }
                   7821:     }
                   7822:     my @secs;
                   7823:     if (defined($homeserver)) {
                   7824:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7825:         unless ($response eq 'refused') {
                   7826:             @secs = split(/:/,$response);
                   7827:         }
1.506     raeburn  7828:     }
                   7829:     return @secs;
                   7830: }
1.776     albertel 7831: 
1.506     raeburn  7832: sub auto_new_course {
1.1099    raeburn  7833:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7834:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7835:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7836:     return $response;
                   7837: }
1.776     albertel 7838: 
1.506     raeburn  7839: sub auto_validate_courseID {
1.508     raeburn  7840:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7841:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7842:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7843:     return $response;
                   7844: }
1.776     albertel 7845: 
1.1007    raeburn  7846: sub auto_validate_instcode {
1.1020    raeburn  7847:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7848:     my ($homeserver,$response);
                   7849:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7850:         $homeserver = &homeserver($cnum,$cdom);
                   7851:     }
                   7852:     if (!defined($homeserver)) {
                   7853:         if ($cdom =~ /^$match_domain$/) {
                   7854:             $homeserver = &domain($cdom,'primary');
                   7855:         }
                   7856:     }
1.1065    raeburn  7857:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7858:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7859:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7860:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7861: }
                   7862: 
1.506     raeburn  7863: sub auto_create_password {
1.873     raeburn  7864:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7865:     my ($homeserver,$response);
1.506     raeburn  7866:     my $create_passwd = 0;
                   7867:     my $authchk = '';
1.873     raeburn  7868:     if ($udom =~ /^$match_domain$/) {
                   7869:         $homeserver = &domain($udom,'primary');
                   7870:     }
                   7871:     if ($homeserver eq '') {
                   7872:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7873:             $homeserver = &homeserver($cnum,$cdom);
                   7874:         }
                   7875:     }
                   7876:     if ($homeserver eq '') {
                   7877:         $authchk = 'nodomain';
1.506     raeburn  7878:     } else {
1.873     raeburn  7879:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7880:         if ($response eq 'refused') {
                   7881:             $authchk = 'refused';
                   7882:         } else {
1.901     albertel 7883:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7884:         }
1.506     raeburn  7885:     }
                   7886:     return ($authparam,$create_passwd,$authchk);
                   7887: }
                   7888: 
1.706     raeburn  7889: sub auto_photo_permission {
                   7890:     my ($cnum,$cdom,$students) = @_;
                   7891:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7892:     my ($outcome,$perm_reqd,$conditions) = 
                   7893: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7894:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7895: 	return (undef,undef);
                   7896:     }
1.706     raeburn  7897:     return ($outcome,$perm_reqd,$conditions);
                   7898: }
                   7899: 
                   7900: sub auto_checkphotos {
                   7901:     my ($uname,$udom,$pid) = @_;
                   7902:     my $homeserver = &homeserver($uname,$udom);
                   7903:     my ($result,$resulttype);
                   7904:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7905: 				   &escape($uname).':'.&escape($pid),
                   7906: 				   $homeserver));
1.709     albertel 7907:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7908: 	return (undef,undef);
                   7909:     }
1.706     raeburn  7910:     if ($outcome) {
                   7911:         ($result,$resulttype) = split(/:/,$outcome);
                   7912:     } 
                   7913:     return ($result,$resulttype);
                   7914: }
                   7915: 
                   7916: sub auto_photochoice {
                   7917:     my ($cnum,$cdom) = @_;
                   7918:     my $homeserver = &homeserver($cnum,$cdom);
                   7919:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7920: 						       &escape($cdom),
                   7921: 						       $homeserver)));
1.709     albertel 7922:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7923: 	return (undef,undef);
                   7924:     }
1.706     raeburn  7925:     return ($update,$comment);
                   7926: }
                   7927: 
                   7928: sub auto_photoupdate {
                   7929:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7930:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7931:     my $host=&hostname($homeserver);
1.706     raeburn  7932:     my $cmd = '';
                   7933:     my $maxtries = 1;
1.800     albertel 7934:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7935:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7936:     }
                   7937:     $cmd =~ s/%%$//;
                   7938:     $cmd = &escape($cmd);
                   7939:     my $query = 'institutionalphotos';
                   7940:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7941:     unless ($queryid=~/^\Q$host\E\_/) {
                   7942:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7943:         return 'error: '.$queryid;
                   7944:     }
                   7945:     my $reply = &get_query_reply($queryid);
                   7946:     my $tries = 1;
                   7947:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7948:         $reply = &get_query_reply($queryid);
                   7949:         $tries ++;
                   7950:     }
                   7951:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7952:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7953:     } else {
                   7954:         my @responses = split(/:/,$reply);
                   7955:         my $outcome = shift(@responses); 
                   7956:         foreach my $item (@responses) {
                   7957:             my ($key,$value) = split(/=/,$item);
                   7958:             $$photo{$key} = $value;
                   7959:         }
                   7960:         return $outcome;
                   7961:     }
                   7962:     return 'error';
                   7963: }
                   7964: 
1.521     raeburn  7965: sub auto_instcode_format {
1.793     albertel 7966:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7967: 	$cat_order) = @_;
1.521     raeburn  7968:     my $courses = '';
1.772     raeburn  7969:     my @homeservers;
1.521     raeburn  7970:     if ($caller eq 'global') {
1.841     albertel 7971: 	my %servers = &get_servers($codedom,'library');
                   7972: 	foreach my $tryserver (keys(%servers)) {
                   7973: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7974: 		push(@homeservers,$tryserver);
                   7975: 	    }
1.584     raeburn  7976:         }
1.1022    raeburn  7977:     } elsif ($caller eq 'requests') {
                   7978:         if ($codedom =~ /^$match_domain$/) {
                   7979:             my $chome = &domain($codedom,'primary');
                   7980:             unless ($chome eq 'no_host') {
                   7981:                 push(@homeservers,$chome);
                   7982:             }
                   7983:         }
1.521     raeburn  7984:     } else {
1.772     raeburn  7985:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7986:     }
1.793     albertel 7987:     foreach my $code (keys(%{$instcodes})) {
                   7988:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7989:     }
                   7990:     chop($courses);
1.772     raeburn  7991:     my $ok_response = 0;
                   7992:     my $response;
                   7993:     while (@homeservers > 0 && $ok_response == 0) {
                   7994:         my $server = shift(@homeservers); 
                   7995:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7996:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7997:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7998: 		split(/:/,$response);
1.772     raeburn  7999:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8000:             push(@{$codetitles},&str2array($codetitles_str));
                   8001:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8002:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8003:             $ok_response = 1;
                   8004:         }
                   8005:     }
                   8006:     if ($ok_response) {
1.521     raeburn  8007:         return 'ok';
1.772     raeburn  8008:     } else {
                   8009:         return $response;
1.521     raeburn  8010:     }
                   8011: }
                   8012: 
1.792     raeburn  8013: sub auto_instcode_defaults {
                   8014:     my ($domain,$returnhash,$code_order) = @_;
                   8015:     my @homeservers;
1.841     albertel 8016: 
                   8017:     my %servers = &get_servers($domain,'library');
                   8018:     foreach my $tryserver (keys(%servers)) {
                   8019: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8020: 	    push(@homeservers,$tryserver);
                   8021: 	}
1.792     raeburn  8022:     }
1.841     albertel 8023: 
1.792     raeburn  8024:     my $response;
1.841     albertel 8025:     foreach my $server (@homeservers) {
1.792     raeburn  8026:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8027:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8028: 	
                   8029: 	foreach my $pair (split(/\&/,$response)) {
                   8030: 	    my ($name,$value)=split(/\=/,$pair);
                   8031: 	    if ($name eq 'code_order') {
                   8032: 		@{$code_order} = split(/\&/,&unescape($value));
                   8033: 	    } else {
                   8034: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8035: 	    }
                   8036: 	}
                   8037: 	return 'ok';
1.792     raeburn  8038:     }
1.841     albertel 8039: 
                   8040:     return $response;
1.1003    raeburn  8041: }
                   8042: 
                   8043: sub auto_possible_instcodes {
1.1007    raeburn  8044:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8045:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8046:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8047:         return;
                   8048:     }
1.1003    raeburn  8049:     my (@homeservers,$uhome);
                   8050:     if (defined(&domain($domain,'primary'))) {
                   8051:         $uhome=&domain($domain,'primary');
                   8052:         push(@homeservers,&domain($domain,'primary'));
                   8053:     } else {
                   8054:         my %servers = &get_servers($domain,'library');
                   8055:         foreach my $tryserver (keys(%servers)) {
                   8056:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8057:                 push(@homeservers,$tryserver);
                   8058:             }
                   8059:         }
                   8060:     }
                   8061:     my $response;
                   8062:     foreach my $server (@homeservers) {
                   8063:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8064:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8065:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8066:             split(':',$response);
                   8067:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8068:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8069:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8070:             my ($name,$value)=split('=',$item);
                   8071:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8072:         }
                   8073:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8074:             my ($name,$value)=split('=',$item);
                   8075:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8076:         }
                   8077:         return 'ok';
                   8078:     }
                   8079:     return $response;
                   8080: }
1.792     raeburn  8081: 
1.1010    raeburn  8082: sub auto_courserequest_checks {
                   8083:     my ($dom) = @_;
1.1020    raeburn  8084:     my ($homeserver,%validations);
                   8085:     if ($dom =~ /^$match_domain$/) {
                   8086:         $homeserver = &domain($dom,'primary');
                   8087:     }
                   8088:     unless ($homeserver eq 'no_host') {
                   8089:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8090:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8091:             my @items = split(/&/,$response);
                   8092:             foreach my $item (@items) {
                   8093:                 my ($key,$value) = split('=',$item);
                   8094:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8095:             }
                   8096:         }
                   8097:     }
1.1010    raeburn  8098:     return %validations; 
                   8099: }
                   8100: 
1.1020    raeburn  8101: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8102:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8103:     my ($homeserver,$response);
                   8104:     if ($dom =~ /^$match_domain$/) {
                   8105:         $homeserver = &domain($dom,'primary');
                   8106:     }
1.1172.2.43  raeburn  8107:     unless ($homeserver eq 'no_host') {
                   8108:         my $customdata;
                   8109:         if (ref($custominfo) eq 'HASH') {
                   8110:             $customdata = &freeze_escape($custominfo);
                   8111:         }
1.1020    raeburn  8112:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8113:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8114:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8115:                                     $customdata,$homeserver));
1.1020    raeburn  8116:     }
                   8117:     return $response;
                   8118: }
                   8119: 
1.777     albertel 8120: sub auto_validate_class_sec {
1.918     raeburn  8121:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8122:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8123:     my $ownerlist;
                   8124:     if (ref($owners) eq 'ARRAY') {
                   8125:         $ownerlist = join(',',@{$owners});
                   8126:     } else {
                   8127:         $ownerlist = $owners;
                   8128:     }
1.773     raeburn  8129:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8130:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8131:     return $response;
                   8132: }
                   8133: 
1.1172.2.38  raeburn  8134: sub auto_crsreq_update {
                   8135:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8136:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8137:     my ($homeserver,%crsreqresponse);
                   8138:     if ($cdom =~ /^$match_domain$/) {
                   8139:         $homeserver = &domain($cdom,'primary');
                   8140:     }
                   8141:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8142:         my $info;
                   8143:         if (ref($inbound) eq 'HASH') {
                   8144:             $info = &freeze_escape($inbound);
                   8145:         }
                   8146:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8147:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8148:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8149:                             &escape($title).':'.&escape($code).':'.
                   8150:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8151:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8152:             my @items = split(/&/,$response);
                   8153:             foreach my $item (@items) {
                   8154:                 my ($key,$value) = split('=',$item);
                   8155:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8156:             }
                   8157:         }
                   8158:     }
                   8159:     return \%crsreqresponse;
                   8160: }
                   8161: 
1.1172.2.68! raeburn  8162: sub check_instcode_cloning {
        !          8163:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
        !          8164:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
        !          8165:         return;
        !          8166:     }
        !          8167:     my $canclone;
        !          8168:     if (@{$code_order} > 0) {
        !          8169:         my $instcoderegexp ='^';
        !          8170:         my @clonecodes = split(/\&/,$cloner);
        !          8171:         foreach my $item (@{$code_order}) {
        !          8172:             if (grep(/^\Q$item\E=/,@clonecodes)) {
        !          8173:                 foreach my $pair (@clonecodes) {
        !          8174:                     my ($key,$val) = split(/\=/,$pair,2);
        !          8175:                     $val = &unescape($val);
        !          8176:                     if ($key eq $item) {
        !          8177:                         $instcoderegexp .= '('.$val.')';
        !          8178:                         last;
        !          8179:                     }
        !          8180:                 }
        !          8181:             } else {
        !          8182:                 $instcoderegexp .= $codedefaults->{$item};
        !          8183:             }
        !          8184:         }
        !          8185:         $instcoderegexp .= '$';
        !          8186:         my (@from,@to);
        !          8187:         eval {
        !          8188:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
        !          8189:                (@to) = ($clonetocode =~ /$instcoderegexp/);
        !          8190:         };
        !          8191:         if ((@from > 0) && (@to > 0)) {
        !          8192:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
        !          8193:             if (!@diffs) {
        !          8194:                 $canclone = 1;
        !          8195:             }
        !          8196:         }
        !          8197:     }
        !          8198:     return $canclone;
        !          8199: }
        !          8200: 
        !          8201: sub default_instcode_cloning {
        !          8202:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
        !          8203:     my (%codedefaults,@code_order,$canclone);
        !          8204:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
        !          8205:         %codedefaults = %{$codedefaultsref};
        !          8206:         @code_order = @{$codeorderref};
        !          8207:     } elsif ($clonedom) {
        !          8208:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
        !          8209:     }
        !          8210:     if (($domdefclone) && (@code_order)) {
        !          8211:         my @clonecodes = split(/\+/,$domdefclone);
        !          8212:         my $instcoderegexp ='^';
        !          8213:         foreach my $item (@code_order) {
        !          8214:             if (grep(/^\Q$item\E$/,@clonecodes)) {
        !          8215:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
        !          8216:             } else {
        !          8217:                 $instcoderegexp .= $codedefaults{$item};
        !          8218:             }
        !          8219:         }
        !          8220:         $instcoderegexp .= '$';
        !          8221:         my (@from,@to);
        !          8222:         eval {
        !          8223:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
        !          8224:             (@to) = ($clonetocode =~ /$instcoderegexp/);
        !          8225:         };
        !          8226:         if ((@from > 0) && (@to > 0)) {
        !          8227:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
        !          8228:             if (!@diffs) {
        !          8229:                 $canclone = 1;
        !          8230:             }
        !          8231:         }
        !          8232:     }
        !          8233:     return $canclone;
        !          8234: }
        !          8235: 
1.679     raeburn  8236: # ------------------------------------------------------- Course Group routines
                   8237: 
                   8238: sub get_coursegroups {
1.809     raeburn  8239:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8240:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8241: }
                   8242: 
1.679     raeburn  8243: sub modify_coursegroup {
                   8244:     my ($cdom,$cnum,$groupsettings) = @_;
                   8245:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8246: }
                   8247: 
1.809     raeburn  8248: sub toggle_coursegroup_status {
                   8249:     my ($cdom,$cnum,$group,$action) = @_;
                   8250:     my ($from_namespace,$to_namespace);
                   8251:     if ($action eq 'delete') {
                   8252:         $from_namespace = 'coursegroups';
                   8253:         $to_namespace = 'deleted_groups';
                   8254:     } else {
                   8255:         $from_namespace = 'deleted_groups';
                   8256:         $to_namespace = 'coursegroups';
                   8257:     }
                   8258:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8259:     if (my $tmp = &error(%curr_group)) {
                   8260:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8261:         return ('read error',$tmp);
                   8262:     } else {
                   8263:         my %savedsettings = %curr_group; 
1.809     raeburn  8264:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8265:         my $deloutcome;
                   8266:         if ($result eq 'ok') {
1.809     raeburn  8267:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8268:         } else {
                   8269:             return ('write error',$result);
                   8270:         }
                   8271:         if ($deloutcome eq 'ok') {
                   8272:             return 'ok';
                   8273:         } else {
                   8274:             return ('delete error',$deloutcome);
                   8275:         }
                   8276:     }
                   8277: }
                   8278: 
1.679     raeburn  8279: sub modify_group_roles {
1.957     raeburn  8280:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8281:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8282:     my $role = 'gr/'.&escape($userprivs);
                   8283:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8284:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8285:     if ($result eq 'ok') {
                   8286:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8287:     }
1.679     raeburn  8288:     return $result;
                   8289: }
                   8290: 
                   8291: sub modify_coursegroup_membership {
                   8292:     my ($cdom,$cnum,$membership) = @_;
                   8293:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8294:     return $result;
                   8295: }
                   8296: 
1.682     raeburn  8297: sub get_active_groups {
                   8298:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8299:     my $now = time;
                   8300:     my %groups = ();
                   8301:     foreach my $key (keys(%env)) {
1.811     albertel 8302:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8303:             my ($start,$end) = split(/\./,$env{$key});
                   8304:             if (($end!=0) && ($end<$now)) { next; }
                   8305:             if (($start!=0) && ($start>$now)) { next; }
                   8306:             if ($1 eq $cdom && $2 eq $cnum) {
                   8307:                 $groups{$3} = $env{$key} ;
                   8308:             }
                   8309:         }
                   8310:     }
                   8311:     return %groups;
                   8312: }
                   8313: 
1.683     raeburn  8314: sub get_group_membership {
                   8315:     my ($cdom,$cnum,$group) = @_;
                   8316:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8317: }
                   8318: 
                   8319: sub get_users_groups {
                   8320:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8321:     my @usersgroups;
1.683     raeburn  8322:     my $cachetime=1800;
                   8323: 
                   8324:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8325:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8326:     if (defined($cached)) {
1.734     albertel 8327:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8328:     } else {  
                   8329:         $grouplist = '';
1.816     raeburn  8330:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8331:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8332:         my $access_end = $env{'course.'.$courseid.
                   8333:                               '.default_enrollment_end_date'};
                   8334:         my $now = time;
                   8335:         foreach my $key (keys(%roleshash)) {
                   8336:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8337:                 my $group = $1;
                   8338:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8339:                     my $start = $2;
                   8340:                     my $end = $1;
                   8341:                     if ($start == -1) { next; } # deleted from group
                   8342:                     if (($start!=0) && ($start>$now)) { next; }
                   8343:                     if (($end!=0) && ($end<$now)) {
                   8344:                         if ($access_end && $access_end < $now) {
                   8345:                             if ($access_end - $end < 86400) {
                   8346:                                 push(@usersgroups,$group);
1.733     raeburn  8347:                             }
                   8348:                         }
1.817     raeburn  8349:                         next;
1.733     raeburn  8350:                     }
1.817     raeburn  8351:                     push(@usersgroups,$group);
1.683     raeburn  8352:                 }
                   8353:             }
                   8354:         }
1.817     raeburn  8355:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8356:         $grouplist = join(':',@usersgroups);
                   8357:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8358:     }
1.733     raeburn  8359:     return @usersgroups;
1.683     raeburn  8360: }
                   8361: 
                   8362: sub devalidate_getgroups_cache {
                   8363:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8364:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8365: 
1.683     raeburn  8366:     my $hashid="$udom:$uname:$courseid";
                   8367:     &devalidate_cache_new('getgroups',$hashid);
                   8368: }
                   8369: 
1.12      www      8370: # ------------------------------------------------------------------ Plain Text
                   8371: 
                   8372: sub plaintext {
1.988     raeburn  8373:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8374:     if ($short =~ m{^cr/}) {
1.758     albertel 8375: 	return (split('/',$short))[-1];
                   8376:     }
1.742     raeburn  8377:     if (!defined($cid)) {
                   8378:         $cid = $env{'request.course.id'};
                   8379:     }
                   8380:     my %rolenames = (
1.1008    raeburn  8381:                       Course    => 'std',
                   8382:                       Community => 'alt1',
1.742     raeburn  8383:                     );
1.1037    raeburn  8384:     if ($cid ne '') {
                   8385:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8386:             unless ($forcedefault) {
                   8387:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8388:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8389:                 return &Apache::lonlocal::mt($roletext);
                   8390:             }
                   8391:         }
                   8392:     }
                   8393:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8394:         (defined($rolenames{$type})) && 
                   8395:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8396:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8397:     } elsif ($cid ne '') {
                   8398:         my $crstype = $env{'course.'.$cid.'.type'};
                   8399:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8400:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8401:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8402:         }
1.742     raeburn  8403:     }
1.1037    raeburn  8404:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8405: }
                   8406: 
                   8407: # ----------------------------------------------------------------- Assign Role
                   8408: 
                   8409: sub assignrole {
1.957     raeburn  8410:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8411:         $context)=@_;
1.21      www      8412:     my $mrole;
                   8413:     if ($role =~ /^cr\//) {
1.393     www      8414:         my $cwosec=$url;
1.811     albertel 8415:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8416: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8417:            my $refused = 1;
                   8418:            if ($context eq 'requestcourses') {
                   8419:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8420:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8421:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8422:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8423:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8424:                            if ($crsenv{'internal.courseowner'} eq
                   8425:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8426:                                $refused = '';
                   8427:                            }
                   8428:                        }
                   8429:                    }
                   8430:                }
                   8431:            }
                   8432:            if ($refused) {
                   8433:                &logthis('Refused custom assignrole: '.
                   8434:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8435:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8436:                return 'refused';
                   8437:            }
1.104     www      8438:         }
1.21      www      8439:         $mrole='cr';
1.678     raeburn  8440:     } elsif ($role =~ /^gr\//) {
                   8441:         my $cwogrp=$url;
1.811     albertel 8442:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8443:         unless (&allowed('mdg',$cwogrp)) {
                   8444:             &logthis('Refused group assignrole: '.
                   8445:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8446:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8447:             return 'refused';
                   8448:         }
                   8449:         $mrole='gr';
1.21      www      8450:     } else {
1.82      www      8451:         my $cwosec=$url;
1.811     albertel 8452:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8453:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8454:             my $refused;
                   8455:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8456:                 if (!(&allowed('c'.$role,$url))) {
                   8457:                     $refused = 1;
                   8458:                 }
                   8459:             } else {
                   8460:                 $refused = 1;
                   8461:             }
1.947     raeburn  8462:             if ($refused) {
1.1045    raeburn  8463:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8464:                 if (!$selfenroll && $context eq 'course') {
                   8465:                     my %crsenv;
                   8466:                     if ($role eq 'cc' || $role eq 'co') {
                   8467:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8468:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8469:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8470:                                 if ($crsenv{'internal.courseowner'} eq 
                   8471:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8472:                                     $refused = '';
                   8473:                                 }
                   8474:                             }
                   8475:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8476:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8477:                                 if ($crsenv{'internal.courseowner'} eq 
                   8478:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8479:                                     $refused = '';
                   8480:                                 }
                   8481:                             }
                   8482:                         }
                   8483:                     }
                   8484:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8485:                     $refused = '';
1.1017    raeburn  8486:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8487:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8488:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8489:                         my $wrongcc;
                   8490:                         if ($cnum =~ /^$match_community$/) {
                   8491:                             $wrongcc = 1 if ($role eq 'cc');
                   8492:                         } else {
                   8493:                             $wrongcc = 1 if ($role eq 'co');
                   8494:                         }
                   8495:                         unless ($wrongcc) {
                   8496:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8497:                             if ($crsenv{'internal.courseowner'} eq 
                   8498:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8499:                                 $refused = '';
                   8500:                             }
1.1017    raeburn  8501:                         }
                   8502:                     }
1.1172.2.9  raeburn  8503:                 } elsif ($context eq 'requestauthor') {
                   8504:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8505:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8506:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8507:                             $refused = '';
                   8508:                         } else {
                   8509:                             my %domdefaults = &get_domain_defaults($udom);
                   8510:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8511:                                 my $checkbystatus;
                   8512:                                 if ($env{'user.adv'}) {
                   8513:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8514:                                     if ($disposition eq 'automatic') {
                   8515:                                         $refused = '';
                   8516:                                     } elsif ($disposition eq '') {
                   8517:                                         $checkbystatus = 1;
                   8518:                                     }
                   8519:                                 } else {
                   8520:                                     $checkbystatus = 1;
                   8521:                                 }
                   8522:                                 if ($checkbystatus) {
                   8523:                                     if ($env{'environment.inststatus'}) {
                   8524:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8525:                                         foreach my $type (@inststatuses) {
                   8526:                                             if (($type ne '') &&
                   8527:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8528:                                                 $refused = '';
                   8529:                                             }
                   8530:                                         }
                   8531:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8532:                                         $refused = '';
                   8533:                                     }
                   8534:                                 }
                   8535:                             }
                   8536:                         }
                   8537:                     }
1.1017    raeburn  8538:                 }
                   8539:                 if ($refused) {
1.947     raeburn  8540:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8541:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8542: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8543:                     return 'refused';
                   8544:                 }
1.932     raeburn  8545:             }
1.1131    raeburn  8546:         } elsif ($role eq 'au') {
                   8547:             if ($url ne '/'.$udom.'/') {
                   8548:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8549:                          ' to assign author role for '.$uname.':'.$udom.
                   8550:                          ' in domain: '.$url.' refused (wrong domain).');
                   8551:                 return 'refused';
                   8552:             }
1.104     www      8553:         }
1.21      www      8554:         $mrole=$role;
                   8555:     }
1.620     albertel 8556:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8557:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8558:     if ($end) { $command.='_'.$end; }
1.21      www      8559:     if ($start) {
                   8560: 	if ($end) { 
1.81      www      8561:            $command.='_'.$start; 
1.21      www      8562:         } else {
1.81      www      8563:            $command.='_0_'.$start;
1.21      www      8564:         }
                   8565:     }
1.739     raeburn  8566:     my $origstart = $start;
                   8567:     my $origend = $end;
1.957     raeburn  8568:     my $delflag;
1.357     www      8569: # actually delete
                   8570:     if ($deleteflag) {
1.373     www      8571: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8572: # modify command to delete the role
1.620     albertel 8573:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8574:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8575: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8576: # set start and finish to negative values for userrolelog
                   8577:            $start=-1;
                   8578:            $end=-1;
1.957     raeburn  8579:            $delflag = 1;
1.357     www      8580:         }
                   8581:     }
                   8582: # send command
1.349     www      8583:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8584: # log new user role if status is ok
1.349     www      8585:     if ($answer eq 'ok') {
1.663     raeburn  8586: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8587:         if (($role eq 'cc') || ($role eq 'in') ||
                   8588:             ($role eq 'ep') || ($role eq 'ad') ||
                   8589:             ($role eq 'ta') || ($role eq 'st') ||
                   8590:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8591:             ($role eq 'co')) {
1.1172.2.13  raeburn  8592: # for course roles, perform group memberships changes triggered by role change.
                   8593:             unless ($role =~ /^gr/) {
                   8594:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8595:                                                  $origstart,$selfenroll,$context);
                   8596:             }
1.1172.2.9  raeburn  8597:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8598:                            $selfenroll,$context);
                   8599:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8600:                  ($role eq 'au') || ($role eq 'dc')) {
                   8601:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8602:                            $context);
                   8603:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8604:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8605:                              $context);
                   8606:         }
1.1053    raeburn  8607:         if ($role eq 'cc') {
                   8608:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8609:         }
1.349     www      8610:     }
                   8611:     return $answer;
1.169     harris41 8612: }
                   8613: 
1.1053    raeburn  8614: sub autoupdate_coowners {
                   8615:     my ($url,$end,$start,$uname,$udom) = @_;
                   8616:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8617:     if (($cdom ne '') && ($cnum ne '')) {
                   8618:         my $now = time;
                   8619:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8620:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8621:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8622:             my $instcode = $coursehash{'internal.coursecode'};
                   8623:             if ($instcode ne '') {
1.1056    raeburn  8624:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8625:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8626:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8627:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8628:                         if ($result eq 'valid') {
                   8629:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8630:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8631:                                     push(@newcoowners,$coowner);
                   8632:                                 }
                   8633:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8634:                                     push(@newcoowners,$uname.':'.$udom);
                   8635:                                 }
                   8636:                                 @newcoowners = sort(@newcoowners);
                   8637:                             } else {
                   8638:                                 push(@newcoowners,$uname.':'.$udom);
                   8639:                             }
                   8640:                         } else {
                   8641:                             if ($coursehash{'internal.co-owners'}) {
                   8642:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8643:                                     unless ($coowner eq $uname.':'.$udom) {
                   8644:                                         push(@newcoowners,$coowner);
                   8645:                                     }
                   8646:                                 }
                   8647:                                 unless (@newcoowners > 0) {
                   8648:                                     $delcoowners = 1;
                   8649:                                     $coowners = '';
                   8650:                                 }
                   8651:                             }
                   8652:                         }
                   8653:                         if (@newcoowners || $delcoowners) {
                   8654:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8655:                                             $delcoowners,@newcoowners);
                   8656:                         }
                   8657:                     }
                   8658:                 }
                   8659:             }
                   8660:         }
                   8661:     }
                   8662: }
                   8663: 
                   8664: sub store_coowners {
                   8665:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8666:     my $cid = $cdom.'_'.$cnum;
                   8667:     my ($coowners,$delresult,$putresult);
                   8668:     if (@newcoowners) {
                   8669:         $coowners = join(',',@newcoowners);
                   8670:         my %coownershash = (
                   8671:                             'internal.co-owners' => $coowners,
                   8672:                            );
                   8673:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8674:         if ($putresult eq 'ok') {
                   8675:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8676:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8677:             }
                   8678:         }
                   8679:     }
                   8680:     if ($delcoowners) {
                   8681:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8682:         if ($delresult eq 'ok') {
                   8683:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8684:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8685:             }
                   8686:         }
                   8687:     }
                   8688:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8689:         my %crsinfo =
                   8690:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8691:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8692:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8693:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8694:         }
                   8695:     }
                   8696: }
                   8697: 
1.169     harris41 8698: # -------------------------------------------------- Modify user authentication
1.197     www      8699: # Overrides without validation
                   8700: 
1.169     harris41 8701: sub modifyuserauth {
                   8702:     my ($udom,$uname,$umode,$upass)=@_;
                   8703:     my $uhome=&homeserver($uname,$udom);
1.197     www      8704:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8705:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8706:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8707:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8708:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8709: 		     &escape($upass),$uhome);
1.620     albertel 8710:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8711:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8712:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8713:     &log($udom,,$uname,$uhome,
1.620     albertel 8714:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8715:                                      $env{'user.name'}.', '.$umode.
1.197     www      8716:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8717:     unless ($reply eq 'ok') {
1.197     www      8718:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8719: 	return 'error: '.$reply;
                   8720:     }   
1.170     harris41 8721:     return 'ok';
1.80      www      8722: }
                   8723: 
1.81      www      8724: # --------------------------------------------------------------- Modify a user
1.80      www      8725: 
1.81      www      8726: sub modifyuser {
1.206     matthew  8727:     my ($udom,    $uname, $uid,
                   8728:         $umode,   $upass, $first,
                   8729:         $middle,  $last,  $gene,
1.1058    raeburn  8730:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8731:     $udom= &LONCAPA::clean_domain($udom);
                   8732:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8733:     my $showcandelete = 'none';
                   8734:     if (ref($candelete) eq 'ARRAY') {
                   8735:         if (@{$candelete} > 0) {
                   8736:             $showcandelete = join(', ',@{$candelete});
                   8737:         }
                   8738:     }
1.81      www      8739:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8740:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8741: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8742:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8743:                                      ' desiredhome not specified'). 
1.620     albertel 8744:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8745:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8746:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8747:     my $newuser;
                   8748:     if ($uhome eq 'no_host') {
                   8749:         $newuser = 1;
                   8750:     }
1.80      www      8751: # ----------------------------------------------------------------- Create User
1.406     albertel 8752:     if (($uhome eq 'no_host') && 
                   8753: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8754:         my $unhome='';
1.844     albertel 8755:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8756:             $unhome = $desiredhome;
1.620     albertel 8757: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8758: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8759:         } else { # load balancing routine for determining $unhome
1.81      www      8760:             my $loadm=10000000;
1.841     albertel 8761: 	    my %servers = &get_servers($udom,'library');
                   8762: 	    foreach my $tryserver (keys(%servers)) {
                   8763: 		my $answer=reply('load',$tryserver);
                   8764: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8765: 		    $loadm=$answer;
                   8766: 		    $unhome=$tryserver;
                   8767: 		}
1.80      www      8768: 	    }
                   8769:         }
                   8770:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8771: 	    return 'error: unable to find a home server for '.$uname.
                   8772:                    ' in domain '.$udom;
1.80      www      8773:         }
                   8774:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8775:                          &escape($upass),$unhome);
                   8776: 	unless ($reply eq 'ok') {
                   8777:             return 'error: '.$reply;
                   8778:         }   
1.230     stredwic 8779:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8780:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8781: 	    return 'error: unable verify users home machine.';
1.80      www      8782:         }
1.209     matthew  8783:     }   # End of creation of new user
1.80      www      8784: # ---------------------------------------------------------------------- Add ID
                   8785:     if ($uid) {
                   8786:        $uid=~tr/A-Z/a-z/;
                   8787:        my %uidhash=&idrget($udom,$uname);
1.196     www      8788:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8789:          && (!$forceid)) {
1.80      www      8790: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8791: 	      return 'error: user id "'.$uid.'" does not match '.
                   8792:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8793:           }
                   8794:        } else {
                   8795: 	  &idput($udom,($uname => $uid));
                   8796:        }
                   8797:     }
                   8798: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8799:     my @tmp=&get('environment',
1.899     raeburn  8800: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8801:                     'permanentemail','inststatus'],
1.134     albertel 8802: 		   $udom,$uname);
1.1075    raeburn  8803:     my (%names,%oldnames);
1.313     matthew  8804:     if ($tmp[0] =~ m/^error:.*/) { 
                   8805:         %names=(); 
                   8806:     } else {
                   8807:         %names = @tmp;
1.1075    raeburn  8808:         %oldnames = %names;
1.313     matthew  8809:     }
1.388     www      8810: #
1.1058    raeburn  8811: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8812: # of users did not contain them), do not overwrite existing values
                   8813: # unless field is in $candelete array ref.  
                   8814: #
                   8815: 
                   8816:     my @fields = ('firstname','middlename','lastname','generation',
                   8817:                   'permanentemail','id');
                   8818:     my %newvalues;
                   8819:     if (ref($candelete) eq 'ARRAY') {
                   8820:         foreach my $field (@fields) {
                   8821:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8822:                 if ($field eq 'firstname') {
                   8823:                     $names{$field} = $first;
                   8824:                 } elsif ($field eq 'middlename') {
                   8825:                     $names{$field} = $middle;
                   8826:                 } elsif ($field eq 'lastname') {
                   8827:                     $names{$field} = $last;
                   8828:                 } elsif ($field eq 'generation') { 
                   8829:                     $names{$field} = $gene;
                   8830:                 } elsif ($field eq 'permanentemail') {
                   8831:                     $names{$field} = $email;
                   8832:                 } elsif ($field eq 'id') {
                   8833:                     $names{$field}  = $uid;
                   8834:                 }
                   8835:             }
                   8836:         }
                   8837:     }
1.388     www      8838:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8839:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8840:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8841:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8842:     if ($email) {
                   8843:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8844:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8845:     }
1.899     raeburn  8846:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8847:     if (defined($inststatus)) {
                   8848:         $names{'inststatus'} = '';
                   8849:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8850:         if (ref($usertypes) eq 'HASH') {
                   8851:             my @okstatuses; 
                   8852:             foreach my $item (split(/:/,$inststatus)) {
                   8853:                 if (defined($usertypes->{$item})) {
                   8854:                     push(@okstatuses,$item);  
                   8855:                 }
                   8856:             }
                   8857:             if (@okstatuses) {
                   8858:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8859:             }
                   8860:         }
                   8861:     }
1.1075    raeburn  8862:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8863:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8864:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8865:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8866:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8867:     } else {
                   8868:         $logmsg .= ' during self creation';
                   8869:     }
1.1075    raeburn  8870:     my $changed;
                   8871:     if ($newuser) {
                   8872:         $changed = 1;
                   8873:     } else {
                   8874:         foreach my $field (@fields) {
                   8875:             if ($names{$field} ne $oldnames{$field}) {
                   8876:                 $changed = 1;
                   8877:                 last;
                   8878:             }
                   8879:         }
                   8880:     }
                   8881:     unless ($changed) {
                   8882:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8883:         &logthis($logmsg);
                   8884:         return 'ok';
                   8885:     }
                   8886:     my $reply = &put('environment', \%names, $udom,$uname);
                   8887:     if ($reply ne 'ok') { 
                   8888:         return 'error: '.$reply;
                   8889:     }
1.1087    raeburn  8890:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8891:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8892:     }
1.1075    raeburn  8893:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8894:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8895:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8896:     &logthis($logmsg);
1.134     albertel 8897:     return 'ok';
1.80      www      8898: }
                   8899: 
1.81      www      8900: # -------------------------------------------------------------- Modify student
1.80      www      8901: 
1.81      www      8902: sub modifystudent {
                   8903:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8904:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8905:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8906:     if (!$cid) {
1.620     albertel 8907: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8908: 	    return 'not_in_class';
                   8909: 	}
1.80      www      8910:     }
                   8911: # --------------------------------------------------------------- Make the user
1.81      www      8912:     my $reply=&modifyuser
1.209     matthew  8913: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8914:          $desiredhome,$email,$inststatus);
1.80      www      8915:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8916:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  8917:     # student's environment
1.297     matthew  8918:     $uid = undef if (!$forceid);
1.455     albertel 8919:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8920: 					$gene,$usec,$end,$start,$type,$locktype,
                   8921:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8922:     return $reply;
                   8923: }
                   8924: 
                   8925: sub modify_student_enrollment {
1.1172.2.23  raeburn  8926:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8927:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8928:     my ($cdom,$cnum,$chome);
                   8929:     if (!$cid) {
1.620     albertel 8930: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8931: 	    return 'not_in_class';
                   8932: 	}
1.620     albertel 8933: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8934: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8935:     } else {
                   8936: 	($cdom,$cnum)=split(/_/,$cid);
                   8937:     }
1.620     albertel 8938:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8939:     if (!$chome) {
1.457     raeburn  8940: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8941:     }
1.455     albertel 8942:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8943:     # Make sure the user exists
1.81      www      8944:     my $uhome=&homeserver($uname,$udom);
                   8945:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8946: 	return 'error: no such user';
                   8947:     }
1.297     matthew  8948:     # Get student data if we were not given enough information
                   8949:     if (!defined($first)  || $first  eq '' || 
                   8950:         !defined($last)   || $last   eq '' || 
                   8951:         !defined($uid)    || $uid    eq '' || 
                   8952:         !defined($middle) || $middle eq '' || 
                   8953:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8954:         # They did not supply us with enough data to enroll the student, so
                   8955:         # we need to pick up more information.
1.297     matthew  8956:         my %tmp = &get('environment',
1.294     matthew  8957:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8958:                        ,$udom,$uname);
                   8959: 
1.800     albertel 8960:         #foreach my $key (keys(%tmp)) {
                   8961:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8962:         #}
1.294     matthew  8963:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8964:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8965:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8966:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8967:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8968:     }
1.556     albertel 8969:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8970:     my $user = "$uname:$udom";
                   8971:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8972:     my $reply=cput('classlist',
1.1148    raeburn  8973: 		   {$user => 
1.1172.2.19  raeburn  8974: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8975: 		   $cdom,$cnum);
1.1148    raeburn  8976:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8977:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8978:     } else { 
1.81      www      8979: 	return 'error: '.$reply;
                   8980:     }
1.297     matthew  8981:     # Add student role to user
1.83      www      8982:     my $uurl='/'.$cid;
1.81      www      8983:     $uurl=~s/\_/\//g;
                   8984:     if ($usec) {
                   8985: 	$uurl.='/'.$usec;
                   8986:     }
1.1148    raeburn  8987:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8988:                              $selfenroll,$context);
                   8989:     if ($result ne 'ok') {
                   8990:         if ($old_entry{$user} ne '') {
                   8991:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8992:         } else {
                   8993:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8994:         }
                   8995:     }
                   8996:     return $result; 
1.21      www      8997: }
                   8998: 
1.556     albertel 8999: sub format_name {
                   9000:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9001:     my $name;
                   9002:     if ($first ne 'lastname') {
                   9003: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9004:     } else {
                   9005: 	if ($lastname=~/\S/) {
                   9006: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9007: 	    $name=~s/\s+,/,/;
                   9008: 	} else {
                   9009: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9010: 	}
                   9011:     }
                   9012:     $name=~s/^\s+//;
                   9013:     $name=~s/\s+$//;
                   9014:     $name=~s/\s+/ /g;
                   9015:     return $name;
                   9016: }
                   9017: 
1.84      www      9018: # ------------------------------------------------- Write to course preferences
                   9019: 
                   9020: sub writecoursepref {
                   9021:     my ($courseid,%prefs)=@_;
                   9022:     $courseid=~s/^\///;
                   9023:     $courseid=~s/\_/\//g;
                   9024:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9025:     my $chome=homeserver($cnum,$cdomain);
                   9026:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9027: 	return 'error: no such course';
                   9028:     }
                   9029:     my $cstring='';
1.800     albertel 9030:     foreach my $pref (keys(%prefs)) {
                   9031: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9032:     }
1.84      www      9033:     $cstring=~s/\&$//;
                   9034:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9035: }
                   9036: 
                   9037: # ---------------------------------------------------------- Make/modify course
                   9038: 
                   9039: sub createcourse {
1.741     raeburn  9040:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9041:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9042:     $url=&declutter($url);
                   9043:     my $cid='';
1.1028    raeburn  9044:     if ($context eq 'requestcourses') {
                   9045:         my $can_create = 0;
                   9046:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9047:         if ($udom eq $ownerdom) {
                   9048:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9049:                                   $context)) {
                   9050:                 $can_create = 1;
                   9051:             }
                   9052:         } else {
                   9053:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9054:                                            $category);
                   9055:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9056:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9057:                 if (@curr > 0) {
                   9058:                     my @options = qw(approval validate autolimit);
                   9059:                     my $optregex = join('|',@options);
                   9060:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9061:                         $can_create = 1;
                   9062:                     }
                   9063:                 }
                   9064:             }
                   9065:         }
                   9066:         if ($can_create) {
                   9067:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9068:                 unless (&allowed('ccc',$udom)) {
                   9069:                     return 'refused'; 
                   9070:                 }
1.1017    raeburn  9071:             }
                   9072:         } else {
                   9073:             return 'refused';
                   9074:         }
1.1028    raeburn  9075:     } elsif (!&allowed('ccc',$udom)) {
                   9076:         return 'refused';
1.84      www      9077:     }
1.1011    raeburn  9078: # --------------------------------------------------------------- Get Unique ID
                   9079:     my $uname;
                   9080:     if ($cnum =~ /^$match_courseid$/) {
                   9081:         my $chome=&homeserver($cnum,$udom,'true');
                   9082:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9083:             $uname = $cnum;
                   9084:         } else {
1.1038    raeburn  9085:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9086:         }
                   9087:     } else {
1.1038    raeburn  9088:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9089:     }
                   9090:     return $uname if ($uname =~ /^error/);
                   9091: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9092:     if (!defined($course_server)) {
                   9093:         if (defined(&domain($udom,'primary'))) {
                   9094:             $course_server = &domain($udom,'primary');
                   9095:         } else {
                   9096:             $course_server = $env{'user.home'}; 
                   9097:         }
                   9098:     }
                   9099:     my %host_servers =
                   9100:         &Apache::lonnet::get_servers($udom,'library');
                   9101:     unless ($host_servers{$course_server}) {
                   9102:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9103:     }
1.84      www      9104: # ------------------------------------------------------------- Make the course
                   9105:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9106:                       $course_server);
1.84      www      9107:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9108:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9109:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9110: 	return 'error: no such course';
                   9111:     }
1.271     www      9112: # ----------------------------------------------------------------- Course made
1.516     raeburn  9113: # log existence
1.1029    raeburn  9114:     my $now = time;
1.918     raeburn  9115:     my $newcourse = {
                   9116:                     $udom.'_'.$uname => {
1.921     raeburn  9117:                                      description => $description,
                   9118:                                      inst_code   => $inst_code,
                   9119:                                      owner       => $course_owner,
                   9120:                                      type        => $crstype,
1.1029    raeburn  9121:                                      creator     => $env{'user.name'}.':'.
                   9122:                                                     $env{'user.domain'},
                   9123:                                      created     => $now,
                   9124:                                      context     => $context,
1.918     raeburn  9125:                                                 },
                   9126:                     };
1.921     raeburn  9127:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9128: # set toplevel url
1.271     www      9129:     my $topurl=$url;
                   9130:     unless ($nonstandard) {
                   9131: # ------------------------------------------ For standard courses, make top url
                   9132:         my $mapurl=&clutter($url);
1.278     www      9133:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9134:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9135: <map>
                   9136: <resource id="1" type="start"></resource>
                   9137: <resource id="2" src="$mapurl"></resource>
                   9138: <resource id="3" type="finish"></resource>
                   9139: <link index="1" from="1" to="2"></link>
                   9140: <link index="2" from="2" to="3"></link>
                   9141: </map>
                   9142: ENDINITMAP
                   9143:         $topurl=&declutter(
1.638     albertel 9144:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9145:                           );
                   9146:     }
                   9147: # ----------------------------------------------------------- Write preferences
1.84      www      9148:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9149:                      ('description'              => $description,
                   9150:                       'url'                      => $topurl,
                   9151:                       'internal.creator'         => $env{'user.name'}.':'.
                   9152:                                                     $env{'user.domain'},
                   9153:                       'internal.created'         => $now,
                   9154:                       'internal.creationcontext' => $context)
                   9155:                     );
1.84      www      9156:     return '/'.$udom.'/'.$uname;
                   9157: }
                   9158: 
1.1011    raeburn  9159: # ------------------------------------------------------------------- Create ID
                   9160: sub generate_coursenum {
1.1038    raeburn  9161:     my ($udom,$crstype) = @_;
1.1011    raeburn  9162:     my $domdesc = &domain($udom);
                   9163:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9164:     my $first;
                   9165:     if ($crstype eq 'Community') {
                   9166:         $first = '0';
                   9167:     } else {
                   9168:         $first = int(1+rand(9)); 
                   9169:     } 
                   9170:     my $uname=$first.
1.1011    raeburn  9171:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9172:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9173:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9174: # ----------------------------------------------- Make sure that does not exist
                   9175:     my $uhome=&homeserver($uname,$udom,'true');
                   9176:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9177:         if ($crstype eq 'Community') {
                   9178:             $first = '0';
                   9179:         } else {
                   9180:             $first = int(1+rand(9));
                   9181:         }
                   9182:         $uname=$first.
1.1011    raeburn  9183:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9184:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9185:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9186:         $uhome=&homeserver($uname,$udom,'true');
                   9187:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9188:             return 'error: unable to generate unique course-ID';
                   9189:         }
                   9190:     }
                   9191:     return $uname;
                   9192: }
                   9193: 
1.813     albertel 9194: sub is_course {
1.1167    droeschl 9195:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9196:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9197: 
                   9198:     return unless $cdom and $cnum;
                   9199: 
                   9200:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9201:         '.');
                   9202: 
1.1172.2.23  raeburn  9203:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9204:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9205: }
                   9206: 
1.1015    raeburn  9207: sub store_userdata {
                   9208:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9209:     my $result;
1.1016    raeburn  9210:     if ($datakey ne '') {
1.1013    raeburn  9211:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9212:             if ($udom eq '' || $uname eq '') {
                   9213:                 $udom = $env{'user.domain'};
                   9214:                 $uname = $env{'user.name'};
                   9215:             }
                   9216:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9217:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9218:                 $result = 'error: no_host';
                   9219:             } else {
                   9220:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9221:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9222: 
                   9223:                 my $namevalue='';
                   9224:                 foreach my $key (keys(%{$storehash})) {
                   9225:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9226:                 }
                   9227:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9228:                 unless ($namespace eq 'courserequests') {
                   9229:                     $datakey = &escape($datakey);
                   9230:                 }
1.1105    raeburn  9231:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9232:                                   $namevalue,$uhome);
1.1013    raeburn  9233:             }
                   9234:         } else {
                   9235:             $result = 'error: data to store was not a hash reference'; 
                   9236:         }
                   9237:     } else {
                   9238:         $result= 'error: invalid requestkey'; 
                   9239:     }
                   9240:     return $result;
                   9241: }
                   9242: 
1.21      www      9243: # ---------------------------------------------------------- Assign Custom Role
                   9244: 
                   9245: sub assigncustomrole {
1.957     raeburn  9246:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9247:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9248:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9249: }
                   9250: 
                   9251: # ----------------------------------------------------------------- Revoke Role
                   9252: 
                   9253: sub revokerole {
1.957     raeburn  9254:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9255:     my $now=time;
1.965     raeburn  9256:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9257: }
                   9258: 
                   9259: # ---------------------------------------------------------- Revoke Custom Role
                   9260: 
                   9261: sub revokecustomrole {
1.957     raeburn  9262:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9263:     my $now=time;
1.357     www      9264:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9265:            $deleteflag,$selfenroll,$context);
1.17      www      9266: }
                   9267: 
1.533     banghart 9268: # ------------------------------------------------------------ Disk usage
1.535     albertel 9269: sub diskusage {
1.955     raeburn  9270:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9271:     $directorypath =~ s/\/$//;
                   9272:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9273:                        .&escape($getpropath).':'.&escape($uname).':'
                   9274:                        .&escape($udom),homeserver($uname,$udom));
                   9275:     if ($listing eq 'unknown_cmd') {
                   9276:         if ($getpropath) {
                   9277:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9278:         }
                   9279:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9280:     }
1.514     albertel 9281:     return $listing;
1.512     banghart 9282: }
                   9283: 
1.566     banghart 9284: sub is_locked {
1.1096    raeburn  9285:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9286:     my @check;
                   9287:     my $is_locked;
1.1093    raeburn  9288:     push (@check,$file_name);
1.613     albertel 9289:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9290: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9291:     my ($tmp)=keys(%locked);
                   9292:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9293:     
1.566     banghart 9294:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9295:         $is_locked = 'false';
                   9296:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9297:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9298:                $is_locked = 'true';
1.1096    raeburn  9299:                if (ref($which) eq 'ARRAY') {
                   9300:                    push(@{$which},$entry);
                   9301:                } else {
                   9302:                    last;
                   9303:                }
1.745     raeburn  9304:            }
                   9305:        }
1.566     banghart 9306:     } else {
                   9307:         $is_locked = 'false';
                   9308:     }
1.1093    raeburn  9309:     return $is_locked;
1.566     banghart 9310: }
                   9311: 
1.759     albertel 9312: sub declutter_portfile {
                   9313:     my ($file) = @_;
1.833     albertel 9314:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9315:     return $file;
                   9316: }
                   9317: 
1.559     banghart 9318: # ------------------------------------------------------------- Mark as Read Only
                   9319: 
                   9320: sub mark_as_readonly {
                   9321:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9322:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9323:     my ($tmp)=keys(%current_permissions);
                   9324:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9325:     foreach my $file (@{$files}) {
1.759     albertel 9326: 	$file = &declutter_portfile($file);
1.561     banghart 9327:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9328:     }
1.613     albertel 9329:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9330:     return;
                   9331: }
                   9332: 
1.572     banghart 9333: # ------------------------------------------------------------Save Selected Files
                   9334: 
                   9335: sub save_selected_files {
                   9336:     my ($user, $path, @files) = @_;
                   9337:     my $filename = $user."savedfiles";
1.573     banghart 9338:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9339:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9340:     foreach my $file (@files) {
1.620     albertel 9341:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9342:     }
                   9343:     foreach my $file (@other_files) {
1.574     banghart 9344:         print (OUT $file."\n");
1.572     banghart 9345:     }
1.574     banghart 9346:     close (OUT);
1.572     banghart 9347:     return 'ok';
                   9348: }
                   9349: 
1.574     banghart 9350: sub clear_selected_files {
                   9351:     my ($user) = @_;
                   9352:     my $filename = $user."savedfiles";
1.1117    foxr     9353:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9354:     print (OUT undef);
                   9355:     close (OUT);
                   9356:     return ("ok");    
                   9357: }
                   9358: 
1.572     banghart 9359: sub files_in_path {
                   9360:     my ($user, $path) = @_;
                   9361:     my $filename = $user."savedfiles";
                   9362:     my %return_files;
1.1117    foxr     9363:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9364:     while (my $line_in = <IN>) {
1.574     banghart 9365:         chomp ($line_in);
                   9366:         my @paths_and_file = split (m!/!, $line_in);
                   9367:         my $file_part = pop (@paths_and_file);
                   9368:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9369:         $path_part.='/';
                   9370:         my $path_and_file = $path_part.$file_part;
                   9371:         if ($path_part eq $path) {
                   9372:             $return_files{$file_part}= 'selected';
                   9373:         }
                   9374:     }
1.574     banghart 9375:     close (IN);
                   9376:     return (\%return_files);
1.572     banghart 9377: }
                   9378: 
                   9379: # called in portfolio select mode, to show files selected NOT in current directory
                   9380: sub files_not_in_path {
                   9381:     my ($user, $path) = @_;
                   9382:     my $filename = $user."savedfiles";
                   9383:     my @return_files;
                   9384:     my $path_part;
1.1117    foxr     9385:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9386:     while (my $line = <IN>) {
1.572     banghart 9387:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9388:         my @paths_and_file = split(m|/|, $line);
                   9389:         my $file_part = pop(@paths_and_file);
                   9390:         chomp($file_part);
                   9391:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9392:         $path_part .= '/';
                   9393:         my $path_and_file = $path_part.$file_part;
                   9394:         if ($path_part ne $path) {
1.800     albertel 9395:             push(@return_files, ($path_and_file));
1.572     banghart 9396:         }
                   9397:     }
1.800     albertel 9398:     close(OUT);
1.574     banghart 9399:     return (@return_files);
1.572     banghart 9400: }
                   9401: 
1.745     raeburn  9402: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9403: 
1.745     raeburn  9404: sub get_portfile_permissions {
                   9405:     my ($domain,$user) = @_;
1.613     albertel 9406:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9407:     my ($tmp)=keys(%current_permissions);
                   9408:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9409:     return \%current_permissions;
                   9410: }
                   9411: 
                   9412: #---------------------------------------------Get portfolio file access controls
                   9413: 
1.749     raeburn  9414: sub get_access_controls {
1.745     raeburn  9415:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9416:     my %access;
                   9417:     my $real_file = $file;
                   9418:     $file =~ s/\.meta$//;
1.745     raeburn  9419:     if (defined($file)) {
1.749     raeburn  9420:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9421:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9422:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9423:             }
                   9424:         }
1.745     raeburn  9425:     } else {
1.749     raeburn  9426:         foreach my $key (keys(%{$current_permissions})) {
                   9427:             if ($key =~ /\0accesscontrol$/) {
                   9428:                 if (defined($group)) {
                   9429:                     if ($key !~ m-^\Q$group\E/-) {
                   9430:                         next;
                   9431:                     }
                   9432:                 }
                   9433:                 my ($fullpath) = split(/\0/,$key);
                   9434:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9435:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9436:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9437:                     }
                   9438:                 }
                   9439:             }
                   9440:         }
                   9441:     }
                   9442:     return %access;
                   9443: }
                   9444: 
                   9445: sub modify_access_controls {
                   9446:     my ($file_name,$changes,$domain,$user)=@_;
                   9447:     my ($outcome,$deloutcome);
                   9448:     my %store_permissions;
                   9449:     my %new_values;
                   9450:     my %new_control;
                   9451:     my %translation;
                   9452:     my @deletions = ();
                   9453:     my $now = time;
                   9454:     if (exists($$changes{'activate'})) {
                   9455:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9456:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9457:             my $numnew = scalar(@newitems);
                   9458:             for (my $i=0; $i<$numnew; $i++) {
                   9459:                 my $newkey = $newitems[$i];
                   9460:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9461:                 if ($newkey =~ /^\d+:/) { 
                   9462:                     $newkey =~ s/^(\d+)/$newid/;
                   9463:                     $translation{$1} = $newid;
                   9464:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9465:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9466:                     $translation{$1} = $newid;
                   9467:                 }
1.749     raeburn  9468:                 $new_values{$file_name."\0".$newkey} = 
                   9469:                                           $$changes{'activate'}{$newitems[$i]};
                   9470:                 $new_control{$newkey} = $now;
                   9471:             }
                   9472:         }
                   9473:     }
                   9474:     my %todelete;
                   9475:     my %changed_items;
                   9476:     foreach my $action ('delete','update') {
                   9477:         if (exists($$changes{$action})) {
                   9478:             if (ref($$changes{$action}) eq 'HASH') {
                   9479:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9480:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9481:                     if ($action eq 'delete') { 
                   9482:                         $todelete{$itemnum} = 1;
                   9483:                     } else {
                   9484:                         $changed_items{$itemnum} = $key;
                   9485:                     }
                   9486:                 }
1.745     raeburn  9487:             }
                   9488:         }
1.749     raeburn  9489:     }
                   9490:     # get lock on access controls for file.
                   9491:     my $lockhash = {
                   9492:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9493:                                                        ':'.$env{'user.domain'},
                   9494:                    }; 
                   9495:     my $tries = 0;
                   9496:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9497:    
                   9498:     while (($gotlock ne 'ok') && $tries <3) {
                   9499:         $tries ++;
                   9500:         sleep 1;
                   9501:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9502:     }
                   9503:     if ($gotlock eq 'ok') {
                   9504:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9505:         my ($tmp)=keys(%curr_permissions);
                   9506:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9507:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9508:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9509:             if (ref($curr_controls) eq 'HASH') {
                   9510:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9511:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9512:                     if (defined($todelete{$itemnum})) {
                   9513:                         push(@deletions,$file_name."\0".$control_item);
                   9514:                     } else {
                   9515:                         if (defined($changed_items{$itemnum})) {
                   9516:                             $new_control{$changed_items{$itemnum}} = $now;
                   9517:                             push(@deletions,$file_name."\0".$control_item);
                   9518:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9519:                         } else {
                   9520:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9521:                         }
                   9522:                     }
1.745     raeburn  9523:                 }
                   9524:             }
                   9525:         }
1.970     raeburn  9526:         my ($group);
                   9527:         if (&is_course($domain,$user)) {
                   9528:             ($group,my $file) = split(/\//,$file_name,2);
                   9529:         }
1.749     raeburn  9530:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9531:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9532:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9533:         #  remove lock
                   9534:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9535:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9536:         my $sqlresult =
1.970     raeburn  9537:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9538:                                     $group);
1.749     raeburn  9539:     } else {
                   9540:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9541:     }
1.749     raeburn  9542:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9543: }
                   9544: 
1.827     raeburn  9545: sub make_public_indefinitely {
                   9546:     my ($requrl) = @_;
                   9547:     my $now = time;
                   9548:     my $action = 'activate';
                   9549:     my $aclnum = 0;
                   9550:     if (&is_portfolio_url($requrl)) {
                   9551:         my (undef,$udom,$unum,$file_name,$group) =
                   9552:             &parse_portfolio_url($requrl);
                   9553:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9554:         my %access_controls = &get_access_controls($current_perms,
                   9555:                                                    $group,$file_name);
                   9556:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9557:             my ($num,$scope,$end,$start) = 
                   9558:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9559:             if ($scope eq 'public') {
                   9560:                 if ($start <= $now && $end == 0) {
                   9561:                     $action = 'none';
                   9562:                 } else {
                   9563:                     $action = 'update';
                   9564:                     $aclnum = $num;
                   9565:                 }
                   9566:                 last;
                   9567:             }
                   9568:         }
                   9569:         if ($action eq 'none') {
                   9570:              return 'ok';
                   9571:         } else {
                   9572:             my %changes;
                   9573:             my $newend = 0;
                   9574:             my $newstart = $now;
                   9575:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9576:             $changes{$action}{$newkey} = {
                   9577:                 type => 'public',
                   9578:                 time => {
                   9579:                     start => $newstart,
                   9580:                     end   => $newend,
                   9581:                 },
                   9582:             };
                   9583:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9584:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9585:             return $outcome;
                   9586:         }
                   9587:     } else {
                   9588:         return 'invalid';
                   9589:     }
                   9590: }
                   9591: 
1.745     raeburn  9592: #------------------------------------------------------Get Marked as Read Only
                   9593: 
                   9594: sub get_marked_as_readonly {
                   9595:     my ($domain,$user,$what,$group) = @_;
                   9596:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9597:     my @readonly_files;
1.629     banghart 9598:     my $cmp1=$what;
                   9599:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9600:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9601:         if (defined($group)) {
                   9602:             if ($file_name !~ m-^\Q$group\E/-) {
                   9603:                 next;
                   9604:             }
                   9605:         }
1.561     banghart 9606:         if (ref($value) eq "ARRAY"){
                   9607:             foreach my $stored_what (@{$value}) {
1.629     banghart 9608:                 my $cmp2=$stored_what;
1.759     albertel 9609:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9610:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9611:                 }
1.629     banghart 9612:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9613:                     push(@readonly_files, $file_name);
1.745     raeburn  9614:                     last;
1.563     banghart 9615:                 } elsif (!defined($what)) {
                   9616:                     push(@readonly_files, $file_name);
1.745     raeburn  9617:                     last;
1.561     banghart 9618:                 }
                   9619:             }
1.745     raeburn  9620:         }
1.561     banghart 9621:     }
                   9622:     return @readonly_files;
                   9623: }
1.577     banghart 9624: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9625: 
1.577     banghart 9626: sub get_marked_as_readonly_hash {
1.745     raeburn  9627:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9628:     my %readonly_files;
1.745     raeburn  9629:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9630:         if (defined($group)) {
                   9631:             if ($file_name !~ m-^\Q$group\E/-) {
                   9632:                 next;
                   9633:             }
                   9634:         }
1.577     banghart 9635:         if (ref($value) eq "ARRAY"){
                   9636:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9637:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9638:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9639:                         if ($lock_descriptor eq 'graded') {
                   9640:                             $readonly_files{$file_name} = 'graded';
                   9641:                         } elsif ($lock_descriptor eq 'handback') {
                   9642:                             $readonly_files{$file_name} = 'handback';
                   9643:                         } else {
                   9644:                             if (!exists($readonly_files{$file_name})) {
                   9645:                                 $readonly_files{$file_name} = 'locked';
                   9646:                             }
                   9647:                         }
1.745     raeburn  9648:                     }
1.750     banghart 9649:                 } 
1.577     banghart 9650:             }
                   9651:         } 
                   9652:     }
                   9653:     return %readonly_files;
                   9654: }
1.559     banghart 9655: # ------------------------------------------------------------ Unmark as Read Only
                   9656: 
                   9657: sub unmark_as_readonly {
1.629     banghart 9658:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9659:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9660:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9661:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9662:     my $symb_crs = $what;
                   9663:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9664:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9665:     my ($tmp)=keys(%current_permissions);
                   9666:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9667:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9668:     foreach my $file (@readonly_files) {
1.759     albertel 9669: 	my $clean_file = &declutter_portfile($file);
                   9670: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9671: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9672:         my @new_locks;
                   9673:         my @del_keys;
                   9674:         if (ref($current_locks) eq "ARRAY"){
                   9675:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9676:                 my $compare=$locker;
1.749     raeburn  9677:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9678:                     $compare=join('',@{$locker});
1.746     raeburn  9679:                     if ($compare ne $symb_crs) {
                   9680:                         push(@new_locks, $locker);
                   9681:                     }
1.563     banghart 9682:                 }
                   9683:             }
1.650     albertel 9684:             if (scalar(@new_locks) > 0) {
1.563     banghart 9685:                 $current_permissions{$file} = \@new_locks;
                   9686:             } else {
                   9687:                 push(@del_keys, $file);
1.613     albertel 9688:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9689:                 delete($current_permissions{$file});
1.563     banghart 9690:             }
                   9691:         }
1.561     banghart 9692:     }
1.613     albertel 9693:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9694:     return;
                   9695: }
1.512     banghart 9696: 
1.17      www      9697: # ------------------------------------------------------------ Directory lister
                   9698: 
                   9699: sub dirlist {
1.955     raeburn  9700:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9701:     $uri=~s/^\///;
                   9702:     $uri=~s/\/$//;
1.253     stredwic 9703:     my ($udom, $uname);
1.955     raeburn  9704:     if ($getuserdir) {
1.253     stredwic 9705:         $udom = $userdomain;
                   9706:         $uname = $username;
1.955     raeburn  9707:     } else {
                   9708:         (undef,$udom,$uname)=split(/\//,$uri);
                   9709:         if(defined($userdomain)) {
                   9710:             $udom = $userdomain;
                   9711:         }
                   9712:         if(defined($username)) {
                   9713:             $uname = $username;
                   9714:         }
1.253     stredwic 9715:     }
1.955     raeburn  9716:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9717: 
1.955     raeburn  9718:     $dirRoot = $perlvar{'lonDocRoot'};
                   9719:     if (defined($getpropath)) {
                   9720:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9721:         $dirRoot =~ s/\/$//;
1.955     raeburn  9722:     } elsif (defined($getuserdir)) {
                   9723:         my $subdir=$uname.'__';
                   9724:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9725:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9726:                    ."/$udom/$subdir/$uname";
                   9727:     } elsif (defined($alternateRoot)) {
                   9728:         $dirRoot = $alternateRoot;
1.751     banghart 9729:     }
1.253     stredwic 9730: 
                   9731:     if($udom) {
                   9732:         if($uname) {
1.1135    raeburn  9733:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9734:             if ($uhome eq 'no_host') {
                   9735:                 return ([],'no_host');
                   9736:             }
1.955     raeburn  9737:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9738:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9739:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9740:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9741:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9742:             } else {
                   9743:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9744:             }
1.605     matthew  9745:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9746:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9747:                 @listing_results = split(/:/,$listing);
                   9748:             } else {
                   9749:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9750:             }
1.1135    raeburn  9751:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9752:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9753:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9754:                 return ([],$listing);
                   9755:             } else {
                   9756:                 return (\@listing_results);
1.1135    raeburn  9757:             }
1.955     raeburn  9758:         } elsif(!$alternateRoot) {
1.1136    raeburn  9759:             my (%allusers,%listerror);
1.841     albertel 9760: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9761:  	    foreach my $tryserver (keys(%servers)) {
                   9762:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9763:                                   &escape($udom),$tryserver);
                   9764:                 if ($listing eq 'unknown_cmd') {
                   9765: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9766: 				      $udom, $tryserver);
                   9767:                 } else {
                   9768:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9769:                 }
1.841     albertel 9770: 		if ($listing eq 'unknown_cmd') {
                   9771: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9772: 				      $udom, $tryserver);
                   9773: 		    @listing_results = split(/:/,$listing);
                   9774: 		} else {
                   9775: 		    @listing_results =
                   9776: 			map { &unescape($_); } split(/:/,$listing);
                   9777: 		}
1.1136    raeburn  9778:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9779:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9780:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9781:                     $listerror{$tryserver} = $listing;
                   9782:                 } else {
1.841     albertel 9783: 		    foreach my $line (@listing_results) {
                   9784: 			my ($entry) = split(/&/,$line,2);
                   9785: 			$allusers{$entry} = 1;
                   9786: 		    }
                   9787: 		}
1.253     stredwic 9788:             }
1.1136    raeburn  9789:             my @alluserslist=();
1.800     albertel 9790:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9791:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9792:             }
1.1136    raeburn  9793:             return (\@alluserslist);
1.253     stredwic 9794:         } else {
1.1136    raeburn  9795:             return ([],'missing username');
1.253     stredwic 9796:         }
1.955     raeburn  9797:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9798:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9799:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9800:         return (\@all_domains);
1.955     raeburn  9801:     } else {
1.1136    raeburn  9802:         return ([],'missing domain');
1.275     stredwic 9803:     }
                   9804: }
                   9805: 
                   9806: # --------------------------------------------- GetFileTimestamp
                   9807: # This function utilizes dirlist and returns the date stamp for
                   9808: # when it was last modified.  It will also return an error of -1
                   9809: # if an error occurs
                   9810: 
                   9811: sub GetFileTimestamp {
1.955     raeburn  9812:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9813:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9814:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9815:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9816:                                     undef,$getuserdir);
                   9817:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9818:         return -1;
                   9819:     }
                   9820:     if (ref($fileref) eq 'ARRAY') {
                   9821:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9822:         # @stats contains first the filename, then the stat output
                   9823:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9824:     } else {
                   9825:         return -1;
1.253     stredwic 9826:     }
1.26      www      9827: }
                   9828: 
1.712     albertel 9829: sub stat_file {
                   9830:     my ($uri) = @_;
1.787     albertel 9831:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9832: 
1.955     raeburn  9833:     my ($udom,$uname,$file);
1.712     albertel 9834:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9835: 	($udom,$uname,$file) =
1.811     albertel 9836: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9837: 	$file = 'userfiles/'.$file;
                   9838:     }
                   9839:     if ($uri =~ m-^/res/-) {
                   9840: 	($udom,$uname) = 
1.807     albertel 9841: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9842: 	$file = $uri;
                   9843:     }
                   9844: 
                   9845:     if (!$udom || !$uname || !$file) {
                   9846: 	# unable to handle the uri
                   9847: 	return ();
                   9848:     }
1.956     raeburn  9849:     my $getpropath;
                   9850:     if ($file =~ /^userfiles\//) {
                   9851:         $getpropath = 1;
                   9852:     }
1.1136    raeburn  9853:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9854:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9855:         return ();
                   9856:     } else {
                   9857:         if (ref($listref) eq 'ARRAY') {
                   9858:             my @stats = split('&',$listref->[0]);
                   9859: 	    shift(@stats); #filename is first
                   9860: 	    return @stats;
                   9861:         }
1.712     albertel 9862:     }
                   9863:     return ();
                   9864: }
                   9865: 
1.26      www      9866: # -------------------------------------------------------- Value of a Condition
                   9867: 
1.713     albertel 9868: # gets the value of a specific preevaluated condition
                   9869: #    stored in the string  $env{user.state.<cid>}
                   9870: # or looks up a condition reference in the bighash and if if hasn't
                   9871: # already been evaluated recurses into docondval to get the value of
                   9872: # the condition, then memoizing it to 
                   9873: #   $env{user.state.<cid>.<condition>}
1.40      www      9874: sub directcondval {
                   9875:     my $number=shift;
1.620     albertel 9876:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9877: 	&Apache::lonuserstate::evalstate();
                   9878:     }
1.713     albertel 9879:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9880: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9881:     } elsif ($number =~ /^_/) {
                   9882: 	my $sub_condition;
                   9883: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9884: 		&GDBM_READER(),0640)) {
                   9885: 	    $sub_condition=$bighash{'conditions'.$number};
                   9886: 	    untie(%bighash);
                   9887: 	}
                   9888: 	my $value = &docondval($sub_condition);
1.949     raeburn  9889: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9890: 	return $value;
                   9891:     }
1.620     albertel 9892:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9893:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9894:     } else {
                   9895:        return 2;
                   9896:     }
                   9897: }
                   9898: 
1.713     albertel 9899: # get the collection of conditions for this resource
1.26      www      9900: sub condval {
                   9901:     my $condidx=shift;
1.54      www      9902:     my $allpathcond='';
1.713     albertel 9903:     foreach my $cond (split(/\|/,$condidx)) {
                   9904: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9905: 	    $allpathcond.=
                   9906: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9907: 	}
1.191     harris41 9908:     }
1.54      www      9909:     $allpathcond=~s/\|$//;
1.713     albertel 9910:     return &docondval($allpathcond);
                   9911: }
                   9912: 
                   9913: #evaluates an expression of conditions
                   9914: sub docondval {
                   9915:     my ($allpathcond) = @_;
                   9916:     my $result=0;
                   9917:     if ($env{'request.course.id'}
                   9918: 	&& defined($allpathcond)) {
                   9919: 	my $operand='|';
                   9920: 	my @stack;
                   9921: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9922: 	    if ($chunk eq '(') {
                   9923: 		push @stack,($operand,$result);
                   9924: 	    } elsif ($chunk eq ')') {
                   9925: 		my $before=pop @stack;
                   9926: 		if (pop @stack eq '&') {
                   9927: 		    $result=$result>$before?$before:$result;
                   9928: 		} else {
                   9929: 		    $result=$result>$before?$result:$before;
                   9930: 		}
                   9931: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9932: 		$operand=$chunk;
                   9933: 	    } else {
                   9934: 		my $new=directcondval($chunk);
                   9935: 		if ($operand eq '&') {
                   9936: 		    $result=$result>$new?$new:$result;
                   9937: 		} else {
                   9938: 		    $result=$result>$new?$result:$new;
                   9939: 		}
                   9940: 	    }
                   9941: 	}
1.26      www      9942:     }
                   9943:     return $result;
1.421     albertel 9944: }
                   9945: 
                   9946: # ---------------------------------------------------- Devalidate courseresdata
                   9947: 
                   9948: sub devalidatecourseresdata {
                   9949:     my ($coursenum,$coursedomain)=@_;
                   9950:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9951:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9952: }
                   9953: 
1.763     www      9954: 
1.200     www      9955: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9956: #
                   9957: #  Parameters:
                   9958: #      $coursenum    - Number of the course.
                   9959: #      $coursedomain - Domain at which the course was created.
                   9960: #  Returns:
                   9961: #     A hash of the course parameters along (I think) with timestamps
                   9962: #     and version info.
1.877     foxr     9963: 
1.624     albertel 9964: sub get_courseresdata {
                   9965:     my ($coursenum,$coursedomain)=@_;
1.200     www      9966:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9967:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9968:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9969:     my %dumpreply;
1.417     albertel 9970:     unless (defined($cached)) {
1.624     albertel 9971: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9972: 	$result=\%dumpreply;
1.251     albertel 9973: 	my ($tmp) = keys(%dumpreply);
                   9974: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9975: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9976: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9977: 	    return $tmp;
1.416     albertel 9978: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9979: 	    $result=undef;
1.599     albertel 9980: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9981: 	}
                   9982:     }
1.624     albertel 9983:     return $result;
                   9984: }
                   9985: 
1.633     albertel 9986: sub devalidateuserresdata {
                   9987:     my ($uname,$udom)=@_;
                   9988:     my $hashid="$udom:$uname";
                   9989:     &devalidate_cache_new('userres',$hashid);
                   9990: }
                   9991: 
1.624     albertel 9992: sub get_userresdata {
                   9993:     my ($uname,$udom)=@_;
                   9994:     #most student don\'t have any data set, check if there is some data
                   9995:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9996: 
                   9997:     my $hashid="$udom:$uname";
                   9998:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9999:     if (!defined($cached)) {
                   10000: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10001: 	$result=\%resourcedata;
                   10002: 	&do_cache_new('userres',$hashid,$result,600);
                   10003:     }
                   10004:     my ($tmp)=keys(%$result);
                   10005:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10006: 	return $result;
                   10007:     }
                   10008:     #error 2 occurs when the .db doesn't exist
                   10009:     if ($tmp!~/error: 2 /) {
1.672     albertel 10010: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 10011: 		 " Trying to get resource data for ".
                   10012: 		 $uname." at ".$udom.": ".
                   10013: 		 $tmp."</font>");
                   10014:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10015: 	#&EXT_cache_set($udom,$uname);
                   10016: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10017: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10018:     }
                   10019:     return $tmp;
                   10020: }
1.879     foxr     10021: #----------------------------------------------- resdata - return resource data
                   10022: #  Purpose:
                   10023: #    Return resource data for either users or for a course.
                   10024: #  Parameters:
                   10025: #     $name      - Course/user name.
                   10026: #     $domain    - Name of the domain the user/course is registered on.
                   10027: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10028: #     @which     - Array of names of resources desired.
                   10029: #  Returns:
                   10030: #     The value of the first reasource in @which that is found in the
                   10031: #     resource hash.
                   10032: #  Exceptional Conditions:
                   10033: #     If the $type passed in is not valid (not the string 'course' or 
                   10034: #     'user', an undefined  reference is returned.
                   10035: #     If none of the resources are found, an undef is returned
1.624     albertel 10036: sub resdata {
                   10037:     my ($name,$domain,$type,@which)=@_;
                   10038:     my $result;
                   10039:     if ($type eq 'course') {
                   10040: 	$result=&get_courseresdata($name,$domain);
                   10041:     } elsif ($type eq 'user') {
                   10042: 	$result=&get_userresdata($name,$domain);
                   10043:     }
                   10044:     if (!ref($result)) { return $result; }    
1.251     albertel 10045:     foreach my $item (@which) {
1.927     albertel 10046: 	if (defined($result->{$item->[0]})) {
                   10047: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10048: 	}
1.250     albertel 10049:     }
1.291     albertel 10050:     return undef;
1.200     www      10051: }
                   10052: 
1.1172.2.31  raeburn  10053: sub get_numsuppfiles {
                   10054:     my ($cnum,$cdom,$ignorecache)=@_;
                   10055:     my $hashid=$cnum.':'.$cdom;
                   10056:     my ($suppcount,$cached);
                   10057:     unless ($ignorecache) {
                   10058:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10059:     }
                   10060:     unless (defined($cached)) {
                   10061:         my $chome=&homeserver($cnum,$cdom);
                   10062:         unless ($chome eq 'no_host') {
                   10063:             ($suppcount,my $errors) = (0,0);
                   10064:             my $suppmap = 'supplemental.sequence';
                   10065:             ($suppcount,$errors) =
                   10066:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10067:         }
                   10068:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10069:     }
                   10070:     return $suppcount;
                   10071: }
                   10072: 
1.379     matthew  10073: #
                   10074: # EXT resource caching routines
                   10075: #
                   10076: 
                   10077: sub clear_EXT_cache_status {
1.383     albertel 10078:     &delenv('cache.EXT.');
1.379     matthew  10079: }
                   10080: 
                   10081: sub EXT_cache_status {
                   10082:     my ($target_domain,$target_user) = @_;
1.383     albertel 10083:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10084:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10085:         # We know already the user has no data
                   10086:         return 1;
                   10087:     } else {
                   10088:         return 0;
                   10089:     }
                   10090: }
                   10091: 
                   10092: sub EXT_cache_set {
                   10093:     my ($target_domain,$target_user) = @_;
1.383     albertel 10094:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10095:     #&appenv({$cachename => time});
1.379     matthew  10096: }
                   10097: 
1.28      www      10098: # --------------------------------------------------------- Value of a Variable
1.58      www      10099: sub EXT {
1.715     albertel 10100: 
1.1172.2.28  raeburn  10101:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10102:     unless ($varname) { return ''; }
1.218     albertel 10103:     #get real user name/domain, courseid and symb
                   10104:     my $courseid;
1.359     albertel 10105:     my $publicuser;
1.427     www      10106:     if ($symbparm) {
                   10107: 	$symbparm=&get_symb_from_alias($symbparm);
                   10108:     }
1.218     albertel 10109:     if (!($uname && $udom)) {
1.790     albertel 10110:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10111:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10112:     } else {
1.620     albertel 10113: 	$courseid=$env{'request.course.id'};
1.218     albertel 10114:     }
1.48      www      10115:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10116:     my $rest;
1.320     albertel 10117:     if (defined($therest[0])) {
1.48      www      10118:        $rest=join('.',@therest);
                   10119:     } else {
                   10120:        $rest='';
                   10121:     }
1.320     albertel 10122: 
1.57      www      10123:     my $qualifierrest=$qualifier;
                   10124:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10125:     my $spacequalifierrest=$space;
                   10126:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10127:     if ($realm eq 'user') {
1.48      www      10128: # --------------------------------------------------------------- user.resource
                   10129: 	if ($space eq 'resource') {
1.651     albertel 10130: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10131: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10132: 		 &&
1.744     albertel 10133: 		 ($symbparm eq &symbread()) ) {	
                   10134: 		# if we are in the middle of processing the resource the
                   10135: 		# get the value we are planning on committing
                   10136:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10137:                     return $Apache::lonhomework::results{$qualifierrest};
                   10138:                 } else {
                   10139:                     return $Apache::lonhomework::history{$qualifierrest};
                   10140:                 }
1.335     albertel 10141: 	    } else {
1.359     albertel 10142: 		my %restored;
1.620     albertel 10143: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10144: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10145: 		} else {
                   10146: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10147: 		}
1.335     albertel 10148: 		return $restored{$qualifierrest};
                   10149: 	    }
1.48      www      10150: # ----------------------------------------------------------------- user.access
                   10151:         } elsif ($space eq 'access') {
1.218     albertel 10152: 	    # FIXME - not supporting calls for a specific user
1.48      www      10153:             return &allowed($qualifier,$rest);
                   10154: # ------------------------------------------ user.preferences, user.environment
                   10155:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10156: 	    if (($uname eq $env{'user.name'}) &&
                   10157: 		($udom eq $env{'user.domain'})) {
                   10158: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10159: 	    } else {
1.359     albertel 10160: 		my %returnhash;
                   10161: 		if (!$publicuser) {
                   10162: 		    %returnhash=&userenvironment($udom,$uname,
                   10163: 						 $qualifierrest);
                   10164: 		}
1.218     albertel 10165: 		return $returnhash{$qualifierrest};
                   10166: 	    }
1.48      www      10167: # ----------------------------------------------------------------- user.course
                   10168:         } elsif ($space eq 'course') {
1.218     albertel 10169: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10170:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10171: # ------------------------------------------------------------------- user.role
                   10172:         } elsif ($space eq 'role') {
1.218     albertel 10173: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10174:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10175:             if ($qualifier eq 'value') {
                   10176: 		return $role;
                   10177:             } elsif ($qualifier eq 'extent') {
                   10178:                 return $where;
                   10179:             }
                   10180: # ----------------------------------------------------------------- user.domain
                   10181:         } elsif ($space eq 'domain') {
1.218     albertel 10182:             return $udom;
1.48      www      10183: # ------------------------------------------------------------------- user.name
                   10184:         } elsif ($space eq 'name') {
1.218     albertel 10185:             return $uname;
1.48      www      10186: # ---------------------------------------------------- Any other user namespace
1.29      www      10187:         } else {
1.359     albertel 10188: 	    my %reply;
                   10189: 	    if (!$publicuser) {
                   10190: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10191: 	    }
                   10192: 	    return $reply{$qualifierrest};
1.48      www      10193:         }
1.236     www      10194:     } elsif ($realm eq 'query') {
                   10195: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10196:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10197: 						[$spacequalifierrest]);
1.620     albertel 10198: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10199:    } elsif ($realm eq 'request') {
1.48      www      10200: # ------------------------------------------------------------- request.browser
                   10201:         if ($space eq 'browser') {
1.1145    bisitz   10202:             return $env{'browser.'.$qualifier};
1.57      www      10203: # ------------------------------------------------------------ request.filename
                   10204:         } else {
1.620     albertel 10205:             return $env{'request.'.$spacequalifierrest};
1.29      www      10206:         }
1.28      www      10207:     } elsif ($realm eq 'course') {
1.48      www      10208: # ---------------------------------------------------------- course.description
1.620     albertel 10209:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10210:     } elsif ($realm eq 'resource') {
1.165     www      10211: 
1.620     albertel 10212: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10213: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10214: 	}
1.693     albertel 10215: 
1.1172.2.30  raeburn  10216:         if ($qualifier eq '') {
                   10217: 	    if ($space eq 'title') {
                   10218: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10219: 	        return &gettitle($symbparm);
                   10220: 	    }
1.693     albertel 10221: 	
1.1172.2.30  raeburn  10222: 	    if ($space eq 'map') {
                   10223: 	        my ($map) = &decode_symb($symbparm);
                   10224: 	        return &symbread($map);
                   10225: 	    }
                   10226:             if ($space eq 'maptitle') {
                   10227:                 my ($map) = &decode_symb($symbparm);
                   10228:                 return &gettitle($map);
                   10229:             }
                   10230: 	    if ($space eq 'filename') {
                   10231: 	        if ($symbparm) {
                   10232: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10233: 	        }
                   10234: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10235: 	    }
1.1172.2.30  raeburn  10236: 
                   10237:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10238:                 if ($space eq 'visibleparts') {
                   10239:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10240:                     my $item;
                   10241:                     if (ref($navmap)) {
                   10242:                         my $res = $navmap->getBySymb($symbparm);
                   10243:                         my $parts = $res->parts();
                   10244:                         if (ref($parts) eq 'ARRAY') {
                   10245:                             $item = join(',',@{$parts});
                   10246:                         }
                   10247:                         undef($navmap);
                   10248:                     }
                   10249:                     return $item;
                   10250:                 }
                   10251:             }
                   10252:         }
1.693     albertel 10253: 
                   10254: 	my ($section, $group, @groups);
1.593     albertel 10255: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10256:         if (($courseid eq '') && ($cid)) {
                   10257:             $courseid = $cid;
                   10258:         }
                   10259: 	if (($symbparm && $courseid) && 
                   10260: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10261: 
1.218     albertel 10262: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10263: 
1.60      www      10264: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10265: 	    my $symbp=$symbparm;
1.735     albertel 10266: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10267: 
                   10268: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10269: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10270: 
1.620     albertel 10271: 	    if (($env{'user.name'} eq $uname) &&
                   10272: 		($env{'user.domain'} eq $udom)) {
                   10273: 		$section=$env{'request.course.sec'};
1.733     raeburn  10274:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10275:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10276: 	    } else {
1.539     albertel 10277: 		if (! defined($usection)) {
1.551     albertel 10278: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10279: 		} else {
                   10280: 		    $section = $usection;
                   10281: 		}
1.733     raeburn  10282:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10283: 	    }
                   10284: 
                   10285: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10286: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10287: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10288: 
1.593     albertel 10289: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10290: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10291: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10292: 
1.60      www      10293: # ----------------------------------------------------------- first, check user
1.624     albertel 10294: 
                   10295: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10296: 				       ([$courselevelr,'resource'],
                   10297: 					[$courselevelm,'map'     ],
                   10298: 					[$courselevel, 'course'  ]));
1.931     albertel 10299: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10300: 
1.594     albertel 10301: # ------------------------------------------------ second, check some of course
1.684     raeburn  10302:             my $coursereply;
1.691     raeburn  10303:             if (@groups > 0) {
                   10304:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10305:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10306:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10307:             }
1.96      www      10308: 
1.684     raeburn  10309: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10310: 				  $env{'course.'.$courseid.'.domain'},
                   10311: 				  'course',
                   10312: 				  ([$seclevelr,   'resource'],
                   10313: 				   [$seclevelm,   'map'     ],
                   10314: 				   [$seclevel,    'course'  ],
                   10315: 				   [$courselevelr,'resource']));
                   10316: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10317: 
1.60      www      10318: # ------------------------------------------------------ third, check map parms
1.218     albertel 10319: 	    my %parmhash=();
                   10320: 	    my $thisparm='';
                   10321: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10322: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10323: 		    &GDBM_READER(),0640)) {
1.218     albertel 10324: 		$thisparm=$parmhash{$symbparm};
                   10325: 		untie(%parmhash);
                   10326: 	    }
1.927     albertel 10327: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10328: 	}
1.594     albertel 10329: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10330: 
1.218     albertel 10331: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10332: 	my $filename;
                   10333: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10334: 	if ($symbparm) {
1.409     www      10335: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10336: 	} else {
1.620     albertel 10337: 	    $filename=$env{'request.filename'};
1.282     albertel 10338: 	}
                   10339: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10340: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10341: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10342: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10343: 
1.927     albertel 10344: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10345: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10346: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10347: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10348: 				     $env{'course.'.$courseid.'.domain'},
                   10349: 				     'course',
1.927     albertel 10350: 				     ([$courselevelm,'map'   ],
                   10351: 				      [$courselevel, 'course']));
                   10352: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10353: 	}
1.145     www      10354: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10355: 	unless ($space eq '0') {
1.336     albertel 10356: 	    my @parts=split(/_/,$space);
                   10357: 	    my $id=pop(@parts);
                   10358: 	    my $part=join('_',@parts);
                   10359: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10360: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10361: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10362: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10363: 	}
1.395     albertel 10364: 	if ($recurse) { return undef; }
                   10365: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10366: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10367: # ---------------------------------------------------- Any other user namespace
                   10368:     } elsif ($realm eq 'environment') {
                   10369: # ----------------------------------------------------------------- environment
1.620     albertel 10370: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10371: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10372: 	} else {
1.770     albertel 10373: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10374: 		return '';
                   10375: 	    }
1.219     albertel 10376: 	    my %returnhash=&userenvironment($udom,$uname,
                   10377: 					    $spacequalifierrest);
                   10378: 	    return $returnhash{$spacequalifierrest};
                   10379: 	}
1.28      www      10380:     } elsif ($realm eq 'system') {
1.48      www      10381: # ----------------------------------------------------------------- system.time
                   10382: 	if ($space eq 'time') {
                   10383: 	    return time;
                   10384:         }
1.696     albertel 10385:     } elsif ($realm eq 'server') {
                   10386: # ----------------------------------------------------------------- system.time
                   10387: 	if ($space eq 'name') {
                   10388: 	    return $ENV{'SERVER_NAME'};
                   10389:         }
1.28      www      10390:     }
1.48      www      10391:     return '';
1.61      www      10392: }
                   10393: 
1.927     albertel 10394: sub get_reply {
                   10395:     my ($reply_value) = @_;
1.940     raeburn  10396:     if (ref($reply_value) eq 'ARRAY') {
                   10397:         if (wantarray) {
                   10398: 	    return @$reply_value;
                   10399:         }
                   10400:         return $reply_value->[0];
                   10401:     } else {
                   10402:         return $reply_value;
1.927     albertel 10403:     }
                   10404: }
                   10405: 
1.691     raeburn  10406: sub check_group_parms {
                   10407:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10408:     my @groupitems = ();
                   10409:     my $resultitem;
1.927     albertel 10410:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10411:     foreach my $group (@{$groups}) {
                   10412:         foreach my $level (@levels) {
1.927     albertel 10413:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10414:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10415:         }
                   10416:     }
                   10417:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10418:                             $env{'course.'.$courseid.'.domain'},
                   10419:                                      'course',@groupitems);
                   10420:     return $coursereply;
                   10421: }
                   10422: 
                   10423: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10424:     my ($courseid,@groups) = @_;
                   10425:     @groups = sort(@groups);
1.691     raeburn  10426:     return @groups;
                   10427: }
                   10428: 
1.395     albertel 10429: sub packages_tab_default {
                   10430:     my ($uri,$varname)=@_;
                   10431:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10432: 
                   10433:     my (@extension,@specifics,$do_default);
                   10434:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10435: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10436: 	if ($pack_type eq 'default') {
                   10437: 	    $do_default=1;
                   10438: 	} elsif ($pack_type eq 'extension') {
                   10439: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10440: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10441: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10442: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10443: 	}
                   10444:     }
                   10445:     # first look for a package that matches the requested part id
                   10446:     foreach my $package (@specifics) {
                   10447: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10448: 	next if ($pack_part ne $part);
                   10449: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10450: 	    return $packagetab{"$pack_type&$name&default"};
                   10451: 	}
                   10452:     }
                   10453:     # look for any possible matching non extension_ package
                   10454:     foreach my $package (@specifics) {
                   10455: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10456: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10457: 	    return $packagetab{"$pack_type&$name&default"};
                   10458: 	}
1.585     albertel 10459: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10460: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10461: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10462: 	}
                   10463:     }
1.738     albertel 10464:     # look for any posible extension_ match
                   10465:     foreach my $package (@extension) {
                   10466: 	my ($package,$pack_type)=@{$package};
                   10467: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10468: 	    return $packagetab{"$pack_type&$name&default"};
                   10469: 	}
                   10470: 	if (defined($packagetab{$package."&$name&default"})) {
                   10471: 	    return $packagetab{$package."&$name&default"};
                   10472: 	}
                   10473:     }
                   10474:     # look for a global default setting
                   10475:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10476: 	return $packagetab{"default&$name&default"};
                   10477:     }
1.395     albertel 10478:     return undef;
                   10479: }
                   10480: 
1.334     albertel 10481: sub add_prefix_and_part {
                   10482:     my ($prefix,$part)=@_;
                   10483:     my $keyroot;
                   10484:     if (defined($prefix) && $prefix !~ /^__/) {
                   10485: 	# prefix that has a part already
                   10486: 	$keyroot=$prefix;
                   10487:     } elsif (defined($prefix)) {
                   10488: 	# prefix that is missing a part
                   10489: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10490:     } else {
                   10491: 	# no prefix at all
                   10492: 	if (defined($part)) { $keyroot='_'.$part; }
                   10493:     }
                   10494:     return $keyroot;
                   10495: }
                   10496: 
1.71      www      10497: # ---------------------------------------------------------------- Get metadata
                   10498: 
1.599     albertel 10499: my %metaentry;
1.1070    www      10500: my %importedpartids;
1.71      www      10501: sub metadata {
1.176     www      10502:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10503:     $uri=&declutter($uri);
1.288     albertel 10504:     # if it is a non metadata possible uri return quickly
1.529     albertel 10505:     if (($uri eq '') || 
                   10506: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10507: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10508:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10509: 	return undef;
                   10510:     }
1.1172.2.49  raeburn  10511:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10512: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10513: 	return undef;
1.288     albertel 10514:     }
1.73      www      10515:     my $filename=$uri;
                   10516:     $uri=~s/\.meta$//;
1.172     www      10517: #
                   10518: # Is the metadata already cached?
1.177     www      10519: # Look at timestamp of caching
1.172     www      10520: # Everything is cached by the main uri, libraries are never directly cached
                   10521: #
1.428     albertel 10522:     if (!defined($liburi)) {
1.599     albertel 10523: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10524: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10525:     }
                   10526:     {
1.1069    www      10527: # Imported parts would go here
1.1070    www      10528:         my %importedids=();
                   10529:         my @origfileimportpartids=();
1.1069    www      10530:         my $importedparts=0;
1.172     www      10531: #
                   10532: # Is this a recursive call for a library?
                   10533: #
1.599     albertel 10534: #	if (! exists($metacache{$uri})) {
                   10535: #	    $metacache{$uri}={};
                   10536: #	}
1.924     albertel 10537: 	my $cachetime = 60*60;
1.171     www      10538:         if ($liburi) {
                   10539: 	    $liburi=&declutter($liburi);
                   10540:             $filename=$liburi;
1.401     bowersj2 10541:         } else {
1.599     albertel 10542: 	    &devalidate_cache_new('meta',$uri);
                   10543: 	    undef(%metaentry);
1.401     bowersj2 10544: 	}
1.140     www      10545:         my %metathesekeys=();
1.73      www      10546:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10547: 	my $metastring;
1.1140    www      10548: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10549: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10550: 	    $metastring = 
1.929     albertel 10551: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10552: 					  ('grade_target' => 'meta'));
                   10553: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10554: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10555:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10556: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10557: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10558: 	    $metastring=&getfile($file);
1.489     albertel 10559: 	}
1.208     albertel 10560:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10561:         my $token;
1.140     www      10562:         undef %metathesekeys;
1.71      www      10563:         while ($token=$parser->get_token) {
1.339     albertel 10564: 	    if ($token->[0] eq 'S') {
                   10565: 		if (defined($token->[2]->{'package'})) {
1.172     www      10566: #
                   10567: # This is a package - get package info
                   10568: #
1.339     albertel 10569: 		    my $package=$token->[2]->{'package'};
                   10570: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10571: 		    if (defined($token->[2]->{'id'})) { 
                   10572: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10573: 		    }
1.599     albertel 10574: 		    if ($metaentry{':packages'}) {
                   10575: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10576: 		    } else {
1.599     albertel 10577: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10578: 		    }
1.736     albertel 10579: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10580: 			my $part=$keyroot;
                   10581: 			$part=~s/^\_//;
1.736     albertel 10582: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10583: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10584: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10585: 			    # ignore package.tab specified default values
                   10586:                             # here &package_tab_default() will fetch those
                   10587: 			    if ($subp eq 'default') { next; }
1.736     albertel 10588: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10589: 			    my $unikey;
                   10590: 			    if ($pack =~ /_0$/) {
                   10591: 				$unikey='parameter_0_'.$name;
                   10592: 				$part=0;
                   10593: 			    } else {
                   10594: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10595: 			    }
1.339     albertel 10596: 			    if ($subp eq 'display') {
                   10597: 				$value.=' [Part: '.$part.']';
                   10598: 			    }
1.599     albertel 10599: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10600: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10601: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10602: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10603: 			    }
1.599     albertel 10604: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10605: 				$metaentry{':'.$unikey}=
                   10606: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10607: 			    }
1.339     albertel 10608: 			}
                   10609: 		    }
                   10610: 		} else {
1.172     www      10611: #
                   10612: # This is not a package - some other kind of start tag
1.339     albertel 10613: #
                   10614: 		    my $entry=$token->[1];
1.1068    www      10615: 		    my $unikey='';
1.175     www      10616: 
1.339     albertel 10617: 		    if ($entry eq 'import') {
1.175     www      10618: #
                   10619: # Importing a library here
1.339     albertel 10620: #
1.1067    www      10621:                         my $location=$parser->get_text('/import');
                   10622:                         my $dir=$filename;
                   10623:                         $dir=~s|[^/]*$||;
                   10624:                         $location=&filelocation($dir,$location);
1.1069    www      10625:                        
1.1068    www      10626:                         my $importmode=$token->[2]->{'importmode'};
                   10627:                         if ($importmode eq 'problem') {
1.1069    www      10628: # Import as problem/response
1.1068    www      10629:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10630:                         } elsif ($importmode eq 'part') {
                   10631: # Import as part(s)
1.1069    www      10632:                            $importedparts=1;
                   10633: # We need to get the original file and the imported file to get the part order correct
                   10634: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10635: # Load and inspect original file
1.1070    www      10636:                            if ($#origfileimportpartids<0) {
                   10637:                               undef(%importedpartids);
                   10638:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10639:                               my $origfile=&getfile($origfilelocation);
                   10640:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10641:                            }
                   10642: 
1.1069    www      10643: # Load and inspect imported file
                   10644:                            my $impfile=&getfile($location);
                   10645:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10646:                            if ($#impfilepartids>=0) {
                   10647: # This problem had parts
1.1070    www      10648:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10649:                            } else {
                   10650: # Importing by turning a single problem into a problem part
                   10651: # It gets the import-tags ID as part-ID
                   10652:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10653:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10654:                            }
1.1068    www      10655:                         } else {
                   10656: # Normal import
                   10657:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10658:                            if (defined($token->[2]->{'id'})) {
                   10659:                               $unikey.='_'.$token->[2]->{'id'};
                   10660:                            }
1.1067    www      10661:                         }
                   10662: 
1.339     albertel 10663: 			if ($depthcount<20) {
1.736     albertel 10664: 			    my $metadata = 
                   10665: 				&metadata($uri,'keys', $location,$unikey,
                   10666: 					  $depthcount+1);
                   10667: 			    foreach my $meta (split(',',$metadata)) {
                   10668: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10669: 				$metathesekeys{$meta}=1;
1.339     albertel 10670: 			    }
1.1068    www      10671: 			
                   10672:                         }
1.1067    www      10673: 		    } else {
                   10674: #
                   10675: # Not importing, some other kind of non-package, non-library start tag
                   10676: # 
                   10677:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10678:                         if (defined($token->[2]->{'id'})) {
                   10679:                             $unikey.='_'.$token->[2]->{'id'};
                   10680:                         }
1.339     albertel 10681: 			if (defined($token->[2]->{'name'})) { 
                   10682: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10683: 			}
                   10684: 			$metathesekeys{$unikey}=1;
1.736     albertel 10685: 			foreach my $param (@{$token->[3]}) {
                   10686: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10687: 				$token->[2]->{$param};
1.339     albertel 10688: 			}
                   10689: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10690: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10691: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10692: 		 # only ws inside the tag, and not in default, so use default
                   10693: 		 # as value
1.599     albertel 10694: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10695: 			} elsif ( $internaltext =~ /\S/ ) {
                   10696: 		  # something interesting inside the tag
                   10697: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10698: 			} else {
1.908     albertel 10699: 		  # no interesting values, don't set a default
1.339     albertel 10700: 			}
1.172     www      10701: # end of not-a-package not-a-library import
1.339     albertel 10702: 		    }
1.172     www      10703: # end of not-a-package start tag
1.339     albertel 10704: 		}
1.172     www      10705: # the next is the end of "start tag"
1.339     albertel 10706: 	    }
                   10707: 	}
1.483     albertel 10708: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10709: 	$extension = lc($extension);
                   10710: 	if ($extension eq 'htm') { $extension='html'; }
                   10711: 
1.737     albertel 10712: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10713: 	    #no specific packages #how's our extension
                   10714: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10715: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10716: 					 \%metathesekeys);
                   10717: 	}
1.883     albertel 10718: 
                   10719: 	if (!exists($metaentry{':packages'})
                   10720: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10721: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10722: 		#no specific packages well let's get default then
                   10723: 		if ($key!~/^default&/) { next; }
1.488     albertel 10724: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10725: 					     \%metathesekeys);
                   10726: 	    }
                   10727: 	}
1.338     www      10728: # are there custom rights to evaluate
1.599     albertel 10729: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10730: 
1.338     www      10731:     #
                   10732:     # Importing a rights file here
1.339     albertel 10733:     #
                   10734: 	    unless ($depthcount) {
1.599     albertel 10735: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10736: 		my $dir=$filename;
                   10737: 		$dir=~s|[^/]*$||;
                   10738: 		$location=&filelocation($dir,$location);
1.736     albertel 10739: 		my $rights_metadata =
                   10740: 		    &metadata($uri,'keys',$location,'_rights',
                   10741: 			      $depthcount+1);
                   10742: 		foreach my $rights (split(',',$rights_metadata)) {
                   10743: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10744: 		    $metathesekeys{$rights}=1;
1.339     albertel 10745: 		}
                   10746: 	    }
                   10747: 	}
1.737     albertel 10748: 	# uniqifiy package listing
                   10749: 	my %seen;
                   10750: 	my @uniq_packages =
                   10751: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10752: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10753: 
1.1070    www      10754:         if ($importedparts) {
                   10755: # We had imported parts and need to rebuild partorder
                   10756:            $metaentry{':partorder'}='';
                   10757:            $metathesekeys{'partorder'}=1;
                   10758:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10759:                if ($origfileimportpartids[$index] eq 'part') {
                   10760: # original part, part of the problem
                   10761:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10762:                } else {
                   10763: # we have imported parts at this position
                   10764:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10765:                }
                   10766:            }
                   10767:            $metaentry{':partorder'}=~s/^\,//;
                   10768:         }
                   10769: 
1.737     albertel 10770: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10771: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  10772: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 10773: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10774: # this is the end of "was not already recently cached
1.71      www      10775:     }
1.599     albertel 10776:     return $metaentry{':'.$what};
1.261     albertel 10777: }
                   10778: 
1.488     albertel 10779: sub metadata_create_package_def {
1.483     albertel 10780:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10781:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10782:     if ($subp eq 'default') { next; }
                   10783:     
1.599     albertel 10784:     if (defined($metaentry{':packages'})) {
                   10785: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10786:     } else {
1.599     albertel 10787: 	$metaentry{':packages'}=$package;
1.483     albertel 10788:     }
                   10789:     my $value=$packagetab{$key};
                   10790:     my $unikey;
                   10791:     $unikey='parameter_0_'.$name;
1.599     albertel 10792:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10793:     $$metathesekeys{$unikey}=1;
1.599     albertel 10794:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10795: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10796:     }
1.599     albertel 10797:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10798: 	$metaentry{':'.$unikey}=
                   10799: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10800:     }
                   10801: }
                   10802: 
1.261     albertel 10803: sub metadata_generate_part0 {
                   10804:     my ($metadata,$metacache,$uri) = @_;
                   10805:     my %allnames;
1.737     albertel 10806:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10807: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10808: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10809: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10810: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10811: 	    $allnames{$name}=$part;
                   10812: 	  }
                   10813: 	}
                   10814:     }
                   10815:     foreach my $name (keys(%allnames)) {
                   10816:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10817:       my $key=":parameter_0_$name";
1.261     albertel 10818:       $$metacache{"$key.part"}='0';
                   10819:       $$metacache{"$key.name"}=$name;
1.428     albertel 10820:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10821: 					   $allnames{$name}.'_'.$name.
                   10822: 					   '.type'};
1.428     albertel 10823:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10824: 			     '.display'};
1.644     www      10825:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10826:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10827:       $$metacache{"$key.display"}=$olddis;
                   10828:     }
1.71      www      10829: }
                   10830: 
1.764     albertel 10831: # ------------------------------------------------------ Devalidate title cache
                   10832: 
                   10833: sub devalidate_title_cache {
                   10834:     my ($url)=@_;
                   10835:     if (!$env{'request.course.id'}) { return; }
                   10836:     my $symb=&symbread($url);
                   10837:     if (!$symb) { return; }
                   10838:     my $key=$env{'request.course.id'}."\0".$symb;
                   10839:     &devalidate_cache_new('title',$key);
                   10840: }
                   10841: 
1.1014    droeschl 10842: # ------------------------------------------------- Get the title of a course
                   10843: 
                   10844: sub current_course_title {
                   10845:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10846: }
1.301     www      10847: # ------------------------------------------------- Get the title of a resource
                   10848: 
                   10849: sub gettitle {
                   10850:     my $urlsymb=shift;
                   10851:     my $symb=&symbread($urlsymb);
1.534     albertel 10852:     if ($symb) {
1.620     albertel 10853: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10854: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10855: 	if (defined($cached)) { 
                   10856: 	    return $result;
                   10857: 	}
1.534     albertel 10858: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10859: 	my $title='';
1.907     albertel 10860: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10861: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10862: 	} else {
                   10863: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10864: 		    &GDBM_READER(),0640)) {
                   10865: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10866: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10867: 		untie(%bighash);
                   10868: 	    }
1.534     albertel 10869: 	}
                   10870: 	$title=~s/\&colon\;/\:/gs;
                   10871: 	if ($title) {
1.1159    www      10872: # Remember both $symb and $title for dynamic metadata
                   10873:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10874:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10875: # Cache this title and then return it
1.599     albertel 10876: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10877: 	}
                   10878: 	$urlsymb=$url;
                   10879:     }
                   10880:     my $title=&metadata($urlsymb,'title');
                   10881:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10882:     return $title;
1.301     www      10883: }
1.613     albertel 10884: 
1.614     albertel 10885: sub get_slot {
                   10886:     my ($which,$cnum,$cdom)=@_;
                   10887:     if (!$cnum || !$cdom) {
1.790     albertel 10888: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10889: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10890: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10891:     }
1.703     albertel 10892:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10893:     my %slotinfo;
                   10894:     if (exists($remembered{$key})) {
                   10895: 	$slotinfo{$which} = $remembered{$key};
                   10896:     } else {
                   10897: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10898: 	&Apache::lonhomework::showhash(%slotinfo);
                   10899: 	my ($tmp)=keys(%slotinfo);
                   10900: 	if ($tmp=~/^error:/) { return (); }
                   10901: 	$remembered{$key} = $slotinfo{$which};
                   10902:     }
1.616     albertel 10903:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10904: 	return %{$slotinfo{$which}};
                   10905:     }
                   10906:     return $slotinfo{$which};
1.614     albertel 10907: }
1.1150    raeburn  10908: 
                   10909: sub get_reservable_slots {
                   10910:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10911:     my $now = time;
                   10912:     my $reservable_info;
                   10913:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10914:     if (exists($remembered{$key})) {
                   10915:         $reservable_info = $remembered{$key};
                   10916:     } else {
                   10917:         my %resv;
                   10918:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10919:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10920:         $reservable_info = \%resv;
                   10921:         $remembered{$key} = $reservable_info;
                   10922:     }
                   10923:     return $reservable_info;
                   10924: }
                   10925: 
                   10926: sub get_course_slots {
                   10927:     my ($cnum,$cdom) = @_;
                   10928:     my $hashid=$cnum.':'.$cdom;
                   10929:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10930:     if (defined($cached)) {
                   10931:         if (ref($result) eq 'HASH') {
                   10932:             return %{$result};
                   10933:         }
                   10934:     } else {
                   10935:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10936:         my ($tmp) = keys(%slots);
                   10937:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  10938:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10939:             return %slots;
                   10940:         }
                   10941:     }
                   10942:     return;
                   10943: }
                   10944: 
                   10945: sub devalidate_slots_cache {
                   10946:     my ($cnum,$cdom)=@_;
                   10947:     my $hashid=$cnum.':'.$cdom;
                   10948:     &devalidate_cache_new('allslots',$hashid);
                   10949: }
                   10950: 
1.1172.2.8  raeburn  10951: sub get_coursechange {
                   10952:     my ($cdom,$cnum) = @_;
                   10953:     if ($cdom eq '' || $cnum eq '') {
                   10954:         return unless ($env{'request.course.id'});
                   10955:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10956:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10957:     }
                   10958:     my $hashid=$cdom.'_'.$cnum;
                   10959:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10960:     if ((defined($cached)) && ($change ne '')) {
                   10961:         return $change;
                   10962:     } else {
                   10963:         my %crshash;
                   10964:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10965:         if ($crshash{'internal.contentchange'} eq '') {
                   10966:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10967:             if ($change eq '') {
                   10968:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10969:                 $change = $crshash{'internal.created'};
                   10970:             }
                   10971:         } else {
                   10972:             $change = $crshash{'internal.contentchange'};
                   10973:         }
                   10974:         my $cachetime = 600;
                   10975:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10976:     }
                   10977:     return $change;
                   10978: }
                   10979: 
                   10980: sub devalidate_coursechange_cache {
                   10981:     my ($cnum,$cdom)=@_;
                   10982:     my $hashid=$cnum.':'.$cdom;
                   10983:     &devalidate_cache_new('crschange',$hashid);
                   10984: }
                   10985: 
1.31      www      10986: # ------------------------------------------------- Update symbolic store links
                   10987: 
                   10988: sub symblist {
                   10989:     my ($mapname,%newhash)=@_;
1.438     www      10990:     $mapname=&deversion(&declutter($mapname));
1.31      www      10991:     my %hash;
1.620     albertel 10992:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10993:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10994:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10995: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10996: 		next if ($url eq 'last_known'
                   10997: 			 && $env{'form.no_update_last_known'});
                   10998: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10999: 						    $newhash{$url}->[1],
                   11000: 						    $newhash{$url}->[0]);
1.191     harris41 11001:             }
1.31      www      11002:             if (untie(%hash)) {
                   11003: 		return 'ok';
                   11004:             }
                   11005:         }
                   11006:     }
                   11007:     return 'error';
1.212     www      11008: }
                   11009: 
                   11010: # --------------------------------------------------------------- Verify a symb
                   11011: 
                   11012: sub symbverify {
1.1172.2.11  raeburn  11013:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11014:     my $thisfn=$thisurl;
1.439     www      11015:     $thisfn=&declutter($thisfn);
1.215     www      11016: # direct jump to resource in page or to a sequence - will construct own symbs
                   11017:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11018: # check URL part
1.409     www      11019:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11020: 
1.431     www      11021:     unless ($url eq $thisfn) { return 0; }
1.213     www      11022: 
1.216     www      11023:     $symb=&symbclean($symb);
1.510     www      11024:     $thisurl=&deversion($thisurl);
1.439     www      11025:     $thisfn=&deversion($thisfn);
1.213     www      11026: 
                   11027:     my %bighash;
                   11028:     my $okay=0;
1.431     www      11029: 
1.620     albertel 11030:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11031:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11032:         my $noclutter;
1.1032    raeburn  11033:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11034:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11035:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11036:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11037:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11038:                 $noclutter = 1;
                   11039:             }
                   11040:         }
                   11041:         my $ids;
                   11042:         if ($noclutter) {
                   11043:             $ids=$bighash{'ids_'.$thisurl};
                   11044:         } else {
                   11045:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11046:         }
1.1102    raeburn  11047:         unless ($ids) {
1.1172.2.13  raeburn  11048:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11049:             $ids=$bighash{$idkey};
1.216     www      11050:         }
                   11051:         if ($ids) {
                   11052: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11053:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11054:                 $symb =~ s/\?.+$//;
                   11055:             }
1.800     albertel 11056: 	    foreach my $id (split(/\,/,$ids)) {
                   11057: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11058:                if (
                   11059:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11060:    eq $symb) {
1.1172.2.11  raeburn  11061:                    if (ref($encstate)) {
                   11062:                        $$encstate = $bighash{'encrypted_'.$id};
                   11063:                    }
1.1172.2.13  raeburn  11064:                    if (($env{'request.role.adv'}) ||
                   11065:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11066:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11067:                        $okay=1;
                   11068:                        last;
                   11069:                    }
                   11070:                }
                   11071:            }
1.216     www      11072:         }
1.213     www      11073: 	untie(%bighash);
                   11074:     }
                   11075:     return $okay;
1.31      www      11076: }
                   11077: 
1.210     www      11078: # --------------------------------------------------------------- Clean-up symb
                   11079: 
                   11080: sub symbclean {
                   11081:     my $symb=shift;
1.568     albertel 11082:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11083: # remove version from map
                   11084:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11085: 
1.210     www      11086: # remove version from URL
                   11087:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11088: 
1.507     www      11089: # remove wrapper
                   11090: 
1.510     www      11091:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11092:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11093:     return $symb;
1.409     www      11094: }
                   11095: 
                   11096: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11097: 
                   11098: sub encode_symb {
                   11099:     my ($map,$resid,$url)=@_;
                   11100:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11101: }
1.409     www      11102: 
                   11103: sub decode_symb {
1.568     albertel 11104:     my $symb=shift;
                   11105:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11106:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11107:     return (&fixversion($map),$resid,&fixversion($url));
                   11108: }
                   11109: 
                   11110: sub fixversion {
                   11111:     my $fn=shift;
1.609     banghart 11112:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11113:     my %bighash;
                   11114:     my $uri=&clutter($fn);
1.620     albertel 11115:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11116: # is this cached?
1.599     albertel 11117:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11118:     if (defined($cached)) { return $result; }
                   11119: # unfortunately not cached, or expired
1.620     albertel 11120:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11121: 	    &GDBM_READER(),0640)) {
                   11122:  	if ($bighash{'version_'.$uri}) {
                   11123:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11124:  	    unless (($version eq 'mostrecent') || 
                   11125: 		    ($version==&getversion($uri))) {
1.440     www      11126:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11127:  	    }
                   11128:  	}
                   11129:  	untie %bighash;
1.413     www      11130:     }
1.599     albertel 11131:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11132: }
                   11133: 
                   11134: sub deversion {
                   11135:     my $url=shift;
                   11136:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11137:     return $url;
1.210     www      11138: }
                   11139: 
1.31      www      11140: # ------------------------------------------------------ Return symb list entry
                   11141: 
                   11142: sub symbread {
1.1172.2.66  raeburn  11143:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11144:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11145:     if (defined($env{$cache_str})) {
                   11146:         if ($ignorecachednull) {
                   11147:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11148:         } else {
                   11149:             return $env{$cache_str};
                   11150:         }
                   11151:     }
1.242     www      11152: # no filename provided? try from environment
1.1172.2.54  raeburn  11153:     unless ($thisfn) {
1.620     albertel 11154:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11155:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11156:         }
                   11157:         $thisfn=$env{'request.filename'};
1.44      www      11158:     }
1.569     albertel 11159:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11160: # is that filename actually a symb? Verify, clean, and return
                   11161:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11162: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11163: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11164: 	}
1.242     www      11165:     }
1.44      www      11166:     $thisfn=declutter($thisfn);
1.31      www      11167:     my %hash;
1.37      www      11168:     my %bighash;
                   11169:     my $syval='';
1.620     albertel 11170:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11171:         my $targetfn = $thisfn;
1.609     banghart 11172:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11173:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11174:         }
1.687     albertel 11175: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11176: 	    $targetfn=$1;
                   11177: 	}
1.620     albertel 11178:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11179:                       &GDBM_READER(),0640)) {
1.481     raeburn  11180: 	    $syval=$hash{$targetfn};
1.37      www      11181:             untie(%hash);
                   11182:         }
                   11183: # ---------------------------------------------------------- There was an entry
                   11184:         if ($syval) {
1.601     albertel 11185: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11186: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11187: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11188: 		    #return $env{$cache_str}='';
1.601     albertel 11189: 		#}    
                   11190: 		#$syval.=$1;
                   11191: 	    #}
1.37      www      11192:         } else {
                   11193: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11194:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11195:                             &GDBM_READER(),0640)) {
1.37      www      11196: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11197:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11198:               unless ($ids) { 
                   11199:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11200:               }
                   11201:               unless ($ids) {
                   11202: # alias?
                   11203: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11204:               }
1.37      www      11205:               if ($ids) {
                   11206: # ------------------------------------------------------------------- Has ID(s)
                   11207:                  my @possibilities=split(/\,/,$ids);
1.39      www      11208:                  if ($#possibilities==0) {
                   11209: # ----------------------------------------------- There is only one possibility
1.37      www      11210: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11211: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11212: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11213:                      if (ref($possibles) eq 'HASH') {
                   11214:                          $possibles->{$syval} = 1;
                   11215:                      }
                   11216:                      if ($checkforblock) {
                   11217:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11218:                          if (@blockers) {
                   11219:                              $syval = '';
                   11220:                              return;
                   11221:                          }
                   11222:                      }
                   11223:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11224: # ------------------------------------------ There is more than one possibility
                   11225:                      my $realpossible=0;
1.800     albertel 11226:                      foreach my $id (@possibilities) {
                   11227: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11228:                          my $canaccess;
                   11229:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11230:                              $canaccess = 1;
                   11231:                          } else {
                   11232:                              $canaccess = &allowed('bre',$file);
                   11233:                          }
                   11234:                          if ($canaccess) {
                   11235:          		     my ($mapid,$resid)=split(/\./,$id);
                   11236:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11237:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11238:                                                              $resid,$thisfn);
                   11239:                                  if (ref($possibles) eq 'HASH') {
                   11240:                                      $possibles->{$syval} = 1;
                   11241:                                  }
                   11242:                                  if ($checkforblock) {
                   11243:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11244:                                      unless (@blockers > 0) {
                   11245:                                          $syval = $poss_syval;
                   11246:                                          $realpossible++;
                   11247:                                      }
                   11248:                                  } else {
                   11249:                                      $syval = $poss_syval;
                   11250:                                      $realpossible++;
                   11251:                                  }
                   11252:                              }
1.39      www      11253: 			 }
1.191     harris41 11254:                      }
1.39      www      11255: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11256:                  } else {
                   11257:                      $syval='';
1.37      www      11258:                  }
                   11259: 	      }
1.1172.2.66  raeburn  11260:               untie(%bighash);
1.481     raeburn  11261:            }
1.31      www      11262:         }
1.62      www      11263:         if ($syval) {
1.620     albertel 11264: 	    return $env{$cache_str}=$syval;
1.62      www      11265:         }
1.31      www      11266:     }
1.949     raeburn  11267:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11268:     return $env{$cache_str}='';
1.31      www      11269: }
                   11270: 
                   11271: # ---------------------------------------------------------- Return random seed
                   11272: 
1.32      www      11273: sub numval {
                   11274:     my $txt=shift;
                   11275:     $txt=~tr/A-J/0-9/;
                   11276:     $txt=~tr/a-j/0-9/;
                   11277:     $txt=~tr/K-T/0-9/;
                   11278:     $txt=~tr/k-t/0-9/;
                   11279:     $txt=~tr/U-Z/0-5/;
                   11280:     $txt=~tr/u-z/0-5/;
                   11281:     $txt=~s/\D//g;
1.564     albertel 11282:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11283:     return int($txt);
1.368     albertel 11284: }
                   11285: 
1.484     albertel 11286: sub numval2 {
                   11287:     my $txt=shift;
                   11288:     $txt=~tr/A-J/0-9/;
                   11289:     $txt=~tr/a-j/0-9/;
                   11290:     $txt=~tr/K-T/0-9/;
                   11291:     $txt=~tr/k-t/0-9/;
                   11292:     $txt=~tr/U-Z/0-5/;
                   11293:     $txt=~tr/u-z/0-5/;
                   11294:     $txt=~s/\D//g;
                   11295:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11296:     my $total;
                   11297:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11298:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11299:     return int($total);
                   11300: }
                   11301: 
1.575     albertel 11302: sub numval3 {
                   11303:     use integer;
                   11304:     my $txt=shift;
                   11305:     $txt=~tr/A-J/0-9/;
                   11306:     $txt=~tr/a-j/0-9/;
                   11307:     $txt=~tr/K-T/0-9/;
                   11308:     $txt=~tr/k-t/0-9/;
                   11309:     $txt=~tr/U-Z/0-5/;
                   11310:     $txt=~tr/u-z/0-5/;
                   11311:     $txt=~s/\D//g;
                   11312:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11313:     my $total;
                   11314:     foreach my $val (@txts) { $total+=$val; }
                   11315:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11316:     return $total;
                   11317: }
                   11318: 
1.675     albertel 11319: sub digest {
                   11320:     my ($data)=@_;
                   11321:     my $digest=&Digest::MD5::md5($data);
                   11322:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11323:     my ($e,$f);
                   11324:     {
                   11325:         use integer;
                   11326:         $e=($a+$b);
                   11327:         $f=($c+$d);
                   11328:         if ($_64bit) {
                   11329:             $e=(($e<<32)>>32);
                   11330:             $f=(($f<<32)>>32);
                   11331:         }
                   11332:     }
                   11333:     if (wantarray) {
                   11334: 	return ($e,$f);
                   11335:     } else {
                   11336: 	my $g;
                   11337: 	{
                   11338: 	    use integer;
                   11339: 	    $g=($e+$f);
                   11340: 	    if ($_64bit) {
                   11341: 		$g=(($g<<32)>>32);
                   11342: 	    }
                   11343: 	}
                   11344: 	return $g;
                   11345:     }
                   11346: }
                   11347: 
1.368     albertel 11348: sub latest_rnd_algorithm_id {
1.675     albertel 11349:     return '64bit5';
1.366     albertel 11350: }
1.32      www      11351: 
1.503     albertel 11352: sub get_rand_alg {
                   11353:     my ($courseid)=@_;
1.790     albertel 11354:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11355:     if ($courseid) {
1.620     albertel 11356: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11357:     }
                   11358:     return &latest_rnd_algorithm_id();
                   11359: }
                   11360: 
1.562     albertel 11361: sub validCODE {
                   11362:     my ($CODE)=@_;
                   11363:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11364:     return 0;
                   11365: }
                   11366: 
1.491     albertel 11367: sub getCODE {
1.620     albertel 11368:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11369:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11370: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11371: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11372: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11373:     }
                   11374:     return undef;
                   11375: }
1.1133    foxr     11376: #
                   11377: #  Determines the random seed for a specific context:
                   11378: #
                   11379: # parameters:
                   11380: #   symb      - in course context the symb for the seed.
                   11381: #   course_id - The course id of the form domain_coursenum.
                   11382: #   domain    - Domain for the user.
                   11383: #   course    - Course for the user.
                   11384: #   cenv      - environment of the course.
                   11385: #
                   11386: # NOTE:
                   11387: #   All parameters are picked out of the environment if missing
                   11388: #   or not defined.
                   11389: #   If a symb cannot be determined the current time is used instead.
                   11390: #
                   11391: #  For a given well defined symb, courside, domain, username,
                   11392: #  and course environment, the seed is reproducible.
                   11393: #
1.31      www      11394: sub rndseed {
1.1133    foxr     11395:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11396:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11397:     if (!defined($symb)) {
1.366     albertel 11398: 	unless ($symb=$wsymb) { return time; }
                   11399:     }
1.1146    foxr     11400:     if (!defined $courseid) { 
                   11401: 	$courseid=$wcourseid; 
                   11402:     }
                   11403:     if (!defined $domain) { $domain=$wdomain; }
                   11404:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11405: 
                   11406:     my $which;
                   11407:     if (defined($cenv->{'rndseed'})) {
                   11408: 	$which = $cenv->{'rndseed'};
                   11409:     } else {
                   11410: 	$which =&get_rand_alg($courseid);
                   11411:     }
1.491     albertel 11412:     if (defined(&getCODE())) {
1.675     albertel 11413: 	if ($which eq '64bit5') {
                   11414: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11415: 	} elsif ($which eq '64bit4') {
1.575     albertel 11416: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11417: 	} else {
                   11418: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11419: 	}
1.675     albertel 11420:     } elsif ($which eq '64bit5') {
                   11421: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11422:     } elsif ($which eq '64bit4') {
                   11423: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11424:     } elsif ($which eq '64bit3') {
                   11425: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11426:     } elsif ($which eq '64bit2') {
                   11427: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11428:     } elsif ($which eq '64bit') {
                   11429: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11430:     }
                   11431:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11432: }
                   11433: 
                   11434: sub rndseed_32bit {
                   11435:     my ($symb,$courseid,$domain,$username)=@_;
                   11436:     {
                   11437: 	use integer;
                   11438: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11439: 	my $symbseed=numval($symb) << 22;
                   11440: 	my $namechck=unpack("%32C*",$username) << 17;
                   11441: 	my $nameseed=numval($username) << 12;
                   11442: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11443: 	my $courseseed=unpack("%32C*",$courseid);
                   11444: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11445: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11446: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11447: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11448: 	return $num;
                   11449:     }
                   11450: }
                   11451: 
                   11452: sub rndseed_64bit {
                   11453:     my ($symb,$courseid,$domain,$username)=@_;
                   11454:     {
                   11455: 	use integer;
                   11456: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11457: 	my $symbseed=numval($symb) << 10;
                   11458: 	my $namechck=unpack("%32S*",$username);
                   11459: 	
                   11460: 	my $nameseed=numval($username) << 21;
                   11461: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11462: 	my $courseseed=unpack("%32S*",$courseid);
                   11463: 	
                   11464: 	my $num1=$symbchck+$symbseed+$namechck;
                   11465: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11466: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11467: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11468: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11469: 	return "$num1,$num2";
1.155     albertel 11470:     }
1.366     albertel 11471: }
                   11472: 
1.443     albertel 11473: sub rndseed_64bit2 {
                   11474:     my ($symb,$courseid,$domain,$username)=@_;
                   11475:     {
                   11476: 	use integer;
                   11477: 	# strings need to be an even # of cahracters long, it it is odd the
                   11478:         # last characters gets thrown away
                   11479: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11480: 	my $symbseed=numval($symb) << 10;
                   11481: 	my $namechck=unpack("%32S*",$username.' ');
                   11482: 	
                   11483: 	my $nameseed=numval($username) << 21;
1.501     albertel 11484: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11485: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11486: 	
                   11487: 	my $num1=$symbchck+$symbseed+$namechck;
                   11488: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11489: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11490: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11491: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11492: 	return "$num1,$num2";
                   11493:     }
                   11494: }
                   11495: 
                   11496: sub rndseed_64bit3 {
                   11497:     my ($symb,$courseid,$domain,$username)=@_;
                   11498:     {
                   11499: 	use integer;
                   11500: 	# strings need to be an even # of cahracters long, it it is odd the
                   11501:         # last characters gets thrown away
                   11502: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11503: 	my $symbseed=numval2($symb) << 10;
                   11504: 	my $namechck=unpack("%32S*",$username.' ');
                   11505: 	
                   11506: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11507: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11508: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11509: 	
                   11510: 	my $num1=$symbchck+$symbseed+$namechck;
                   11511: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11512: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11513: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11514: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11515: 	
1.503     albertel 11516: 	return "$num1:$num2";
1.443     albertel 11517:     }
                   11518: }
                   11519: 
1.575     albertel 11520: sub rndseed_64bit4 {
                   11521:     my ($symb,$courseid,$domain,$username)=@_;
                   11522:     {
                   11523: 	use integer;
                   11524: 	# strings need to be an even # of cahracters long, it it is odd the
                   11525:         # last characters gets thrown away
                   11526: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11527: 	my $symbseed=numval3($symb) << 10;
                   11528: 	my $namechck=unpack("%32S*",$username.' ');
                   11529: 	
                   11530: 	my $nameseed=numval3($username) << 21;
                   11531: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11532: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11533: 	
                   11534: 	my $num1=$symbchck+$symbseed+$namechck;
                   11535: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11536: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11537: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11538: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11539: 	
1.575     albertel 11540: 	return "$num1:$num2";
                   11541:     }
                   11542: }
                   11543: 
1.675     albertel 11544: sub rndseed_64bit5 {
                   11545:     my ($symb,$courseid,$domain,$username)=@_;
                   11546:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11547:     return "$num1:$num2";
                   11548: }
                   11549: 
1.366     albertel 11550: sub rndseed_CODE_64bit {
                   11551:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11552:     {
1.366     albertel 11553: 	use integer;
1.443     albertel 11554: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11555: 	my $symbseed=numval2($symb);
1.491     albertel 11556: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11557: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11558: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11559: 	my $num1=$symbseed+$CODEchck;
                   11560: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11561: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11562: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11563: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11564: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11565: 	return "$num1:$num2";
1.366     albertel 11566:     }
                   11567: }
                   11568: 
1.575     albertel 11569: sub rndseed_CODE_64bit4 {
                   11570:     my ($symb,$courseid,$domain,$username)=@_;
                   11571:     {
                   11572: 	use integer;
                   11573: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11574: 	my $symbseed=numval3($symb);
                   11575: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11576: 	my $CODEseed=numval3(&getCODE());
                   11577: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11578: 	my $num1=$symbseed+$CODEchck;
                   11579: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11580: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11581: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11582: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11583: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11584: 	return "$num1:$num2";
                   11585:     }
                   11586: }
                   11587: 
1.675     albertel 11588: sub rndseed_CODE_64bit5 {
                   11589:     my ($symb,$courseid,$domain,$username)=@_;
                   11590:     my $code = &getCODE();
                   11591:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11592:     return "$num1:$num2";
                   11593: }
                   11594: 
1.366     albertel 11595: sub setup_random_from_rndseed {
                   11596:     my ($rndseed)=@_;
1.503     albertel 11597:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  11598: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11599:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11600:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11601:         } else {
                   11602:             &Math::Random::random_set_seed($num1,$num2);
                   11603:         }
1.366     albertel 11604:     } else {
                   11605: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11606:     }
1.36      albertel 11607: }
                   11608: 
1.474     albertel 11609: sub latest_receipt_algorithm_id {
1.835     albertel 11610:     return 'receipt3';
1.474     albertel 11611: }
                   11612: 
1.480     www      11613: sub recunique {
                   11614:     my $fucourseid=shift;
                   11615:     my $unique;
1.835     albertel 11616:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11617: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11618: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11619:     } else {
                   11620: 	$unique=$perlvar{'lonReceipt'};
                   11621:     }
                   11622:     return unpack("%32C*",$unique);
                   11623: }
                   11624: 
                   11625: sub recprefix {
                   11626:     my $fucourseid=shift;
                   11627:     my $prefix;
1.835     albertel 11628:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11629: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11630: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11631:     } else {
                   11632: 	$prefix=$perlvar{'lonHostID'};
                   11633:     }
                   11634:     return unpack("%32C*",$prefix);
                   11635: }
                   11636: 
1.76      www      11637: sub ireceipt {
1.474     albertel 11638:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11639: 
                   11640:     my $return =&recprefix($fucourseid).'-';
                   11641: 
                   11642:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11643: 	$env{'request.state'} eq 'construct') {
                   11644: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11645: 	return $return;
                   11646:     }
                   11647: 
1.76      www      11648:     my $cuname=unpack("%32C*",$funame);
                   11649:     my $cudom=unpack("%32C*",$fudom);
                   11650:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11651:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11652:     my $cunique=&recunique($fucourseid);
1.474     albertel 11653:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11654:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11655: 
1.790     albertel 11656: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11657: 			       
                   11658: 	$return.= ($cunique%$cuname+
                   11659: 		   $cunique%$cudom+
                   11660: 		   $cusymb%$cuname+
                   11661: 		   $cusymb%$cudom+
                   11662: 		   $cucourseid%$cuname+
                   11663: 		   $cucourseid%$cudom+
                   11664: 		   $cpart%$cuname+
                   11665: 		   $cpart%$cudom);
                   11666:     } else {
                   11667: 	$return.= ($cunique%$cuname+
                   11668: 		   $cunique%$cudom+
                   11669: 		   $cusymb%$cuname+
                   11670: 		   $cusymb%$cudom+
                   11671: 		   $cucourseid%$cuname+
                   11672: 		   $cucourseid%$cudom);
                   11673:     }
                   11674:     return $return;
1.76      www      11675: }
                   11676: 
                   11677: sub receipt {
1.474     albertel 11678:     my ($part)=@_;
1.790     albertel 11679:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11680:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11681: }
1.260     ng       11682: 
1.790     albertel 11683: sub whichuser {
                   11684:     my ($passedsymb)=@_;
                   11685:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11686:     if (defined($env{'form.grade_symb'})) {
                   11687: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11688: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11689: 	if (!$allowed &&
                   11690: 	    exists($env{'request.course.sec'}) &&
                   11691: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11692: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11693: 			      '/'.$env{'request.course.sec'});
                   11694: 	}
                   11695: 	if ($allowed) {
                   11696: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11697: 	    $courseid=$tmp_courseid;
                   11698: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11699: 	    ($name)=&get_env_multiple('form.grade_username');
                   11700: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11701: 	}
                   11702:     }
                   11703:     if (!$passedsymb) {
                   11704: 	$symb=&symbread();
                   11705:     } else {
                   11706: 	$symb=$passedsymb;
                   11707:     }
                   11708:     $courseid=$env{'request.course.id'};
                   11709:     $domain=$env{'user.domain'};
                   11710:     $name=$env{'user.name'};
                   11711:     if ($name eq 'public' && $domain eq 'public') {
                   11712: 	if (!defined($env{'form.username'})) {
                   11713: 	    $env{'form.username'}.=time.rand(10000000);
                   11714: 	}
                   11715: 	$name.=$env{'form.username'};
                   11716:     }
                   11717:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11718: 
                   11719: }
                   11720: 
1.36      albertel 11721: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11722: # returns either the contents of the file or 
                   11723: # -1 if the file doesn't exist
1.481     raeburn  11724: #
                   11725: # if the target is a file that was uploaded via DOCS, 
                   11726: # a check will be made to see if a current copy exists on the local server,
                   11727: # if it does this will be served, otherwise a copy will be retrieved from
                   11728: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11729: # the local server.   
1.472     albertel 11730: 
1.36      albertel 11731: sub getfile {
1.538     albertel 11732:     my ($file) = @_;
1.609     banghart 11733:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11734:     &repcopy($file);
                   11735:     return &readfile($file);
                   11736: }
                   11737: 
                   11738: sub repcopy_userfile {
                   11739:     my ($file)=@_;
1.1142    raeburn  11740:     my $londocroot = $perlvar{'lonDocRoot'};
                   11741:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11742:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11743:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11744: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11745:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11746:     if (-e "$file") {
1.828     www      11747: # we already have a local copy, check it out
1.538     albertel 11748: 	my @fileinfo = stat($file);
1.828     www      11749: 	my $rtncode;
                   11750: 	my $info;
1.538     albertel 11751: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11752: 	if ($lwpresp ne 'ok') {
1.828     www      11753: # there is no such file anymore, even though we had a local copy
1.482     albertel 11754: 	    if ($rtncode eq '404') {
1.538     albertel 11755: 		unlink($file);
1.482     albertel 11756: 	    }
                   11757: 	    return -1;
                   11758: 	}
                   11759: 	if ($info < $fileinfo[9]) {
1.828     www      11760: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11761: 	    return 'ok';
1.828     www      11762: 	} else {
                   11763: # the file is outdated, get rid of it
                   11764: 	    unlink($file);
1.482     albertel 11765: 	}
1.828     www      11766:     }
                   11767: # one way or the other, at this point, we don't have the file
                   11768: # construct the correct path for the file
                   11769:     my @parts = ($cdom,$cnum); 
                   11770:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11771: 	push @parts, split(/\//,$1);
                   11772:     }
                   11773:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11774:     foreach my $part (@parts) {
                   11775: 	$path .= '/'.$part;
                   11776: 	if (!-e $path) {
                   11777: 	    mkdir($path,0770);
1.482     albertel 11778: 	}
                   11779:     }
1.828     www      11780: # now the path exists for sure
                   11781: # get a user agent
                   11782:     my $ua=new LWP::UserAgent;
                   11783:     my $transferfile=$file.'.in.transfer';
                   11784: # FIXME: this should flock
                   11785:     if (-e $transferfile) { return 'ok'; }
                   11786:     my $request;
                   11787:     $uri=~s/^\///;
1.980     raeburn  11788:     my $homeserver = &homeserver($cnum,$cdom);
                   11789:     my $protocol = $protocol{$homeserver};
                   11790:     $protocol = 'http' if ($protocol ne 'https');
                   11791:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11792:     my $response=$ua->request($request,$transferfile);
                   11793: # did it work?
                   11794:     if ($response->is_error()) {
                   11795: 	unlink($transferfile);
                   11796: 	&logthis("Userfile repcopy failed for $uri");
                   11797: 	return -1;
                   11798:     }
                   11799: # worked, rename the transfer file
                   11800:     rename($transferfile,$file);
1.607     raeburn  11801:     return 'ok';
1.481     raeburn  11802: }
                   11803: 
1.517     albertel 11804: sub tokenwrapper {
                   11805:     my $uri=shift;
1.980     raeburn  11806:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11807:     $uri=~s|^/||;
1.620     albertel 11808:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11809:     my $token=$1;
1.552     albertel 11810:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11811:     if ($udom && $uname && $file) {
                   11812: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11813:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11814:         my $homeserver = &homeserver($uname,$udom);
                   11815:         my $protocol = $protocol{$homeserver};
                   11816:         $protocol = 'http' if ($protocol ne 'https');
                   11817:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11818:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11819:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11820:     } else {
                   11821:         return '/adm/notfound.html';
                   11822:     }
                   11823: }
                   11824: 
1.828     www      11825: # call with reqtype HEAD: get last modification time
                   11826: # call with reqtype GET: get the file contents
                   11827: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11828: #
1.481     raeburn  11829: sub getuploaded {
                   11830:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11831:     $uri=~s/^\///;
1.980     raeburn  11832:     my $homeserver = &homeserver($cnum,$cdom);
                   11833:     my $protocol = $protocol{$homeserver};
                   11834:     $protocol = 'http' if ($protocol ne 'https');
                   11835:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11836:     my $ua=new LWP::UserAgent;
                   11837:     my $request=new HTTP::Request($reqtype,$uri);
                   11838:     my $response=$ua->request($request);
                   11839:     $$rtncode = $response->code;
1.482     albertel 11840:     if (! $response->is_success()) {
                   11841: 	return 'failed';
                   11842:     }      
                   11843:     if ($reqtype eq 'HEAD') {
1.486     www      11844: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11845:     } elsif ($reqtype eq 'GET') {
                   11846: 	$$info = $response->content;
1.472     albertel 11847:     }
1.482     albertel 11848:     return 'ok';
1.36      albertel 11849: }
                   11850: 
1.481     raeburn  11851: sub readfile {
                   11852:     my $file = shift;
                   11853:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11854:     my $fh;
                   11855:     open($fh,"<$file");
                   11856:     my $a='';
1.800     albertel 11857:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11858:     return $a;
                   11859: }
                   11860: 
1.36      albertel 11861: sub filelocation {
1.590     banghart 11862:     my ($dir,$file) = @_;
                   11863:     my $location;
                   11864:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11865: 
                   11866:     if ($file =~ m-^/adm/-) {
                   11867: 	$file=~s-^/adm/wrapper/-/-;
                   11868: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11869:     }
1.882     albertel 11870: 
1.1139    www      11871:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11872:         $location = $file;
1.609     banghart 11873:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11874:         my ($udom,$uname,$filename)=
1.811     albertel 11875:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11876:         my $home=&homeserver($uname,$udom);
                   11877:         my $is_me=0;
                   11878:         my @ids=&current_machine_ids();
                   11879:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11880:         if ($is_me) {
1.1117    foxr     11881:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11882:         } else {
                   11883:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11884:   	      $udom.'/'.$uname.'/'.$filename;
                   11885:         }
1.882     albertel 11886:     } elsif ($file =~ m-^/adm/-) {
                   11887: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11888:     } else {
                   11889:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11890:         $file=~s:^/(res|priv)/:/:;
                   11891:         my $space=$1;
1.590     banghart 11892:         if ( !( $file =~ m:^/:) ) {
                   11893:             $location = $dir. '/'.$file;
                   11894:         } else {
1.1142    raeburn  11895:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11896:         }
1.59      albertel 11897:     }
1.590     banghart 11898:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11899:     while ($location=~m{/\.\./}) {
                   11900: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11901: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11902: 	} else {
                   11903: 	    $location=~ s{/\.\./}{/}g;
                   11904: 	}
                   11905:     } #remove dir/..
1.590     banghart 11906:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11907:     return $location;
1.46      www      11908: }
1.36      albertel 11909: 
1.46      www      11910: sub hreflocation {
                   11911:     my ($dir,$file)=@_;
1.980     raeburn  11912:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11913: 	$file=filelocation($dir,$file);
1.700     albertel 11914:     } elsif ($file=~m-^/adm/-) {
                   11915: 	$file=~s-^/adm/wrapper/-/-;
                   11916: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11917:     }
                   11918:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11919: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11920:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11921: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11922: 	        {/uploaded/$1/$2/}x;
1.46      www      11923:     }
1.913     albertel 11924:     if ($file=~ m{^/userfiles/}) {
                   11925: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11926:     }
1.462     albertel 11927:     return $file;
1.465     albertel 11928: }
                   11929: 
1.1139    www      11930: 
                   11931: 
                   11932: 
                   11933: 
1.465     albertel 11934: sub current_machine_domains {
1.853     albertel 11935:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11936: }
                   11937: 
                   11938: sub machine_domains {
                   11939:     my ($hostname) = @_;
1.465     albertel 11940:     my @domains;
1.838     albertel 11941:     my %hostname = &all_hostnames();
1.465     albertel 11942:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11943: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11944: 	if ($hostname eq $name) {
1.844     albertel 11945: 	    push(@domains,&host_domain($id));
1.465     albertel 11946: 	}
                   11947:     }
                   11948:     return @domains;
                   11949: }
                   11950: 
                   11951: sub current_machine_ids {
1.853     albertel 11952:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11953: }
                   11954: 
                   11955: sub machine_ids {
                   11956:     my ($hostname) = @_;
                   11957:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11958:     my @ids;
1.888     albertel 11959:     my %name_to_host = &all_names();
1.889     albertel 11960:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11961: 	return @{ $name_to_host{$hostname} };
                   11962:     }
                   11963:     return;
1.31      www      11964: }
                   11965: 
1.824     raeburn  11966: sub additional_machine_domains {
                   11967:     my @domains;
                   11968:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11969:     while( my $line = <$fh>) {
                   11970:         $line =~ s/\s//g;
                   11971:         push(@domains,$line);
                   11972:     }
                   11973:     return @domains;
                   11974: }
                   11975: 
                   11976: sub default_login_domain {
                   11977:     my $domain = $perlvar{'lonDefDomain'};
                   11978:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11979:     foreach my $posdom (&current_machine_domains(),
                   11980:                         &additional_machine_domains()) {
                   11981:         if (lc($posdom) eq lc($testdomain)) {
                   11982:             $domain=$posdom;
                   11983:             last;
                   11984:         }
                   11985:     }
                   11986:     return $domain;
                   11987: }
                   11988: 
1.31      www      11989: # ------------------------------------------------------------- Declutters URLs
                   11990: 
                   11991: sub declutter {
                   11992:     my $thisfn=shift;
1.569     albertel 11993:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  11994:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   11995:         $thisfn=~s{^/home/httpd/html}{};
                   11996:     }
1.31      www      11997:     $thisfn=~s/^\///;
1.697     albertel 11998:     $thisfn=~s|^adm/wrapper/||;
                   11999:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12000:     $thisfn=~s/^res\///;
1.1172    bisitz   12001:     $thisfn=~s/^priv\///;
1.1032    raeburn  12002:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12003:         $thisfn=~s/\?.+$//;
                   12004:     }
1.268     www      12005:     return $thisfn;
                   12006: }
                   12007: 
                   12008: # ------------------------------------------------------------- Clutter up URLs
                   12009: 
                   12010: sub clutter {
                   12011:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12012:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12013: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12014:        $thisfn='/res'.$thisfn; 
                   12015:     }
1.1031    raeburn  12016:     if ($thisfn !~m|^/adm|) {
                   12017: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12018: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12019: 	} else {
                   12020: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12021: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12022: 	    if ($embstyle eq 'ssi'
                   12023: 		|| ($embstyle eq 'hdn')
                   12024: 		|| ($embstyle eq 'rat')
                   12025: 		|| ($embstyle eq 'prv')
                   12026: 		|| ($embstyle eq 'ign')) {
                   12027: 		#do nothing with these
                   12028: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12029: 		|| ($embstyle eq 'emb')
                   12030: 		|| ($embstyle eq 'wrp')) {
                   12031: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12032: 	    } elsif ($embstyle eq 'unk'
                   12033: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12034: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12035: 	    } else {
1.718     www      12036: #		&logthis("Got a blank emb style");
1.695     albertel 12037: 	    }
1.694     albertel 12038: 	}
                   12039:     }
1.31      www      12040:     return $thisfn;
1.12      www      12041: }
                   12042: 
1.787     albertel 12043: sub clutter_with_no_wrapper {
                   12044:     my $uri = &clutter(shift);
                   12045:     if ($uri =~ m-^/adm/-) {
                   12046: 	$uri =~ s-^/adm/wrapper/-/-;
                   12047: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12048:     }
                   12049:     return $uri;
                   12050: }
                   12051: 
1.557     albertel 12052: sub freeze_escape {
                   12053:     my ($value)=@_;
                   12054:     if (ref($value)) {
                   12055: 	$value=&nfreeze($value);
                   12056: 	return '__FROZEN__'.&escape($value);
                   12057:     }
                   12058:     return &escape($value);
                   12059: }
                   12060: 
1.11      www      12061: 
1.557     albertel 12062: sub thaw_unescape {
                   12063:     my ($value)=@_;
                   12064:     if ($value =~ /^__FROZEN__/) {
                   12065: 	substr($value,0,10,undef);
                   12066: 	$value=&unescape($value);
                   12067: 	return &thaw($value);
                   12068:     }
                   12069:     return &unescape($value);
                   12070: }
                   12071: 
1.436     albertel 12072: sub correct_line_ends {
                   12073:     my ($result)=@_;
                   12074:     $$result =~s/\r\n/\n/mg;
                   12075:     $$result =~s/\r/\n/mg;
1.415     albertel 12076: }
1.1       albertel 12077: # ================================================================ Main Program
                   12078: 
1.184     www      12079: sub goodbye {
1.204     albertel 12080:    &logthis("Starting Shut down");
1.443     albertel 12081: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12082:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12083: #converted
1.599     albertel 12084: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12085:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12086: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12087: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12088: #1.1 only
1.870     albertel 12089: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12090: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12091: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12092: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12093:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12094:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12095:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12096:    &flushcourselogs();
                   12097:    &logthis("Shutting down");
                   12098: }
                   12099: 
1.852     albertel 12100: sub get_dns {
1.1172.2.17  raeburn  12101:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12102:     if (!$ignore_cache) {
                   12103: 	my ($content,$cached)=
                   12104: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12105: 	if ($cached) {
1.1172.2.17  raeburn  12106: 	    &$func($content,$hashref);
1.869     albertel 12107: 	    return;
                   12108: 	}
                   12109:     }
                   12110: 
                   12111:     my %alldns;
1.852     albertel 12112:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12113:     foreach my $dns (<$config>) {
                   12114: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12115:         my $line = $1;
                   12116:         my ($host,$protocol) = split(/:/,$line);
                   12117:         if ($protocol ne 'https') {
                   12118:             $protocol = 'http';
                   12119:         }
                   12120: 	$alldns{$host} = $protocol;
1.869     albertel 12121:     }
                   12122:     while (%alldns) {
1.1172.2.52  raeburn  12123: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12124: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12125:         $ua->timeout(30);
1.979     raeburn  12126: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12127: 	my $response=$ua->request($request);
1.979     raeburn  12128:         delete($alldns{$dns});
1.852     albertel 12129: 	next if ($response->is_error());
                   12130: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12131:         unless ($nocache) {
1.1172.2.23  raeburn  12132: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12133:         }
                   12134: 	&$func(\@content,$hashref);
1.869     albertel 12135: 	return;
1.852     albertel 12136:     }
                   12137:     close($config);
1.871     albertel 12138:     my $which = (split('/',$url))[3];
                   12139:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12140:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12141:     my @content = <$config>;
1.1172.2.17  raeburn  12142:     &$func(\@content,$hashref);
                   12143:     return;
                   12144: }
                   12145: 
                   12146: # ------------------------------------------------------Get DNS checksums file
                   12147: sub parse_dns_checksums_tab {
                   12148:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12149:     my $lonhost = $perlvar{'lonHostID'};
                   12150:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12151:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12152:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12153:     my $webconfdir = '/etc/httpd/conf';
                   12154:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12155:         $webconfdir = '/etc/apache2';
                   12156:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12157:         if ($1 >= 10) {
                   12158:             $webconfdir = '/etc/apache2';
                   12159:         }
                   12160:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12161:         if ($1 >= 10.0) {
                   12162:             $webconfdir = '/etc/apache2';
                   12163:         }
                   12164:     }
1.1172.2.17  raeburn  12165:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12166:     my (%chksum,%revnum);
                   12167:     if (ref($lines) eq 'ARRAY') {
                   12168:         chomp(@{$lines});
1.1172.2.34  raeburn  12169:         my $version = shift(@{$lines});
                   12170:         if ($version eq $release) {
1.1172.2.17  raeburn  12171:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12172:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12173:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12174:                     if ($webconfdir eq '/etc/apache2') {
                   12175:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12176:                     }
                   12177:                 }
1.1172.2.34  raeburn  12178:                 $chksum{$file} = $shasum;
                   12179:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12180:             }
                   12181:             if (ref($hashref) eq 'HASH') {
                   12182:                 %{$hashref} = (
                   12183:                                 sums     => \%chksum,
                   12184:                                 versions => \%revnum,
                   12185:                               );
                   12186:             }
                   12187:         }
                   12188:     }
1.869     albertel 12189:     return;
1.852     albertel 12190: }
1.1172.2.17  raeburn  12191: 
                   12192: sub fetch_dns_checksums {
                   12193:     my %checksums;
1.1172.2.34  raeburn  12194:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12195:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12196:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12197:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12198:              \%checksums);
                   12199:     return \%checksums;
                   12200: }
                   12201: 
1.327     albertel 12202: # ------------------------------------------------------------ Read domain file
                   12203: {
1.852     albertel 12204:     my $loaded;
1.846     albertel 12205:     my %domain;
                   12206: 
1.852     albertel 12207:     sub parse_domain_tab {
                   12208: 	my ($lines) = @_;
                   12209: 	foreach my $line (@$lines) {
                   12210: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12211: 
1.846     albertel 12212: 	    chomp($line);
1.852     albertel 12213: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12214: 	    my %this_domain;
                   12215: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12216: 			       'lang_def', 'city', 'longi', 'lati',
                   12217: 			       'primary') {
                   12218: 		$this_domain{$field} = shift(@elements);
                   12219: 	    }
                   12220: 	    $domain{$name} = \%this_domain;
1.852     albertel 12221: 	}
                   12222:     }
1.864     albertel 12223: 
                   12224:     sub reset_domain_info {
                   12225: 	undef($loaded);
                   12226: 	undef(%domain);
                   12227:     }
                   12228: 
1.852     albertel 12229:     sub load_domain_tab {
1.869     albertel 12230: 	my ($ignore_cache) = @_;
                   12231: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 12232: 	my $fh;
                   12233: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12234: 	    my @lines = <$fh>;
                   12235: 	    &parse_domain_tab(\@lines);
1.448     albertel 12236: 	}
1.852     albertel 12237: 	close($fh);
                   12238: 	$loaded = 1;
1.327     albertel 12239:     }
1.846     albertel 12240: 
                   12241:     sub domain {
1.852     albertel 12242: 	&load_domain_tab() if (!$loaded);
                   12243: 
1.846     albertel 12244: 	my ($name,$what) = @_;
                   12245: 	return if ( !exists($domain{$name}) );
                   12246: 
                   12247: 	if (!$what) {
                   12248: 	    return $domain{$name}{'description'};
                   12249: 	}
                   12250: 	return $domain{$name}{$what};
                   12251:     }
1.974     raeburn  12252: 
                   12253:     sub domain_info {
                   12254:         &load_domain_tab() if (!$loaded);
                   12255:         return %domain;
                   12256:     }
                   12257: 
1.327     albertel 12258: }
                   12259: 
                   12260: 
1.1       albertel 12261: # ------------------------------------------------------------- Read hosts file
                   12262: {
1.838     albertel 12263:     my %hostname;
1.844     albertel 12264:     my %hostdom;
1.845     albertel 12265:     my %libserv;
1.852     albertel 12266:     my $loaded;
1.888     albertel 12267:     my %name_to_host;
1.1074    raeburn  12268:     my %internetdom;
1.1107    raeburn  12269:     my %LC_dns_serv;
1.852     albertel 12270: 
                   12271:     sub parse_hosts_tab {
                   12272: 	my ($file) = @_;
                   12273: 	foreach my $configline (@$file) {
                   12274: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12275:             chomp($configline);
                   12276: 	    if ($configline =~ /^\^/) {
                   12277:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12278:                     $LC_dns_serv{$1} = 1;
                   12279:                 }
                   12280:                 next;
                   12281:             }
1.1074    raeburn  12282: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12283: 	    $name=~s/\s//g;
                   12284: 	    if ($id && $domain && $role && $name) {
                   12285: 		$hostname{$id}=$name;
1.888     albertel 12286: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12287: 		$hostdom{$id}=$domain;
                   12288: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12289:                 if (defined($protocol)) {
                   12290:                     if ($protocol eq 'https') {
                   12291:                         $protocol{$id} = $protocol;
                   12292:                     } else {
                   12293:                         $protocol{$id} = 'http'; 
                   12294:                     }
1.968     raeburn  12295:                 } else {
1.969     raeburn  12296:                     $protocol{$id} = 'http';
1.968     raeburn  12297:                 }
1.1074    raeburn  12298:                 if (defined($intdom)) {
                   12299:                     $internetdom{$id} = $intdom;
                   12300:                 }
1.852     albertel 12301: 	    }
                   12302: 	}
                   12303:     }
1.864     albertel 12304:     
                   12305:     sub reset_hosts_info {
1.897     albertel 12306: 	&purge_remembered();
1.864     albertel 12307: 	&reset_domain_info();
                   12308: 	&reset_hosts_ip_info();
1.892     albertel 12309: 	undef(%name_to_host);
1.864     albertel 12310: 	undef(%hostname);
                   12311: 	undef(%hostdom);
                   12312: 	undef(%libserv);
                   12313: 	undef($loaded);
                   12314:     }
1.1       albertel 12315: 
1.852     albertel 12316:     sub load_hosts_tab {
1.869     albertel 12317: 	my ($ignore_cache) = @_;
                   12318: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 12319: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12320: 	my @config = <$config>;
                   12321: 	&parse_hosts_tab(\@config);
                   12322: 	close($config);
                   12323: 	$loaded=1;
1.1       albertel 12324:     }
1.852     albertel 12325: 
1.838     albertel 12326:     sub hostname {
1.852     albertel 12327: 	&load_hosts_tab() if (!$loaded);
                   12328: 
1.838     albertel 12329: 	my ($lonid) = @_;
                   12330: 	return $hostname{$lonid};
                   12331:     }
1.845     albertel 12332: 
1.838     albertel 12333:     sub all_hostnames {
1.852     albertel 12334: 	&load_hosts_tab() if (!$loaded);
                   12335: 
1.838     albertel 12336: 	return %hostname;
                   12337:     }
1.845     albertel 12338: 
1.888     albertel 12339:     sub all_names {
                   12340: 	&load_hosts_tab() if (!$loaded);
                   12341: 
                   12342: 	return %name_to_host;
                   12343:     }
                   12344: 
1.974     raeburn  12345:     sub all_host_domain {
                   12346:         &load_hosts_tab() if (!$loaded);
                   12347:         return %hostdom;
                   12348:     }
                   12349: 
1.845     albertel 12350:     sub is_library {
1.852     albertel 12351: 	&load_hosts_tab() if (!$loaded);
                   12352: 
1.845     albertel 12353: 	return exists($libserv{$_[0]});
                   12354:     }
                   12355: 
                   12356:     sub all_library {
1.852     albertel 12357: 	&load_hosts_tab() if (!$loaded);
                   12358: 
1.845     albertel 12359: 	return %libserv;
                   12360:     }
                   12361: 
1.1062    droeschl 12362:     sub unique_library {
                   12363: 	#2x reverse removes all hostnames that appear more than once
                   12364:         my %unique = reverse &all_library();
                   12365:         return reverse %unique;
                   12366:     }
                   12367: 
1.841     albertel 12368:     sub get_servers {
1.852     albertel 12369: 	&load_hosts_tab() if (!$loaded);
                   12370: 
1.841     albertel 12371: 	my ($domain,$type) = @_;
                   12372: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12373: 	                                          : %hostname;
                   12374: 	my %result;
1.842     albertel 12375: 	if (ref($domain) eq 'ARRAY') {
                   12376: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12377: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12378: 		    $result{$host} = $hostname;
                   12379: 		}
                   12380: 	    }
                   12381: 	} else {
                   12382: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12383: 		if ($hostdom{$host} eq $domain) {
                   12384: 		    $result{$host} = $hostname;
                   12385: 		}
1.841     albertel 12386: 	    }
                   12387: 	}
                   12388: 	return %result;
                   12389:     }
1.845     albertel 12390: 
1.1062    droeschl 12391:     sub get_unique_servers {
                   12392:         my %unique = reverse &get_servers(@_);
                   12393: 	return reverse %unique;
                   12394:     }
                   12395: 
1.844     albertel 12396:     sub host_domain {
1.852     albertel 12397: 	&load_hosts_tab() if (!$loaded);
                   12398: 
1.844     albertel 12399: 	my ($lonid) = @_;
                   12400: 	return $hostdom{$lonid};
                   12401:     }
                   12402: 
1.841     albertel 12403:     sub all_domains {
1.852     albertel 12404: 	&load_hosts_tab() if (!$loaded);
                   12405: 
1.841     albertel 12406: 	my %seen;
                   12407: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12408: 	return @uniq;
                   12409:     }
1.1074    raeburn  12410: 
                   12411:     sub internet_dom {
                   12412:         &load_hosts_tab() if (!$loaded);
                   12413: 
                   12414:         my ($lonid) = @_;
                   12415:         return $internetdom{$lonid};
                   12416:     }
1.1107    raeburn  12417: 
                   12418:     sub is_LC_dns {
                   12419:         &load_hosts_tab() if (!$loaded);
                   12420: 
                   12421:         my ($hostname) = @_;
                   12422:         return exists($LC_dns_serv{$hostname});
                   12423:     }
                   12424: 
1.1       albertel 12425: }
                   12426: 
1.847     albertel 12427: { 
                   12428:     my %iphost;
1.856     albertel 12429:     my %name_to_ip;
                   12430:     my %lonid_to_ip;
1.869     albertel 12431: 
1.847     albertel 12432:     sub get_hosts_from_ip {
                   12433: 	my ($ip) = @_;
                   12434: 	my %iphosts = &get_iphost();
                   12435: 	if (ref($iphosts{$ip})) {
                   12436: 	    return @{$iphosts{$ip}};
                   12437: 	}
                   12438: 	return;
1.839     albertel 12439:     }
1.864     albertel 12440:     
                   12441:     sub reset_hosts_ip_info {
                   12442: 	undef(%iphost);
                   12443: 	undef(%name_to_ip);
                   12444: 	undef(%lonid_to_ip);
                   12445:     }
1.856     albertel 12446: 
                   12447:     sub get_host_ip {
                   12448: 	my ($lonid) = @_;
                   12449: 	if (exists($lonid_to_ip{$lonid})) {
                   12450: 	    return $lonid_to_ip{$lonid};
                   12451: 	}
                   12452: 	my $name=&hostname($lonid);
                   12453:    	my $ip = gethostbyname($name);
                   12454: 	return if (!$ip || length($ip) ne 4);
                   12455: 	$ip=inet_ntoa($ip);
                   12456: 	$name_to_ip{$name}   = $ip;
                   12457: 	$lonid_to_ip{$lonid} = $ip;
                   12458: 	return $ip;
                   12459:     }
1.847     albertel 12460:     
                   12461:     sub get_iphost {
1.869     albertel 12462: 	my ($ignore_cache) = @_;
1.894     albertel 12463: 
1.869     albertel 12464: 	if (!$ignore_cache) {
                   12465: 	    if (%iphost) {
                   12466: 		return %iphost;
                   12467: 	    }
                   12468: 	    my ($ip_info,$cached)=
                   12469: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12470: 	    if ($cached) {
                   12471: 		%iphost      = %{$ip_info->[0]};
                   12472: 		%name_to_ip  = %{$ip_info->[1]};
                   12473: 		%lonid_to_ip = %{$ip_info->[2]};
                   12474: 		return %iphost;
                   12475: 	    }
                   12476: 	}
1.894     albertel 12477: 
                   12478: 	# get yesterday's info for fallback
                   12479: 	my %old_name_to_ip;
                   12480: 	my ($ip_info,$cached)=
                   12481: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12482: 	if ($cached) {
                   12483: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12484: 	}
                   12485: 
1.888     albertel 12486: 	my %name_to_host = &all_names();
                   12487: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12488: 	    my $ip;
                   12489: 	    if (!exists($name_to_ip{$name})) {
                   12490: 		$ip = gethostbyname($name);
                   12491: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12492: 		    if (defined($old_name_to_ip{$name})) {
                   12493: 			$ip = $old_name_to_ip{$name};
                   12494: 			&logthis("Can't find $name defaulting to old $ip");
                   12495: 		    } else {
                   12496: 			&logthis("Name $name no IP found");
                   12497: 			next;
                   12498: 		    }
                   12499: 		} else {
                   12500: 		    $ip=inet_ntoa($ip);
1.847     albertel 12501: 		}
                   12502: 		$name_to_ip{$name} = $ip;
                   12503: 	    } else {
                   12504: 		$ip = $name_to_ip{$name};
1.653     albertel 12505: 	    }
1.888     albertel 12506: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12507: 		$lonid_to_ip{$id} = $ip;
                   12508: 	    }
                   12509: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12510: 	}
1.1172.2.23  raeburn  12511: 	&do_cache_new('iphost','iphost',
                   12512: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12513: 		      48*60*60);
1.869     albertel 12514: 
1.847     albertel 12515: 	return %iphost;
1.598     albertel 12516:     }
                   12517: 
1.992     raeburn  12518:     #
                   12519:     #  Given a DNS returns the loncapa host name for that DNS 
                   12520:     # 
                   12521:     sub host_from_dns {
                   12522:         my ($dns) = @_;
                   12523:         my @hosts;
                   12524:         my $ip;
                   12525: 
1.993     raeburn  12526:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12527:             $ip = $name_to_ip{$dns};
                   12528:         }
                   12529:         if (!$ip) {
                   12530:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12531:             if (length($ip) == 4) { 
                   12532: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12533:             }
                   12534:         }
                   12535:         if ($ip) {
                   12536: 	    @hosts = get_hosts_from_ip($ip);
                   12537: 	    return $hosts[0];
                   12538:         }
                   12539:         return undef;
1.986     foxr     12540:     }
1.992     raeburn  12541: 
1.1074    raeburn  12542:     sub get_internet_names {
                   12543:         my ($lonid) = @_;
                   12544:         return if ($lonid eq '');
                   12545:         my ($idnref,$cached)=
                   12546:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12547:         if ($cached) {
                   12548:             return $idnref;
                   12549:         }
                   12550:         my $ip = &get_host_ip($lonid);
                   12551:         my @hosts = &get_hosts_from_ip($ip);
                   12552:         my %iphost = &get_iphost();
                   12553:         my (@idns,%seen);
                   12554:         foreach my $id (@hosts) {
                   12555:             my $dom = &host_domain($id);
                   12556:             my $prim_id = &domain($dom,'primary');
                   12557:             my $prim_ip = &get_host_ip($prim_id);
                   12558:             next if ($seen{$prim_ip});
                   12559:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12560:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12561:                     my $intdom = &internet_dom($id);
                   12562:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12563:                         push(@idns,$intdom);
                   12564:                     }
                   12565:                 }
                   12566:             }
                   12567:             $seen{$prim_ip} = 1;
                   12568:         }
1.1172.2.23  raeburn  12569:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12570:     }
                   12571: 
1.986     foxr     12572: }
                   12573: 
1.1079    raeburn  12574: sub all_loncaparevs {
1.1172.2.39  raeburn  12575:     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  12576: }
                   12577: 
1.1172.2.27  raeburn  12578: # ------------------------------------------------------- Read loncaparev table
                   12579: {
                   12580:     sub load_loncaparevs {
                   12581:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12582:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12583:                 while (my $configline=<$config>) {
                   12584:                     chomp($configline);
                   12585:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12586:                     $loncaparevs{$hostid}=$loncaparev;
                   12587:                 }
                   12588:                 close($config);
                   12589:             }
                   12590:         }
                   12591:     }
                   12592: }
                   12593: 
                   12594: # ----------------------------------------------------- Read serverhostID table
                   12595: {
                   12596:     sub load_serverhomeIDs {
                   12597:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12598:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12599:                 while (my $configline=<$config>) {
                   12600:                     chomp($configline);
                   12601:                     my ($name,$id)=split(/:/,$configline);
                   12602:                     $serverhomeIDs{$name}=$id;
                   12603:                 }
                   12604:                 close($config);
                   12605:             }
                   12606:         }
                   12607:     }
                   12608: }
                   12609: 
                   12610: 
1.862     albertel 12611: BEGIN {
                   12612: 
                   12613: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12614:     unless ($readit) {
                   12615: {
                   12616:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12617:     %perlvar = (%perlvar,%{$configvars});
                   12618: }
                   12619: 
                   12620: 
1.1       albertel 12621: # ------------------------------------------------------ Read spare server file
                   12622: {
1.448     albertel 12623:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12624: 
                   12625:     while (my $configline=<$config>) {
                   12626:        chomp($configline);
1.284     matthew  12627:        if ($configline) {
1.784     albertel 12628: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12629: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12630: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12631:        }
                   12632:     }
1.448     albertel 12633:     close($config);
1.1       albertel 12634: }
1.11      www      12635: # ------------------------------------------------------------ Read permissions
                   12636: {
1.448     albertel 12637:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12638: 
                   12639:     while (my $configline=<$config>) {
1.448     albertel 12640: 	chomp($configline);
                   12641: 	if ($configline) {
                   12642: 	    my ($role,$perm)=split(/ /,$configline);
                   12643: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12644: 	}
1.11      www      12645:     }
1.448     albertel 12646:     close($config);
1.11      www      12647: }
                   12648: 
                   12649: # -------------------------------------------- Read plain texts for permissions
                   12650: {
1.448     albertel 12651:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12652: 
                   12653:     while (my $configline=<$config>) {
1.448     albertel 12654: 	chomp($configline);
                   12655: 	if ($configline) {
1.742     raeburn  12656: 	    my ($short,@plain)=split(/:/,$configline);
                   12657:             %{$prp{$short}} = ();
                   12658: 	    if (@plain > 0) {
                   12659:                 $prp{$short}{'std'} = $plain[0];
                   12660:                 for (my $i=1; $i<@plain; $i++) {
                   12661:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12662:                 }
                   12663:             }
1.448     albertel 12664: 	}
1.135     www      12665:     }
1.448     albertel 12666:     close($config);
1.135     www      12667: }
                   12668: 
                   12669: # ---------------------------------------------------------- Read package table
                   12670: {
1.448     albertel 12671:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12672: 
                   12673:     while (my $configline=<$config>) {
1.483     albertel 12674: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12675: 	chomp($configline);
                   12676: 	my ($short,$plain)=split(/:/,$configline);
                   12677: 	my ($pack,$name)=split(/\&/,$short);
                   12678: 	if ($plain ne '') {
                   12679: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12680: 	    $packagetab{$short}=$plain; 
                   12681: 	}
1.11      www      12682:     }
1.448     albertel 12683:     close($config);
1.329     matthew  12684: }
                   12685: 
1.1172.2.27  raeburn  12686: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12687: 
1.1172.2.27  raeburn  12688: &load_loncaparevs();
                   12689: 
                   12690: # ------------------------------------------------------- Read serverhostID table
                   12691: 
                   12692: &load_serverhomeIDs();
1.1074    raeburn  12693: 
1.1172.2.27  raeburn  12694: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12695: {
                   12696:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12697:     if (-e $file) {
                   12698:         my $parser = HTML::LCParser->new($file);
                   12699:         while (my $token = $parser->get_token()) {
                   12700:             if ($token->[0] eq 'S') {
                   12701:                 my $item = $token->[1];
                   12702:                 my $name = $token->[2]{'name'};
                   12703:                 my $value = $token->[2]{'value'};
                   12704:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12705:                     my $release = $parser->get_text();
                   12706:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12707:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12708:                 }
                   12709:             }
                   12710:         }
                   12711:     }
1.1073    raeburn  12712: }
                   12713: 
1.1138    raeburn  12714: # ---------------------------------------------------------- Read managers table
                   12715: {
                   12716:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12717:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12718:             while (my $configline=<$config>) {
                   12719:                 chomp($configline);
                   12720:                 next if ($configline =~ /^\#/);
                   12721:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12722:                     $managerstab{$configline} = 1;
                   12723:                 }
                   12724:             }
                   12725:             close($config);
                   12726:         }
                   12727:     }
                   12728: }
                   12729: 
1.329     matthew  12730: # ------------- set up temporary directory
                   12731: {
1.1117    foxr     12732:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12733: 
1.11      www      12734: }
                   12735: 
1.794     albertel 12736: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12737: 				'compress_threshold'=> 20_000,
                   12738:  			        });
1.185     www      12739: 
1.281     www      12740: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12741: $dumpcount=0;
1.958     www      12742: $locknum=0;
1.22      www      12743: 
1.163     harris41 12744: &logtouch();
1.672     albertel 12745: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12746: $readit=1;
1.564     albertel 12747:     {
                   12748: 	use integer;
                   12749: 	my $test=(2**32)+1;
1.568     albertel 12750: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12751: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12752:     }
1.195     www      12753: }
1.1       albertel 12754: }
1.179     www      12755: 
1.1       albertel 12756: 1;
1.191     harris41 12757: __END__
                   12758: 
1.243     albertel 12759: =pod
                   12760: 
1.191     harris41 12761: =head1 NAME
                   12762: 
1.243     albertel 12763: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12764: 
                   12765: =head1 SYNOPSIS
                   12766: 
1.243     albertel 12767: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12768: 
                   12769:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12770: 
1.243     albertel 12771: Common parameters:
                   12772: 
                   12773: =over 4
                   12774: 
                   12775: =item *
                   12776: 
                   12777: $uname : an internal username (if $cname expecting a course Id specifically)
                   12778: 
                   12779: =item *
                   12780: 
                   12781: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12782: 
                   12783: =item *
                   12784: 
                   12785: $symb : a resource instance identifier
                   12786: 
                   12787: =item *
                   12788: 
                   12789: $namespace : the name of a .db file that contains the data needed or
                   12790: being set.
                   12791: 
                   12792: =back
                   12793: 
1.394     bowersj2 12794: =head1 OVERVIEW
1.191     harris41 12795: 
1.394     bowersj2 12796: lonnet provides subroutines which interact with the
                   12797: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12798: about classes, users, and resources.
1.243     albertel 12799: 
                   12800: For many of these objects you can also use this to store data about
                   12801: them or modify them in various ways.
1.191     harris41 12802: 
1.394     bowersj2 12803: =head2 Symbs
1.191     harris41 12804: 
1.394     bowersj2 12805: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12806: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12807: map, the resource number of the resource in the map, and the URL of
                   12808: the resource itself. The latter is somewhat redundant, but might help
                   12809: if maps change.
                   12810: 
                   12811: An example is
                   12812: 
                   12813:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12814: 
                   12815: The respective map entry is
                   12816: 
                   12817:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12818:   title="Problem 2">
                   12819:  </resource>
                   12820: 
                   12821: Symbs are used by the random number generator, as well as to store and
                   12822: restore data specific to a certain instance of for example a problem.
                   12823: 
                   12824: =head2 Storing And Retrieving Data
                   12825: 
                   12826: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12827: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12828: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12829: is is the non-critical message twin of cstore. These functions are for
                   12830: handlers to store a perl hash to a user's permanent data space in an
                   12831: easy manner, and to retrieve it again on another call. It is expected
                   12832: that a handler would use this once at the beginning to retrieve data,
                   12833: and then again once at the end to send only the new data back.
                   12834: 
                   12835: The data is stored in the user's data directory on the user's
                   12836: homeserver under the ID of the course.
                   12837: 
                   12838: The hash that is returned by restore will have all of the previous
                   12839: value for all of the elements of the hash.
                   12840: 
                   12841: Example:
                   12842: 
                   12843:  #creating a hash
                   12844:  my %hash;
                   12845:  $hash{'foo'}='bar';
                   12846: 
                   12847:  #storing it
                   12848:  &Apache::lonnet::cstore(\%hash);
                   12849: 
                   12850:  #changing a value
                   12851:  $hash{'foo'}='notbar';
                   12852: 
                   12853:  #adding a new value
                   12854:  $hash{'bar'}='foo';
                   12855:  &Apache::lonnet::cstore(\%hash);
                   12856: 
                   12857:  #retrieving the hash
                   12858:  my %history=&Apache::lonnet::restore();
                   12859: 
                   12860:  #print the hash
                   12861:  foreach my $key (sort(keys(%history))) {
                   12862:    print("\%history{$key} = $history{$key}");
                   12863:  }
                   12864: 
                   12865: Will print out:
1.191     harris41 12866: 
1.394     bowersj2 12867:  %history{1:foo} = bar
                   12868:  %history{1:keys} = foo:timestamp
                   12869:  %history{1:timestamp} = 990455579
                   12870:  %history{2:bar} = foo
                   12871:  %history{2:foo} = notbar
                   12872:  %history{2:keys} = foo:bar:timestamp
                   12873:  %history{2:timestamp} = 990455580
                   12874:  %history{bar} = foo
                   12875:  %history{foo} = notbar
                   12876:  %history{timestamp} = 990455580
                   12877:  %history{version} = 2
                   12878: 
                   12879: Note that the special hash entries C<keys>, C<version> and
                   12880: C<timestamp> were added to the hash. C<version> will be equal to the
                   12881: total number of versions of the data that have been stored. The
                   12882: C<timestamp> attribute will be the UNIX time the hash was
                   12883: stored. C<keys> is available in every historical section to list which
                   12884: keys were added or changed at a specific historical revision of a
                   12885: hash.
                   12886: 
                   12887: B<Warning>: do not store the hash that restore returns directly. This
                   12888: will cause a mess since it will restore the historical keys as if the
                   12889: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12890: 
1.394     bowersj2 12891: Calling convention:
1.191     harris41 12892: 
1.1172.2.27  raeburn  12893:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  12894:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 12895: 
1.394     bowersj2 12896: For more detailed information, see lonnet specific documentation.
1.191     harris41 12897: 
1.394     bowersj2 12898: =head1 RETURN MESSAGES
1.191     harris41 12899: 
1.394     bowersj2 12900: =over 4
1.191     harris41 12901: 
1.394     bowersj2 12902: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12903: 
1.394     bowersj2 12904: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12905: when the connection is brought back up
1.191     harris41 12906: 
1.394     bowersj2 12907: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12908: for later delivery
1.191     harris41 12909: 
1.967     bisitz   12910: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12911: 
1.394     bowersj2 12912: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12913: that was requested
1.191     harris41 12914: 
1.243     albertel 12915: =back
1.191     harris41 12916: 
1.243     albertel 12917: =head1 PUBLIC SUBROUTINES
1.191     harris41 12918: 
1.243     albertel 12919: =head2 Session Environment Functions
1.191     harris41 12920: 
1.243     albertel 12921: =over 4
1.191     harris41 12922: 
1.394     bowersj2 12923: =item * 
                   12924: X<appenv()>
1.949     raeburn  12925: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12926: the user envirnoment file, and will be restored for each access this
1.620     albertel 12927: user makes during this session, also modifies the %env for the current
1.949     raeburn  12928: process. Optional rolesarrayref - if defined contains a reference to an array
                   12929: of roles which are exempt from the restriction on modifying user.role entries 
                   12930: in the user's environment.db and in %env.    
1.191     harris41 12931: 
                   12932: =item *
1.394     bowersj2 12933: X<delenv()>
1.987     raeburn  12934: B<delenv($delthis,$regexp)>: removes all items from the session
                   12935: environment file that begin with $delthis. If the 
                   12936: optional second arg - $regexp - is true, $delthis is treated as a 
                   12937: regular expression, otherwise \Q$delthis\E is used. 
                   12938: The values are also deleted from the current processes %env.
1.191     harris41 12939: 
1.795     albertel 12940: =item * get_env_multiple($name) 
                   12941: 
                   12942: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12943: values may be defined and end up as an array ref.
                   12944: 
                   12945: returns an array of values
                   12946: 
1.243     albertel 12947: =back
                   12948: 
                   12949: =head2 User Information
1.191     harris41 12950: 
1.243     albertel 12951: =over 4
1.191     harris41 12952: 
                   12953: =item *
1.394     bowersj2 12954: X<queryauthenticate()>
                   12955: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12956: authentication scheme
                   12957: 
                   12958: =item *
1.394     bowersj2 12959: X<authenticate()>
1.1073    raeburn  12960: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12961: authenticate user from domain's lib servers (first use the current
                   12962: one). C<$upass> should be the users password.
1.1073    raeburn  12963: $checkdefauth is optional (value is 1 if a check should be made to
                   12964:    authenticate user using default authentication method, and allow
                   12965:    account creation if username does not have account in the domain).
                   12966: $clientcancheckhost is optional (value is 1 if checking whether the
                   12967:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12968: 
                   12969: =item *
1.394     bowersj2 12970: X<homeserver()>
                   12971: B<homeserver($uname,$udom)>: find the server which has
                   12972: the user's directory and files (there must be only one), this caches
                   12973: the answer, and also caches if there is a borken connection.
1.191     harris41 12974: 
                   12975: =item *
1.394     bowersj2 12976: X<idget()>
                   12977: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12978: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12979: username, and only 1 username per ID in a specific domain) (returns
                   12980: hash: id=>name,id=>name)
1.191     harris41 12981: 
                   12982: =item *
1.394     bowersj2 12983: X<idrget()>
                   12984: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12985: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12986: 
                   12987: =item *
1.394     bowersj2 12988: X<idput()>
                   12989: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12990: 
                   12991: =item *
1.394     bowersj2 12992: X<rolesinit()>
1.1169    droeschl 12993: B<rolesinit($udom,$username)>: get user privileges.
                   12994: returns user role, first access and timer interval hashes
1.243     albertel 12995: 
                   12996: =item *
1.1171    droeschl 12997: X<privileged()>
                   12998: B<privileged($username,$domain)>: returns a true if user has a
                   12999: privileged and active role (i.e. su or dc), false otherwise.
                   13000: 
                   13001: =item *
1.551     albertel 13002: X<getsection()>
                   13003: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13004: course $cname, return section name/number or '' for "not in course"
                   13005: and '-1' for "no section"
                   13006: 
                   13007: =item *
1.394     bowersj2 13008: X<userenvironment()>
                   13009: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13010: passed in @what from the requested user's environment, returns a hash
                   13011: 
1.858     raeburn  13012: =item * 
                   13013: X<userlog_query()>
1.859     albertel 13014: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13015: activity.log file. %filters defines filters applied when parsing the
                   13016: log file. These can be start or end timestamps, or the type of action
                   13017: - log to look for Login or Logout events, check for Checkin or
                   13018: Checkout, role for role selection. The response is in the form
                   13019: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13020: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13021: 
1.243     albertel 13022: =back
                   13023: 
                   13024: =head2 User Roles
                   13025: 
                   13026: =over 4
                   13027: 
                   13028: =item *
                   13029: 
1.1172.2.65  raeburn  13030: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13031: returns codes for allowed actions.
                   13032: 
                   13033: The first argument is required, all others are optional.
                   13034: 
                   13035: $priv is the privilege being checked.
                   13036: $uri contains additional information about what is being checked for access (e.g.,
                   13037: URL, course ID etc.).
                   13038: $symb is the unique resource instance identifier in a course; if needed,
                   13039: but not provided, it will be retrieved via a call to &symbread().
                   13040: $role is the role for which a priv is being checked (only used if priv is evb).
                   13041: $clientip is the user's IP address (only used when checking for access to portfolio
                   13042: files).
                   13043: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13044: prevents recursive calls to &allowed.
                   13045: 
1.243     albertel 13046:  F: full access
                   13047:  U,I,K: authentication modes (cxx only)
                   13048:  '': forbidden
                   13049:  1: user needs to choose course
                   13050:  2: browse allowed
1.766     albertel 13051:  A: passphrase authentication needed
1.1172.2.65  raeburn  13052:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13053: 
                   13054: =item *
                   13055: 
1.1172.2.13  raeburn  13056: constructaccess($url,$setpriv) : check for access to construction space URL
                   13057: 
                   13058: See if the owner domain and name in the URL match those in the
                   13059: expected environment.  If so, return three element list
                   13060: ($ownername,$ownerdomain,$ownerhome).
                   13061: 
                   13062: Otherwise return the null string.
                   13063: 
                   13064: If second argument 'setpriv' is true, it assigns the privileges,
                   13065: and returns the same three element list, unless the owner has
                   13066: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13067: in which case the null string is returned.
                   13068: 
                   13069: =item *
                   13070: 
1.243     albertel 13071: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13072: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13073: and course level
                   13074: 
                   13075: =item *
                   13076: 
1.988     raeburn  13077: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13078: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13079: $type is Course (default) or Community.
1.988     raeburn  13080: If $forcedefault evaluates to true, text returned will be default 
                   13081: text for $type. Otherwise, if this is a course, the text returned 
                   13082: will be a custom name for the role (if defined in the course's 
                   13083: environment).  If no custom name is defined the default is returned.
                   13084:    
1.832     raeburn  13085: =item *
                   13086: 
1.1172.2.23  raeburn  13087: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13088: All arguments are optional. Returns a hash of a roles, either for
                   13089: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13090: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13091: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13092: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13093: For each key, value is set to colon-separated start and end times for
                   13094: the role.  If no username and domain are specified, will default to
1.934     raeburn  13095: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13096: of role statuses (active, future or previous), roles 
                   13097: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13098: to restrict the list of roles reported. If no array ref is 
                   13099: provided for types, will default to return only active roles.
1.834     albertel 13100: 
1.1172.2.13  raeburn  13101: =item *
                   13102: 
                   13103: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13104: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13105: 
                   13106: Additional optional arguments are: $type (if role checking is to be restricted
                   13107: to certain user status types -- previous (expired roles), active (currently
                   13108: available roles) or future (roles available in the future), and
                   13109: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13110: have active Domain Coordinator role in course's domain or in additional
                   13111: domains (specified in 'Domains to check for privileged users' in course
                   13112: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13113: 
                   13114: =item *
                   13115: 
                   13116: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13117: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13118: $possdomains and $possroles are optional array refs -- to domains to check and
                   13119: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13120: users' roles.db to check for a dc or su role in any domain. This can be
                   13121: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13122: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13123: this then allows &privileged_by_domain() to be used, which caches the identity
                   13124: of privileged users, eliminating the need for repeated calls to &dump().
                   13125: 
                   13126: =item *
                   13127: 
                   13128: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13129: where the outer hash keys are domains specified in the $possdomains array ref,
                   13130: next inner hash keys are privileged roles specified in the $roles array ref,
                   13131: and the innermost hash contains key = value pairs for username:domain = end:start
                   13132: for active or future "privileged" users with that role in that domain. To avoid
                   13133: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13134: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13135: 
1.243     albertel 13136: =back
                   13137: 
                   13138: =head2 User Modification
                   13139: 
                   13140: =over 4
                   13141: 
                   13142: =item *
                   13143: 
1.957     raeburn  13144: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13145: user for the level given by URL.  Optional start and end dates (leave empty
                   13146: string or zero for "no date")
1.191     harris41 13147: 
                   13148: =item *
                   13149: 
1.243     albertel 13150: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13151: change a users, password, possible return values are: ok,
                   13152: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13153: refused
1.191     harris41 13154: 
                   13155: =item *
                   13156: 
1.243     albertel 13157: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13158: 
                   13159: =item *
                   13160: 
1.1058    raeburn  13161: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13162:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13163: 
                   13164: will update user information (firstname,middlename,lastname,generation,
                   13165: permanentemail), and if forceid is true, student/employee ID also.
                   13166: A user's institutional affiliation(s) can also be updated.
                   13167: User information fields will not be overwritten with empty entries 
                   13168: unless the field is included in the $candelete array reference.
                   13169: This array is included when a single user is modified via "Manage Users",
                   13170: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13171: 
                   13172: =item *
                   13173: 
1.286     matthew  13174: modifystudent
                   13175: 
1.957     raeburn  13176: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13177: The course id is resolved based on the current user's environment.  
                   13178: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13179: associated with a course.
                   13180: 
1.297     matthew  13181: This call is essentially a wrapper for lonnet::modifyuser and
                   13182: lonnet::modify_student_enrollment
1.286     matthew  13183: 
                   13184: Inputs: 
                   13185: 
                   13186: =over 4
                   13187: 
1.957     raeburn  13188: =item B<$udom> Student's loncapa domain
1.286     matthew  13189: 
1.957     raeburn  13190: =item B<$uname> Student's loncapa login name
1.286     matthew  13191: 
1.964     bisitz   13192: =item B<$uid> Student/Employee ID
1.286     matthew  13193: 
1.957     raeburn  13194: =item B<$umode> Student's authentication mode
1.286     matthew  13195: 
1.957     raeburn  13196: =item B<$upass> Student's password
1.286     matthew  13197: 
1.957     raeburn  13198: =item B<$first> Student's first name
1.286     matthew  13199: 
1.957     raeburn  13200: =item B<$middle> Student's middle name
1.286     matthew  13201: 
1.957     raeburn  13202: =item B<$last> Student's last name
1.286     matthew  13203: 
1.957     raeburn  13204: =item B<$gene> Student's generation
1.286     matthew  13205: 
1.957     raeburn  13206: =item B<$usec> Student's section in course
1.286     matthew  13207: 
                   13208: =item B<$end> Unix time of the roles expiration
                   13209: 
                   13210: =item B<$start> Unix time of the roles start date
                   13211: 
                   13212: =item B<$forceid> If defined, allow $uid to be changed
                   13213: 
                   13214: =item B<$desiredhome> server to use as home server for student
                   13215: 
1.957     raeburn  13216: =item B<$email> Student's permanent e-mail address
                   13217: 
                   13218: =item B<$type> Type of enrollment (auto or manual)
                   13219: 
1.963     raeburn  13220: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13221: 
                   13222: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13223: 
1.963     raeburn  13224: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13225: 
1.963     raeburn  13226: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13227: 
1.1172.2.19  raeburn  13228: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13229: 
                   13230: =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  13231: 
1.286     matthew  13232: =back
1.297     matthew  13233: 
                   13234: =item *
                   13235: 
                   13236: modify_student_enrollment
                   13237: 
1.1172.2.31  raeburn  13238: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13239: 'role.request.course' must be defined for this function to proceed.
                   13240: 
                   13241: Inputs:
                   13242: 
                   13243: =over 4
                   13244: 
1.1172.2.31  raeburn  13245: =item $udom, student's domain
1.297     matthew  13246: 
1.1172.2.31  raeburn  13247: =item $uname, student's name
1.297     matthew  13248: 
1.1172.2.31  raeburn  13249: =item $uid, student's user id
1.297     matthew  13250: 
1.1172.2.31  raeburn  13251: =item $first, student's first name
1.297     matthew  13252: 
                   13253: =item $middle
                   13254: 
                   13255: =item $last
                   13256: 
                   13257: =item $gene
                   13258: 
                   13259: =item $usec
                   13260: 
                   13261: =item $end
                   13262: 
                   13263: =item $start
                   13264: 
1.957     raeburn  13265: =item $type
                   13266: 
                   13267: =item $locktype
                   13268: 
                   13269: =item $cid
                   13270: 
                   13271: =item $selfenroll
                   13272: 
                   13273: =item $context
                   13274: 
1.1172.2.19  raeburn  13275: =item $credits, number of credits student will earn from this class
                   13276: 
1.297     matthew  13277: =back
                   13278: 
1.191     harris41 13279: 
                   13280: =item *
                   13281: 
1.243     albertel 13282: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13283: custom role; give a custom role to a user for the level given by URL.  Specify
                   13284: name and domain of role author, and role name
1.191     harris41 13285: 
                   13286: =item *
                   13287: 
1.243     albertel 13288: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13289: 
                   13290: =item *
                   13291: 
1.243     albertel 13292: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13293: 
                   13294: =back
                   13295: 
                   13296: =head2 Course Infomation
                   13297: 
                   13298: =over 4
1.191     harris41 13299: 
                   13300: =item *
                   13301: 
1.1118    foxr     13302: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13303: specified course id, including all environment settings for the
                   13304: course, the description of the course will be in the hash under the
                   13305: key 'description'
1.191     harris41 13306: 
1.1118    foxr     13307: $options is an optional parameter that if supplied is a hash reference that controls
                   13308: what how this function works.  It has the following key/values:
                   13309: 
                   13310: =over 4
                   13311: 
                   13312: =item freshen_cache
                   13313: 
                   13314: If defined, and the environment cache for the course is valid, it is 
                   13315: returned in the returned hash.
                   13316: 
                   13317: =item one_time
                   13318: 
                   13319: If defined, the last cache time is set to _now_
                   13320: 
                   13321: =item user
                   13322: 
                   13323: If defined, the supplied username is used instead of the current user.
                   13324: 
                   13325: 
                   13326: =back
                   13327: 
1.191     harris41 13328: =item *
                   13329: 
1.624     albertel 13330: resdata($name,$domain,$type,@which) : request for current parameter
                   13331: setting for a specific $type, where $type is either 'course' or 'user',
                   13332: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  13333: answers for 10 minutes.
1.243     albertel 13334: 
1.877     foxr     13335: =item *
                   13336: 
                   13337: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13338: data base, returning a hash that is keyed by the resource name and has
                   13339: values that are the resource value.  I believe that the timestamps and
                   13340: versions are also returned.
                   13341: 
1.1172.2.31  raeburn  13342: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13343: supplemental content area. This routine caches the number of files for
                   13344: 10 minutes.
                   13345: 
1.243     albertel 13346: =back
                   13347: 
                   13348: =head2 Course Modification
                   13349: 
                   13350: =over 4
1.191     harris41 13351: 
                   13352: =item *
                   13353: 
1.243     albertel 13354: writecoursepref($courseid,%prefs) : write preferences (environment
                   13355: database) for a course
1.191     harris41 13356: 
                   13357: =item *
                   13358: 
1.1011    raeburn  13359: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13360: 
                   13361: =item *
                   13362: 
1.1038    raeburn  13363: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13364: 
1.1167    droeschl 13365: =item *
                   13366: 
                   13367: is_course($courseid), is_course($cdom, $cnum)
                   13368: 
                   13369: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13370: two component version $cdom, $cnum. It checks if the specified course exists.
                   13371: 
                   13372: Returns:
                   13373:     undef if the course doesn't exist, otherwise
                   13374:     in scalar context the combined courseid.
                   13375:     in list context the two components of the course identifier, domain and 
                   13376:     courseid.    
                   13377: 
1.243     albertel 13378: =back
                   13379: 
                   13380: =head2 Resource Subroutines
                   13381: 
                   13382: =over 4
1.191     harris41 13383: 
                   13384: =item *
                   13385: 
1.243     albertel 13386: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13387: 
                   13388: =item *
                   13389: 
1.243     albertel 13390: repcopy($filename) : subscribes to the requested file, and attempts to
                   13391: replicate from the owning library server, Might return
1.607     raeburn  13392: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13393: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13394: resource. Expects the local filesystem pathname
                   13395: (/home/httpd/html/res/....)
                   13396: 
                   13397: =back
                   13398: 
                   13399: =head2 Resource Information
                   13400: 
                   13401: =over 4
1.191     harris41 13402: 
                   13403: =item *
                   13404: 
1.1172.2.28  raeburn  13405: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13406: and returns the value of a variety of different possible values,
                   13407: $varname should be a request string, and the other parameters can be
                   13408: used to specify who and what one is asking about. Ordinarily, $cid 
                   13409: does not need to be specified, as it is retrived from 
                   13410: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13411: within lonuserstate::loadmap() when initializing a course, before
                   13412: $env{'request.course.id'} has been set, so it needs to be provided
                   13413: in that one case.
1.243     albertel 13414: 
                   13415: Possible values for $varname are environment.lastname (or other item
                   13416: from the envirnment hash), user.name (or someother aspect about the
                   13417: user), resource.0.maxtries (or some other part and parameter of a
                   13418: resource)
1.204     albertel 13419: 
                   13420: =item *
                   13421: 
1.243     albertel 13422: directcondval($number) : get current value of a condition; reads from a state
                   13423: string
1.204     albertel 13424: 
                   13425: =item *
                   13426: 
1.243     albertel 13427: condval($condidx) : value of condition index based on state
1.204     albertel 13428: 
                   13429: =item *
                   13430: 
1.243     albertel 13431: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13432: resource's metadata, $what should be either a specific key, or either
                   13433: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13434: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13435: 
                   13436: this function automatically caches all requests
1.191     harris41 13437: 
                   13438: =item *
                   13439: 
1.243     albertel 13440: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13441: network of library servers; returns file handle of where SQL and regex results
                   13442: will be stored for query
1.191     harris41 13443: 
                   13444: =item *
                   13445: 
1.1172.2.66  raeburn  13446: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   13447: return symbolic list entry (all arguments optional).
                   13448: 
                   13449: Args: filename is the filename (including path) for the file for which a symb
                   13450: is required; donotrecurse, if true will prevent calls to allowed() being made
                   13451: to check access status if more than one resource was found in the bighash
                   13452: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   13453: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   13454: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13455: cause possible symbs to be checked to determine if they are subject to content
                   13456: blocking, if so they will not be included as possible symbs; possibles is a
                   13457: ref to a hash, which, as a side effect, will be populated with all possible
                   13458: symbs (content blocking not tested).
                   13459: 
1.243     albertel 13460: returns the data handle
1.191     harris41 13461: 
                   13462: =item *
                   13463: 
1.1172.2.17  raeburn  13464: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13465: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13466: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13467: on failure, user must be in a course, as it assumes the existence of
                   13468: the course initial hash, and uses $env('request.course.id'}.  The third
                   13469: arg is an optional reference to a scalar.  If this arg is passed in the
                   13470: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13471: encrypted; otherwise it will be null.
1.243     albertel 13472: 
1.191     harris41 13473: =item *
                   13474: 
1.243     albertel 13475: symbclean($symb) : removes versions numbers from a symb, returns the
                   13476: cleaned symb
1.191     harris41 13477: 
                   13478: =item *
                   13479: 
1.243     albertel 13480: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13481: course map, user must be in a course for it to work.
1.191     harris41 13482: 
                   13483: =item *
                   13484: 
1.243     albertel 13485: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13486: 
                   13487: =item *
                   13488: 
1.243     albertel 13489: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13490: a random seed, all arguments are optional, if they aren't sent it uses the
                   13491: environment to derive them. Note: if symb isn't sent and it can't get one
                   13492: from &symbread it will use the current time as its return value
1.191     harris41 13493: 
                   13494: =item *
                   13495: 
1.243     albertel 13496: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13497: unfakeable, receipt
1.191     harris41 13498: 
                   13499: =item *
                   13500: 
1.620     albertel 13501: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13502: 
                   13503: =item *
                   13504: 
1.243     albertel 13505: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13506: 
                   13507: =item *
                   13508: 
1.243     albertel 13509: 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 13510: 
                   13511: =item *
                   13512: 
1.243     albertel 13513: 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 13514: 
                   13515: =item *
                   13516: 
1.243     albertel 13517: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13518: 
                   13519: =item *
                   13520: 
1.243     albertel 13521: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13522: forcing spreadsheet to reevaluate the resource scores next time.
                   13523: 
1.1172.2.13  raeburn  13524: =item *
                   13525: 
                   13526: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13527: when viewing in course context.
                   13528: 
                   13529:  input: six args -- filename (decluttered), course number, course domain,
                   13530:                     url, symb (if registered) and group (if this is a
                   13531:                     group item -- e.g., bulletin board, group page etc.).
                   13532: 
                   13533:  output: array of five scalars --
                   13534:          $cfile -- url for file editing if editable on current server
                   13535:          $home -- homeserver of resource (i.e., for author if published,
                   13536:                                           or course if uploaded.).
                   13537:          $switchserver --  1 if server switch will be needed.
                   13538:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13539:          $forceview -- 1 if icon/link should be to go to view mode
                   13540: 
                   13541: =item *
                   13542: 
                   13543: is_course_upload($file,$cnum,$cdom)
                   13544: 
                   13545: Used in course context to determine if current file was uploaded to
                   13546: the course (i.e., would be found in /userfiles/docs on the course's
                   13547: homeserver.
                   13548: 
                   13549:   input: 3 args -- filename (decluttered), course number and course domain.
                   13550:   output: boolean -- 1 if file was uploaded.
                   13551: 
1.243     albertel 13552: =back
                   13553: 
                   13554: =head2 Storing/Retreiving Data
                   13555: 
                   13556: =over 4
1.191     harris41 13557: 
                   13558: =item *
                   13559: 
1.1172.2.64  raeburn  13560: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   13561: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13562: the remaining args aren't required and if they aren't passed or are '' they will
                   13563: be derived from the env (with the exception of $laststore, which is an
                   13564: optional arg used when a user's submission is stored in grading).
                   13565: $laststore is $version=$timestamp, where $version is the most recent version
                   13566: number retrieved for the corresponding $symb in the $namespace db file, and
                   13567: $timestamp is the timestamp for that transaction (UNIX time).
                   13568: $laststore is currently only passed when cstore() is called by
                   13569: structuretags::finalize_storage().
1.191     harris41 13570: 
                   13571: =item *
                   13572: 
1.1172.2.64  raeburn  13573: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   13574: but uses critical subroutine
1.191     harris41 13575: 
                   13576: =item *
                   13577: 
1.243     albertel 13578: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13579: all args are optional
1.191     harris41 13580: 
                   13581: =item *
                   13582: 
1.717     albertel 13583: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13584: dumps the complete (or key matching regexp) namespace into a hash
                   13585: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13586: normally &store()ed into
                   13587: 
                   13588: $range should be either an integer '100' (give me the first 100
                   13589:                                            matching records)
                   13590:               or be  two integers sperated by a - with no spaces
                   13591:                  '30-50' (give me the 30th through the 50th matching
                   13592:                           records)
                   13593: 
                   13594: 
                   13595: =item *
                   13596: 
1.1172.2.59  raeburn  13597: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 13598: replaces a &store() version of data with a replacement set of data
                   13599: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  13600: reference. If $tolog is true, the transaction is logged in the courselog
                   13601: with an action=PUTSTORE.
1.717     albertel 13602: 
                   13603: =item *
                   13604: 
1.243     albertel 13605: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13606: works very similar to store/cstore, but all data is stored in a
                   13607: temporary location and can be reset using tmpreset, $storehash should
                   13608: be a hash reference, returns nothing on success
1.191     harris41 13609: 
                   13610: =item *
                   13611: 
1.243     albertel 13612: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13613: similar to restore, but all data is stored in a temporary location and
                   13614: can be reset using tmpreset. Returns a hash of values on success,
                   13615: error string otherwise.
1.191     harris41 13616: 
                   13617: =item *
                   13618: 
1.243     albertel 13619: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13620: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13621: 
                   13622: =item *
                   13623: 
1.243     albertel 13624: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13625: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13626: 
                   13627: =item *
                   13628: 
1.243     albertel 13629: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13630: namesp ($udom and $uname are optional)
1.191     harris41 13631: 
                   13632: =item *
                   13633: 
1.702     albertel 13634: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13635: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13636: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13637: 
1.702     albertel 13638: $range should be either an integer '100' (give me the first 100
                   13639:                                            matching records)
                   13640:               or be  two integers sperated by a - with no spaces
                   13641:                  '30-50' (give me the 30th through the 50th matching
                   13642:                           records)
1.449     matthew  13643: =item *
                   13644: 
                   13645: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13646: $store can be a scalar, an array reference, or if the amount to be 
                   13647: incremented is > 1, a hash reference.
                   13648: 
                   13649: ($udom and $uname are optional)
1.191     harris41 13650: 
                   13651: =item *
                   13652: 
1.243     albertel 13653: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13654: ($udom and $uname are optional)
1.191     harris41 13655: 
                   13656: =item *
                   13657: 
1.243     albertel 13658: cput($namespace,$storehash,$udom,$uname) : critical put
                   13659: ($udom and $uname are optional)
1.191     harris41 13660: 
                   13661: =item *
                   13662: 
1.748     albertel 13663: newput($namespace,$storehash,$udom,$uname) :
                   13664: 
                   13665: Attempts to store the items in the $storehash, but only if they don't
                   13666: currently exist, if this succeeds you can be certain that you have 
                   13667: successfully created a new key value pair in the $namespace db.
                   13668: 
                   13669: 
                   13670: Args:
                   13671:  $namespace: name of database to store values to
                   13672:  $storehash: hashref to store to the db
                   13673:  $udom: (optional) domain of user containing the db
                   13674:  $uname: (optional) name of user caontaining the db
                   13675: 
                   13676: Returns:
                   13677:  'ok' -> succeeded in storing all keys of $storehash
                   13678:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13679:                         least <key> already existed in the db (other
                   13680:                         requested keys may also already exist)
1.967     bisitz   13681:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13682:  'con_lost' -> unable to contact request server
                   13683:  'refused' -> action was not allowed by remote machine
                   13684: 
                   13685: 
                   13686: =item *
                   13687: 
1.243     albertel 13688: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13689: reference filled in from namesp (encrypts the return communication)
                   13690: ($udom and $uname are optional)
1.191     harris41 13691: 
                   13692: =item *
                   13693: 
1.243     albertel 13694: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13695: critical subroutine
                   13696: 
1.806     raeburn  13697: =item *
                   13698: 
1.860     raeburn  13699: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13700: array reference filled in from namespace found in domain level on either
                   13701: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13702: 
                   13703: =item *
                   13704: 
1.860     raeburn  13705: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13706: domain level either on specified domain server ($uhome) or primary domain 
                   13707: server ($udom and $uhome are optional)
1.806     raeburn  13708: 
1.943     raeburn  13709: =item * 
                   13710: 
1.1172.2.35  raeburn  13711: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   13712: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13713: the target domain.
                   13714: 
                   13715: May also include additional key => value pairs for the following groups:
                   13716: 
                   13717: =over
                   13718: 
                   13719: =item
                   13720: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13721: 
                   13722: =over
                   13723: 
                   13724: =item defaultquota, authorquota
                   13725: 
                   13726: =back
                   13727: 
                   13728: =item
                   13729: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13730: portfolio for users).
                   13731: 
                   13732: =over
                   13733: 
                   13734: =item
                   13735: aboutme, blog, webdav, portfolio
                   13736: 
                   13737: =back
                   13738: 
                   13739: =item
                   13740: requestcourses: ability to request courses, and how requests are processed.
                   13741: 
                   13742: =over
                   13743: 
                   13744: =item
1.1172.2.37  raeburn  13745: official, unofficial, community, textbook
1.1172.2.35  raeburn  13746: 
                   13747: =back
                   13748: 
                   13749: =item
                   13750: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13751: 
                   13752: =over
                   13753: 
                   13754: =item
1.1172.2.44  raeburn  13755: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  13756: 
                   13757: =back
                   13758: 
                   13759: =item
                   13760: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13761: for course's uploaded content.
                   13762: 
                   13763: =over
                   13764: 
                   13765: =item
1.1172.2.68! raeburn  13766: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
        !          13767: communityquota, textbookquota
1.1172.2.35  raeburn  13768: 
                   13769: =back
                   13770: 
                   13771: =item
                   13772: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13773: on your servers.
                   13774: 
                   13775: =over
                   13776: 
                   13777: =item
                   13778: remotesessions, hostedsessions
                   13779: 
                   13780: =back
                   13781: 
                   13782: =back
                   13783: 
                   13784: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13785: utility to create a configuration.db file on a domain's primary library server
                   13786: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13787: -- corresponding values are authentication type (internal, krb4, krb5,
                   13788: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   13789: will be available. Values are retrieved from cache (if current), unless the
                   13790: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13791: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13792: 
                   13793: Typical usage:
1.943     raeburn  13794: 
1.1172.2.35  raeburn  13795: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13796: 
1.243     albertel 13797: =back
                   13798: 
                   13799: =head2 Network Status Functions
                   13800: 
                   13801: =over 4
1.191     harris41 13802: 
                   13803: =item *
                   13804: 
1.1137    raeburn  13805: dirlist() : return directory list based on URI (first arg).
                   13806: 
                   13807: Inputs: 1 required, 5 optional.
                   13808: 
                   13809: =over
                   13810: 
                   13811: =item 
                   13812: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13813: 
                   13814: =item
                   13815: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13816: 
                   13817: =item
                   13818: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13819: 
                   13820: =item
                   13821: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13822: 
                   13823: =item
                   13824: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13825: 
                   13826: =item 
                   13827: $alternateRoot - path to prepend in place of path from $uri.
                   13828: 
                   13829: =back
                   13830: 
                   13831: Returns: Array of up to two items.
                   13832: 
                   13833: =over
                   13834: 
                   13835: a reference to an array of files/subdirectories
                   13836: 
                   13837: =over
                   13838: 
                   13839: Each element in the array of files/subdirectories is a & separated list of
                   13840: item name and the result of running stat on the item.  If dirlist was requested
                   13841: for a file instead of a directory, the item name will be ''. For a directory 
                   13842: listing, if the item is a metadata file, the element will end &N&M 
                   13843: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13844: default copyright set (1).  
                   13845: 
                   13846: =back
                   13847: 
                   13848: a scalar containing error condition (if encountered).
                   13849: 
                   13850: =over
                   13851: 
                   13852: =item 
                   13853: no_host (no homeserver identified for $username:$domain).
                   13854: 
                   13855: =item 
                   13856: no_such_host (server contacted for listing not identified as valid host).
                   13857: 
                   13858: =item 
                   13859: con_lost (connection to remote server failed).
                   13860: 
                   13861: =item 
                   13862: refused (invalid $username:$domain received on lond side).
                   13863: 
                   13864: =item 
                   13865: no_such_dir (directory at specified path on lond side does not exist). 
                   13866: 
                   13867: =item 
                   13868: empty (directory at specified path on lond side is empty).
                   13869: 
                   13870: =over
                   13871: 
                   13872: This is currently not encountered because the &ls3, &ls2, 
                   13873: &ls (_handler) routines on the lond side do not filter out
                   13874: . and .. from a directory listing. 
                   13875: 
                   13876: =back
                   13877: 
                   13878: =back
                   13879: 
                   13880: =back
1.191     harris41 13881: 
                   13882: =item *
                   13883: 
1.243     albertel 13884: spareserver() : find server with least workload from spare.tab
                   13885: 
1.986     foxr     13886: 
                   13887: =item *
                   13888: 
                   13889: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13890: if there is no corresponding loncapa host.
                   13891: 
1.243     albertel 13892: =back
                   13893: 
1.986     foxr     13894: 
1.243     albertel 13895: =head2 Apache Request
                   13896: 
                   13897: =over 4
1.191     harris41 13898: 
                   13899: =item *
                   13900: 
1.243     albertel 13901: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13902: localhost, posts hash
                   13903: 
                   13904: =back
                   13905: 
                   13906: =head2 Data to String to Data
                   13907: 
                   13908: =over 4
1.191     harris41 13909: 
                   13910: =item *
                   13911: 
1.243     albertel 13912: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13913: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13914: 
                   13915: =item *
                   13916: 
1.243     albertel 13917: hashref2str($hashref) : convert a hashref into a string complete with
                   13918: escaping and '=' and '&' separators, supports elements that are
                   13919: arrayrefs and hashrefs
1.191     harris41 13920: 
                   13921: =item *
                   13922: 
1.243     albertel 13923: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13924: with escaping and '&' separators, supports elements that are arrayrefs
                   13925: and hashrefs
1.191     harris41 13926: 
                   13927: =item *
                   13928: 
1.243     albertel 13929: str2hash($string) : convert string to hash using unescaping and
                   13930: splitting on '=' and '&', supports elements that are arrayrefs and
                   13931: hashrefs
1.191     harris41 13932: 
                   13933: =item *
                   13934: 
1.243     albertel 13935: str2array($string) : convert string to hash using unescaping and
                   13936: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13937: 
                   13938: =back
                   13939: 
                   13940: =head2 Logging Routines
                   13941: 
                   13942: 
                   13943: These routines allow one to make log messages in the lonnet.log and
                   13944: lonnet.perm logfiles.
1.191     harris41 13945: 
1.1119    foxr     13946: =over 4
                   13947: 
1.191     harris41 13948: =item *
                   13949: 
1.243     albertel 13950: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13951: 
                   13952: =item *
                   13953: 
1.243     albertel 13954: logthis() : append message to the normal lonnet.log file, it gets
                   13955: preiodically rolled over and deleted.
1.191     harris41 13956: 
                   13957: =item *
                   13958: 
1.243     albertel 13959: logperm() : append a permanent message to lonnet.perm.log, this log
                   13960: file never gets deleted by any automated portion of the system, only
                   13961: messages of critical importance should go in here.
                   13962: 
1.1119    foxr     13963: 
1.243     albertel 13964: =back
                   13965: 
                   13966: =head2 General File Helper Routines
                   13967: 
                   13968: =over 4
1.191     harris41 13969: 
                   13970: =item *
                   13971: 
1.481     raeburn  13972: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13973: (a) files in /uploaded
                   13974:   (i) If a local copy of the file exists - 
                   13975:       compares modification date of local copy with last-modified date for 
                   13976:       definitive version stored on home server for course. If local copy is 
                   13977:       stale, requests a new version from the home server and stores it. 
                   13978:       If the original has been removed from the home server, then local copy 
                   13979:       is unlinked.
                   13980:   (ii) If local copy does not exist -
                   13981:       requests the file from the home server and stores it. 
                   13982:   
                   13983:   If $caller is 'uploadrep':  
                   13984:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13985:     for request for files originally uploaded via DOCS. 
                   13986:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13987:   
                   13988:   Otherwise:
                   13989:      This indicates a call from the content generation phase of the request.
                   13990:      -  returns the entire contents of the file or -1.
                   13991:      
                   13992: (b) files in /res
                   13993:    - returns the entire contents of a file or -1; 
                   13994:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13995: 
1.712     albertel 13996: 
                   13997: =item *
                   13998: 
                   13999: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14000:                   reference
                   14001: 
                   14002: returns either a stat() list of data about the file or an empty list
                   14003: if the file doesn't exist or couldn't find out about it (connection
                   14004: problems or user unknown)
                   14005: 
1.191     harris41 14006: =item *
                   14007: 
1.243     albertel 14008: filelocation($dir,$file) : returns file system location of a file
                   14009: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14010: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14011: and a file of ../bob will become /a/bob)
1.191     harris41 14012: 
                   14013: =item *
                   14014: 
                   14015: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14016: filelocation except for hrefs
                   14017: 
                   14018: =item *
                   14019: 
1.1172.2.49  raeburn  14020: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14021: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14022: 
1.243     albertel 14023: =back
                   14024: 
1.608     albertel 14025: =head2 Usererfile file routines (/uploaded*)
                   14026: 
                   14027: =over 4
                   14028: 
                   14029: =item *
                   14030: 
                   14031: userfileupload(): main rotine for putting a file in a user or course's
                   14032:                   filespace, arguments are,
                   14033: 
1.620     albertel 14034:  formname - required - this is the name of the element in $env where the
1.608     albertel 14035:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14036:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14037:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14038:  context - if coursedoc, store the file in the course of the active role
                   14039:              of the current user; 
                   14040:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14041:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14042:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14043:          if undefined, it will be placed in "unknown"
                   14044: 
                   14045:  (This routine calls clean_filename() to remove any dangerous
                   14046:  characters from the filename, and then calls finuserfileupload() to
                   14047:  complete the transaction)
                   14048: 
                   14049:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14050:  and /adm/notfound.html if unsuccessful
                   14051: 
                   14052: =item *
                   14053: 
                   14054: clean_filename(): routine for cleaing a filename up for storage in
                   14055:                  userfile space, argument is:
                   14056: 
                   14057:  filename - proposed filename
                   14058: 
                   14059: returns: the new clean filename
                   14060: 
                   14061: =item *
                   14062: 
1.1090    raeburn  14063: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14064: userspace, probably shouldn't be called directly
                   14065: 
                   14066:   docuname: username or courseid of destination for the file
                   14067:   docudom: domain of user/course of destination for the file
                   14068:   formname: same as for userfileupload()
1.1090    raeburn  14069:   fname: filename (including subdirectories) for the file
                   14070:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14071:   allfiles: reference to hash used to store objects found by parser
                   14072:   codebase: reference to hash used for codebases of java objects found by parser
                   14073:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14074:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14075:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14076:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14077:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14078:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14079:   mimetype: reference to scalar to accommodate mime type determined
                   14080:             from File::MMagic if $parser = parse.
1.608     albertel 14081: 
                   14082:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14083:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14084:  was 'overwrite').
                   14085:  
1.608     albertel 14086: 
                   14087: =item *
                   14088: 
                   14089: renameuserfile(): renames an existing userfile to a new name
                   14090: 
                   14091:   Args:
                   14092:    docuname: username or courseid of destination for the file
                   14093:    docudom: domain of user/course of destination for the file
                   14094:    old: current file name (including any subdirs under userfiles)
                   14095:    new: desired file name (including any subdirs under userfiles)
                   14096: 
                   14097: =item *
                   14098: 
                   14099: mkdiruserfile(): creates a directory is a userfiles dir
                   14100: 
                   14101:   Args:
                   14102:    docuname: username or courseid of destination for the file
                   14103:    docudom: domain of user/course of destination for the file
                   14104:    dir: dir to create (including any subdirs under userfiles)
                   14105: 
                   14106: =item *
                   14107: 
                   14108: removeuserfile(): removes a file that exists in userfiles
                   14109: 
                   14110:   Args:
                   14111:    docuname: username or courseid of destination for the file
                   14112:    docudom: domain of user/course of destination for the file
                   14113:    fname: filname to delete (including any subdirs under userfiles)
                   14114: 
                   14115: =item *
                   14116: 
                   14117: removeuploadedurl(): convience function for removeuserfile()
                   14118: 
                   14119:   Args:
                   14120:    url:  a full /uploaded/... url to delete
                   14121: 
1.747     albertel 14122: =item * 
                   14123: 
                   14124: get_portfile_permissions():
                   14125:   Args:
                   14126:     domain: domain of user or course contain the portfolio files
                   14127:     user: name of user or num of course contain the portfolio files
                   14128:   Returns:
                   14129:     hashref of a dump of the proper file_permissions.db
                   14130:    
                   14131: 
                   14132: =item * 
                   14133: 
                   14134: get_access_controls():
                   14135: 
                   14136: Args:
                   14137:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14138:   group: (optional) the group you want the files associated with
                   14139:   file: (optional) the file you want access info on
                   14140: 
                   14141: Returns:
1.749     raeburn  14142:     a hash (keys are file names) of hashes containing
                   14143:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14144:         values are XML containing access control settings (see below) 
1.747     albertel 14145: 
                   14146: Internal notes:
                   14147: 
1.749     raeburn  14148:  access controls are stored in file_permissions.db as key=value pairs.
                   14149:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14150:         where scope -> public,guest,course,group,domains or users.
                   14151:               end -> UNIX time for end of access (0 -> no end date)
                   14152:               start -> UNIX time for start of access
                   14153: 
                   14154:     value -> XML description of access control
                   14155:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14156:             <start></start>
                   14157:             <end></end>
                   14158: 
                   14159:             <password></password>  for scope type = guest
                   14160: 
                   14161:             <domain></domain>     for scope type = course or group
                   14162:             <number></number>
                   14163:             <roles id="">
                   14164:              <role></role>
                   14165:              <access></access>
                   14166:              <section></section>
                   14167:              <group></group>
                   14168:             </roles>
                   14169: 
                   14170:             <dom></dom>         for scope type = domains
                   14171: 
                   14172:             <users>             for scope type = users
                   14173:              <user>
                   14174:               <uname></uname>
                   14175:               <udom></udom>
                   14176:              </user>
                   14177:             </users>
                   14178:            </scope> 
                   14179:               
                   14180:  Access data is also aggregated for each file in an additional key=value pair:
                   14181:  key -> path to file/file_name\0accesscontrol 
                   14182:  value -> reference to hash
                   14183:           hash contains key = value pairs
                   14184:           where key = uniqueID:scope_end_start
                   14185:                 value = UNIX time record was last updated
                   14186: 
                   14187:           Used to improve speed of look-ups of access controls for each file.  
                   14188:  
                   14189:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14190: 
1.1172.2.13  raeburn  14191: =item *
                   14192: 
1.749     raeburn  14193: modify_access_controls():
                   14194: 
                   14195: Modifies access controls for a portfolio file
                   14196: Args
                   14197: 1. file name
                   14198: 2. reference to hash of required changes,
                   14199: 3. domain
                   14200: 4. username
                   14201:   where domain,username are the domain of the portfolio owner 
                   14202:   (either a user or a course) 
                   14203: 
                   14204: Returns:
                   14205: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14206: 2. result of deletions ('ok' or 'error', with error message).
                   14207: 3. reference to hash of any new or updated access controls.
                   14208: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14209:    key = integer (inbound ID)
1.1172.2.13  raeburn  14210:    value = uniqueID
                   14211: 
                   14212: =item *
                   14213: 
                   14214: get_timebased_id():
                   14215: 
                   14216: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14217: course via the Course Editor (e.g., folders, composite pages,
                   14218: group bulletin boards).
                   14219: 
                   14220: Args: (first three required; six others optional)
                   14221: 
                   14222: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14223:    docssequence, or name of group
                   14224: 
                   14225: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14226:    e.g., num, boardids
                   14227: 
                   14228: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14229:    file will be named nohist_namespace.db
                   14230: 
                   14231: 4. cdom: domain of course; default is current course domain from %env
                   14232: 
                   14233: 5. cnum: course number; default is current course number from %env
                   14234: 
                   14235: 6. idtype: set to concat if an additional digit is to be appended to the
                   14236:    unix timestamp to form the suffix, if the plain timestamp is already
                   14237:    in use.  Default is to not do this, but simply increment the unix
                   14238:    timestamp by 1 until a unique key is obtained.
                   14239: 
                   14240: 7. who: holder of locking key; defaults to user:domain for user.
                   14241: 
                   14242: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14243:    retrying); default is 3.
                   14244: 
                   14245: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14246: 
                   14247: Returns:
                   14248: 
                   14249: 1. suffix obtained (numeric)
                   14250: 
                   14251: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14252: 
                   14253: 3. error: contains (localized) error message if an error occurred.
                   14254: 
1.747     albertel 14255: 
1.608     albertel 14256: =back
                   14257: 
1.243     albertel 14258: =head2 HTTP Helper Routines
                   14259: 
                   14260: =over 4
                   14261: 
1.191     harris41 14262: =item *
                   14263: 
                   14264: escape() : unpack non-word characters into CGI-compatible hex codes
                   14265: 
                   14266: =item *
                   14267: 
                   14268: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14269: 
1.243     albertel 14270: =back
                   14271: 
                   14272: =head1 PRIVATE SUBROUTINES
                   14273: 
                   14274: =head2 Underlying communication routines (Shouldn't call)
                   14275: 
                   14276: =over 4
                   14277: 
                   14278: =item *
                   14279: 
                   14280: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14281: 
                   14282: =item *
                   14283: 
                   14284: reply() : uses subreply to send a message to remote machine, logs all failures
                   14285: 
                   14286: =item *
                   14287: 
                   14288: critical() : passes a critical message to another server; if cannot
                   14289: get through then place message in connection buffer directory and
                   14290: returns con_delayed, if incapable of saving message, returns
                   14291: con_failed
                   14292: 
                   14293: =item *
                   14294: 
                   14295: reconlonc() : tries to reconnect lonc client processes.
                   14296: 
                   14297: =back
                   14298: 
                   14299: =head2 Resource Access Logging
                   14300: 
                   14301: =over 4
                   14302: 
                   14303: =item *
                   14304: 
                   14305: flushcourselogs() : flush (save) buffer logs and access logs
                   14306: 
                   14307: =item *
                   14308: 
                   14309: courselog($what) : save message for course in hash
                   14310: 
                   14311: =item *
                   14312: 
                   14313: courseacclog($what) : save message for course using &courselog().  Perform
                   14314: special processing for specific resource types (problems, exams, quizzes, etc).
                   14315: 
1.191     harris41 14316: =item *
                   14317: 
                   14318: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14319: as a PerlChildExitHandler
1.243     albertel 14320: 
                   14321: =back
                   14322: 
                   14323: =head2 Other
                   14324: 
                   14325: =over 4
                   14326: 
                   14327: =item *
                   14328: 
                   14329: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14330: 
                   14331: =back
                   14332: 
                   14333: =cut
1.877     foxr     14334: 

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