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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.86! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.85 2016/10/30 01:48:38 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1172.2.36  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    92: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   100: use LONCAPA::Lond;
1.1117    foxr      101: 
1.1090    raeburn   102: use File::Copy;
1.676     albertel  103: 
1.195     www       104: my $readit;
1.1172.2.79  raeburn   105: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  106: 
1.619     albertel  107: require Exporter;
                    108: 
                    109: our @ISA = qw (Exporter);
                    110: our @EXPORT = qw(%env);
                    111: 
1.1172.2.9  raeburn   112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       113: {
                    114:     my $logid;
1.1172.2.9  raeburn   115:     sub write_log {
                    116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    117:         if ($context eq 'course') {
                    118:             if (($cnum eq '') || ($cdom eq '')) {
                    119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    121:             }
1.957     raeburn   122:         }
1.1172.2.13  raeburn   123: 	$logid ++;
1.957     raeburn   124:         my $now = time();
                    125: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   126:         my $logentry = {
                    127:                          $id => {
                    128:                                   'exe_uname' => $env{'user.name'},
                    129:                                   'exe_udom'  => $env{'user.domain'},
                    130:                                   'exe_time'  => $now,
                    131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    132:                                   'delflag'   => $delflag,
                    133:                                   'logentry'  => $storehash,
                    134:                                   'uname'     => $uname,
                    135:                                   'udom'      => $udom,
                    136:                                 }
                    137:                        };
                    138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       139:     }
                    140: }
1.1       albertel  141: 
1.163     harris41  142: sub logtouch {
                    143:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  144:     unless (-e "$execdir/logs/lonnet.log") {	
                    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.
1.1172.2.79  raeburn   373: 	sleep(0.1);
1.549     foxr      374:     }
                    375:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      376:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      377:     #
1.550     foxr      378:     #   We'll give the connection a few tries before abandoning it.  If
                    379:     #   connection is not possible, we'll con_lost back to the client.
                    380:     #   
                    381:     my $client;
                    382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    384: 				      Type    => SOCK_STREAM,
                    385: 				      Timeout => 10);
1.869     albertel  386: 	if ($client) {
1.550     foxr      387: 	    last;		# Connected!
1.850     albertel  388: 	} else {
1.853     albertel  389: 	    &create_connection(&hostname($server),$server);
1.550     foxr      390: 	}
1.1172.2.79  raeburn   391:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      392:     }
                    393:     my $answer;
                    394:     if ($client) {
1.704     albertel  395: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      396: 	$answer=<$client>;
                    397: 	if (!$answer) { $answer="con_lost"; }
                    398: 	chomp($answer);
                    399:     } else {
                    400: 	$answer = 'con_lost';	# Failed connection.
                    401:     }
1.1       albertel  402:     return $answer;
                    403: }
                    404: 
                    405: sub reply {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  408:     my $answer=subreply($cmd,$server);
1.65      www       409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  410:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       411:                 " $cmd to $server returned $answer</font>");
                    412:     }
1.1       albertel  413:     return $answer;
                    414: }
                    415: 
                    416: # ----------------------------------------------------------- Send USR1 to lonc
                    417: 
                    418: sub reconlonc {
1.891     albertel  419:     my ($lonid) = @_;
                    420:     if ($lonid) {
1.1172.2.72  raeburn   421:         my $hostname = &hostname($lonid);
1.891     albertel  422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    423: 	if ($hostname && -e $peerfile) {
                    424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    426: 					     Type    => SOCK_STREAM,
                    427: 					     Timeout => 10);
                    428: 	    if ($client) {
                    429: 		print $client ("reset_retries\n");
                    430: 		my $answer=<$client>;
                    431: 		#reset just this one.
                    432: 	    }
                    433: 	}
                    434: 	return;
                    435:     }
                    436: 
1.836     www       437:     &logthis("Trying to reconnect lonc");
1.1       albertel  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.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') {
1.1172.2.72  raeburn   467: 	&reconlonc($server);
1.589     albertel  468: 	my $answer=reply($cmd,$server);
1.1       albertel  469:         if ($answer eq 'con_lost') {
                    470:             my $now=time;
                    471:             my $middlename=$cmd;
1.5       www       472:             $middlename=substr($middlename,0,16);
1.1       albertel  473:             $middlename=~s/\W//g;
                    474:             my $dfilename=
1.305     www       475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    476:             $dumpcount++;
1.1       albertel  477:             {
1.448     albertel  478: 		my $dfh;
                    479: 		if (open($dfh,">$dfilename")) {
                    480: 		    print $dfh "$cmd\n"; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
1.1172.2.79  raeburn   484:             sleep 1;
1.1       albertel  485:             my $wcmd='';
                    486:             {
1.448     albertel  487: 		my $dfh;
                    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);
1.1172.2.75  raeburn  1286:     my $domneedscache; 
1.1129    raeburn  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.1172.2.75  raeburn  1301:         } else {
                   1302:             $domneedscache = $dom_in_use;
1.1129    raeburn  1303:         }
                   1304:     }
                   1305:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1306:         ($is_balancer,$currtargets,$currrules) =
                   1307:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1308:         if ($is_balancer) {
                   1309:             if (ref($currrules) eq 'HASH') {
                   1310:                 if ($homeintdom) {
                   1311:                     if ($uname ne '') {
                   1312:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1313:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1314:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1315:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1316:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1317:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1318:                             }
                   1319:                         }
                   1320:                         if ($rule_in_effect eq '') {
                   1321:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1322:                             if ($userenv{'inststatus'} ne '') {
                   1323:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1324:                                 my ($othertitle,$usertypes,$types) =
                   1325:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1326:                                 if (ref($types) eq 'ARRAY') {
                   1327:                                     foreach my $type (@{$types}) {
                   1328:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1329:                                             if (exists($currrules->{$type})) {
                   1330:                                                 $rule_in_effect = $currrules->{$type};
                   1331:                                             }
                   1332:                                         }
                   1333:                                     }
                   1334:                                 }
                   1335:                             } else {
                   1336:                                 if (exists($currrules->{'default'})) {
                   1337:                                     $rule_in_effect = $currrules->{'default'};
                   1338:                                 }
                   1339:                             }
                   1340:                         }
                   1341:                     } else {
                   1342:                         if (exists($currrules->{'default'})) {
                   1343:                             $rule_in_effect = $currrules->{'default'};
                   1344:                         }
                   1345:                     }
                   1346:                 } else {
                   1347:                     if ($currrules->{'_LC_external'} ne '') {
                   1348:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1349:                     }
                   1350:                 }
                   1351:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1352:                                                        $uname,$udom);
                   1353:             }
                   1354:         }
                   1355:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1356:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1357:         unless (defined($cached)) {
                   1358:             my %domconfig =
                   1359:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1360:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1361:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1362:             } else {
                   1363:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1364:             }
                   1365:         }
                   1366:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1367:             ($is_balancer,$currtargets,$currrules) =
                   1368:                 &check_balancer_result($result,@hosts);
                   1369:             if ($is_balancer) {
1.1129    raeburn  1370:                 if (ref($currrules) eq 'HASH') {
                   1371:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1372:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1373:                     }
                   1374:                 }
                   1375:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1376:                                                        $uname,$udom);
                   1377:             }
                   1378:         } else {
                   1379:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1380:                 $is_balancer = 1;
                   1381:                 $offloadto = &this_host_spares($dom_in_use);
                   1382:             }
1.1172.2.75  raeburn  1383:             unless (defined($cached)) {
                   1384:                 $domneedscache = $serverhomedom;
                   1385:             }
1.1129    raeburn  1386:         }
                   1387:     } else {
                   1388:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1389:             $is_balancer = 1;
                   1390:             $offloadto = &this_host_spares($dom_in_use);
                   1391:         }
1.1172.2.75  raeburn  1392:         unless (defined($cached)) {
                   1393:             $domneedscache = $serverhomedom;
                   1394:         }
                   1395:     }
                   1396:     if ($domneedscache) {
                   1397:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1398:     }
1.1172.2.5  raeburn  1399:     if ($is_balancer) {
                   1400:         my $lowest_load = 30000;
                   1401:         if (ref($offloadto) eq 'HASH') {
                   1402:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1403:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1404:                     ($otherserver,$lowest_load) =
                   1405:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1406:                 }
1.1129    raeburn  1407:             }
1.1172.2.5  raeburn  1408:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1409: 
1.1172.2.5  raeburn  1410:             if (!$found_server) {
                   1411:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1412:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1413:                         ($otherserver,$lowest_load) =
                   1414:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1415:                     }
                   1416:                 }
                   1417:             }
                   1418:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1419:             if (@{$offloadto} == 1) {
                   1420:                 $otherserver = $offloadto->[0];
                   1421:             } elsif (@{$offloadto} > 1) {
                   1422:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1423:                     ($otherserver,$lowest_load) =
                   1424:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1425:                 }
                   1426:             }
                   1427:         }
1.1172.2.5  raeburn  1428:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1429:             $is_balancer = 0;
                   1430:             if ($uname ne '' && $udom ne '') {
                   1431:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1432: 
                   1433:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1434:                              'user.loadbalcheck.time' => time});
                   1435:                 }
1.1129    raeburn  1436:             }
                   1437:         }
                   1438:     }
                   1439:     return ($is_balancer,$otherserver);
                   1440: }
                   1441: 
1.1172.2.12  raeburn  1442: sub check_balancer_result {
                   1443:     my ($result,@hosts) = @_;
                   1444:     my ($is_balancer,$currtargets,$currrules);
                   1445:     if (ref($result) eq 'HASH') {
                   1446:         if ($result->{'lonhost'} ne '') {
                   1447:             my $currbalancer = $result->{'lonhost'};
                   1448:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1449:                 $is_balancer = 1;
                   1450:                 $currtargets = $result->{'targets'};
                   1451:                 $currrules = $result->{'rules'};
                   1452:             }
                   1453:         } else {
                   1454:             foreach my $key (keys(%{$result})) {
                   1455:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1456:                     (ref($result->{$key}) eq 'HASH')) {
                   1457:                     $is_balancer = 1;
                   1458:                     $currrules = $result->{$key}{'rules'};
                   1459:                     $currtargets = $result->{$key}{'targets'};
                   1460:                     last;
                   1461:                 }
                   1462:             }
                   1463:         }
                   1464:     }
                   1465:     return ($is_balancer,$currtargets,$currrules);
                   1466: }
                   1467: 
1.1129    raeburn  1468: sub get_loadbalancer_targets {
                   1469:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1470:     my $offloadto;
1.1172.2.4  raeburn  1471:     if ($rule_in_effect eq 'none') {
                   1472:         return [$perlvar{'lonHostID'}];
                   1473:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1474:         $offloadto = $currtargets;
                   1475:     } else {
                   1476:         if ($rule_in_effect eq 'homeserver') {
                   1477:             my $homeserver = &homeserver($uname,$udom);
                   1478:             if ($homeserver ne 'no_host') {
                   1479:                 $offloadto = [$homeserver];
                   1480:             }
                   1481:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1482:             my %domconfig =
                   1483:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1484:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1485:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1486:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1487:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1488:                     }
                   1489:                 }
                   1490:             } else {
1.1172.2.7  raeburn  1491:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1492:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1493:                 if (&hostname($remotebalancer) ne '') {
                   1494:                     $offloadto = [$remotebalancer];
                   1495:                 }
                   1496:             }
                   1497:         } elsif (&hostname($rule_in_effect) ne '') {
                   1498:             $offloadto = [$rule_in_effect];
                   1499:         }
                   1500:     }
                   1501:     return $offloadto;
                   1502: }
                   1503: 
1.1127    raeburn  1504: sub internet_dom_servers {
                   1505:     my ($dom) = @_;
                   1506:     my (%uniqservers,%servers);
                   1507:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1508:     my @machinedoms = &machine_domains($primaryserver);
                   1509:     foreach my $mdom (@machinedoms) {
                   1510:         my %currservers = %servers;
                   1511:         my %server = &get_servers($mdom);
                   1512:         %servers = (%currservers,%server);
                   1513:     }
                   1514:     my %by_hostname;
                   1515:     foreach my $id (keys(%servers)) {
                   1516:         push(@{$by_hostname{$servers{$id}}},$id);
                   1517:     }
                   1518:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1519:         if (@{$by_hostname{$hostname}} > 1) {
                   1520:             my $match = 0;
                   1521:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1522:                 if (&host_domain($id) eq $dom) {
                   1523:                     $uniqservers{$id} = $hostname;
                   1524:                     $match = 1;
                   1525:                 }
                   1526:             }
                   1527:             unless ($match) {
                   1528:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1529:             }
                   1530:         } else {
                   1531:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1532:         }
                   1533:     }
                   1534:     return %uniqservers;
                   1535: }
                   1536: 
1.1       albertel 1537: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1538: 
1.599     albertel 1539: my %homecache;
1.1       albertel 1540: sub homeserver {
1.230     stredwic 1541:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1542:     my $index="$uname:$udom";
1.426     albertel 1543: 
1.599     albertel 1544:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1545: 
                   1546:     my %servers = &get_servers($udom,'library');
                   1547:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1548:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1549: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1550: 
                   1551: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1552: 	if ($answer eq 'found') {
                   1553: 	    delete($badServerCache{$tryserver}); 
                   1554: 	    return $homecache{$index}=$tryserver;
                   1555: 	} elsif ($answer eq 'no_host') {
                   1556: 	    $badServerCache{$tryserver}=1;
                   1557: 	}
1.1       albertel 1558:     }    
                   1559:     return 'no_host';
1.70      www      1560: }
                   1561: 
                   1562: # ------------------------------------- Find the usernames behind a list of IDs
                   1563: 
                   1564: sub idget {
                   1565:     my ($udom,@ids)=@_;
                   1566:     my %returnhash=();
                   1567:     
1.841     albertel 1568:     my %servers = &get_servers($udom,'library');
                   1569:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1570: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1571: 	$idlist=~tr/A-Z/a-z/; 
                   1572: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1573: 	my @answer=();
                   1574: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1575: 	    @answer=split(/\&/,$reply);
                   1576: 	}                    ;
                   1577: 	my $i;
                   1578: 	for ($i=0;$i<=$#ids;$i++) {
                   1579: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1580: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1581: 	    } 
                   1582: 	}
                   1583:     } 
1.70      www      1584:     return %returnhash;
                   1585: }
                   1586: 
                   1587: # ------------------------------------- Find the IDs behind a list of usernames
                   1588: 
                   1589: sub idrget {
                   1590:     my ($udom,@unames)=@_;
                   1591:     my %returnhash=();
1.800     albertel 1592:     foreach my $uname (@unames) {
                   1593:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1594:     }
1.70      www      1595:     return %returnhash;
                   1596: }
                   1597: 
                   1598: # ------------------------------- Store away a list of names and associated IDs
                   1599: 
                   1600: sub idput {
                   1601:     my ($udom,%ids)=@_;
                   1602:     my %servers=();
1.800     albertel 1603:     foreach my $uname (keys(%ids)) {
                   1604: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1605:         my $uhom=&homeserver($uname,$udom);
1.70      www      1606:         if ($uhom ne 'no_host') {
1.800     albertel 1607:             my $id=&escape($ids{$uname});
1.70      www      1608:             $id=~tr/A-Z/a-z/;
1.800     albertel 1609:             my $esc_unam=&escape($uname);
1.70      www      1610: 	    if ($servers{$uhom}) {
1.800     albertel 1611: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1612:             } else {
1.800     albertel 1613:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1614:             }
                   1615:         }
1.191     harris41 1616:     }
1.800     albertel 1617:     foreach my $server (keys(%servers)) {
                   1618:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1619:     }
1.344     www      1620: }
                   1621: 
1.1172.2.30  raeburn  1622: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1623: 
                   1624: sub iddel {
                   1625:     my ($udom,$idshashref,$uhome)=@_;
                   1626:     my %result=();
                   1627:     unless (ref($idshashref) eq 'HASH') {
                   1628:         return %result;
                   1629:     }
                   1630:     my %servers=();
                   1631:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1632:         my $uhom;
                   1633:         if ($uhome) {
                   1634:             $uhom = $uhome;
                   1635:         } else {
                   1636:             $uhom=&homeserver($uname,$udom);
                   1637:         }
                   1638:         if ($uhom ne 'no_host') {
                   1639:             if ($servers{$uhom}) {
                   1640:                 $servers{$uhom}.='&'.&escape($id);
                   1641:             } else {
                   1642:                 $servers{$uhom}=&escape($id);
                   1643:             }
                   1644:         }
                   1645:     }
                   1646:     foreach my $server (keys(%servers)) {
                   1647:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1648:     }
                   1649:     return %result;
                   1650: }
                   1651: 
1.1023    raeburn  1652: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1653: sub dump_dom {
1.1165    droeschl 1654:     my ($namespace, $udom, $regexp) = @_;
                   1655: 
                   1656:     $udom ||= $env{'user.domain'};
                   1657: 
                   1658:     return () unless $udom;
                   1659: 
                   1660:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1661: }
                   1662: 
1.1023    raeburn  1663: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1664: 
                   1665: sub get_dom {
1.860     raeburn  1666:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1667:     return if ($udom eq 'public');
1.806     raeburn  1668:     my $items='';
                   1669:     foreach my $item (@$storearr) {
                   1670:         $items.=&escape($item).'&';
                   1671:     }
                   1672:     $items=~s/\&$//;
1.860     raeburn  1673:     if (!$udom) {
                   1674:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1675:         return if ($udom eq 'public');
1.860     raeburn  1676:         if (defined(&domain($udom,'primary'))) {
                   1677:             $uhome=&domain($udom,'primary');
                   1678:         } else {
1.874     albertel 1679:             undef($uhome);
1.860     raeburn  1680:         }
                   1681:     } else {
                   1682:         if (!$uhome) {
                   1683:             if (defined(&domain($udom,'primary'))) {
                   1684:                 $uhome=&domain($udom,'primary');
                   1685:             }
                   1686:         }
                   1687:     }
                   1688:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1689:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1690:         my %returnhash;
1.875     albertel 1691:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1692:             return %returnhash;
                   1693:         }
1.806     raeburn  1694:         my @pairs=split(/\&/,$rep);
                   1695:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1696:             return @pairs;
                   1697:         }
                   1698:         my $i=0;
                   1699:         foreach my $item (@$storearr) {
                   1700:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1701:             $i++;
                   1702:         }
                   1703:         return %returnhash;
                   1704:     } else {
1.880     banghart 1705:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1706:     }
                   1707: }
                   1708: 
                   1709: # -------------------------------------------- put items in domain db files 
                   1710: 
                   1711: sub put_dom {
1.860     raeburn  1712:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1713:     if (!$udom) {
                   1714:         $udom=$env{'user.domain'};
                   1715:         if (defined(&domain($udom,'primary'))) {
                   1716:             $uhome=&domain($udom,'primary');
                   1717:         } else {
1.874     albertel 1718:             undef($uhome);
1.860     raeburn  1719:         }
                   1720:     } else {
                   1721:         if (!$uhome) {
                   1722:             if (defined(&domain($udom,'primary'))) {
                   1723:                 $uhome=&domain($udom,'primary');
                   1724:             }
                   1725:         }
                   1726:     } 
                   1727:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1728:         my $items='';
                   1729:         foreach my $item (keys(%$storehash)) {
                   1730:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1731:         }
                   1732:         $items=~s/\&$//;
                   1733:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1734:     } else {
1.860     raeburn  1735:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1736:     }
                   1737: }
                   1738: 
1.1023    raeburn  1739: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1740: sub newput_dom {
1.1023    raeburn  1741:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1742:     my $result;
                   1743:     if (!$udom) {
                   1744:         $udom=$env{'user.domain'};
                   1745:     }
1.1023    raeburn  1746:     if ($udom) {
                   1747:         my $uname = &get_domainconfiguser($udom);
                   1748:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1749:     }
                   1750:     return $result;
                   1751: }
                   1752: 
1.1023    raeburn  1753: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1754: sub del_dom {
1.1023    raeburn  1755:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1756:     if (ref($storearr) eq 'ARRAY') {
                   1757:         if (!$udom) {
                   1758:             $udom=$env{'user.domain'};
                   1759:         }
1.1023    raeburn  1760:         if ($udom) {
                   1761:             my $uname = &get_domainconfiguser($udom); 
                   1762:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1763:         }
                   1764:     }
                   1765: }
                   1766: 
1.1023    raeburn  1767: # ----------------------------------construct domainconfig user for a domain 
                   1768: sub get_domainconfiguser {
                   1769:     my ($udom) = @_;
                   1770:     return $udom.'-domainconfig';
                   1771: }
                   1772: 
1.837     raeburn  1773: sub retrieve_inst_usertypes {
                   1774:     my ($udom) = @_;
                   1775:     my (%returnhash,@order);
1.989     raeburn  1776:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1777:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1778:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1779:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1780:     } else {
                   1781:         if (defined(&domain($udom,'primary'))) {
                   1782:             my $uhome=&domain($udom,'primary');
                   1783:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1784:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1785:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1786:                 return (\%returnhash,\@order);
                   1787:             }
                   1788:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1789:             my @pairs=split(/\&/,$hashitems);
                   1790:             foreach my $item (@pairs) {
                   1791:                 my ($key,$value)=split(/=/,$item,2);
                   1792:                 $key = &unescape($key);
                   1793:                 next if ($key =~ /^error: 2 /);
                   1794:                 $returnhash{$key}=&thaw_unescape($value);
                   1795:             }
                   1796:             my @esc_order = split(/\&/,$orderitems);
                   1797:             foreach my $item (@esc_order) {
                   1798:                 push(@order,&unescape($item));
                   1799:             }
                   1800:         } else {
1.1172.2.44  raeburn  1801:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1802:         }
1.1172.2.44  raeburn  1803:         return (\%returnhash,\@order);
1.837     raeburn  1804:     }
                   1805: }
                   1806: 
1.868     raeburn  1807: sub is_domainimage {
                   1808:     my ($url) = @_;
1.1172.2.74  raeburn  1809:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1810:         if (&domain($1) ne '') {
                   1811:             return '1';
                   1812:         }
                   1813:     }
                   1814:     return;
                   1815: }
                   1816: 
1.899     raeburn  1817: sub inst_directory_query {
                   1818:     my ($srch) = @_;
                   1819:     my $udom = $srch->{'srchdomain'};
                   1820:     my %results;
                   1821:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1822:     my $outcome;
1.899     raeburn  1823:     if ($homeserver ne '') {
1.904     albertel 1824: 	my $queryid=&reply("querysend:instdirsearch:".
                   1825: 			   &escape($srch->{'srchby'}).':'.
                   1826: 			   &escape($srch->{'srchterm'}).':'.
                   1827: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1828: 	my $host=&hostname($homeserver);
                   1829: 	if ($queryid !~/^\Q$host\E\_/) {
                   1830: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1831: 	    return;
                   1832: 	}
                   1833: 	my $response = &get_query_reply($queryid);
                   1834: 	my $maxtries = 5;
                   1835: 	my $tries = 1;
                   1836: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1837: 	    $response = &get_query_reply($queryid);
                   1838: 	    $tries ++;
                   1839: 	}
                   1840: 
                   1841:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1842:             if ($response eq 'unavailable') {
                   1843:                 $outcome = $response;
                   1844:             } else {
                   1845:                 $outcome = 'ok';
                   1846:                 my @matches = split(/\n/,$response);
                   1847:                 foreach my $match (@matches) {
                   1848:                     my ($key,$value) = split(/=/,$match);
                   1849:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1850:                 }
1.899     raeburn  1851:             }
                   1852:         }
                   1853:     }
1.909     raeburn  1854:     return ($outcome,%results);
1.899     raeburn  1855: }
                   1856: 
                   1857: sub usersearch {
                   1858:     my ($srch) = @_;
                   1859:     my $dom = $srch->{'srchdomain'};
                   1860:     my %results;
                   1861:     my %libserv = &all_library();
                   1862:     my $query = 'usersearch';
                   1863:     foreach my $tryserver (keys(%libserv)) {
                   1864:         if (&host_domain($tryserver) eq $dom) {
                   1865:             my $host=&hostname($tryserver);
                   1866:             my $queryid=
1.911     raeburn  1867:                 &reply("querysend:".&escape($query).':'.
                   1868:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1869:                        &escape($srch->{'srchtype'}).':'.
                   1870:                        &escape($srch->{'srchterm'}),$tryserver);
                   1871:             if ($queryid !~/^\Q$host\E\_/) {
                   1872:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1873:                 next;
1.899     raeburn  1874:             }
                   1875:             my $reply = &get_query_reply($queryid);
                   1876:             my $maxtries = 1;
                   1877:             my $tries = 1;
                   1878:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1879:                 $reply = &get_query_reply($queryid);
                   1880:                 $tries ++;
                   1881:             }
                   1882:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1883:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1884:             } else {
1.911     raeburn  1885:                 my @matches;
                   1886:                 if ($reply =~ /\n/) {
                   1887:                     @matches = split(/\n/,$reply);
                   1888:                 } else {
                   1889:                     @matches = split(/\&/,$reply);
                   1890:                 }
1.899     raeburn  1891:                 foreach my $match (@matches) {
                   1892:                     my ($uname,$udom,%userhash);
1.911     raeburn  1893:                     foreach my $entry (split(/:/,$match)) {
                   1894:                         my ($key,$value) =
                   1895:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1896:                         $userhash{$key} = $value;
                   1897:                         if ($key eq 'username') {
                   1898:                             $uname = $value;
                   1899:                         } elsif ($key eq 'domain') {
                   1900:                             $udom = $value;
1.911     raeburn  1901:                         }
1.899     raeburn  1902:                     }
                   1903:                     $results{$uname.':'.$udom} = \%userhash;
                   1904:                 }
                   1905:             }
                   1906:         }
                   1907:     }
                   1908:     return %results;
                   1909: }
                   1910: 
1.912     raeburn  1911: sub get_instuser {
                   1912:     my ($udom,$uname,$id) = @_;
                   1913:     my $homeserver = &domain($udom,'primary');
                   1914:     my ($outcome,%results);
                   1915:     if ($homeserver ne '') {
                   1916:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1917:                            &escape($id).':'.&escape($udom),$homeserver);
                   1918:         my $host=&hostname($homeserver);
                   1919:         if ($queryid !~/^\Q$host\E\_/) {
                   1920:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1921:             return;
                   1922:         }
                   1923:         my $response = &get_query_reply($queryid);
                   1924:         my $maxtries = 5;
                   1925:         my $tries = 1;
                   1926:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1927:             $response = &get_query_reply($queryid);
                   1928:             $tries ++;
                   1929:         }
                   1930:         if (!&error($response) && $response ne 'refused') {
                   1931:             if ($response eq 'unavailable') {
                   1932:                 $outcome = $response;
                   1933:             } else {
                   1934:                 $outcome = 'ok';
                   1935:                 my @matches = split(/\n/,$response);
                   1936:                 foreach my $match (@matches) {
                   1937:                     my ($key,$value) = split(/=/,$match);
                   1938:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1939:                 }
                   1940:             }
                   1941:         }
                   1942:     }
                   1943:     my %userinfo;
                   1944:     if (ref($results{$uname}) eq 'HASH') {
                   1945:         %userinfo = %{$results{$uname}};
                   1946:     } 
                   1947:     return ($outcome,%userinfo);
                   1948: }
                   1949: 
1.1172.2.69  raeburn  1950: sub get_multiple_instusers {
                   1951:     my ($udom,$users,$caller) = @_;
                   1952:     my ($outcome,$results);
                   1953:     if (ref($users) eq 'HASH') {
                   1954:         my $count = keys(%{$users});
                   1955:         my $requested = &freeze_escape($users);
                   1956:         my $homeserver = &domain($udom,'primary');
                   1957:         if ($homeserver ne '') {
                   1958:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   1959:             my $host=&hostname($homeserver);
                   1960:             if ($queryid !~/^\Q$host\E\_/) {
                   1961:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   1962:                          ' for host: '.$homeserver.'in domain '.$udom);
                   1963:                 return ($outcome,$results);
                   1964:             }
                   1965:             my $response = &get_query_reply($queryid);
                   1966:             my $maxtries = 5;
                   1967:             if ($count > 100) {
                   1968:                 $maxtries = 1+int($count/20);
                   1969:             }
                   1970:             my $tries = 1;
                   1971:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   1972:                 $response = &get_query_reply($queryid);
                   1973:                 $tries ++;
                   1974:             }
                   1975:             if ($response eq '') {
                   1976:                 $results = {};
                   1977:                 foreach my $key (keys(%{$users})) {
                   1978:                     my ($uname,$id);
                   1979:                     if ($caller eq 'id') {
                   1980:                         $id = $key;
                   1981:                     } else {
                   1982:                         $uname = $key;
                   1983:                     }
                   1984:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   1985:                     $outcome = $resp;
                   1986:                     if ($resp eq 'ok') {
                   1987:                         %{$results} = (%{$results}, %info);
                   1988:                     } else {
                   1989:                         last;
                   1990:                     }
                   1991:                 }
                   1992:             } elsif(!&error($response) && ($response ne 'refused')) {
                   1993:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   1994:                     $outcome = $response;
                   1995:                 } else {
                   1996:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   1997:                     if ($outcome eq 'ok') {
                   1998:                         $results = &thaw_unescape($userdata);
                   1999:                     }
                   2000:                 }
                   2001:             }
                   2002:         }
                   2003:     }
                   2004:     return ($outcome,$results);
                   2005: }
                   2006: 
1.912     raeburn  2007: sub inst_rulecheck {
1.923     raeburn  2008:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2009:     my %returnhash;
                   2010:     if ($udom ne '') {
                   2011:         if (ref($rules) eq 'ARRAY') {
                   2012:             @{$rules} = map {&escape($_);} (@{$rules});
                   2013:             my $rulestr = join(':',@{$rules});
                   2014:             my $homeserver=&domain($udom,'primary');
                   2015:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2016:                 my $response;
                   2017:                 if ($item eq 'username') {                
                   2018:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2019:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2020:                                               $homeserver));
1.923     raeburn  2021:                 } elsif ($item eq 'id') {
                   2022:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2023:                                               ':'.&escape($id).':'.$rulestr,
                   2024:                                               $homeserver));
1.945     raeburn  2025:                 } elsif ($item eq 'selfcreate') {
                   2026:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2027:                                                &escape($udom).':'.&escape($uname).
                   2028:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2029:                 }
1.912     raeburn  2030:                 if ($response ne 'refused') {
                   2031:                     my @pairs=split(/\&/,$response);
                   2032:                     foreach my $item (@pairs) {
                   2033:                         my ($key,$value)=split(/=/,$item,2);
                   2034:                         $key = &unescape($key);
                   2035:                         next if ($key =~ /^error: 2 /);
                   2036:                         $returnhash{$key}=&thaw_unescape($value);
                   2037:                     }
                   2038:                 }
                   2039:             }
                   2040:         }
                   2041:     }
                   2042:     return %returnhash;
                   2043: }
                   2044: 
                   2045: sub inst_userrules {
1.923     raeburn  2046:     my ($udom,$check) = @_;
1.912     raeburn  2047:     my (%ruleshash,@ruleorder);
                   2048:     if ($udom ne '') {
                   2049:         my $homeserver=&domain($udom,'primary');
                   2050:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2051:             my $response;
                   2052:             if ($check eq 'id') {
                   2053:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2054:                                  $homeserver);
1.943     raeburn  2055:             } elsif ($check eq 'email') {
                   2056:                 $response=&reply('instemailrules:'.&escape($udom),
                   2057:                                  $homeserver);
1.923     raeburn  2058:             } else {
                   2059:                 $response=&reply('instuserrules:'.&escape($udom),
                   2060:                                  $homeserver);
                   2061:             }
1.912     raeburn  2062:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2063:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2064:                 ($response ne 'no_such_host')) {
                   2065:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2066:                 my @pairs=split(/\&/,$hashitems);
                   2067:                 foreach my $item (@pairs) {
                   2068:                     my ($key,$value)=split(/=/,$item,2);
                   2069:                     $key = &unescape($key);
                   2070:                     next if ($key =~ /^error: 2 /);
                   2071:                     $ruleshash{$key}=&thaw_unescape($value);
                   2072:                 }
                   2073:                 my @esc_order = split(/\&/,$orderitems);
                   2074:                 foreach my $item (@esc_order) {
                   2075:                     push(@ruleorder,&unescape($item));
                   2076:                 }
                   2077:             }
                   2078:         }
                   2079:     }
                   2080:     return (\%ruleshash,\@ruleorder);
                   2081: }
                   2082: 
1.976     raeburn  2083: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2084: 
                   2085: sub get_domain_defaults {
1.1172.2.35  raeburn  2086:     my ($domain,$ignore_cache) = @_;
                   2087:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2088:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2089:     unless ($ignore_cache) {
                   2090:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2091:         if (defined($cached)) {
                   2092:             if (ref($result) eq 'HASH') {
                   2093:                 return %{$result};
                   2094:             }
1.943     raeburn  2095:         }
                   2096:     }
                   2097:     my %domdefaults;
                   2098:     my %domconfig =
1.989     raeburn  2099:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2100:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2101:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2102:                                   'requestauthor','selfenrollment',
1.1172.2.76  raeburn  2103:                                   'coursecategories','autoenroll'],$domain);
1.1172.2.41  raeburn  2104:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2105:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2106:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2107:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2108:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2109:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2110:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2111:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2112:     } else {
                   2113:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2114:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2115:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2116:     }
1.976     raeburn  2117:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2118:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2119:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2120:         } else {
                   2121:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2122:         }
1.1172.2.6  raeburn  2123:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2124:         foreach my $item (@usertools) {
                   2125:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2126:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2127:             }
                   2128:         }
1.1172.2.29  raeburn  2129:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2130:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2131:         }
1.976     raeburn  2132:     }
1.985     raeburn  2133:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2134:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2135:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2136:         }
                   2137:     }
1.1172.2.9  raeburn  2138:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2139:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2140:     }
1.989     raeburn  2141:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2142:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2143:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2144:         }
                   2145:     }
1.1047    raeburn  2146:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2147:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2148:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2149:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2150:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2151:         }
1.1172.2.41  raeburn  2152:         foreach my $type (@coursetypes) {
                   2153:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2154:                 unless ($type eq 'community') {
                   2155:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2156:                 }
                   2157:             }
                   2158:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2159:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2160:             }
1.1172.2.60  raeburn  2161:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2162:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2163:                     $domdefaults{$type.'postsubtimeout'} =
                   2164:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2165:                 }
                   2166:             }
1.1172.2.30  raeburn  2167:         }
1.1172.2.67  raeburn  2168:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2169:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2170:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2171:                 if (@clonecodes) {
                   2172:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2173:                 }
                   2174:             }
                   2175:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2176:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2177:         }
1.1047    raeburn  2178:     }
1.1073    raeburn  2179:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2180:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2181:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2182:         }
                   2183:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2184:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2185:         }
1.1172.2.62  raeburn  2186:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2187:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2188:         }
1.1073    raeburn  2189:     }
1.1172.2.41  raeburn  2190:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2191:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2192:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2193:                             'approval','limit');
                   2194:             foreach my $type (@coursetypes) {
                   2195:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2196:                     my @mgrdc = ();
                   2197:                     foreach my $item (@settings) {
                   2198:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2199:                             push(@mgrdc,$item);
                   2200:                         }
                   2201:                     }
                   2202:                     if (@mgrdc) {
                   2203:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2204:                     }
                   2205:                 }
                   2206:             }
                   2207:         }
                   2208:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2209:             foreach my $type (@coursetypes) {
                   2210:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2211:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2212:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2213:                     }
                   2214:                 }
                   2215:             }
                   2216:         }
                   2217:     }
1.1172.2.46  raeburn  2218:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2219:         $domdefaults{'catauth'} = 'std';
                   2220:         $domdefaults{'catunauth'} = 'std';
                   2221:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2222:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2223:         }
                   2224:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2225:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2226:         }
                   2227:     }
1.1172.2.76  raeburn  2228:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2229:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2230:     }
1.1172.2.23  raeburn  2231:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2232:     return %domdefaults;
                   2233: }
                   2234: 
1.344     www      2235: # --------------------------------------------------- Assign a key to a student
                   2236: 
                   2237: sub assign_access_key {
1.364     www      2238: #
                   2239: # a valid key looks like uname:udom#comments
                   2240: # comments are being appended
                   2241: #
1.498     www      2242:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2243:     $kdom=
1.620     albertel 2244:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2245:     $knum=
1.620     albertel 2246:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2247:     $cdom=
1.620     albertel 2248:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2249:     $cnum=
1.620     albertel 2250:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2251:     $udom=$env{'user.name'} unless (defined($udom));
                   2252:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2253:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2254:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2255:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2256:                                                   # assigned to this person
                   2257:                                                   # - this should not happen,
1.345     www      2258:                                                   # unless something went wrong
                   2259:                                                   # the first time around
                   2260: # ready to assign
1.364     www      2261:         $logentry=$1.'; '.$logentry;
1.496     www      2262:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2263:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2264: # key now belongs to user
1.346     www      2265: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2266:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2267:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2268:                 return 'ok';
                   2269:             } else {
                   2270:                 return 
                   2271:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2272: 	    }
                   2273:         } else {
                   2274:             return 'error: Could not assign key, try again later.';
                   2275:         }
1.364     www      2276:     } elsif (!$existing{$ckey}) {
1.345     www      2277: # the key does not exist
                   2278: 	return 'error: The key does not exist';
                   2279:     } else {
                   2280: # the key is somebody else's
                   2281: 	return 'error: The key is already in use';
                   2282:     }
1.344     www      2283: }
                   2284: 
1.364     www      2285: # ------------------------------------------ put an additional comment on a key
                   2286: 
                   2287: sub comment_access_key {
                   2288: #
                   2289: # a valid key looks like uname:udom#comments
                   2290: # comments are being appended
                   2291: #
                   2292:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2293:     $cdom=
1.620     albertel 2294:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2295:     $cnum=
1.620     albertel 2296:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2297:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2298:     if ($existing{$ckey}) {
                   2299:         $existing{$ckey}.='; '.$logentry;
                   2300: # ready to assign
1.367     www      2301:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2302:                                                  $cdom,$cnum) eq 'ok') {
                   2303: 	    return 'ok';
                   2304:         } else {
                   2305: 	    return 'error: Count not store comment.';
                   2306:         }
                   2307:     } else {
                   2308: # the key does not exist
                   2309: 	return 'error: The key does not exist';
                   2310:     }
                   2311: }
                   2312: 
1.344     www      2313: # ------------------------------------------------------ Generate a set of keys
                   2314: 
                   2315: sub generate_access_keys {
1.364     www      2316:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2317:     $cdom=
1.620     albertel 2318:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2319:     $cnum=
1.620     albertel 2320:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2321:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2322:     unless (($cdom) && ($cnum)) { return 0; }
                   2323:     if ($number>10000) { return 0; }
                   2324:     sleep(2); # make sure don't get same seed twice
                   2325:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2326:     my $total=0;
                   2327:     for (my $i=1;$i<=$number;$i++) {
                   2328:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2329:                   sprintf("%lx",int(100000*rand)).'-'.
                   2330:                   sprintf("%lx",int(100000*rand));
                   2331:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2332:        $newkey=~s/0/h/g; # and also 0 and O
                   2333:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2334:        if ($existing{$newkey}) {
                   2335:            $i--;
                   2336:        } else {
1.364     www      2337: 	  if (&put('accesskeys',
                   2338:               { $newkey => '# generated '.localtime().
1.620     albertel 2339:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2340:                            '; '.$logentry },
                   2341: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2342:               $total++;
                   2343: 	  }
                   2344:        }
                   2345:     }
1.620     albertel 2346:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2347:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2348:     return $total;
                   2349: }
                   2350: 
                   2351: # ------------------------------------------------------- Validate an accesskey
                   2352: 
                   2353: sub validate_access_key {
                   2354:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2355:     $cdom=
1.620     albertel 2356:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2357:     $cnum=
1.620     albertel 2358:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2359:     $udom=$env{'user.domain'} unless (defined($udom));
                   2360:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2361:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2362:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2363: }
                   2364: 
                   2365: # ------------------------------------- Find the section of student in a course
1.652     albertel 2366: sub devalidate_getsection_cache {
                   2367:     my ($udom,$unam,$courseid)=@_;
                   2368:     my $hashid="$udom:$unam:$courseid";
                   2369:     &devalidate_cache_new('getsection',$hashid);
                   2370: }
1.298     matthew  2371: 
1.815     albertel 2372: sub courseid_to_courseurl {
                   2373:     my ($courseid) = @_;
                   2374:     #already url style courseid
                   2375:     return $courseid if ($courseid =~ m{^/});
                   2376: 
                   2377:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2378: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2379: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2380: 	return "/$cdom/$cnum";
                   2381:     }
                   2382: 
                   2383:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2384:     if (exists($courseinfo{'num'})) {
                   2385: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2386:     }
                   2387: 
                   2388:     return undef;
                   2389: }
                   2390: 
1.298     matthew  2391: sub getsection {
                   2392:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2393:     my $cachetime=1800;
1.551     albertel 2394: 
                   2395:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2396:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2397:     if (defined($cached)) { return $result; }
                   2398: 
1.298     matthew  2399:     my %Pending; 
                   2400:     my %Expired;
                   2401:     #
                   2402:     # Each role can either have not started yet (pending), be active, 
                   2403:     #    or have expired.
                   2404:     #
                   2405:     # If there is an active role, we are done.
                   2406:     #
                   2407:     # If there is more than one role which has not started yet, 
                   2408:     #     choose the one which will start sooner
                   2409:     # If there is one role which has not started yet, return it.
                   2410:     #
                   2411:     # If there is more than one expired role, choose the one which ended last.
                   2412:     # If there is a role which has expired, return it.
                   2413:     #
1.815     albertel 2414:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2415:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2416:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2417:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2418:         my $section=$1;
                   2419:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2420:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2421:         my $now=time;
1.548     albertel 2422:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2423:             $Expired{$end}=$section;
                   2424:             next;
                   2425:         }
1.548     albertel 2426:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2427:             $Pending{$start}=$section;
                   2428:             next;
                   2429:         }
1.599     albertel 2430:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2431:     }
                   2432:     #
                   2433:     # Presumedly there will be few matching roles from the above
                   2434:     # loop and the sorting time will be negligible.
                   2435:     if (scalar(keys(%Pending))) {
                   2436:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2437:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2438:     } 
                   2439:     if (scalar(keys(%Expired))) {
                   2440:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2441:         my $time = pop(@sorted);
1.599     albertel 2442:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2443:     }
1.599     albertel 2444:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2445: }
1.70      www      2446: 
1.599     albertel 2447: sub save_cache {
                   2448:     &purge_remembered();
1.722     albertel 2449:     #&Apache::loncommon::validate_page();
1.620     albertel 2450:     undef(%env);
1.780     albertel 2451:     undef($env_loaded);
1.599     albertel 2452: }
1.452     albertel 2453: 
1.599     albertel 2454: my $to_remember=-1;
                   2455: my %remembered;
                   2456: my %accessed;
                   2457: my $kicks=0;
                   2458: my $hits=0;
1.849     albertel 2459: sub make_key {
                   2460:     my ($name,$id) = @_;
1.872     albertel 2461:     if (length($id) > 65 
                   2462: 	&& length(&escape($id)) > 200) {
                   2463: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2464:     }
1.849     albertel 2465:     return &escape($name.':'.$id);
                   2466: }
                   2467: 
1.599     albertel 2468: sub devalidate_cache_new {
                   2469:     my ($name,$id,$debug) = @_;
                   2470:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2471:     my $remembered_id=$name.':'.$id;
1.849     albertel 2472:     $id=&make_key($name,$id);
1.599     albertel 2473:     $memcache->delete($id);
1.1172.2.81  raeburn  2474:     delete($remembered{$remembered_id});
                   2475:     delete($accessed{$remembered_id});
1.599     albertel 2476: }
                   2477: 
                   2478: sub is_cached_new {
                   2479:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2480:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2481:                                      # keys in %remembered hash, which persists for
                   2482:                                      # duration of request (no restriction on key length).
                   2483:     if (exists($remembered{$remembered_id})) {
                   2484: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2485: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2486: 	$hits++;
1.1172.2.81  raeburn  2487: 	return ($remembered{$remembered_id},1);
1.599     albertel 2488:     }
1.1172.2.81  raeburn  2489:     $id=&make_key($name,$id);
1.599     albertel 2490:     my $value = $memcache->get($id);
                   2491:     if (!(defined($value))) {
                   2492: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2493: 	return (undef,undef);
1.416     albertel 2494:     }
1.599     albertel 2495:     if ($value eq '__undef__') {
                   2496: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2497: 	$value=undef;
                   2498:     }
1.1172.2.81  raeburn  2499:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2500:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2501:     return ($value,1);
                   2502: }
                   2503: 
                   2504: sub do_cache_new {
                   2505:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2506:     my $remembered_id=$name.':'.$id;
1.849     albertel 2507:     $id=&make_key($name,$id);
1.599     albertel 2508:     my $setvalue=$value;
                   2509:     if (!defined($setvalue)) {
                   2510: 	$setvalue='__undef__';
                   2511:     }
1.623     albertel 2512:     if (!defined($time) ) {
                   2513: 	$time=600;
                   2514:     }
1.599     albertel 2515:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2516:     my $result = $memcache->set($id,$setvalue,$time);
                   2517:     if (! $result) {
1.872     albertel 2518: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2519: 	$memcache->disconnect_all();
1.872     albertel 2520:     }
1.600     albertel 2521:     # need to make a copy of $value
1.1172.2.81  raeburn  2522:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2523:     return $value;
                   2524: }
                   2525: 
                   2526: sub make_room {
1.1172.2.81  raeburn  2527:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2528: 
1.1172.2.81  raeburn  2529:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2530:                                     : $value;
1.599     albertel 2531:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2532:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2533:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2534:     my $to_kick;
                   2535:     my $max_time=0;
                   2536:     foreach my $other (keys(%accessed)) {
                   2537: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2538: 	    $to_kick=$other;
                   2539: 	    $max_time=&tv_interval($accessed{$other});
                   2540: 	}
                   2541:     }
                   2542:     delete($remembered{$to_kick});
                   2543:     delete($accessed{$to_kick});
                   2544:     $kicks++;
                   2545:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2546:     return;
                   2547: }
                   2548: 
1.599     albertel 2549: sub purge_remembered {
1.604     albertel 2550:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2551:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2552:     undef(%remembered);
                   2553:     undef(%accessed);
1.428     albertel 2554: }
1.70      www      2555: # ------------------------------------- Read an entry from a user's environment
                   2556: 
                   2557: sub userenvironment {
                   2558:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2559:     my $items;
                   2560:     foreach my $item (@what) {
                   2561:         $items.=&escape($item).'&';
                   2562:     }
                   2563:     $items=~s/\&$//;
1.70      www      2564:     my %returnhash=();
1.1009    raeburn  2565:     my $uhome = &homeserver($unam,$udom);
                   2566:     unless ($uhome eq 'no_host') {
                   2567:         my @answer=split(/\&/, 
                   2568:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2569:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2570:             return %returnhash;
                   2571:         }
1.1009    raeburn  2572:         my $i;
                   2573:         for ($i=0;$i<=$#what;$i++) {
                   2574: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2575:         }
1.70      www      2576:     }
                   2577:     return %returnhash;
1.1       albertel 2578: }
                   2579: 
1.617     albertel 2580: # ---------------------------------------------------------- Get a studentphoto
                   2581: sub studentphoto {
                   2582:     my ($udom,$unam,$ext) = @_;
                   2583:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2584:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2585:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2586:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2587:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2588:             } else {
                   2589:                 my ($result,$perm_reqd)=
1.707     albertel 2590: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2591:                 if ($result eq 'ok') {
                   2592:                     if (!($perm_reqd eq 'yes')) {
                   2593:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2594:                     }
                   2595:                 }
                   2596:             }
                   2597:         }
                   2598:     } else {
                   2599:         my ($result,$perm_reqd) = 
1.707     albertel 2600: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2601:         if ($result eq 'ok') {
                   2602:             if (!($perm_reqd eq 'yes')) {
                   2603:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2604:             }
                   2605:         }
                   2606:     }
                   2607:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2608: }
                   2609: 
                   2610: sub retrievestudentphoto {
                   2611:     my ($udom,$unam,$ext,$type) = @_;
                   2612:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2613:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2614:     if ($ret eq 'ok') {
                   2615:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2616:         if ($type eq 'thumbnail') {
                   2617:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2618:         }
                   2619:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2620:         return $tokenurl;
                   2621:     } else {
                   2622:         if ($type eq 'thumbnail') {
                   2623:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2624:         } else { 
                   2625:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2626:         }
1.617     albertel 2627:     }
                   2628: }
                   2629: 
1.263     www      2630: # -------------------------------------------------------------------- New chat
                   2631: 
                   2632: sub chatsend {
1.724     raeburn  2633:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2634:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2635:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2636:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2637:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2638: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2639: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2640: }
                   2641: 
                   2642: # ------------------------------------------ Find current version of a resource
                   2643: 
                   2644: sub getversion {
                   2645:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2646:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2647:     return &currentversion(&filelocation('',$fname));
                   2648: }
                   2649: 
                   2650: sub currentversion {
                   2651:     my $fname=shift;
                   2652:     my $author=$fname;
                   2653:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2654:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2655:     my $home=&homeserver($uname,$udom);
1.292     www      2656:     if ($home eq 'no_host') { 
                   2657:         return -1; 
                   2658:     }
1.1112    www      2659:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2660:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2661: 	return -1;
                   2662:     }
1.1112    www      2663:     return $answer;
1.263     www      2664: }
                   2665: 
1.1111    www      2666: #
                   2667: # Return special version number of resource if set by override, empty otherwise
                   2668: #
                   2669: sub usedversion {
                   2670:     my $fname=shift;
                   2671:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2672:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2673:     if ($urlversion) { return $urlversion; }
                   2674:     return '';
                   2675: }
                   2676: 
1.1       albertel 2677: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2678: 
1.1       albertel 2679: sub subscribe {
                   2680:     my $fname=shift;
1.761     raeburn  2681:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2682:     $fname=~s/[\n\r]//g;
1.1       albertel 2683:     my $author=$fname;
                   2684:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2685:     my ($udom,$uname)=split(/\//,$author);
                   2686:     my $home=homeserver($uname,$udom);
1.335     albertel 2687:     if ($home eq 'no_host') {
                   2688:         return 'not_found';
1.1       albertel 2689:     }
                   2690:     my $answer=reply("sub:$fname",$home);
1.64      www      2691:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2692: 	$answer.=' by '.$home;
                   2693:     }
1.1       albertel 2694:     return $answer;
                   2695: }
                   2696:     
1.8       www      2697: # -------------------------------------------------------------- Replicate file
                   2698: 
                   2699: sub repcopy {
                   2700:     my $filename=shift;
1.23      www      2701:     $filename=~s/\/+/\//g;
1.1142    raeburn  2702:     my $londocroot = $perlvar{'lonDocRoot'};
                   2703:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2704:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2705:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2706: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2707: 	return &repcopy_userfile($filename);
                   2708:     }
1.532     albertel 2709:     $filename=~s/[\n\r]//g;
1.8       www      2710:     my $transname="$filename.in.transfer";
1.828     www      2711: # FIXME: this should flock
1.607     raeburn  2712:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2713:     my $remoteurl=subscribe($filename);
1.64      www      2714:     if ($remoteurl =~ /^con_lost by/) {
                   2715: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2716:            return 'unavailable';
1.8       www      2717:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2718: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2719: 	   return 'not_found';
1.64      www      2720:     } elsif ($remoteurl =~ /^rejected by/) {
                   2721: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2722:            return 'forbidden';
1.20      www      2723:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2724:            return 'ok';
1.8       www      2725:     } else {
1.290     www      2726:         my $author=$filename;
                   2727:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2728:         my ($udom,$uname)=split(/\//,$author);
                   2729:         my $home=homeserver($uname,$udom);
                   2730:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2731:            my @parts=split(/\//,$filename);
                   2732:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2733:            if ($path ne "$londocroot/res") {
1.8       www      2734:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2735: 	       return 'bad_request';
1.8       www      2736:            }
                   2737:            my $count;
                   2738:            for ($count=5;$count<$#parts;$count++) {
                   2739:                $path.="/$parts[$count]";
                   2740:                if ((-e $path)!=1) {
                   2741: 		   mkdir($path,0777);
                   2742:                }
                   2743:            }
                   2744:            my $ua=new LWP::UserAgent;
                   2745:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2746:            my $response=$ua->request($request,$transname);
                   2747:            if ($response->is_error()) {
                   2748: 	       unlink($transname);
                   2749:                my $message=$response->status_line;
1.672     albertel 2750:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2751:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2752:                return 'unavailable';
1.8       www      2753:            } else {
1.16      www      2754: 	       if ($remoteurl!~/\.meta$/) {
                   2755:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2756:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2757:                   if ($mresponse->is_error()) {
                   2758: 		      unlink($filename.'.meta');
                   2759:                       &logthis(
1.672     albertel 2760:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2761:                   }
                   2762: 	       }
1.8       www      2763:                rename($transname,$filename);
1.607     raeburn  2764:                return 'ok';
1.8       www      2765:            }
1.290     www      2766:        }
1.8       www      2767:     }
1.330     www      2768: }
                   2769: 
                   2770: # ------------------------------------------------ Get server side include body
                   2771: sub ssi_body {
1.381     albertel 2772:     my ($filelink,%form)=@_;
1.606     matthew  2773:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2774:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2775:     }
1.953     www      2776:     my $output='';
                   2777:     my $response;
1.980     raeburn  2778:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2779:        ($output,$response)=&externalssi($filelink);
1.953     www      2780:     } else {
1.1004    droeschl 2781:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2782:        $filelink .= 'inhibitmenu=yes';
1.953     www      2783:        ($output,$response)=&ssi($filelink,%form);
                   2784:     }
1.778     albertel 2785:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2786:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2787:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2788:     if (wantarray) {
                   2789:         return ($output, $response);
                   2790:     } else {
                   2791:         return $output;
                   2792:     }
1.8       www      2793: }
                   2794: 
1.15      www      2795: # --------------------------------------------------------- Server Side Include
                   2796: 
1.782     albertel 2797: sub absolute_url {
                   2798:     my ($host_name) = @_;
                   2799:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2800:     if ($host_name eq '') {
                   2801: 	$host_name = $ENV{'SERVER_NAME'};
                   2802:     }
                   2803:     return $protocol.$host_name;
                   2804: }
                   2805: 
1.942     foxr     2806: #
                   2807: #   Server side include.
                   2808: # Parameters:
                   2809: #  fn     Possibly encrypted resource name/id.
                   2810: #  form   Hash that describes how the rendering should be done
                   2811: #         and other things.
1.944     foxr     2812: # Returns:
1.950     raeburn  2813: #   Scalar context: The content of the response.
                   2814: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2815: #     
1.15      www      2816: sub ssi {
                   2817: 
1.944     foxr     2818:     my ($fn,%form)=@_;
1.15      www      2819:     my $ua=new LWP::UserAgent;
1.23      www      2820:     my $request;
1.711     albertel 2821: 
                   2822:     $form{'no_update_last_known'}=1;
1.895     albertel 2823:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2824:     if (%form) {
1.782     albertel 2825:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2826:       $request->content(join('&',map {
                   2827:             my $name = escape($_);
                   2828:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2829:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2830:             : &escape($form{$_}) );
                   2831:         } keys(%form)));
1.23      www      2832:     } else {
1.782     albertel 2833:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2834:     }
                   2835: 
1.15      www      2836:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2837:     my $response= $ua->request($request);
1.944     foxr     2838:     if (wantarray) {
1.1172.2.3  raeburn  2839: 	return ($response->content, $response);
1.944     foxr     2840:     } else {
1.1172.2.3  raeburn  2841: 	return $response->content;
1.942     foxr     2842:     }
1.324     www      2843: }
                   2844: 
                   2845: sub externalssi {
                   2846:     my ($url)=@_;
                   2847:     my $ua=new LWP::UserAgent;
                   2848:     my $request=new HTTP::Request('GET',$url);
                   2849:     my $response=$ua->request($request);
1.954     raeburn  2850:     if (wantarray) {
                   2851:         return ($response->content, $response);
                   2852:     } else {
                   2853:         return $response->content;
                   2854:     }
1.15      www      2855: }
1.254     www      2856: 
1.492     albertel 2857: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2858: 
                   2859: sub allowuploaded {
                   2860:     my ($srcurl,$url)=@_;
                   2861:     $url=&clutter(&declutter($url));
                   2862:     my $dir=$url;
                   2863:     $dir=~s/\/[^\/]+$//;
                   2864:     my %httpref=();
                   2865:     my $httpurl=&hreflocation('',$url);
                   2866:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2867:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2868: }
1.477     raeburn  2869: 
1.1172.2.13  raeburn  2870: #
                   2871: # Determine if the current user should be able to edit a particular resource,
                   2872: # when viewing in course context.
                   2873: # (a) When viewing resource used to determine if "Edit" item is included in
                   2874: #     Functions.
                   2875: # (b) When displaying folder contents in course editor, used to determine if
                   2876: #     "Edit" link will be displayed alongside resource.
                   2877: #
                   2878: #  input: six args -- filename (decluttered), course number, course domain,
                   2879: #                   url, symb (if registered) and group (if this is a group
                   2880: #                   item -- e.g., bulletin board, group page etc.).
                   2881: #  output: array of five scalars --
                   2882: #          $cfile -- url for file editing if editable on current server
                   2883: #          $home -- homeserver of resource (i.e., for author if published,
                   2884: #                                           or course if uploaded.).
                   2885: #          $switchserver --  1 if server switch will be needed.
                   2886: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2887: #          $forceview -- 1 if icon/link should be to go to view mode
                   2888: #
                   2889: 
                   2890: sub can_edit_resource {
                   2891:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2892:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2893: #
                   2894: # For aboutme pages user can only edit his/her own.
                   2895: #
                   2896:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2897:         my ($sdom,$sname) = ($1,$2);
                   2898:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2899:             $home = $env{'user.home'};
                   2900:             $cfile = $resurl;
                   2901:             if ($env{'form.forceedit'}) {
                   2902:                 $forceview = 1;
                   2903:             } else {
                   2904:                 $forceedit = 1;
                   2905:             }
                   2906:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2907:         } else {
                   2908:             return;
                   2909:         }
                   2910:     }
                   2911: 
                   2912:     if ($env{'request.course.id'}) {
                   2913:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2914:         if ($group ne '') {
                   2915: # if this is a group homepage or group bulletin board, check group privs
                   2916:             my $allowed = 0;
                   2917:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2918:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2919:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2920:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2921:                     $allowed = 1;
                   2922:                 }
                   2923:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2924:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2925:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2926:                     $allowed = 1;
                   2927:                 }
                   2928:             }
                   2929:             if ($allowed) {
                   2930:                 $home=&homeserver($cnum,$cdom);
                   2931:                 if ($env{'form.forceedit'}) {
                   2932:                     $forceview = 1;
                   2933:                 } else {
                   2934:                     $forceedit = 1;
                   2935:                 }
                   2936:                 $cfile = $resurl;
                   2937:             } else {
                   2938:                 return;
                   2939:             }
                   2940:         } else {
1.1172.2.15  raeburn  2941:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2942:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2943:                     return;
                   2944:                 }
                   2945:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2946: #
                   2947: # No edit allowed where CC has switched to student role.
                   2948: #
                   2949:                 return;
                   2950:             }
                   2951:         }
                   2952:     }
                   2953: 
                   2954:     if ($file ne '') {
                   2955:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2956:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2957:                 $uploaded = 1;
                   2958:                 $incourse = 1;
                   2959:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2960:                     $cfile = &hreflocation('',$file);
                   2961:                     if ($env{'form.forceedit'}) {
                   2962:                         $forceview = 1;
                   2963:                     } else {
                   2964:                         $forceedit = 1;
                   2965:                     }
                   2966:                 }
                   2967:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2968:                 $incourse = 1;
                   2969:                 if ($env{'form.forceedit'}) {
                   2970:                     $forceview = 1;
                   2971:                 } else {
                   2972:                     $forceedit = 1;
                   2973:                 }
                   2974:                 $cfile = $resurl;
                   2975:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2976:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2977:                     $incourse = 1;
                   2978:                     if ($env{'form.forceedit'}) {
                   2979:                         $forceview = 1;
                   2980:                     } else {
                   2981:                         $forceedit = 1;
                   2982:                     }
                   2983:                     $cfile = $resurl;
                   2984:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2985:                     $incourse = 1;
                   2986:                     $cfile = $resurl.'/smpedit';
                   2987:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2988:                     $incourse = 1;
                   2989:                     if ($env{'form.forceedit'}) {
                   2990:                         $forceview = 1;
                   2991:                     } else {
                   2992:                         $forceedit = 1;
                   2993:                     }
                   2994:                     $cfile = $resurl;
1.1172.2.15  raeburn  2995:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2996:                     $incourse = 1;
                   2997:                     if ($env{'form.forceedit'}) {
                   2998:                         $forceview = 1;
                   2999:                     } else {
                   3000:                         $forceedit = 1;
                   3001:                     }
                   3002:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3003:                 }
                   3004:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3005:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3006:                 if (&is_on_map($template)) {
                   3007:                     $incourse = 1;
                   3008:                     $forceview = 1;
                   3009:                     $cfile = $template;
                   3010:                 }
                   3011:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3012:                     $incourse = 1;
                   3013:                     if ($env{'form.forceedit'}) {
                   3014:                         $forceview = 1;
                   3015:                     } else {
                   3016:                         $forceedit = 1;
                   3017:                     }
                   3018:                     $cfile = $resurl;
                   3019:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3020:                 $incourse = 1;
                   3021:                 $forceview = 1;
                   3022:                 if ($symb) {
                   3023:                     my ($map,$id,$res)=&decode_symb($symb);
                   3024:                     $env{'request.symb'} = $symb;
                   3025:                     $cfile = &clutter($res);
                   3026:                 } else {
                   3027:                     $cfile = $env{'form.suppurl'};
                   3028:                     $cfile =~ s{^http://}{};
                   3029:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3030:                 }
1.1172.2.31  raeburn  3031:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3032:                 if ($env{'form.forceedit'}) {
                   3033:                     $forceview = 1;
                   3034:                 } else {
                   3035:                     $forceedit = 1;
                   3036:                 }
                   3037:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3038:             }
                   3039:         }
                   3040:         if ($uploaded || $incourse) {
                   3041:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3042:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3043:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3044:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3045:             # Check that the user has permission to edit this resource
                   3046:             my $setpriv = 1;
                   3047:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3048:             if (defined($cfudom)) {
                   3049:                 $home=&homeserver($cfuname,$cfudom);
                   3050:                 $cfile=$file;
                   3051:             }
                   3052:         }
                   3053:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3054:             (($home ne '') && ($home ne 'no_host'))) {
                   3055:             my @ids=&current_machine_ids();
                   3056:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3057:                 $switchserver=1;
                   3058:             }
                   3059:         }
                   3060:     }
                   3061:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3062: }
                   3063: 
                   3064: sub is_course_upload {
                   3065:     my ($file,$cnum,$cdom) = @_;
                   3066:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3067:     $uploadpath =~ s{^\/}{};
                   3068:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3069:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3070:         return 1;
                   3071:     }
                   3072:     return;
                   3073: }
                   3074: 
                   3075: sub in_course {
                   3076:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3077:     if ($hideprivileged) {
                   3078:         my $skipuser;
1.1172.2.23  raeburn  3079:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3080:         my @possdoms = ($cdom);
                   3081:         if ($coursehash{'checkforpriv'}) {
                   3082:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3083:         }
                   3084:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3085:             $skipuser = 1;
                   3086:             if ($coursehash{'nothideprivileged'}) {
                   3087:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3088:                     my $user;
                   3089:                     if ($item =~ /:/) {
                   3090:                         $user = $item;
                   3091:                     } else {
                   3092:                         $user = join(':',split(/[\@]/,$item));
                   3093:                     }
                   3094:                     if ($user eq $uname.':'.$udom) {
                   3095:                         undef($skipuser);
                   3096:                         last;
                   3097:                     }
                   3098:                 }
                   3099:             }
                   3100:             if ($skipuser) {
                   3101:                 return 0;
                   3102:             }
                   3103:         }
                   3104:     }
                   3105:     $type ||= 'any';
                   3106:     if (!defined($cdom) || !defined($cnum)) {
                   3107:         my $cid  = $env{'request.course.id'};
                   3108:         $cdom = $env{'course.'.$cid.'.domain'};
                   3109:         $cnum = $env{'course.'.$cid.'.num'};
                   3110:     }
                   3111:     my $typesref;
                   3112:     if (($type eq 'any') || ($type eq 'all')) {
                   3113:         $typesref = ['active','previous','future'];
                   3114:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3115:         $typesref = [$type];
                   3116:     }
                   3117:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3118:                               $typesref,undef,[$cdom]);
                   3119:     my ($tmp) = keys(%roles);
                   3120:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3121:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3122:     if (@course_roles > 0) {
                   3123:         return 1;
                   3124:     }
                   3125:     return 0;
                   3126: }
                   3127: 
1.478     albertel 3128: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3129: # input: action, courseID, current domain, intended
1.637     raeburn  3130: #        path to file, source of file, instruction to parse file for objects,
                   3131: #        ref to hash for embedded objects,
                   3132: #        ref to hash for codebase of java objects.
1.1095    raeburn  3133: #        reference to scalar to accommodate mime type determined
                   3134: #          from File::MMagic if $parser = parse.
1.637     raeburn  3135: #
1.485     raeburn  3136: # output: url to file (if action was uploaddoc), 
                   3137: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3138: #
1.478     albertel 3139: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3140: # course.
1.477     raeburn  3141: #
1.478     albertel 3142: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3143: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3144: #          course's home server.
1.477     raeburn  3145: #
1.478     albertel 3146: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3147: #          be copied from $source (current location) to 
                   3148: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3149: #         and will then be copied to
                   3150: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3151: #         course's home server.
1.485     raeburn  3152: #
1.481     raeburn  3153: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3154: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3155: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3156: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3157: #         in course's home server.
1.637     raeburn  3158: #
1.477     raeburn  3159: 
                   3160: sub process_coursefile {
1.1095    raeburn  3161:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3162:         $mimetype)=@_;
1.477     raeburn  3163:     my $fetchresult;
1.638     albertel 3164:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3165:     if ($action eq 'propagate') {
1.638     albertel 3166:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3167: 			     $home);
1.481     raeburn  3168:     } else {
1.477     raeburn  3169:         my $fpath = '';
                   3170:         my $fname = $file;
1.478     albertel 3171:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3172:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3173:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3174:         if ($action eq 'copy') {
                   3175:             if ($source eq '') {
                   3176:                 $fetchresult = 'no source file';
                   3177:                 return $fetchresult;
                   3178:             } else {
                   3179:                 my $destination = $filepath.'/'.$fname;
                   3180:                 rename($source,$destination);
                   3181:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3182:                                  $home);
1.481     raeburn  3183:             }
                   3184:         } elsif ($action eq 'uploaddoc') {
                   3185:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3186:             print $fh $env{'form.'.$source};
1.481     raeburn  3187:             close($fh);
1.637     raeburn  3188:             if ($parser eq 'parse') {
1.1024    raeburn  3189:                 my $mm = new File::MMagic;
1.1095    raeburn  3190:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3191:                 if ($type eq 'text/html') {
1.1024    raeburn  3192:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3193:                     unless ($parse_result eq 'ok') {
                   3194:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3195:                     }
1.637     raeburn  3196:                 }
1.1095    raeburn  3197:                 if (ref($mimetype)) {
                   3198:                     $$mimetype = $type;
                   3199:                 } 
1.637     raeburn  3200:             }
1.477     raeburn  3201:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3202:                                  $home);
1.481     raeburn  3203:             if ($fetchresult eq 'ok') {
                   3204:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3205:             } else {
                   3206:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3207:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3208:                 return '/adm/notfound.html';
                   3209:             }
1.477     raeburn  3210:         }
                   3211:     }
1.485     raeburn  3212:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3213:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3214:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3215:     }
                   3216:     return $fetchresult;
                   3217: }
                   3218: 
1.637     raeburn  3219: sub build_filepath {
                   3220:     my ($fpath) = @_;
                   3221:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3222:     unless ($fpath eq '') {
                   3223:         my @parts=split('/',$fpath);
                   3224:         foreach my $part (@parts) {
                   3225:             $filepath.= '/'.$part;
                   3226:             if ((-e $filepath)!=1) {
                   3227:                 mkdir($filepath,0777);
                   3228:             }
                   3229:         }
                   3230:     }
                   3231:     return $filepath;
                   3232: }
                   3233: 
                   3234: sub store_edited_file {
1.638     albertel 3235:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3236:     my $file = $primary_url;
                   3237:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3238:     my $fpath = '';
                   3239:     my $fname = $file;
                   3240:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3241:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3242:     my $filepath = &build_filepath($fpath);
                   3243:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3244:     print $fh $content;
                   3245:     close($fh);
1.638     albertel 3246:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3247:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3248: 			  $home);
1.637     raeburn  3249:     if ($$fetchresult eq 'ok') {
                   3250:         return '/uploaded/'.$fpath.'/'.$fname;
                   3251:     } else {
1.638     albertel 3252:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3253: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3254:         return '/adm/notfound.html';
                   3255:     }
                   3256: }
                   3257: 
1.531     albertel 3258: sub clean_filename {
1.831     albertel 3259:     my ($fname,$args)=@_;
1.315     www      3260: # Replace Windows backslashes by forward slashes
1.257     www      3261:     $fname=~s/\\/\//g;
1.831     albertel 3262:     if (!$args->{'keep_path'}) {
                   3263:         # Get rid of everything but the actual filename
                   3264: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3265:     }
1.315     www      3266: # Replace spaces by underscores
                   3267:     $fname=~s/\s+/\_/g;
                   3268: # Replace all other weird characters by nothing
1.831     albertel 3269:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3270: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3271: # numbers
                   3272:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3273:     return $fname;
                   3274: }
1.1051    raeburn  3275: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3276: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3277: # image with the same aspect ratio as the original, but with dimensions which do 
                   3278: # not exceed $resizewidth and $resizeheight.
                   3279:  
1.984     neumanie 3280: sub resizeImage {
1.1051    raeburn  3281:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3282:     my $ima = Image::Magick->new;
                   3283:     my $resized;
                   3284:     if (-e $img_path) {
                   3285:         $ima->Read($img_path);
                   3286:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3287:             my $width = $ima->Get('width');
                   3288:             my $height = $ima->Get('height');
                   3289:             if ($width > $resizewidth) {
                   3290: 	        my $factor = $width/$resizewidth;
                   3291:                 my $newheight = $height/$factor;
                   3292:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3293:                 $resized = 1;
                   3294:             }
                   3295:         }
                   3296:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3297:             my $width = $ima->Get('width');
                   3298:             my $height = $ima->Get('height');
                   3299:             if ($height > $resizeheight) {
                   3300:                 my $factor = $height/$resizeheight;
                   3301:                 my $newwidth = $width/$factor;
                   3302:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3303:                 $resized = 1;
                   3304:             }
                   3305:         }
                   3306:         if ($resized) {
                   3307:             $ima->Write($img_path);
                   3308:         }
                   3309:     }
                   3310:     return;
1.977     amueller 3311: }
                   3312: 
1.608     albertel 3313: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3314: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3315: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3316: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3317: #                                    canceloverwrite, or ''. 
                   3318: #                   if 'coursedoc': upload to the current course
                   3319: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3320: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3321: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3322: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3323: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3324: #        $allfiles - reference to hash for embedded objects
                   3325: #        $codebase - reference to hash for codebase of java objects
                   3326: #        $desuname - username for permanent storage of uploaded file
                   3327: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3328: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3329: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3330: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3331: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3332: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3333: #                    from File::MMagic.
1.858     raeburn  3334: # 
1.686     albertel 3335: # output: url of file in userspace, or error: <message> 
                   3336: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3337: 
1.531     albertel 3338: sub userfileupload {
1.1090    raeburn  3339:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3340:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3341:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3342:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3343:     $fname=&clean_filename($fname);
1.1090    raeburn  3344:     # See if there is anything left
1.257     www      3345:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3346:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3347:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3348:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3349:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3350:         my $now = time;
1.1090    raeburn  3351:         my $filepath;
1.1095    raeburn  3352:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3353:              $filepath = 'tmp/helprequests/'.$now;
                   3354:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3355:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3356:                          '_'.$env{'user.domain'}.'/pending';
                   3357:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3358:             my ($docuname,$docudom);
                   3359:             if ($destudom) {
                   3360:                 $docudom = $destudom;
                   3361:             } else {
                   3362:                 $docudom = $env{'user.domain'};
                   3363:             }
                   3364:             if ($destuname) {
                   3365:                 $docuname = $destuname;
                   3366:             } else {
                   3367:                 $docuname = $env{'user.name'};
                   3368:             }
                   3369:             if (exists($env{'form.group'})) {
                   3370:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3371:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3372:             }
                   3373:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3374:             if ($context eq 'canceloverwrite') {
                   3375:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3376:                 if (-e  $tempfile) {
                   3377:                     my @info = stat($tempfile);
                   3378:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3379:                         unlink($tempfile);
                   3380:                     }
                   3381:                 }
                   3382:                 return;
1.523     raeburn  3383:             }
                   3384:         }
1.1090    raeburn  3385:         # Create the directory if not present
1.741     raeburn  3386:         my @parts=split(/\//,$filepath);
                   3387:         my $fullpath = $perlvar{'lonDaemons'};
                   3388:         for (my $i=0;$i<@parts;$i++) {
                   3389:             $fullpath .= '/'.$parts[$i];
                   3390:             if ((-e $fullpath)!=1) {
                   3391:                 mkdir($fullpath,0777);
                   3392:             }
                   3393:         }
                   3394:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3395:         print $fh $env{'form.'.$formname};
                   3396:         close($fh);
1.1090    raeburn  3397:         if ($context eq 'existingfile') {
                   3398:             my @info = stat($fullpath.'/'.$fname);
                   3399:             return ($fullpath.'/'.$fname,$info[9]);
                   3400:         } else {
                   3401:             return $fullpath.'/'.$fname;
                   3402:         }
1.523     raeburn  3403:     }
1.995     raeburn  3404:     if ($subdir eq 'scantron') {
                   3405:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3406:     } else {
1.995     raeburn  3407:         $fname="$subdir/$fname";
                   3408:     }
1.1090    raeburn  3409:     if ($context eq 'coursedoc') {
1.638     albertel 3410: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3411: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3412:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3413:             return &finishuserfileupload($docuname,$docudom,
                   3414: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3415: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3416:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3417:         } else {
1.1172.2.21  raeburn  3418:             if ($env{'form.folder'}) {
                   3419:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3420:             }
1.638     albertel 3421:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3422: 				       $fname,$formname,$parser,
1.1095    raeburn  3423: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3424:         }
1.719     banghart 3425:     } elsif (defined($destuname)) {
                   3426:         my $docuname=$destuname;
                   3427:         my $docudom=$destudom;
1.860     raeburn  3428: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3429: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3430:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3431:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3432:     } else {
1.638     albertel 3433:         my $docuname=$env{'user.name'};
                   3434:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3435:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3436:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3437:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3438:         }
1.860     raeburn  3439: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3440: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3441:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3442:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3443:     }
1.271     www      3444: }
                   3445: 
                   3446: sub finishuserfileupload {
1.860     raeburn  3447:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3448:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3449:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3450:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3451:   
1.860     raeburn  3452:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3453:     $file=$fname;
                   3454:     if ($fname=~m|/|) {
                   3455:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3456: 	$path.=$fnamepath.'/';
                   3457:     }
1.259     www      3458:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3459:     my $count;
                   3460:     for ($count=4;$count<=$#parts;$count++) {
                   3461:         $filepath.="/$parts[$count]";
                   3462:         if ((-e $filepath)!=1) {
                   3463: 	    mkdir($filepath,0777);
                   3464:         }
                   3465:     }
1.984     neumanie 3466: 
1.258     www      3467: # Save the file
                   3468:     {
1.701     albertel 3469: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3470: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3471: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3472: 	    return '/adm/notfound.html';
                   3473: 	}
1.1090    raeburn  3474:         if ($context eq 'overwrite') {
1.1117    foxr     3475:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3476:             my $target = $filepath.'/'.$file;
                   3477:             if (-e $source) {
                   3478:                 my @info = stat($source);
                   3479:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3480:                     unless (&File::Copy::move($source,$target)) {
                   3481:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3482:                         return "Moving from $source failed";
                   3483:                     }
                   3484:                 } else {
                   3485:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3486:                 }
                   3487:             } else {
                   3488:                 return "Temporary file: $source missing";
                   3489:             }
                   3490:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3491: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3492: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3493: 	    return '/adm/notfound.html';
                   3494: 	}
1.570     albertel 3495: 	close(FH);
1.1051    raeburn  3496:         if ($resizewidth && $resizeheight) {
                   3497:             my $mm = new File::MMagic;
                   3498:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3499:             if ($mime_type =~ m{^image/}) {
                   3500: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3501:             }  
1.977     amueller 3502: 	}
1.258     www      3503:     }
1.1152    raeburn  3504:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3505:         if (ref($mimetype)) {
                   3506:             if ($$mimetype eq '') {
                   3507:                 my $mm = new File::MMagic;
                   3508:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3509:                 $$mimetype = $type;
                   3510:             }
                   3511:         }
                   3512:     }
1.637     raeburn  3513:     if ($parser eq 'parse') {
1.1152    raeburn  3514:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3515:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3516:                                                        $allfiles,$codebase);
                   3517:             unless ($parse_result eq 'ok') {
                   3518:                 &logthis('Failed to parse '.$filepath.$file.
                   3519: 	   	         ' for embedded media: '.$parse_result); 
                   3520:             }
1.637     raeburn  3521:         }
                   3522:     }
1.860     raeburn  3523:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3524:         my $input = $filepath.'/'.$file;
                   3525:         my $output = $filepath.'/'.'tn-'.$file;
                   3526:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3527:         system("convert -sample $thumbsize $input $output");
                   3528:         if (-e $filepath.'/'.'tn-'.$file) {
                   3529:             $fetchthumb  = 1; 
                   3530:         }
                   3531:     }
1.858     raeburn  3532:  
1.259     www      3533: # Notify homeserver to grep it
                   3534: #
1.984     neumanie 3535:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3536:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3537:     if ($fetchresult eq 'ok') {
1.860     raeburn  3538:         if ($fetchthumb) {
                   3539:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3540:             if ($thumbresult ne 'ok') {
                   3541:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3542:                          $docuhome.': '.$thumbresult);
                   3543:             }
                   3544:         }
1.259     www      3545: #
1.258     www      3546: # Return the URL to it
1.494     albertel 3547:         return '/uploaded/'.$path.$file;
1.263     www      3548:     } else {
1.494     albertel 3549:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3550: 		 ': '.$fetchresult);
1.263     www      3551:         return '/adm/notfound.html';
1.858     raeburn  3552:     }
1.493     albertel 3553: }
                   3554: 
1.637     raeburn  3555: sub extract_embedded_items {
1.961     raeburn  3556:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3557:     my @state = ();
1.1164    raeburn  3558:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3559:     my %javafiles = (
                   3560:                       codebase => '',
                   3561:                       code => '',
                   3562:                       archive => ''
                   3563:                     );
                   3564:     my %mediafiles = (
                   3565:                       src => '',
                   3566:                       movie => '',
                   3567:                      );
1.648     raeburn  3568:     my $p;
                   3569:     if ($content) {
                   3570:         $p = HTML::LCParser->new($content);
                   3571:     } else {
1.961     raeburn  3572:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3573:     }
1.641     albertel 3574:     while (my $t=$p->get_token()) {
1.640     albertel 3575: 	if ($t->[0] eq 'S') {
                   3576: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3577: 	    push(@state, $tagname);
1.648     raeburn  3578:             if (lc($tagname) eq 'allow') {
                   3579:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3580:             }
1.640     albertel 3581: 	    if (lc($tagname) eq 'img') {
                   3582: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3583: 	    }
1.886     albertel 3584: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3585:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3586: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3587:                 }
1.886     albertel 3588: 	    }
1.645     raeburn  3589:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3590:                 my $src;
1.645     raeburn  3591:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3592:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3593:                 } else {
1.1164    raeburn  3594:                     if ($attr->{'src'} ne '') {
                   3595:                         $src = $attr->{'src'};
                   3596:                         &add_filetype($allfiles,$src,'src');
                   3597:                     }
                   3598:                 }
                   3599:                 my $text = $p->get_trimmed_text();
                   3600:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3601:                     my @swfargs = split(/,/,$1);
                   3602:                     foreach my $item (@swfargs) {
                   3603:                         $item =~ s/["']//g;
                   3604:                         $item =~ s/^\s+//;
                   3605:                         $item =~ s/\s+$//;
                   3606:                     }
                   3607:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3608:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3609:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3610:                         } else {
                   3611:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3612:                         }
                   3613:                     }
1.645     raeburn  3614:                 }
                   3615:             }
                   3616:             if (lc($tagname) eq 'link') {
                   3617:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3618:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3619:                 }
                   3620:             }
1.640     albertel 3621: 	    if (lc($tagname) eq 'object' ||
                   3622: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3623: 		foreach my $item (keys(%javafiles)) {
                   3624: 		    $javafiles{$item} = '';
                   3625: 		}
1.1164    raeburn  3626:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3627:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3628:                 }
1.640     albertel 3629: 	    }
                   3630: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3631: 		my $name = lc($attr->{'name'});
                   3632: 		foreach my $item (keys(%javafiles)) {
                   3633: 		    if ($name eq $item) {
                   3634: 			$javafiles{$item} = $attr->{'value'};
                   3635: 			last;
                   3636: 		    }
                   3637: 		}
1.1164    raeburn  3638:                 my $pathfrom;
1.640     albertel 3639: 		foreach my $item (keys(%mediafiles)) {
                   3640: 		    if ($name eq $item) {
1.1164    raeburn  3641:                         $pathfrom = $attr->{'value'};
                   3642:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3643: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3644: 			last;
                   3645: 		    }
                   3646: 		}
1.1164    raeburn  3647:                 if ($name eq 'flashvars') {
                   3648:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3649:                 }
                   3650:                 if ($pathfrom ne '') {
                   3651:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3652:                                          $pathfrom);
                   3653:                 }
1.640     albertel 3654: 	    }
                   3655: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3656: 		foreach my $item (keys(%javafiles)) {
                   3657: 		    if ($attr->{$item}) {
                   3658: 			$javafiles{$item} = $attr->{$item};
                   3659: 			last;
                   3660: 		    }
                   3661: 		}
                   3662: 		foreach my $item (keys(%mediafiles)) {
                   3663: 		    if ($attr->{$item}) {
                   3664: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3665: 			last;
                   3666: 		    }
                   3667: 		}
1.1164    raeburn  3668:                 if (lc($tagname) eq 'embed') {
                   3669:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3670:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3671:                                              $attr->{'src'});
                   3672:                     }
                   3673:                 }
1.640     albertel 3674: 	    }
1.1172.2.35  raeburn  3675:             if (lc($tagname) eq 'iframe') {
                   3676:                 my $src = $attr->{'src'} ;
                   3677:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3678:                     &add_filetype($allfiles,$src,'src');
                   3679:                 } elsif ($src =~ m{^/}) {
                   3680:                     if ($env{'request.course.id'}) {
                   3681:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3682:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3683:                         my $url = &hreflocation('',$fullpath);
                   3684:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3685:                             my $relpath = $1;
                   3686:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3687:                                 &add_filetype($allfiles,$1,'src');
                   3688:                             }
                   3689:                         }
                   3690:                     }
                   3691:                 }
                   3692:             }
1.1164    raeburn  3693:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3694:                 pop(@state);
1.1164    raeburn  3695:             }
1.640     albertel 3696: 	} elsif ($t->[0] eq 'E') {
                   3697: 	    my ($tagname) = ($t->[1]);
                   3698: 	    if ($javafiles{'codebase'} ne '') {
                   3699: 		$javafiles{'codebase'} .= '/';
                   3700: 	    }  
                   3701: 	    if (lc($tagname) eq 'applet' ||
                   3702: 		lc($tagname) eq 'object' ||
                   3703: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3704: 		) {
                   3705: 		foreach my $item (keys(%javafiles)) {
                   3706: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3707: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3708: 			&add_filetype($allfiles,$file,$item);
                   3709: 		    }
                   3710: 		}
                   3711: 	    } 
                   3712: 	    pop @state;
                   3713: 	}
                   3714:     }
1.1164    raeburn  3715:     foreach my $id (sort(keys(%flashvars))) {
                   3716:         if ($shockwave{$id} ne '') {
                   3717:             my @pairs = split(/\&/,$flashvars{$id});
                   3718:             foreach my $pair (@pairs) {
                   3719:                 my ($key,$value) = split(/\=/,$pair);
                   3720:                 if ($key eq 'thumb') {
                   3721:                     &add_filetype($allfiles,$value,$key);
                   3722:                 } elsif ($key eq 'content') {
                   3723:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3724:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3725:                     if ($ext ne '') {
                   3726:                         &add_filetype($allfiles,$path.$value,$ext);
                   3727:                     }
                   3728:                 }
                   3729:             }
                   3730:         }
                   3731:     }
1.637     raeburn  3732:     return 'ok';
                   3733: }
                   3734: 
1.639     albertel 3735: sub add_filetype {
                   3736:     my ($allfiles,$file,$type)=@_;
                   3737:     if (exists($allfiles->{$file})) {
                   3738: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3739: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3740: 	}
                   3741:     } else {
                   3742: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3743:     }
                   3744: }
                   3745: 
1.1164    raeburn  3746: sub embedded_dependency {
                   3747:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3748:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3749:         if (($identifier ne '') &&
                   3750:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3751:             ($pathfrom ne '')) {
                   3752:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3753:             foreach my $dep (@{$related->{$identifier}}) {
                   3754:                 &add_filetype($allfiles,$path.$dep,'object');
                   3755:             }
                   3756:         }
                   3757:     }
                   3758:     return;
                   3759: }
                   3760: 
1.493     albertel 3761: sub removeuploadedurl {
1.984     neumanie 3762:     my ($url)=@_;	
                   3763:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3764:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3765: }
                   3766: 
                   3767: sub removeuserfile {
                   3768:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3769:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3770:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3771:     if ($result eq 'ok') {	
1.798     raeburn  3772:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3773:             my $metafile = $fname.'.meta';
                   3774:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3775: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3776:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3777:             my $sqlresult = 
1.823     albertel 3778:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3779:                                         'portfolio_metadata',$group,
                   3780:                                         'delete');
1.798     raeburn  3781:         }
                   3782:     }
                   3783:     return $result;
1.257     www      3784: }
1.15      www      3785: 
1.530     albertel 3786: sub mkdiruserfile {
                   3787:     my ($docuname,$docudom,$dir)=@_;
                   3788:     my $home=&homeserver($docuname,$docudom);
                   3789:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3790: }
                   3791: 
1.531     albertel 3792: sub renameuserfile {
                   3793:     my ($docuname,$docudom,$old,$new)=@_;
                   3794:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3795:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3796:                         &escape("$old").':'.&escape("$new"),$home);
                   3797:     if ($result eq 'ok') {
                   3798:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3799:             my $oldmeta = $old.'.meta';
                   3800:             my $newmeta = $new.'.meta';
                   3801:             my $metaresult = 
                   3802:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3803: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3804:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3805:             my $sqlresult = 
1.823     albertel 3806:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3807:                                         'portfolio_metadata',$group,
                   3808:                                         'delete');
1.798     raeburn  3809:         }
                   3810:     }
                   3811:     return $result;
1.531     albertel 3812: }
                   3813: 
1.14      www      3814: # ------------------------------------------------------------------------- Log
                   3815: 
                   3816: sub log {
                   3817:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3818:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3819: }
                   3820: 
                   3821: # ------------------------------------------------------------------ Course Log
1.352     www      3822: #
                   3823: # This routine flushes several buffers of non-mission-critical nature
                   3824: #
1.157     www      3825: 
                   3826: sub flushcourselogs {
1.352     www      3827:     &logthis('Flushing log buffers');
                   3828: #
                   3829: # course logs
                   3830: # This is a log of all transactions in a course, which can be used
                   3831: # for data mining purposes
                   3832: #
                   3833: # It also collects the courseid database, which lists last transaction
                   3834: # times and course titles for all courseids
                   3835: #
                   3836:     my %courseidbuffer=();
1.921     raeburn  3837:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3838:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3839: 		          &escape($courselogs{$crsid}),
                   3840: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3841: 	    delete $courselogs{$crsid};
                   3842:         } else {
                   3843:             &logthis('Failed to flush log buffer for '.$crsid);
                   3844:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3845:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3846:                         " exceeded maximum size, deleting.</font>");
                   3847:                delete $courselogs{$crsid};
                   3848:             }
1.352     www      3849:         }
1.920     raeburn  3850:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3851:             'description' => $coursedescrbuf{$crsid},
                   3852:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3853:             'type'        => $coursetypebuf{$crsid},
                   3854:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3855:         };
1.191     harris41 3856:     }
1.352     www      3857: #
                   3858: # Write course id database (reverse lookup) to homeserver of courses 
                   3859: # Is used in pickcourse
                   3860: #
1.840     albertel 3861:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3862:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3863:                                     $courseidbuffer{$crs_home},
                   3864:                                     $crs_home,'timeonly');
1.352     www      3865:     }
                   3866: #
                   3867: # File accesses
                   3868: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3869: #
1.449     matthew  3870:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3871:         if ($entry =~ /___count$/) {
                   3872:             my ($dom,$name);
1.807     albertel 3873:             ($dom,$name,undef)=
1.811     albertel 3874: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3875:             if (! defined($dom) || $dom eq '' || 
                   3876:                 ! defined($name) || $name eq '') {
1.620     albertel 3877:                 my $cid = $env{'request.course.id'};
                   3878:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3879:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3880:             }
1.450     matthew  3881:             my $value = $accesshash{$entry};
                   3882:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3883:             my %temphash=($url => $value);
1.449     matthew  3884:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3885:             if ($result eq 'ok') {
                   3886:                 delete $accesshash{$entry};
                   3887:             }
                   3888:         } else {
1.811     albertel 3889:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3890:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3891:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3892:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3893:                 delete $accesshash{$entry};
                   3894:             }
1.185     www      3895:         }
1.191     harris41 3896:     }
1.352     www      3897: #
                   3898: # Roles
                   3899: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3900: #
1.800     albertel 3901:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3902:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3903: 	    split(/\:/,$entry);
                   3904:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3905:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3906:                 $rudom,$runame) eq 'ok') {
                   3907: 	    delete $userrolehash{$entry};
                   3908:         }
                   3909:     }
1.662     raeburn  3910: #
1.1172.2.84  raeburn  3911: # Reverse lookup of domain roles (dc, ad, li, sc, dh, au)
1.662     raeburn  3912: #
                   3913:     my %domrolebuffer = ();
1.1000    raeburn  3914:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3915:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3916:         if ($domrolebuffer{$rudom}) {
                   3917:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3918:                       '='.&escape($domainrolehash{$entry});
                   3919:         } else {
                   3920:             $domrolebuffer{$rudom}.=&escape($entry).
                   3921:                       '='.&escape($domainrolehash{$entry});
                   3922:         }
                   3923:         delete $domainrolehash{$entry};
                   3924:     }
                   3925:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  3926:         my %servers;
                   3927:         if (defined(&domain($dom,'primary'))) {
                   3928:             my $primary=&domain($dom,'primary');
                   3929:             my $hostname=&hostname($primary);
                   3930:             $servers{$primary} = $hostname;
                   3931:         } else {
                   3932:             %servers = &get_servers($dom,'library');
                   3933:         }
1.841     albertel 3934: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  3935: 	    if (&reply('domroleput:'.$dom.':'.
                   3936: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3937: 	        last;
                   3938: 	    } else {
1.841     albertel 3939: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3940: 	    }
1.662     raeburn  3941:         }
                   3942:     }
1.186     www      3943:     $dumpcount++;
1.157     www      3944: }
                   3945: 
                   3946: sub courselog {
                   3947:     my $what=shift;
1.158     www      3948:     $what=time.':'.$what;
1.620     albertel 3949:     unless ($env{'request.course.id'}) { return ''; }
                   3950:     $coursedombuf{$env{'request.course.id'}}=
                   3951:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3952:     $coursenumbuf{$env{'request.course.id'}}=
                   3953:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3954:     $coursehombuf{$env{'request.course.id'}}=
                   3955:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3956:     $coursedescrbuf{$env{'request.course.id'}}=
                   3957:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3958:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3959:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3960:     $courseownerbuf{$env{'request.course.id'}}=
                   3961:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3962:     $coursetypebuf{$env{'request.course.id'}}=
                   3963:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3964:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3965: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3966:     } else {
1.620     albertel 3967: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3968:     }
1.620     albertel 3969:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3970: 	&flushcourselogs();
                   3971:     }
1.158     www      3972: }
                   3973: 
                   3974: sub courseacclog {
                   3975:     my $fnsymb=shift;
1.620     albertel 3976:     unless ($env{'request.course.id'}) { return ''; }
                   3977:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3978:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3979:         $what.=':POST';
1.583     matthew  3980:         # FIXME: Probably ought to escape things....
1.800     albertel 3981: 	foreach my $key (keys(%env)) {
                   3982:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3983:                 my $formitem = $1;
                   3984:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3985:                     $what.=':'.$formitem.'='.$env{$key};
                   3986:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3987:                     $what.=':'.$formitem.'='.$env{$key};
                   3988:                 }
1.158     www      3989:             }
1.191     harris41 3990:         }
1.583     matthew  3991:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3992:         # FIXME: We should not be depending on a form parameter that someone
                   3993:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3994:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3995:             $what.= ':POST';
                   3996:             # FIXME: Probably ought to escape things....
                   3997:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3998:                                  'crsdiscuss') {
1.620     albertel 3999:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4000:             }
                   4001:         }
1.158     www      4002:     }
                   4003:     &courselog($what);
1.149     www      4004: }
                   4005: 
1.185     www      4006: sub countacc {
                   4007:     my $url=&declutter(shift);
1.458     matthew  4008:     return if (! defined($url) || $url eq '');
1.620     albertel 4009:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4010: #
                   4011: # Mark that this url was used in this course
                   4012: #
1.620     albertel 4013:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4014: #
                   4015: # Increase the access count for this resource in this child process
                   4016: #
1.281     www      4017:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4018:     $accesshash{$key}++;
1.185     www      4019: }
1.349     www      4020: 
1.361     www      4021: sub linklog {
                   4022:     my ($from,$to)=@_;
                   4023:     $from=&declutter($from);
                   4024:     $to=&declutter($to);
                   4025:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4026:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4027: }
1.1160    www      4028: 
                   4029: sub statslog {
                   4030:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4031:     if ($users<2) { return; }
                   4032:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4033:             'course'       => $env{'request.course.id'},
                   4034:             'sections'     => '"all"',
                   4035:             'num_students' => $users,
                   4036:             'part'         => $part,
                   4037:             'symb'         => $symb,
                   4038:             'mean_tries'   => $av_attempts,
                   4039:             'deg_of_diff'  => $degdiff});
                   4040:     foreach my $key (keys(%dynstore)) {
                   4041:         $accesshash{$key}=$dynstore{$key};
                   4042:     }
                   4043: }
1.361     www      4044:   
1.349     www      4045: sub userrolelog {
                   4046:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4047:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4048:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4049:        $userrolehash
                   4050:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4051:                     =$tend.':'.$tstart;
1.662     raeburn  4052:     }
1.1169    droeschl 4053:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4054:        $userrolehash
                   4055:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4056:                     =$tend.':'.$tstart;
                   4057:     }
1.1172.2.84  raeburn  4058:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh)/ ) {
1.662     raeburn  4059:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4060:        $domainrolehash
                   4061:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4062:                     = $tend.':'.$tstart;
                   4063:     }
1.351     www      4064: }
                   4065: 
1.957     raeburn  4066: sub courserolelog {
                   4067:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4068:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4069:         my $cdom = $1;
                   4070:         my $cnum = $2;
                   4071:         my $sec = $3;
                   4072:         my $namespace = 'rolelog';
                   4073:         my %storehash = (
                   4074:                            role    => $trole,
                   4075:                            start   => $tstart,
                   4076:                            end     => $tend,
                   4077:                            selfenroll => $selfenroll,
                   4078:                            context    => $context,
                   4079:                         );
                   4080:         if ($trole eq 'gr') {
                   4081:             $namespace = 'groupslog';
                   4082:             $storehash{'group'} = $sec;
                   4083:         } else {
                   4084:             $storehash{'section'} = $sec;
                   4085:         }
                   4086:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4087:                    $domain,$cnum,$cdom);
                   4088:         if (($trole ne 'st') || ($sec ne '')) {
                   4089:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4090:         }
                   4091:     }
                   4092:     return;
                   4093: }
                   4094: 
1.1172.2.9  raeburn  4095: sub domainrolelog {
                   4096:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4097:     if ($area =~ m{^/($match_domain)/$}) {
                   4098:         my $cdom = $1;
                   4099:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4100:         my $namespace = 'rolelog';
                   4101:         my %storehash = (
                   4102:                            role    => $trole,
                   4103:                            start   => $tstart,
                   4104:                            end     => $tend,
                   4105:                            context => $context,
                   4106:                         );
                   4107:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4108:                    $domain,$domconfiguser,$cdom);
                   4109:     }
                   4110:     return;
                   4111: 
                   4112: }
                   4113: 
                   4114: sub coauthorrolelog {
                   4115:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4116:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4117:         my $audom = $1;
                   4118:         my $auname = $2;
                   4119:         my $namespace = 'rolelog';
                   4120:         my %storehash = (
                   4121:                            role    => $trole,
                   4122:                            start   => $tstart,
                   4123:                            end     => $tend,
                   4124:                            context => $context,
                   4125:                         );
                   4126:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4127:                    $domain,$auname,$audom);
                   4128:     }
                   4129:     return;
                   4130: }
                   4131: 
1.351     www      4132: sub get_course_adv_roles {
1.948     raeburn  4133:     my ($cid,$codes) = @_;
1.620     albertel 4134:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4135:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4136:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4137:     my %nothide=();
1.800     albertel 4138:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4139:         if ($user !~ /:/) {
                   4140: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4141:         } else {
                   4142:             $nothide{$user}=1;
                   4143:         }
1.470     www      4144:     }
1.1172.2.23  raeburn  4145:     my @possdoms = ($coursehash{'domain'});
                   4146:     if ($coursehash{'checkforpriv'}) {
                   4147:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4148:     }
1.351     www      4149:     my %returnhash=();
                   4150:     my %dumphash=
                   4151:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4152:     my $now=time;
1.997     raeburn  4153:     my %privileged;
1.1000    raeburn  4154:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4155: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4156:         if (($tstart) && ($tstart<0)) { next; }
                   4157:         if (($tend) && ($tend<$now)) { next; }
                   4158:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4159:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4160: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4161:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4162:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4163: 	if ($role eq 'cr') { next; }
1.948     raeburn  4164:         if ($codes) {
                   4165:             if ($section) { $role .= ':'.$section; }
                   4166:             if ($returnhash{$role}) {
                   4167:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4168:             } else {
                   4169:                 $returnhash{$role}=$username.':'.$domain;
                   4170:             }
1.351     www      4171:         } else {
1.988     raeburn  4172:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4173:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4174:             if ($returnhash{$key}) {
                   4175: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4176:             } else {
                   4177:                 $returnhash{$key}=$username.':'.$domain;
                   4178:             }
1.351     www      4179:         }
1.948     raeburn  4180:     }
1.400     www      4181:     return %returnhash;
                   4182: }
                   4183: 
                   4184: sub get_my_roles {
1.937     raeburn  4185:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4186:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4187:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4188:     my (%dumphash,%nothide);
1.1086    raeburn  4189:     if ($context eq 'userroles') {
1.1166    raeburn  4190:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4191:     } else {
1.1172.2.23  raeburn  4192:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4193:         if ($hidepriv) {
                   4194:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4195:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4196:                 if ($user !~ /:/) {
                   4197:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4198:                 } else {
                   4199:                     $nothide{$user} = 1;
                   4200:                 }
                   4201:             }
                   4202:         }
1.858     raeburn  4203:     }
1.400     www      4204:     my %returnhash=();
                   4205:     my $now=time;
1.999     raeburn  4206:     my %privileged;
1.800     albertel 4207:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4208:         my ($role,$tend,$tstart);
                   4209:         if ($context eq 'userroles') {
1.1149    raeburn  4210:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4211: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4212:         } else {
                   4213:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4214:         }
1.400     www      4215:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4216:         my $status = 'active';
1.939     raeburn  4217:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4218:             $status = 'previous';
                   4219:         } 
                   4220:         if (($tstart) && ($now<$tstart)) {
                   4221:             $status = 'future';
                   4222:         }
                   4223:         if (ref($types) eq 'ARRAY') {
                   4224:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4225:                 next;
                   4226:             } 
                   4227:         } else {
                   4228:             if ($status ne 'active') {
                   4229:                 next;
                   4230:             }
                   4231:         }
1.867     raeburn  4232:         my ($rolecode,$username,$domain,$section,$area);
                   4233:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4234:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4235:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4236:         } else {
                   4237:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4238:         }
1.832     raeburn  4239:         if (ref($roledoms) eq 'ARRAY') {
                   4240:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4241:                 next;
                   4242:             }
                   4243:         }
                   4244:         if (ref($roles) eq 'ARRAY') {
                   4245:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4246:                 if ($role =~ /^cr\//) {
                   4247:                     if (!grep(/^cr$/,@{$roles})) {
                   4248:                         next;
                   4249:                     }
1.1104    raeburn  4250:                 } elsif ($role =~ /^gr\//) {
                   4251:                     if (!grep(/^gr$/,@{$roles})) {
                   4252:                         next;
                   4253:                     }
1.922     raeburn  4254:                 } else {
                   4255:                     next;
                   4256:                 }
1.832     raeburn  4257:             }
1.867     raeburn  4258:         }
1.937     raeburn  4259:         if ($hidepriv) {
1.1172.2.23  raeburn  4260:             my @privroles = ('dc','su');
1.999     raeburn  4261:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4262:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4263:             } else {
1.1172.2.23  raeburn  4264:                 my $possdoms = [$domain];
                   4265:                 if (ref($roledoms) eq 'ARRAY') {
                   4266:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4267:                 }
1.1172.2.23  raeburn  4268:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4269:                     if (!$nothide{$username.':'.$domain}) {
                   4270:                         next;
                   4271:                     }
                   4272:                 }
1.937     raeburn  4273:             }
                   4274:         }
1.933     raeburn  4275:         if ($withsec) {
                   4276:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4277:                 $tstart.':'.$tend;
                   4278:         } else {
                   4279:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4280:         }
1.832     raeburn  4281:     }
1.373     www      4282:     return %returnhash;
1.399     www      4283: }
                   4284: 
                   4285: # ----------------------------------------------------- Frontpage Announcements
                   4286: #
                   4287: #
                   4288: 
                   4289: sub postannounce {
                   4290:     my ($server,$text)=@_;
1.844     albertel 4291:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4292:     unless ($text=~/\w/) { $text=''; }
                   4293:     return &reply('setannounce:'.&escape($text),$server);
                   4294: }
                   4295: 
                   4296: sub getannounce {
1.448     albertel 4297: 
                   4298:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4299: 	my $announcement='';
1.800     albertel 4300: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4301: 	close($fh);
1.399     www      4302: 	if ($announcement=~/\w/) { 
                   4303: 	    return 
                   4304:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4305:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4306: 	} else {
                   4307: 	    return '';
                   4308: 	}
                   4309:     } else {
                   4310: 	return '';
                   4311:     }
1.351     www      4312: }
1.353     www      4313: 
                   4314: # ---------------------------------------------------------- Course ID routines
                   4315: # Deal with domain's nohist_courseid.db files
                   4316: #
                   4317: 
                   4318: sub courseidput {
1.921     raeburn  4319:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4320:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4321:     my $outcome;
                   4322:     if ($caller eq 'timeonly') {
                   4323:         my $cids = '';
                   4324:         foreach my $item (keys(%$storehash)) {
                   4325:             $cids.=&escape($item).'&';
                   4326:         }
                   4327:         $cids=~s/\&$//;
                   4328:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4329:                           $coursehome);       
                   4330:     } else {
                   4331:         my $items = '';
                   4332:         foreach my $item (keys(%$storehash)) {
                   4333:             $items.= &escape($item).'='.
                   4334:                      &freeze_escape($$storehash{$item}).'&';
                   4335:         }
                   4336:         $items=~s/\&$//;
                   4337:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4338:                           $coursehome);
1.918     raeburn  4339:     }
                   4340:     if ($outcome eq 'unknown_cmd') {
                   4341:         my $what;
                   4342:         foreach my $cid (keys(%$storehash)) {
                   4343:             $what .= &escape($cid).'=';
1.921     raeburn  4344:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4345:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4346:             }
                   4347:             $what =~ s/\:$/&/;
                   4348:         }
                   4349:         $what =~ s/\&$//;  
                   4350:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4351:     } else {
                   4352:         return $outcome;
                   4353:     }
1.353     www      4354: }
                   4355: 
                   4356: sub courseiddump {
1.921     raeburn  4357:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4358:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4359:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4360:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4361:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4362:     my $as_hash = 1;
                   4363:     my %returnhash;
                   4364:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4365:     my %libserv = &all_library();
                   4366:     foreach my $tryserver (keys(%libserv)) {
                   4367:         if ( (  $hostidflag == 1 
                   4368: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4369: 	     || (!defined($hostidflag)) ) {
                   4370: 
1.918     raeburn  4371: 	    if (($domfilter eq '') ||
                   4372: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4373:                 my $rep;
                   4374:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4375:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4376:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4377:                                 &escape($descfilter), &escape($instcodefilter),
                   4378:                                 &escape($ownerfilter), &escape($coursefilter),
                   4379:                                 &escape($typefilter), &escape($regexp_ok),
                   4380:                                 $as_hash, &escape($selfenrollonly),
                   4381:                                 &escape($catfilter), $showhidden, $caller,
                   4382:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4383:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4384:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4385:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4386:                 } else {
                   4387:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4388:                              $sincefilter.':'.&escape($descfilter).':'.
                   4389:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4390:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4391:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4392:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4393:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4394:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4395:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4396:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4397:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4398:                 }
                   4399: 
1.918     raeburn  4400:                 my @pairs=split(/\&/,$rep);
                   4401:                 foreach my $item (@pairs) {
                   4402:                     my ($key,$value)=split(/\=/,$item,2);
                   4403:                     $key = &unescape($key);
                   4404:                     next if ($key =~ /^error: 2 /);
                   4405:                     my $result = &thaw_unescape($value);
                   4406:                     if (ref($result) eq 'HASH') {
                   4407:                         $returnhash{$key}=$result;
                   4408:                     } else {
1.921     raeburn  4409:                         my @responses = split(/:/,$value);
                   4410:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4411:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4412:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4413:                         }
1.1008    raeburn  4414:                     }
1.353     www      4415:                 }
                   4416:             }
                   4417:         }
                   4418:     }
                   4419:     return %returnhash;
                   4420: }
                   4421: 
1.1055    raeburn  4422: sub courselastaccess {
                   4423:     my ($cdom,$cnum,$hostidref) = @_;
                   4424:     my %returnhash;
                   4425:     if ($cdom && $cnum) {
                   4426:         my $chome = &homeserver($cnum,$cdom);
                   4427:         if ($chome ne 'no_host') {
                   4428:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4429:             &extract_lastaccess(\%returnhash,$rep);
                   4430:         }
                   4431:     } else {
                   4432:         if (!$cdom) { $cdom=''; }
                   4433:         my %libserv = &all_library();
                   4434:         foreach my $tryserver (keys(%libserv)) {
                   4435:             if (ref($hostidref) eq 'ARRAY') {
                   4436:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4437:             } 
                   4438:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4439:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4440:                 &extract_lastaccess(\%returnhash,$rep);
                   4441:             }
                   4442:         }
                   4443:     }
                   4444:     return %returnhash;
                   4445: }
                   4446: 
                   4447: sub extract_lastaccess {
                   4448:     my ($returnhash,$rep) = @_;
                   4449:     if (ref($returnhash) eq 'HASH') {
                   4450:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4451:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4452:                  $rep eq '') {
                   4453:             my @pairs=split(/\&/,$rep);
                   4454:             foreach my $item (@pairs) {
                   4455:                 my ($key,$value)=split(/\=/,$item,2);
                   4456:                 $key = &unescape($key);
                   4457:                 next if ($key =~ /^error: 2 /);
                   4458:                 $returnhash->{$key} = &thaw_unescape($value);
                   4459:             }
                   4460:         }
                   4461:     }
                   4462:     return;
                   4463: }
                   4464: 
1.658     raeburn  4465: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4466: 
                   4467: sub dcmailput {
1.685     raeburn  4468:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4469:     my $status = &Apache::lonnet::critical(
1.740     www      4470:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4471:        &escape($message),$server);
1.662     raeburn  4472:     return $status;
                   4473: }
                   4474: 
1.658     raeburn  4475: sub dcmaildump {
                   4476:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4477:     my %returnhash=();
1.846     albertel 4478: 
                   4479:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4480:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4481:                                                          &escape($enddate).':';
                   4482: 	my @esc_senders=map { &escape($_)} @$senders;
                   4483: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4484: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4485:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4486:             if (($key) && ($value)) {
                   4487:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4488:             }
                   4489:         }
                   4490:     }
                   4491:     return %returnhash;
                   4492: }
1.662     raeburn  4493: # ---------------------------------------------------------- Domain roles
                   4494: 
                   4495: sub get_domain_roles {
                   4496:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4497:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4498:         $startdate = '.';
                   4499:     }
1.1018    raeburn  4500:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4501:         $enddate = '.';
                   4502:     }
1.922     raeburn  4503:     my $rolelist;
                   4504:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4505:         $rolelist = join('&',@{$roles});
1.922     raeburn  4506:     }
1.662     raeburn  4507:     my %personnel = ();
1.841     albertel 4508: 
                   4509:     my %servers = &get_servers($dom,'library');
                   4510:     foreach my $tryserver (keys(%servers)) {
                   4511: 	%{$personnel{$tryserver}}=();
                   4512: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4513: 					    &escape($startdate).':'.
                   4514: 					    &escape($enddate).':'.
                   4515: 					    &escape($rolelist), $tryserver))) {
                   4516: 	    my ($key,$value) = split(/\=/,$line,2);
                   4517: 	    if (($key) && ($value)) {
                   4518: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4519: 	    }
                   4520: 	}
1.662     raeburn  4521:     }
                   4522:     return %personnel;
                   4523: }
1.658     raeburn  4524: 
1.1057    www      4525: # ----------------------------------------------------------- Interval timing 
1.149     www      4526: 
1.1153    www      4527: {
                   4528: # Caches needed for speedup of navmaps
                   4529: # We don't want to cache this for very long at all (5 seconds at most)
                   4530: # 
                   4531: # The user for whom we cache
                   4532: my $cachedkey='';
                   4533: # The cached times for this user
                   4534: my %cachedtimes=();
                   4535: # When this was last done
1.1172.2.66  raeburn  4536: my $cachedtime='';
1.1153    www      4537: 
                   4538: sub load_all_first_access {
1.1154    raeburn  4539:     my ($uname,$udom)=@_;
1.1156    www      4540:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4541:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4542:         return;
                   4543:     }
                   4544:     $cachedtime=time;
                   4545:     $cachedkey=$uname.':'.$udom;
                   4546:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4547: }
                   4548: 
1.504     albertel 4549: sub get_first_access {
1.1162    raeburn  4550:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4551:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4552:     if ($argsymb) { $symb=$argsymb; }
                   4553:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4554:     if ($argmap) { $map = $argmap; }
1.926     albertel 4555:     if ($type eq 'course') {
                   4556: 	$res='course';
                   4557:     } elsif ($type eq 'map') {
1.588     albertel 4558: 	$res=&symbread($map);
                   4559:     } else {
                   4560: 	$res=$symb;
                   4561:     }
1.1153    www      4562:     &load_all_first_access($uname,$udom);
                   4563:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4564: }
                   4565: 
                   4566: sub set_first_access {
1.1162    raeburn  4567:     my ($type,$interval)=@_;
1.790     albertel 4568:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4569:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4570:     if ($type eq 'course') {
                   4571: 	$res='course';
                   4572:     } elsif ($type eq 'map') {
1.588     albertel 4573: 	$res=&symbread($map);
                   4574:     } else {
                   4575: 	$res=$symb;
                   4576:     }
1.1153    www      4577:     $cachedkey='';
1.1162    raeburn  4578:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4579:     if (!$firstaccess) {
1.1162    raeburn  4580:         my $start = time;
                   4581: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4582:                           $udom,$uname);
                   4583:         if ($putres eq 'ok') {
                   4584:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4585:                  $udom,$uname); 
                   4586:             &appenv(
                   4587:                      {
                   4588:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4589:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4590:                      }
                   4591:                   );
                   4592:         }
                   4593:         return $putres;
1.505     albertel 4594:     }
                   4595:     return 'already_set';
1.504     albertel 4596: }
1.1153    www      4597: }
1.1172.2.32  raeburn  4598: 
                   4599: sub checkout {
                   4600:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4601:     my $now=time;
                   4602:     my $lonhost=$perlvar{'lonHostID'};
                   4603:     my $infostr=&escape(
                   4604:                  'CHECKOUTTOKEN&'.
                   4605:                  $tuname.'&'.
                   4606:                  $tudom.'&'.
                   4607:                  $tcrsid.'&'.
                   4608:                  $symb.'&'.
                   4609:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4610:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4611:     if ($token=~/^error\:/) {
                   4612:         &logthis("<font color=\"blue\">WARNING: ".
                   4613:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4614:                  "</font>");
                   4615:         return '';
                   4616:     }
                   4617: 
                   4618:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4619:     $token=~tr/a-z/A-Z/;
                   4620: 
                   4621:     my %infohash=('resource.0.outtoken' => $token,
                   4622:                   'resource.0.checkouttime' => $now,
                   4623:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4624: 
                   4625:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4626:        return '';
                   4627:     } else {
                   4628:         &logthis("<font color=\"blue\">WARNING: ".
                   4629:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4630:                  "</font>");
                   4631:     }
                   4632: 
                   4633:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4634:                          &escape('Checkout '.$infostr.' - '.
                   4635:                                                  $token)) ne 'ok') {
                   4636:         return '';
                   4637:     } else {
                   4638:         &logthis("<font color=\"blue\">WARNING: ".
                   4639:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4640:                  "</font>");
                   4641:     }
                   4642:     return $token;
                   4643: }
                   4644: 
                   4645: # ------------------------------------------------------------ Check in an item
                   4646: 
                   4647: sub checkin {
                   4648:     my $token=shift;
                   4649:     my $now=time;
                   4650:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4651:     $lonhost=~tr/A-Z/a-z/;
                   4652:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4653:     $dtoken=~s/\W/\_/g;
                   4654:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4655:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4656: 
                   4657:     unless (($tuname) && ($tudom)) {
                   4658:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4659:         return '';
                   4660:     }
                   4661: 
                   4662:     unless (&allowed('mgr',$tcrsid)) {
                   4663:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4664:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4665:         return '';
                   4666:     }
                   4667: 
                   4668:     my %infohash=('resource.0.intoken' => $token,
                   4669:                   'resource.0.checkintime' => $now,
                   4670:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4671: 
                   4672:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4673:        return '';
                   4674:     }
                   4675: 
                   4676:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4677:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4678:         return '';
                   4679:     }
                   4680: 
                   4681:     return ($symb,$tuname,$tudom,$tcrsid);
                   4682: }
                   4683: 
1.110     www      4684: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4685: 
                   4686: sub expirespread {
                   4687:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4688:     my $cid=$env{'request.course.id'}; 
1.110     www      4689:     if ($cid) {
                   4690:        my $now=time;
                   4691:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4692:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4693:                             $env{'course.'.$cid.'.num'}.
1.110     www      4694: 	        	    ':nohist_expirationdates:'.
                   4695:                             &escape($key).'='.$now,
1.620     albertel 4696:                             $env{'course.'.$cid.'.home'})
1.110     www      4697:     }
                   4698:     return 'ok';
1.14      www      4699: }
                   4700: 
1.109     www      4701: # ----------------------------------------------------- Devalidate Spreadsheets
                   4702: 
                   4703: sub devalidate {
1.325     www      4704:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4705:     my $cid=$env{'request.course.id'}; 
1.109     www      4706:     if ($cid) {
1.391     matthew  4707:         # delete the stored spreadsheets for
                   4708:         # - the student level sheet of this user in course's homespace
                   4709:         # - the assessment level sheet for this resource 
                   4710:         #   for this user in user's homespace
1.553     albertel 4711: 	# - current conditional state info
1.325     www      4712: 	my $key=$uname.':'.$udom.':';
1.109     www      4713:         my $status=
1.299     matthew  4714: 	    &del('nohist_calculatedsheets',
1.391     matthew  4715: 		 [$key.'studentcalc:'],
1.620     albertel 4716: 		 $env{'course.'.$cid.'.domain'},
                   4717: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4718: 		.' '.
                   4719: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4720: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4721:         unless ($status eq 'ok ok') {
                   4722:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4723:                     $uname.' at '.$udom.' for '.
1.109     www      4724: 		    $symb.': '.$status);
1.133     albertel 4725:         }
1.553     albertel 4726: 	&delenv('user.state.'.$cid);
1.109     www      4727:     }
                   4728: }
                   4729: 
1.265     albertel 4730: sub get_scalar {
                   4731:     my ($string,$end) = @_;
                   4732:     my $value;
                   4733:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4734: 	$value = $1;
                   4735:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4736: 	$value = $1;
                   4737:     }
                   4738:     return &unescape($value);
                   4739: }
                   4740: 
                   4741: sub array2str {
                   4742:   my (@array) = @_;
                   4743:   my $result=&arrayref2str(\@array);
                   4744:   $result=~s/^__ARRAY_REF__//;
                   4745:   $result=~s/__END_ARRAY_REF__$//;
                   4746:   return $result;
                   4747: }
                   4748: 
1.204     albertel 4749: sub arrayref2str {
                   4750:   my ($arrayref) = @_;
1.265     albertel 4751:   my $result='__ARRAY_REF__';
1.204     albertel 4752:   foreach my $elem (@$arrayref) {
1.265     albertel 4753:     if(ref($elem) eq 'ARRAY') {
                   4754:       $result.=&arrayref2str($elem).'&';
                   4755:     } elsif(ref($elem) eq 'HASH') {
                   4756:       $result.=&hashref2str($elem).'&';
                   4757:     } elsif(ref($elem)) {
                   4758:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4759:     } else {
                   4760:       $result.=&escape($elem).'&';
                   4761:     }
                   4762:   }
                   4763:   $result=~s/\&$//;
1.265     albertel 4764:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4765:   return $result;
                   4766: }
                   4767: 
1.168     albertel 4768: sub hash2str {
1.204     albertel 4769:   my (%hash) = @_;
                   4770:   my $result=&hashref2str(\%hash);
1.265     albertel 4771:   $result=~s/^__HASH_REF__//;
                   4772:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4773:   return $result;
                   4774: }
                   4775: 
                   4776: sub hashref2str {
                   4777:   my ($hashref)=@_;
1.265     albertel 4778:   my $result='__HASH_REF__';
1.800     albertel 4779:   foreach my $key (sort(keys(%$hashref))) {
                   4780:     if (ref($key) eq 'ARRAY') {
                   4781:       $result.=&arrayref2str($key).'=';
                   4782:     } elsif (ref($key) eq 'HASH') {
                   4783:       $result.=&hashref2str($key).'=';
                   4784:     } elsif (ref($key)) {
1.265     albertel 4785:       $result.='=';
1.800     albertel 4786:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4787:     } else {
1.1132    raeburn  4788: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4789:     }
                   4790: 
1.800     albertel 4791:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4792:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4793:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4794:       $result.=&hashref2str($hashref->{$key}).'&';
                   4795:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4796:        $result.='&';
1.800     albertel 4797:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4798:     } else {
1.800     albertel 4799:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4800:     }
                   4801:   }
1.168     albertel 4802:   $result=~s/\&$//;
1.265     albertel 4803:   $result .= '__END_HASH_REF__';
1.168     albertel 4804:   return $result;
                   4805: }
                   4806: 
                   4807: sub str2hash {
1.265     albertel 4808:     my ($string)=@_;
                   4809:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4810:     return %$hash;
                   4811: }
                   4812: 
                   4813: sub str2hashref {
1.168     albertel 4814:   my ($string) = @_;
1.265     albertel 4815: 
                   4816:   my %hash;
                   4817: 
                   4818:   if($string !~ /^__HASH_REF__/) {
                   4819:       if (! ($string eq '' || !defined($string))) {
                   4820: 	  $hash{'error'}='Not hash reference';
                   4821:       }
                   4822:       return (\%hash, $string);
                   4823:   }
                   4824: 
                   4825:   $string =~ s/^__HASH_REF__//;
                   4826: 
                   4827:   while($string !~ /^__END_HASH_REF__/) {
                   4828:       #key
                   4829:       my $key='';
                   4830:       if($string =~ /^__HASH_REF__/) {
                   4831:           ($key, $string)=&str2hashref($string);
                   4832:           if(defined($key->{'error'})) {
                   4833:               $hash{'error'}='Bad data';
                   4834:               return (\%hash, $string);
                   4835:           }
                   4836:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4837:           ($key, $string)=&str2arrayref($string);
                   4838:           if($key->[0] eq 'Array reference error') {
                   4839:               $hash{'error'}='Bad data';
                   4840:               return (\%hash, $string);
                   4841:           }
                   4842:       } else {
                   4843:           $string =~ s/^(.*?)=//;
1.267     albertel 4844: 	  $key=&unescape($1);
1.265     albertel 4845:       }
                   4846:       $string =~ s/^=//;
                   4847: 
                   4848:       #value
                   4849:       my $value='';
                   4850:       if($string =~ /^__HASH_REF__/) {
                   4851:           ($value, $string)=&str2hashref($string);
                   4852:           if(defined($value->{'error'})) {
                   4853:               $hash{'error'}='Bad data';
                   4854:               return (\%hash, $string);
                   4855:           }
                   4856:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4857:           ($value, $string)=&str2arrayref($string);
                   4858:           if($value->[0] eq 'Array reference error') {
                   4859:               $hash{'error'}='Bad data';
                   4860:               return (\%hash, $string);
                   4861:           }
                   4862:       } else {
                   4863: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4864:       }
                   4865:       $string =~ s/^&//;
                   4866: 
                   4867:       $hash{$key}=$value;
1.204     albertel 4868:   }
1.265     albertel 4869: 
                   4870:   $string =~ s/^__END_HASH_REF__//;
                   4871: 
                   4872:   return (\%hash, $string);
1.204     albertel 4873: }
                   4874: 
                   4875: sub str2array {
1.265     albertel 4876:     my ($string)=@_;
                   4877:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4878:     return @$array;
                   4879: }
                   4880: 
                   4881: sub str2arrayref {
1.204     albertel 4882:   my ($string) = @_;
1.265     albertel 4883:   my @array;
                   4884: 
                   4885:   if($string !~ /^__ARRAY_REF__/) {
                   4886:       if (! ($string eq '' || !defined($string))) {
                   4887: 	  $array[0]='Array reference error';
                   4888:       }
                   4889:       return (\@array, $string);
                   4890:   }
                   4891: 
                   4892:   $string =~ s/^__ARRAY_REF__//;
                   4893: 
                   4894:   while($string !~ /^__END_ARRAY_REF__/) {
                   4895:       my $value='';
                   4896:       if($string =~ /^__HASH_REF__/) {
                   4897:           ($value, $string)=&str2hashref($string);
                   4898:           if(defined($value->{'error'})) {
                   4899:               $array[0] ='Array reference error';
                   4900:               return (\@array, $string);
                   4901:           }
                   4902:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4903:           ($value, $string)=&str2arrayref($string);
                   4904:           if($value->[0] eq 'Array reference error') {
                   4905:               $array[0] ='Array reference error';
                   4906:               return (\@array, $string);
                   4907:           }
                   4908:       } else {
                   4909: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4910:       }
                   4911:       $string =~ s/^&//;
                   4912: 
                   4913:       push(@array, $value);
1.191     harris41 4914:   }
1.265     albertel 4915: 
                   4916:   $string =~ s/^__END_ARRAY_REF__//;
                   4917: 
                   4918:   return (\@array, $string);
1.168     albertel 4919: }
                   4920: 
1.167     albertel 4921: # -------------------------------------------------------------------Temp Store
                   4922: 
1.168     albertel 4923: sub tmpreset {
                   4924:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4925:   if (!$symb) {
                   4926:     $symb=&symbread();
1.620     albertel 4927:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4928:   }
                   4929:   $symb=escape($symb);
                   4930: 
1.620     albertel 4931:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4932:   $namespace=~s/\//\_/g;
                   4933:   $namespace=~s/\W//g;
                   4934: 
1.620     albertel 4935:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4936:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4937:   if ($domain eq 'public' && $stuname eq 'public') {
                   4938:       $stuname=$ENV{'REMOTE_ADDR'};
                   4939:   }
1.1117    foxr     4940:   my $path=LONCAPA::tempdir();
1.168     albertel 4941:   my %hash;
                   4942:   if (tie(%hash,'GDBM_File',
                   4943: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4944: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4945:     foreach my $key (keys(%hash)) {
1.180     albertel 4946:       if ($key=~ /:$symb/) {
1.168     albertel 4947: 	delete($hash{$key});
                   4948:       }
                   4949:     }
                   4950:   }
                   4951: }
                   4952: 
1.167     albertel 4953: sub tmpstore {
1.168     albertel 4954:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4955: 
                   4956:   if (!$symb) {
                   4957:     $symb=&symbread();
1.620     albertel 4958:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4959:   }
                   4960:   $symb=escape($symb);
                   4961: 
                   4962:   if (!$namespace) {
                   4963:     # I don't think we would ever want to store this for a course.
                   4964:     # it seems this will only be used if we don't have a course.
1.620     albertel 4965:     #$namespace=$env{'request.course.id'};
1.168     albertel 4966:     #if (!$namespace) {
1.620     albertel 4967:       $namespace=$env{'request.state'};
1.168     albertel 4968:     #}
                   4969:   }
                   4970:   $namespace=~s/\//\_/g;
                   4971:   $namespace=~s/\W//g;
1.620     albertel 4972:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4973:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4974:   if ($domain eq 'public' && $stuname eq 'public') {
                   4975:       $stuname=$ENV{'REMOTE_ADDR'};
                   4976:   }
1.168     albertel 4977:   my $now=time;
                   4978:   my %hash;
1.1117    foxr     4979:   my $path=LONCAPA::tempdir();
1.168     albertel 4980:   if (tie(%hash,'GDBM_File',
                   4981: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4982: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4983:     $hash{"version:$symb"}++;
                   4984:     my $version=$hash{"version:$symb"};
                   4985:     my $allkeys=''; 
                   4986:     foreach my $key (keys(%$storehash)) {
                   4987:       $allkeys.=$key.':';
1.591     albertel 4988:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4989:     }
                   4990:     $hash{"$version:$symb:timestamp"}=$now;
                   4991:     $allkeys.='timestamp';
                   4992:     $hash{"$version:keys:$symb"}=$allkeys;
                   4993:     if (untie(%hash)) {
                   4994:       return 'ok';
                   4995:     } else {
                   4996:       return "error:$!";
                   4997:     }
                   4998:   } else {
                   4999:     return "error:$!";
                   5000:   }
                   5001: }
1.167     albertel 5002: 
1.168     albertel 5003: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5004: 
1.168     albertel 5005: sub tmprestore {
                   5006:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5007: 
1.168     albertel 5008:   if (!$symb) {
                   5009:     $symb=&symbread();
1.620     albertel 5010:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5011:   }
                   5012:   $symb=escape($symb);
                   5013: 
1.620     albertel 5014:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5015: 
1.620     albertel 5016:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5017:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5018:   if ($domain eq 'public' && $stuname eq 'public') {
                   5019:       $stuname=$ENV{'REMOTE_ADDR'};
                   5020:   }
1.168     albertel 5021:   my %returnhash;
                   5022:   $namespace=~s/\//\_/g;
                   5023:   $namespace=~s/\W//g;
                   5024:   my %hash;
1.1117    foxr     5025:   my $path=LONCAPA::tempdir();
1.168     albertel 5026:   if (tie(%hash,'GDBM_File',
                   5027: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5028: 	  &GDBM_READER(),0640)) {
1.168     albertel 5029:     my $version=$hash{"version:$symb"};
                   5030:     $returnhash{'version'}=$version;
                   5031:     my $scope;
                   5032:     for ($scope=1;$scope<=$version;$scope++) {
                   5033:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5034:       my @keys=split(/:/,$vkeys);
                   5035:       my $key;
                   5036:       $returnhash{"$scope:keys"}=$vkeys;
                   5037:       foreach $key (@keys) {
1.591     albertel 5038: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5039: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5040:       }
                   5041:     }
1.168     albertel 5042:     if (!(untie(%hash))) {
                   5043:       return "error:$!";
                   5044:     }
                   5045:   } else {
                   5046:     return "error:$!";
                   5047:   }
                   5048:   return %returnhash;
1.167     albertel 5049: }
                   5050: 
1.9       www      5051: # ----------------------------------------------------------------------- Store
                   5052: 
                   5053: sub store {
1.1172.2.64  raeburn  5054:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5055:     my $home='';
                   5056: 
1.168     albertel 5057:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5058: 
1.213     www      5059:     $symb=&symbclean($symb);
1.122     albertel 5060:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5061: 
1.620     albertel 5062:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5063:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5064: 
                   5065:     &devalidate($symb,$stuname,$domain);
1.109     www      5066: 
                   5067:     $symb=escape($symb);
1.187     www      5068:     if (!$namespace) { 
1.620     albertel 5069:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5070:           return ''; 
                   5071:        } 
                   5072:     }
1.620     albertel 5073:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5074: 
                   5075:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5076:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5077: 
1.12      www      5078:     my $namevalue='';
1.800     albertel 5079:     foreach my $key (keys(%$storehash)) {
                   5080:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5081:     }
1.12      www      5082:     $namevalue=~s/\&$//;
1.187     www      5083:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5084:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5085: }
                   5086: 
1.47      www      5087: # -------------------------------------------------------------- Critical Store
                   5088: 
                   5089: sub cstore {
1.1172.2.64  raeburn  5090:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5091:     my $home='';
                   5092: 
1.168     albertel 5093:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5094: 
1.213     www      5095:     $symb=&symbclean($symb);
1.122     albertel 5096:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5097: 
1.620     albertel 5098:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5099:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5100: 
                   5101:     &devalidate($symb,$stuname,$domain);
1.109     www      5102: 
                   5103:     $symb=escape($symb);
1.187     www      5104:     if (!$namespace) { 
1.620     albertel 5105:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5106:           return ''; 
                   5107:        } 
                   5108:     }
1.620     albertel 5109:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5110: 
                   5111:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5112:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5113: 
1.47      www      5114:     my $namevalue='';
1.800     albertel 5115:     foreach my $key (keys(%$storehash)) {
                   5116:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5117:     }
1.47      www      5118:     $namevalue=~s/\&$//;
1.187     www      5119:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5120:     return critical
1.1172.2.64  raeburn  5121:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5122: }
                   5123: 
1.9       www      5124: # --------------------------------------------------------------------- Restore
                   5125: 
                   5126: sub restore {
1.124     www      5127:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5128:     my $home='';
                   5129: 
1.168     albertel 5130:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5131: 
1.122     albertel 5132:     if (!$symb) {
1.1172.2.26  raeburn  5133:         return if ($namespace eq 'courserequests');
                   5134:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5135:     } else {
1.1172.2.26  raeburn  5136:         unless ($namespace eq 'courserequests') {
                   5137:             $symb=&escape(&symbclean($symb));
                   5138:         }
1.122     albertel 5139:     }
1.188     www      5140:     if (!$namespace) { 
1.620     albertel 5141:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5142:           return ''; 
                   5143:        } 
                   5144:     }
1.620     albertel 5145:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5146:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5147:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5148:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5149: 
1.12      www      5150:     my %returnhash=();
1.800     albertel 5151:     foreach my $line (split(/\&/,$answer)) {
                   5152: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5153:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5154:     }
1.75      www      5155:     my $version;
                   5156:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5157:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5158:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5159:        }
1.75      www      5160:     }
1.13      www      5161:     return %returnhash;
1.34      www      5162: }
                   5163: 
                   5164: # ---------------------------------------------------------- Course Description
1.1118    foxr     5165: #
                   5166: #  
1.34      www      5167: 
                   5168: sub coursedescription {
1.731     albertel 5169:     my ($courseid,$args)=@_;
1.34      www      5170:     $courseid=~s/^\///;
1.49      www      5171:     $courseid=~s/\_/\//g;
1.34      www      5172:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5173:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5174:     my $normalid=$cdomain.'_'.$cnum;
                   5175:     # need to always cache even if we get errors otherwise we keep 
                   5176:     # trying and trying and trying to get the course description.
                   5177:     my %envhash=();
                   5178:     my %returnhash=();
1.731     albertel 5179:     
                   5180:     my $expiretime=600;
                   5181:     if ($env{'request.course.id'} eq $normalid) {
                   5182: 	$expiretime=120;
                   5183:     }
                   5184: 
                   5185:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5186:     if (!$args->{'freshen_cache'}
                   5187: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5188: 	foreach my $key (keys(%env)) {
                   5189: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5190: 	    my ($setting) = $1;
                   5191: 	    $returnhash{$setting} = $env{$key};
                   5192: 	}
                   5193: 	return %returnhash;
                   5194:     }
                   5195: 
1.1118    foxr     5196:     # get the data again
                   5197: 
1.731     albertel 5198:     if (!$args->{'one_time'}) {
                   5199: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5200:     }
1.811     albertel 5201: 
1.34      www      5202:     if ($chome ne 'no_host') {
1.302     albertel 5203:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5204:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5205: 	   my $username = $env{'user.name'}; # Defult username
                   5206: 	   if(defined $args->{'user'}) {
                   5207: 	       $username = $args->{'user'};
                   5208: 	   }
1.129     albertel 5209:            $returnhash{'home'}= $chome;
                   5210: 	   $returnhash{'domain'} = $cdomain;
                   5211: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5212:            if (!defined($returnhash{'type'})) {
                   5213:                $returnhash{'type'} = 'Course';
                   5214:            }
1.130     albertel 5215:            while (my ($name,$value) = each %returnhash) {
1.53      www      5216:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5217:            }
1.270     www      5218:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5219:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5220: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5221:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5222:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5223:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5224:        }
                   5225:     }
1.731     albertel 5226:     if (!$args->{'one_time'}) {
1.949     raeburn  5227: 	&appenv(\%envhash);
1.731     albertel 5228:     }
1.302     albertel 5229:     return %returnhash;
1.461     www      5230: }
                   5231: 
1.1080    raeburn  5232: sub update_released_required {
                   5233:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5234:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5235:         $cid = $env{'request.course.id'};
                   5236:         $cdom = $env{'course.'.$cid.'.domain'};
                   5237:         $cnum = $env{'course.'.$cid.'.num'};
                   5238:         $chome = $env{'course.'.$cid.'.home'};
                   5239:     }
                   5240:     if ($needsrelease) {
                   5241:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5242:         my $needsupdate;
                   5243:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5244:             $needsupdate = 1;
                   5245:         } else {
                   5246:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5247:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5248:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5249:                 $needsupdate = 1;
                   5250:             }
                   5251:         }
                   5252:         if ($needsupdate) {
                   5253:             my %needshash = (
                   5254:                              'internal.releaserequired' => $needsrelease,
                   5255:                             );
                   5256:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5257:             if ($putresult eq 'ok') {
                   5258:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5259:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5260:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5261:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5262:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5263:                 }
                   5264:             }
                   5265:         }
                   5266:     }
                   5267:     return;
                   5268: }
                   5269: 
1.461     www      5270: # -------------------------------------------------See if a user is privileged
                   5271: 
                   5272: sub privileged {
1.1172.2.23  raeburn  5273:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5274:     my $now = time;
1.1172.2.23  raeburn  5275:     my $roles;
                   5276:     if (ref($possroles) eq 'ARRAY') {
                   5277:         $roles = $possroles;
                   5278:     } else {
                   5279:         $roles = ['dc','su'];
                   5280:     }
                   5281:     if (ref($possdomains) eq 'ARRAY') {
                   5282:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5283:         foreach my $dom (@{$possdomains}) {
                   5284:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5285:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5286:                 foreach my $role (@{$roles}) {
                   5287:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5288:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5289:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5290:                             return 1 unless (($end && $end < $now) ||
                   5291:                                              ($start && $start > $now));
                   5292:                         }
                   5293:                     }
                   5294:                 }
                   5295:             }
                   5296:         }
                   5297:     } else {
                   5298:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5299:         my $now = time;
1.1170    droeschl 5300: 
1.1172.2.58  raeburn  5301:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5302:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5303:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5304:                 return 1 unless ($tend && $tend < $now)
                   5305:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5306:             }
1.1172.2.23  raeburn  5307:         }
                   5308:     }
1.461     www      5309:     return 0;
1.9       www      5310: }
1.1       albertel 5311: 
1.1172.2.23  raeburn  5312: sub privileged_by_domain {
                   5313:     my ($domains,$roles) = @_;
                   5314:     my %privileged = ();
                   5315:     my $cachetime = 60*60*24;
                   5316:     my $now = time;
                   5317:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5318:         return %privileged;
                   5319:     }
                   5320:     foreach my $dom (@{$domains}) {
                   5321:         next if (ref($privileged{$dom}) eq 'HASH');
                   5322:         my $needroles;
                   5323:         foreach my $role (@{$roles}) {
                   5324:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5325:             if (defined($cached)) {
                   5326:                 if (ref($result) eq 'HASH') {
                   5327:                     $privileged{$dom}{$role} = $result;
                   5328:                 }
                   5329:             } else {
                   5330:                 $needroles = 1;
                   5331:             }
                   5332:         }
                   5333:         if ($needroles) {
                   5334:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5335:             $privileged{$dom} = {};
                   5336:             foreach my $server (keys(%dompersonnel)) {
                   5337:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5338:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5339:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5340:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5341:                         next if ($end && $end < $now);
                   5342:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5343:                             $dompersonnel{$server}{$item};
                   5344:                     }
                   5345:                 }
                   5346:             }
                   5347:             if (ref($privileged{$dom}) eq 'HASH') {
                   5348:                 foreach my $role (@{$roles}) {
                   5349:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5350:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5351:                     } else {
                   5352:                         my %hash = ();
                   5353:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5354:                     }
                   5355:                 }
                   5356:             }
                   5357:         }
                   5358:     }
                   5359:     return %privileged;
                   5360: }
                   5361: 
1.103     harris41 5362: # -------------------------------------------------------- Get user privileges
1.11      www      5363: 
                   5364: sub rolesinit {
1.1169    droeschl 5365:     my ($domain, $username) = @_;
                   5366:     my %userroles = ('user.login.time' => time);
                   5367:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5368: 
                   5369:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5370:     # also, blocking can be triggered by an activating timer
                   5371:     # it's saved in the user's %env.
                   5372:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5373:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5374:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5375:         %timerintchk, %timerintenv);
                   5376: 
1.1162    raeburn  5377:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5378:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5379:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5380:     }
1.1169    droeschl 5381: 
1.1162    raeburn  5382:     foreach my $key (keys(%timerinterval)) {
                   5383:         my ($cid,$rest) = split(/\0/,$key);
                   5384:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5385:     }
1.1169    droeschl 5386: 
1.11      www      5387:     my %allroles=();
1.1162    raeburn  5388:     my %allgroups=();
1.11      www      5389: 
1.1172.2.58  raeburn  5390:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5391:         my $role = $rolesdump{$area};
                   5392:         $area =~ s/\_\w\w$//;
                   5393: 
                   5394:         my ($trole, $tend, $tstart, $group_privs);
                   5395: 
                   5396:         if ($role =~ /^cr/) {
                   5397:         # Custom role, defined by a user 
                   5398:         # e.g., user.role.cr/msu/smith/mynewrole
                   5399:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5400:                 $trole = $1;
                   5401:                 ($tend, $tstart) = split('_', $2);
                   5402:             } else {
                   5403:                 $trole = $role;
                   5404:             }
                   5405:         } elsif ($role =~ m|^gr/|) {
                   5406:         # Role of member in a group, defined within a course/community
                   5407:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5408:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5409:             next if $tstart eq '-1';
                   5410:             ($trole, $group_privs) = split(/\//, $trole);
                   5411:             $group_privs = &unescape($group_privs);
                   5412:         } else {
                   5413:         # Just a normal role, defined in roles.tab
                   5414:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5415:         }
                   5416: 
                   5417:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5418:                  $username);
                   5419:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5420: 
                   5421:         # role expired or not available yet?
                   5422:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5423:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5424: 
                   5425:         next if $area eq '' or $trole eq '';
                   5426: 
                   5427:         my $spec = "$trole.$area";
                   5428:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5429: 
                   5430:         if ($trole =~ /^cr\//) {
                   5431:         # Custom role, defined by a user
                   5432:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5433:         } elsif ($trole eq 'gr') {
                   5434:         # Role of a member in a group, defined within a course/community
                   5435:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5436:             next;
                   5437:         } else {
                   5438:         # Normal role, defined in roles.tab
                   5439:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5440:         }
                   5441: 
                   5442:         my $cid = $tdomain.'_'.$trest;
                   5443:         unless ($firstaccchk{$cid}) {
                   5444:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5445:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5446:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5447:                         $coursetimerstarts{$cid}{$item}; 
                   5448:                 }
                   5449:             }
                   5450:             $firstaccchk{$cid} = 1;
                   5451:         }
                   5452:         unless ($timerintchk{$cid}) {
                   5453:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5454:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5455:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5456:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5457:                 }
1.12      www      5458:             }
1.1169    droeschl 5459:             $timerintchk{$cid} = 1;
1.191     harris41 5460:         }
1.11      www      5461:     }
1.1169    droeschl 5462: 
                   5463:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5464:         \%allroles, \%allgroups);
                   5465:     $env{'user.adv'} = $userroles{'user.adv'};
                   5466: 
1.1162    raeburn  5467:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5468: }
                   5469: 
1.567     raeburn  5470: sub set_arearole {
1.1172.2.19  raeburn  5471:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5472:     unless ($nolog) {
1.567     raeburn  5473: # log the associated role with the area
1.1172.2.19  raeburn  5474:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5475:     }
1.743     albertel 5476:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5477: }
                   5478: 
                   5479: sub custom_roleprivs {
                   5480:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5481:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5482:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5483:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5484:         my ($rdummy,$roledef)=
                   5485:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5486:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5487:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5488:             if (defined($syspriv)) {
1.1043    raeburn  5489:                 if ($trest =~ /^$match_community$/) {
                   5490:                     $syspriv =~ s/bre\&S//; 
                   5491:                 }
1.567     raeburn  5492:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5493:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5494:             }
                   5495:             if ($tdomain ne '') {
                   5496:                 if (defined($dompriv)) {
                   5497:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5498:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5499:                 }
                   5500:                 if (($trest ne '') && (defined($coursepriv))) {
                   5501:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5502:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5503:                 }
                   5504:             }
                   5505:         }
                   5506:     }
                   5507: }
                   5508: 
1.678     raeburn  5509: sub group_roleprivs {
                   5510:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5511:     my $access = 1;
                   5512:     my $now = time;
                   5513:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5514:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5515:     if ($access) {
1.811     albertel 5516:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5517:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5518:     }
                   5519: }
1.567     raeburn  5520: 
                   5521: sub standard_roleprivs {
                   5522:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5523:     if (defined($pr{$trole.':s'})) {
                   5524:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5525:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5526:     }
                   5527:     if ($tdomain ne '') {
                   5528:         if (defined($pr{$trole.':d'})) {
                   5529:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5530:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5531:         }
                   5532:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5533:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5534:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5535:         }
                   5536:     }
                   5537: }
                   5538: 
                   5539: sub set_userprivs {
1.1064    raeburn  5540:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5541:     my $author=0;
                   5542:     my $adv=0;
1.678     raeburn  5543:     my %grouproles = ();
                   5544:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5545:         my @groupkeys; 
1.1000    raeburn  5546:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5547:             push(@groupkeys,$role);
                   5548:         }
                   5549:         if (ref($groups_roles) eq 'HASH') {
                   5550:             foreach my $key (keys(%{$groups_roles})) {
                   5551:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5552:                     push(@groupkeys,$key);
                   5553:                 }
                   5554:             }
                   5555:         }
                   5556:         if (@groupkeys > 0) {
                   5557:             foreach my $role (@groupkeys) {
                   5558:                 my ($trole,$area,$sec,$extendedarea);
                   5559:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5560:                     $trole = $1;
                   5561:                     $area = $2;
                   5562:                     $sec = $3;
                   5563:                     $extendedarea = $area.$sec;
                   5564:                     if (exists($$allgroups{$area})) {
                   5565:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5566:                             my $spec = $trole.'.'.$extendedarea;
                   5567:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5568:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5569:                         }
1.678     raeburn  5570:                     }
                   5571:                 }
                   5572:             }
                   5573:         }
                   5574:     }
1.800     albertel 5575:     foreach my $group (keys(%grouproles)) {
                   5576:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5577:     }
1.800     albertel 5578:     foreach my $role (keys(%{$allroles})) {
                   5579:         my %thesepriv;
1.941     raeburn  5580:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5581:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5582:             if ($item ne '') {
                   5583:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5584:                 if ($restrictions eq '') {
                   5585:                     $thesepriv{$privilege}='F';
                   5586:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5587:                     $thesepriv{$privilege}.=$restrictions;
                   5588:                 }
                   5589:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5590:             }
                   5591:         }
                   5592:         my $thesestr='';
1.1104    raeburn  5593:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5594: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5595: 	}
                   5596:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5597:     }
                   5598:     return ($author,$adv);
                   5599: }
                   5600: 
1.994     raeburn  5601: sub role_status {
1.1104    raeburn  5602:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5603:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5604:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5605:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5606:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5607:             $$where = '/'.$two;
1.994     raeburn  5608:             $$trolecode=$$role.'.'.$$where;
                   5609:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5610:             $$tstatus='is';
1.1104    raeburn  5611:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5612:                 $$tstatus='future';
1.1034    raeburn  5613:                 if ($$tstart<$now) {
                   5614:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5615:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5616:                             my (%allroles,%allgroups,$group_privs,
                   5617:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5618:                             my %userroles = (
                   5619:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5620:                             );
1.1064    raeburn  5621:                             @rolecodes = ('cm'); 
1.1002    raeburn  5622:                             my $spec=$$role.'.'.$$where;
                   5623:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5624:                             if ($$role =~ /^cr\//) {
                   5625:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5626:                                 push(@rolecodes,'cr');
1.1002    raeburn  5627:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5628:                                 push(@rolecodes,$$role);
1.1002    raeburn  5629:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5630:                                                     $env{'user.name'});
1.1064    raeburn  5631:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5632:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5633:                                 $group_privs = &unescape($group_privs);
                   5634:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5635:                                 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  5636:                                 &get_groups_roles($tdomain,$trest,
                   5637:                                                   \%course_roles,\@rolecodes,
                   5638:                                                   \%groups_roles);
1.1002    raeburn  5639:                             } else {
1.1064    raeburn  5640:                                 push(@rolecodes,$$role);
1.1002    raeburn  5641:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5642:                             }
1.1064    raeburn  5643:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5644:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5645:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5646:                         }
                   5647:                     }
1.1034    raeburn  5648:                     $$tstatus = 'is';
1.1002    raeburn  5649:                 }
1.994     raeburn  5650:             }
                   5651:             if ($$tend) {
1.1104    raeburn  5652:                 if ($$tend<$update) {
1.994     raeburn  5653:                     $$tstatus='expired';
                   5654:                 } elsif ($$tend<$now) {
                   5655:                     $$tstatus='will_not';
                   5656:                 }
                   5657:             }
                   5658:         }
                   5659:     }
                   5660: }
                   5661: 
1.1104    raeburn  5662: sub get_groups_roles {
                   5663:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5664:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5665:                   (ref($rolecodes) eq 'ARRAY') && 
                   5666:                   (ref($groups_roles) eq 'HASH')); 
                   5667:     if (keys(%{$cdom_courseroles}) > 0) {
                   5668:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5669:         if ($cdom ne '' && $cnum ne '') {
                   5670:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5671:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5672:                     my $crsrole = $1;
                   5673:                     my $crssec = $2;
                   5674:                     if ($crsrole =~ /^cr/) {
                   5675:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5676:                             push(@{$rolecodes},'cr');
                   5677:                         }
                   5678:                     } else {
                   5679:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5680:                             push(@{$rolecodes},$crsrole);
                   5681:                         }
                   5682:                     }
                   5683:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5684:                     if ($crssec ne '') {
                   5685:                         $rolekey .= "/$crssec";
                   5686:                     }
                   5687:                     $rolekey .= './';
                   5688:                     $groups_roles->{$rolekey} = $rolecodes;
                   5689:                 }
                   5690:             }
                   5691:         }
                   5692:     }
                   5693:     return;
                   5694: }
                   5695: 
                   5696: sub delete_env_groupprivs {
                   5697:     my ($where,$courseroles,$possroles) = @_;
                   5698:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5699:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5700:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5701:         %{$courseroles->{$udom}} =
                   5702:             &get_my_roles('','','userroles',['active'],
                   5703:                           $possroles,[$udom],1);
                   5704:     }
                   5705:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5706:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5707:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5708:             my $area = '/'.$cdom.'/'.$cnum;
                   5709:             my $privkey = "user.priv.$crsrole.$area";
                   5710:             if ($crssec ne '') {
                   5711:                 $privkey .= '/'.$crssec;
                   5712:             }
                   5713:             $privkey .= ".$area/$group";
                   5714:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5715:         }
                   5716:     }
                   5717:     return;
                   5718: }
                   5719: 
1.994     raeburn  5720: sub check_adhoc_privs {
1.1172.2.86! raeburn  5721:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  5722:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86! raeburn  5723:     if ($sec) {
        !          5724:         $cckey .= '/'.$sec;
        !          5725:     }
1.1172.2.9  raeburn  5726:     my $setprivs;
1.994     raeburn  5727:     if ($env{$cckey}) {
                   5728:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5729:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5730:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86! raeburn  5731:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  5732:             $setprivs = 1;
1.994     raeburn  5733:         }
                   5734:     } else {
1.1088    raeburn  5735:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5736:         $setprivs = 1;
1.994     raeburn  5737:     }
1.1172.2.9  raeburn  5738:     return $setprivs;
1.994     raeburn  5739: }
                   5740: 
                   5741: sub set_adhoc_privileges {
1.1172.2.84  raeburn  5742: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86! raeburn  5743:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  5744:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86! raeburn  5745:     if ($sec ne '') {
        !          5746:         $area .= '/'.$sec;
        !          5747:     }
1.994     raeburn  5748:     my $spec = $role.'.'.$area;
                   5749:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5750:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  5751:     my %rolehash = ();
                   5752:     if ($role =~ m{^cr/$dcdom/$dcdom\Q-domainconfig\E/}) {
                   5753:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
                   5754:     } else {
                   5755:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   5756:     }
                   5757:     my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  5758:     &appenv(\%userroles,[$role,'cm']);
                   5759:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5760:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5761:         &appenv( {'request.role'        => $spec,
                   5762:                   'request.role.domain' => $dcdom,
                   5763:                   'request.course.sec'  => ''
                   5764:                  }
                   5765:                );
                   5766:         my $tadv=0;
                   5767:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5768:         &appenv({'request.role.adv'    => $tadv});
                   5769:     }
1.994     raeburn  5770: }
                   5771: 
1.12      www      5772: # --------------------------------------------------------------- get interface
                   5773: 
                   5774: sub get {
1.131     albertel 5775:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5776:    my $items='';
1.800     albertel 5777:    foreach my $item (@$storearr) {
                   5778:        $items.=&escape($item).'&';
1.191     harris41 5779:    }
1.12      www      5780:    $items=~s/\&$//;
1.620     albertel 5781:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5782:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5783:    my $uhome=&homeserver($uname,$udomain);
                   5784: 
1.133     albertel 5785:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5786:    my @pairs=split(/\&/,$rep);
1.273     albertel 5787:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5788:      return @pairs;
                   5789:    }
1.15      www      5790:    my %returnhash=();
1.42      www      5791:    my $i=0;
1.800     albertel 5792:    foreach my $item (@$storearr) {
                   5793:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5794:       $i++;
1.191     harris41 5795:    }
1.15      www      5796:    return %returnhash;
1.27      www      5797: }
                   5798: 
                   5799: # --------------------------------------------------------------- del interface
                   5800: 
                   5801: sub del {
1.133     albertel 5802:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5803:    my $items='';
1.800     albertel 5804:    foreach my $item (@$storearr) {
                   5805:        $items.=&escape($item).'&';
1.191     harris41 5806:    }
1.984     neumanie 5807: 
1.27      www      5808:    $items=~s/\&$//;
1.620     albertel 5809:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5810:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5811:    my $uhome=&homeserver($uname,$udomain);
                   5812:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5813: }
                   5814: 
                   5815: # -------------------------------------------------------------- dump interface
                   5816: 
1.1172.2.22  raeburn  5817: sub unserialize {
                   5818:     my ($rep, $escapedkeys) = @_;
                   5819: 
                   5820:     return {} if $rep =~ /^error/;
                   5821: 
                   5822:     my %returnhash=();
                   5823:     foreach my $item (split(/\&/,$rep)) {
                   5824:         my ($key, $value) = split(/=/, $item, 2);
                   5825:         $key = unescape($key) unless $escapedkeys;
                   5826:         next if $key =~ /^error: 2 /;
                   5827:         $returnhash{$key} = &thaw_unescape($value);
                   5828:     }
                   5829:     return \%returnhash;
                   5830: }
                   5831: 
                   5832: # see Lond::dump_with_regexp
                   5833: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5834: sub dump {
1.1172.2.22  raeburn  5835:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5836:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5837:     if (!$uname) { $uname=$env{'user.name'}; }
                   5838:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5839: 
1.1172.2.55  raeburn  5840:     if ($regexp) {
                   5841:         $regexp=&escape($regexp);
                   5842:     } else {
                   5843:         $regexp='.';
                   5844:     }
1.1172.2.22  raeburn  5845:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5846:         # user is hosted on this machine
1.1172.2.55  raeburn  5847:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5848:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5849:         return %{&unserialize($reply, $escapedkeys)};
                   5850:     }
1.1166    raeburn  5851:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5852:     my @pairs=split(/\&/,$rep);
                   5853:     my %returnhash=();
1.1098    foxr     5854:     if (!($rep =~ /^error/ )) {
                   5855: 	foreach my $item (@pairs) {
                   5856: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5857:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5858: 	    next if ($key =~ /^error: 2 /);
                   5859: 	    $returnhash{$key}=&thaw_unescape($value);
                   5860: 	}
1.755     albertel 5861:     }
                   5862:     return %returnhash;
1.407     www      5863: }
                   5864: 
1.1098    foxr     5865: 
1.717     albertel 5866: # --------------------------------------------------------- dumpstore interface
                   5867: 
                   5868: sub dumpstore {
                   5869:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5870:    # same as dump but keys must be escaped. They may contain colon separated
                   5871:    # lists of values that may themself contain colons (e.g. symbs).
                   5872:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5873: }
                   5874: 
1.407     www      5875: # -------------------------------------------------------------- keys interface
                   5876: 
                   5877: sub getkeys {
                   5878:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5879:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5880:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5881:    my $uhome=&homeserver($uname,$udomain);
                   5882:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5883:    my @keyarray=();
1.800     albertel 5884:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5885:       next if ($key =~ /^error: 2 /);
1.800     albertel 5886:       push(@keyarray,&unescape($key));
1.407     www      5887:    }
                   5888:    return @keyarray;
1.318     matthew  5889: }
                   5890: 
1.319     matthew  5891: # --------------------------------------------------------------- currentdump
                   5892: sub currentdump {
1.328     matthew  5893:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5894:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5895:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5896:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5897:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  5898:    my $rep;
                   5899: 
                   5900:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5901:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   5902:                    $courseid)));
                   5903:    } else {
                   5904:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5905:    }
                   5906: 
1.318     matthew  5907:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5908:    #
1.318     matthew  5909:    my %returnhash=();
1.319     matthew  5910:    #
                   5911:    if ($rep eq "unknown_cmd") { 
                   5912:        # an old lond will not know currentdump
                   5913:        # Do a dump and make it look like a currentdump
1.822     albertel 5914:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5915:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5916:        my %hash = @tmp;
                   5917:        @tmp=();
1.424     matthew  5918:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5919:    } else {
                   5920:        my @pairs=split(/\&/,$rep);
1.800     albertel 5921:        foreach my $pair (@pairs) {
                   5922:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5923:            my ($symb,$param) = split(/:/,$key);
                   5924:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5925:                                                         &thaw_unescape($value);
1.319     matthew  5926:        }
1.191     harris41 5927:    }
1.12      www      5928:    return %returnhash;
1.424     matthew  5929: }
                   5930: 
                   5931: sub convert_dump_to_currentdump{
                   5932:     my %hash = %{shift()};
                   5933:     my %returnhash;
                   5934:     # Code ripped from lond, essentially.  The only difference
                   5935:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5936:     # we might run in to problems with parameter names =~ /^v\./
                   5937:     while (my ($key,$value) = each(%hash)) {
                   5938:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5939: 	$symb  = &unescape($symb);
                   5940: 	$param = &unescape($param);
1.424     matthew  5941:         next if ($v eq 'version' || $symb eq 'keys');
                   5942:         next if (exists($returnhash{$symb}) &&
                   5943:                  exists($returnhash{$symb}->{$param}) &&
                   5944:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5945:         $returnhash{$symb}->{$param}=$value;
                   5946:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5947:     }
                   5948:     #
                   5949:     # Remove all of the keys in the hashes which keep track of
                   5950:     # the version of the parameter.
                   5951:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5952:         # use a foreach because we are going to delete from the hash.
                   5953:         foreach my $key (keys(%$param_hash)) {
                   5954:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5955:         }
                   5956:     }
                   5957:     return \%returnhash;
1.12      www      5958: }
                   5959: 
1.627     albertel 5960: # ------------------------------------------------------ critical inc interface
                   5961: 
                   5962: sub cinc {
                   5963:     return &inc(@_,'critical');
                   5964: }
                   5965: 
1.449     matthew  5966: # --------------------------------------------------------------- inc interface
                   5967: 
                   5968: sub inc {
1.627     albertel 5969:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5970:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5971:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5972:     my $uhome=&homeserver($uname,$udomain);
                   5973:     my $items='';
                   5974:     if (! ref($store)) {
                   5975:         # got a single value, so use that instead
                   5976:         $items = &escape($store).'=&';
                   5977:     } elsif (ref($store) eq 'SCALAR') {
                   5978:         $items = &escape($$store).'=&';        
                   5979:     } elsif (ref($store) eq 'ARRAY') {
                   5980:         $items = join('=&',map {&escape($_);} @{$store});
                   5981:     } elsif (ref($store) eq 'HASH') {
                   5982:         while (my($key,$value) = each(%{$store})) {
                   5983:             $items.= &escape($key).'='.&escape($value).'&';
                   5984:         }
                   5985:     }
                   5986:     $items=~s/\&$//;
1.627     albertel 5987:     if ($critical) {
                   5988: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5989:     } else {
                   5990: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5991:     }
1.449     matthew  5992: }
                   5993: 
1.12      www      5994: # --------------------------------------------------------------- put interface
                   5995: 
                   5996: sub put {
1.134     albertel 5997:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5998:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5999:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6000:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6001:    my $items='';
1.800     albertel 6002:    foreach my $item (keys(%$storehash)) {
                   6003:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6004:    }
1.12      www      6005:    $items=~s/\&$//;
1.134     albertel 6006:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6007: }
                   6008: 
1.631     albertel 6009: # ------------------------------------------------------------ newput interface
                   6010: 
                   6011: sub newput {
                   6012:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6013:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6014:    if (!$uname) { $uname=$env{'user.name'}; }
                   6015:    my $uhome=&homeserver($uname,$udomain);
                   6016:    my $items='';
                   6017:    foreach my $key (keys(%$storehash)) {
                   6018:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6019:    }
                   6020:    $items=~s/\&$//;
                   6021:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6022: }
                   6023: 
                   6024: # ---------------------------------------------------------  putstore interface
                   6025: 
1.524     raeburn  6026: sub putstore {
1.1172.2.59  raeburn  6027:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6028:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6029:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6030:    my $uhome=&homeserver($uname,$udomain);
                   6031:    my $items='';
1.715     albertel 6032:    foreach my $key (keys(%$storehash)) {
                   6033:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6034:    }
1.715     albertel 6035:    $items=~s/\&$//;
1.716     albertel 6036:    my $esc_symb=&escape($symb);
                   6037:    my $esc_v=&escape($version);
1.715     albertel 6038:    my $reply =
1.716     albertel 6039:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6040: 	      $uhome);
1.1172.2.59  raeburn  6041:    if (($tolog) && ($reply eq 'ok')) {
                   6042:        my $namevalue='';
                   6043:        foreach my $key (keys(%{$storehash})) {
                   6044:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6045:        }
                   6046:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6047:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6048:                      '&version='.$esc_v.
                   6049:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6050:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6051:    }
1.715     albertel 6052:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6053:        # gfall back to way things use to be done
1.715     albertel 6054:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6055: 			    $uname);
1.524     raeburn  6056:    }
1.715     albertel 6057:    return $reply;
                   6058: }
                   6059: 
                   6060: sub old_putstore {
1.716     albertel 6061:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6062:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6063:     if (!$uname) { $uname=$env{'user.name'}; }
                   6064:     my $uhome=&homeserver($uname,$udomain);
                   6065:     my %newstorehash;
1.800     albertel 6066:     foreach my $item (keys(%$storehash)) {
                   6067: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6068: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6069:     }
                   6070:     my $items='';
                   6071:     my %allitems = ();
1.800     albertel 6072:     foreach my $item (keys(%newstorehash)) {
                   6073: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6074: 	    my $key = $1.':keys:'.$2;
                   6075: 	    $allitems{$key} .= $3.':';
                   6076: 	}
1.800     albertel 6077: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6078:     }
1.800     albertel 6079:     foreach my $item (keys(%allitems)) {
                   6080: 	$allitems{$item} =~ s/\:$//;
                   6081: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6082:     }
                   6083:     $items=~s/\&$//;
                   6084:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6085: }
                   6086: 
1.47      www      6087: # ------------------------------------------------------ critical put interface
                   6088: 
                   6089: sub cput {
1.134     albertel 6090:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6091:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6092:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6093:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6094:    my $items='';
1.800     albertel 6095:    foreach my $item (keys(%$storehash)) {
                   6096:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6097:    }
1.47      www      6098:    $items=~s/\&$//;
1.134     albertel 6099:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6100: }
                   6101: 
                   6102: # -------------------------------------------------------------- eget interface
                   6103: 
                   6104: sub eget {
1.133     albertel 6105:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6106:    my $items='';
1.800     albertel 6107:    foreach my $item (@$storearr) {
                   6108:        $items.=&escape($item).'&';
1.191     harris41 6109:    }
1.12      www      6110:    $items=~s/\&$//;
1.620     albertel 6111:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6112:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6113:    my $uhome=&homeserver($uname,$udomain);
                   6114:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6115:    my @pairs=split(/\&/,$rep);
                   6116:    my %returnhash=();
1.42      www      6117:    my $i=0;
1.800     albertel 6118:    foreach my $item (@$storearr) {
                   6119:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6120:       $i++;
1.191     harris41 6121:    }
1.12      www      6122:    return %returnhash;
                   6123: }
                   6124: 
1.667     albertel 6125: # ------------------------------------------------------------ tmpput interface
                   6126: sub tmpput {
1.802     raeburn  6127:     my ($storehash,$server,$context)=@_;
1.667     albertel 6128:     my $items='';
1.800     albertel 6129:     foreach my $item (keys(%$storehash)) {
                   6130: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6131:     }
                   6132:     $items=~s/\&$//;
1.802     raeburn  6133:     if (defined($context)) {
                   6134:         $items .= ':'.&escape($context);
                   6135:     }
1.667     albertel 6136:     return &reply("tmpput:$items",$server);
                   6137: }
                   6138: 
                   6139: # ------------------------------------------------------------ tmpget interface
                   6140: sub tmpget {
1.688     albertel 6141:     my ($token,$server)=@_;
                   6142:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6143:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6144:     my %returnhash;
1.1172.2.85  raeburn  6145:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6146:         return %returnhash;
                   6147:     }
1.667     albertel 6148:     foreach my $item (split(/\&/,$rep)) {
                   6149: 	my ($key,$value)=split(/=/,$item);
                   6150: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6151:     }
                   6152:     return %returnhash;
                   6153: }
                   6154: 
1.1113    raeburn  6155: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6156: sub tmpdel {
                   6157:     my ($token,$server)=@_;
                   6158:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6159:     return &reply("tmpdel:$token",$server);
                   6160: }
                   6161: 
1.1172.2.13  raeburn  6162: # ------------------------------------------------------------ get_timebased_id
                   6163: 
                   6164: sub get_timebased_id {
                   6165:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6166:         $maxtries) = @_;
                   6167:     my ($newid,$error,$dellock);
                   6168:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6169:         return ('','ok','invalid call to get suffix');
                   6170:     }
                   6171: 
                   6172: # set defaults for any optional args for which values were not supplied
                   6173:     if ($who eq '') {
                   6174:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6175:     }
                   6176:     if (!$locktries) {
                   6177:         $locktries = 3;
                   6178:     }
                   6179:     if (!$maxtries) {
                   6180:         $maxtries = 10;
                   6181:     }
                   6182: 
                   6183:     if (($cdom eq '') || ($cnum eq '')) {
                   6184:         if ($env{'request.course.id'}) {
                   6185:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6186:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6187:         }
                   6188:         if (($cdom eq '') || ($cnum eq '')) {
                   6189:             return ('','ok','call to get suffix not in course context');
                   6190:         }
                   6191:     }
                   6192: 
                   6193: # construct locking item
                   6194:     my $lockhash = {
                   6195:                       $prefix."\0".'locked_'.$keyid => $who,
                   6196:                    };
                   6197:     my $tries = 0;
                   6198: 
                   6199: # attempt to get lock on nohist_$namespace file
                   6200:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6201:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6202:         $tries ++;
                   6203:         sleep 1;
                   6204:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6205:     }
                   6206: 
                   6207: # attempt to get unique identifier, based on current timestamp
                   6208:     if ($gotlock eq 'ok') {
                   6209:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6210:         my $id = time;
                   6211:         $newid = $id;
1.1172.2.56  raeburn  6212:         if ($idtype eq 'addcode') {
                   6213:             $newid .= &sixnum_code();
                   6214:         }
1.1172.2.13  raeburn  6215:         my $idtries = 0;
                   6216:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6217:             if ($idtype eq 'concat') {
                   6218:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6219:             } elsif ($idtype eq 'addcode') {
                   6220:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6221:             } else {
                   6222:                 $newid ++;
                   6223:             }
                   6224:             $idtries ++;
                   6225:         }
                   6226:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6227:             my %new_item =  (
                   6228:                               $prefix."\0".$newid => $who,
                   6229:                             );
                   6230:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6231:                                                  $cdom,$cnum);
                   6232:             if ($putresult ne 'ok') {
                   6233:                 undef($newid);
                   6234:                 $error = 'error saving new item: '.$putresult;
                   6235:             }
                   6236:         } else {
1.1172.2.56  raeburn  6237:              undef($newid);
1.1172.2.13  raeburn  6238:              $error = ('error: no unique suffix available for the new item ');
                   6239:         }
                   6240: #  remove lock
                   6241:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6242:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6243:     } else {
                   6244:         $error = "error: could not obtain lockfile\n";
                   6245:         $dellock = 'ok';
1.1172.2.58  raeburn  6246:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6247:             $dellock = 'nolock';
                   6248:         }
1.1172.2.13  raeburn  6249:     }
                   6250:     return ($newid,$dellock,$error);
                   6251: }
                   6252: 
1.1172.2.56  raeburn  6253: sub sixnum_code {
                   6254:     my $code;
                   6255:     for (0..6) {
                   6256:         $code .= int( rand(9) );
                   6257:     }
                   6258:     return $code;
                   6259: }
                   6260: 
1.765     albertel 6261: # -------------------------------------------------- portfolio access checking
                   6262: 
                   6263: sub portfolio_access {
1.1172.2.77  raeburn  6264:     my ($requrl,$clientip) = @_;
1.765     albertel 6265:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6266:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6267:     if ($result) {
                   6268:         my %setters;
                   6269:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6270:             my ($startblock,$endblock) =
                   6271:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6272:             if ($startblock && $endblock) {
                   6273:                 return 'B';
                   6274:             }
                   6275:         } else {
                   6276:             my ($startblock,$endblock) =
                   6277:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6278:             if ($startblock && $endblock) {
                   6279:                 return 'B';
                   6280:             }
                   6281:         }
                   6282:     }
1.765     albertel 6283:     if ($result eq 'ok') {
1.766     albertel 6284:        return 'F';
1.765     albertel 6285:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6286:        return 'A';
1.765     albertel 6287:     }
1.766     albertel 6288:     return '';
1.765     albertel 6289: }
                   6290: 
                   6291: sub get_portfolio_access {
1.1172.2.77  raeburn  6292:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6293: 
                   6294:     if (!ref($access_hash)) {
                   6295: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6296: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6297: 						   $file_name);
                   6298: 	$access_hash = $access_controls{$file_name};
                   6299:     }
                   6300: 
1.1172.2.77  raeburn  6301:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6302:     my $now = time;
                   6303:     if (ref($access_hash) eq 'HASH') {
                   6304:         foreach my $key (keys(%{$access_hash})) {
                   6305:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6306:             if ($start > $now) {
                   6307:                 next;
                   6308:             }
                   6309:             if ($end && $end<$now) {
                   6310:                 next;
                   6311:             }
                   6312:             if ($scope eq 'public') {
                   6313:                 $public = $key;
                   6314:                 last;
                   6315:             } elsif ($scope eq 'guest') {
                   6316:                 $guest = $key;
                   6317:             } elsif ($scope eq 'domains') {
                   6318:                 push(@domains,$key);
                   6319:             } elsif ($scope eq 'users') {
                   6320:                 push(@users,$key);
                   6321:             } elsif ($scope eq 'course') {
                   6322:                 push(@courses,$key);
                   6323:             } elsif ($scope eq 'group') {
                   6324:                 push(@groups,$key);
1.1172.2.77  raeburn  6325:             } elsif ($scope eq 'ip') {
                   6326:                 push(@ips,$key);
1.765     albertel 6327:             }
                   6328:         }
                   6329:         if ($public) {
                   6330:             return 'ok';
1.1172.2.77  raeburn  6331:         } elsif (@ips > 0) {
                   6332:             my $allowed;
                   6333:             foreach my $ipkey (@ips) {
                   6334:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6335:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6336:                         $allowed = 1;
                   6337:                         last;
                   6338:                     }
                   6339:                 }
                   6340:             }
                   6341:             if ($allowed) {
                   6342:                 return 'ok';
                   6343:             }
1.765     albertel 6344:         }
                   6345:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6346:             if ($guest) {
                   6347:                 return $guest;
                   6348:             }
                   6349:         } else {
                   6350:             if (@domains > 0) {
                   6351:                 foreach my $domkey (@domains) {
                   6352:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6353:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6354:                             return 'ok';
                   6355:                         }
                   6356:                     }
                   6357:                 }
                   6358:             }
                   6359:             if (@users > 0) {
                   6360:                 foreach my $userkey (@users) {
1.865     raeburn  6361:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6362:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6363:                             if (ref($item) eq 'HASH') {
                   6364:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6365:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6366:                                     return 'ok';
                   6367:                                 }
                   6368:                             }
                   6369:                         }
                   6370:                     } 
1.765     albertel 6371:                 }
                   6372:             }
                   6373:             my %roleshash;
                   6374:             my @courses_and_groups = @courses;
                   6375:             push(@courses_and_groups,@groups); 
                   6376:             if (@courses_and_groups > 0) {
                   6377:                 my (%allgroups,%allroles); 
                   6378:                 my ($start,$end,$role,$sec,$group);
                   6379:                 foreach my $envkey (%env) {
1.1060    raeburn  6380:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6381:                         my $cid = $2.'_'.$3; 
                   6382:                         if ($1 eq 'gr') {
                   6383:                             $group = $4;
                   6384:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6385:                         } else {
                   6386:                             if ($4 eq '') {
                   6387:                                 $sec = 'none';
                   6388:                             } else {
                   6389:                                 $sec = $4;
                   6390:                             }
                   6391:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6392:                         }
1.811     albertel 6393:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6394:                         my $cid = $2.'_'.$3;
                   6395:                         if ($4 eq '') {
                   6396:                             $sec = 'none';
                   6397:                         } else {
                   6398:                             $sec = $4;
                   6399:                         }
                   6400:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6401:                     }
                   6402:                 }
                   6403:                 if (keys(%allroles) == 0) {
                   6404:                     return;
                   6405:                 }
                   6406:                 foreach my $key (@courses_and_groups) {
                   6407:                     my %content = %{$$access_hash{$key}};
                   6408:                     my $cnum = $content{'number'};
                   6409:                     my $cdom = $content{'domain'};
                   6410:                     my $cid = $cdom.'_'.$cnum;
                   6411:                     if (!exists($allroles{$cid})) {
                   6412:                         next;
                   6413:                     }    
                   6414:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6415:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6416:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6417:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6418:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6419:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6420:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6421:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6422:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6423:                                         if (grep/^all$/,@sections) {
                   6424:                                             return 'ok';
                   6425:                                         } else {
                   6426:                                             if (grep/^$sec$/,@sections) {
                   6427:                                                 return 'ok';
                   6428:                                             }
                   6429:                                         }
                   6430:                                     }
                   6431:                                 }
                   6432:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6433:                                     if (grep/^none$/,@groups) {
                   6434:                                         return 'ok';
                   6435:                                     }
                   6436:                                 } else {
                   6437:                                     if (grep/^all$/,@groups) {
                   6438:                                         return 'ok';
                   6439:                                     } 
                   6440:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6441:                                         if (grep/^$group$/,@groups) {
                   6442:                                             return 'ok';
                   6443:                                         }
                   6444:                                     }
                   6445:                                 } 
                   6446:                             }
                   6447:                         }
                   6448:                     }
                   6449:                 }
                   6450:             }
                   6451:             if ($guest) {
                   6452:                 return $guest;
                   6453:             }
                   6454:         }
                   6455:     }
                   6456:     return;
                   6457: }
                   6458: 
                   6459: sub course_group_datechecker {
                   6460:     my ($dates,$now,$status) = @_;
                   6461:     my ($start,$end) = split(/\./,$dates);
                   6462:     if (!$start && !$end) {
                   6463:         return 'ok';
                   6464:     }
                   6465:     if (grep/^active$/,@{$status}) {
                   6466:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6467:             return 'ok';
                   6468:         }
                   6469:     }
                   6470:     if (grep/^previous$/,@{$status}) {
                   6471:         if ($end > $now ) {
                   6472:             return 'ok';
                   6473:         }
                   6474:     }
                   6475:     if (grep/^future$/,@{$status}) {
                   6476:         if ($start > $now) {
                   6477:             return 'ok';
                   6478:         }
                   6479:     }
                   6480:     return; 
                   6481: }
                   6482: 
                   6483: sub parse_portfolio_url {
                   6484:     my ($url) = @_;
                   6485: 
                   6486:     my ($type,$udom,$unum,$group,$file_name);
                   6487:     
1.823     albertel 6488:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6489: 	$type = 1;
                   6490:         $udom = $1;
                   6491:         $unum = $2;
                   6492:         $file_name = $3;
1.823     albertel 6493:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6494: 	$type = 2;
                   6495:         $udom = $1;
                   6496:         $unum = $2;
                   6497:         $group = $3;
                   6498:         $file_name = $3.'/'.$4;
                   6499:     }
                   6500:     if (wantarray) {
                   6501: 	return ($type,$udom,$unum,$file_name,$group);
                   6502:     }
                   6503:     return $type;
                   6504: }
                   6505: 
                   6506: sub is_portfolio_url {
                   6507:     my ($url) = @_;
                   6508:     return scalar(&parse_portfolio_url($url));
                   6509: }
                   6510: 
1.798     raeburn  6511: sub is_portfolio_file {
                   6512:     my ($file) = @_;
1.820     raeburn  6513:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6514:         return 1;
                   6515:     }
                   6516:     return;
                   6517: }
                   6518: 
1.976     raeburn  6519: sub usertools_access {
1.1084    raeburn  6520:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6521:     my ($access,%tools);
                   6522:     if ($context eq '') {
                   6523:         $context = 'tools';
                   6524:     }
                   6525:     if ($context eq 'requestcourses') {
                   6526:         %tools = (
                   6527:                       official   => 1,
                   6528:                       unofficial => 1,
1.1006    raeburn  6529:                       community  => 1,
1.1172.2.37  raeburn  6530:                       textbook   => 1,
1.985     raeburn  6531:                  );
1.1172.2.9  raeburn  6532:     } elsif ($context eq 'requestauthor') {
                   6533:         %tools = (
                   6534:                       requestauthor => 1,
                   6535:                  );
1.985     raeburn  6536:     } else {
                   6537:         %tools = (
                   6538:                       aboutme   => 1,
                   6539:                       blog      => 1,
1.1172.2.6  raeburn  6540:                       webdav    => 1,
1.985     raeburn  6541:                       portfolio => 1,
                   6542:                  );
                   6543:     }
1.976     raeburn  6544:     return if (!defined($tools{$tool}));
                   6545: 
1.1172.2.35  raeburn  6546:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6547:         $udom = $env{'user.domain'};
                   6548:         $uname = $env{'user.name'};
                   6549:     }
                   6550: 
1.978     raeburn  6551:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6552:         if ($action ne 'reload') {
1.985     raeburn  6553:             if ($context eq 'requestcourses') {
                   6554:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6555:             } elsif ($context eq 'requestauthor') {
                   6556:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6557:             } else {
                   6558:                 return $env{'environment.availabletools.'.$tool};
                   6559:             }
                   6560:         }
1.976     raeburn  6561:     }
                   6562: 
1.1172.2.9  raeburn  6563:     my ($toolstatus,$inststatus,$envkey);
                   6564:     if ($context eq 'requestauthor') {
                   6565:         $envkey = $context;
                   6566:     } else {
                   6567:         $envkey = $context.'.'.$tool;
                   6568:     }
1.976     raeburn  6569: 
1.985     raeburn  6570:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6571:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6572:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6573:         $inststatus = $env{'environment.inststatus'};
                   6574:     } else {
1.1084    raeburn  6575:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6576:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6577:             $inststatus = $userenvref->{'inststatus'};
                   6578:         } else {
1.1172.2.9  raeburn  6579:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6580:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6581:             $inststatus = $userenv{'inststatus'};
                   6582:         }
1.976     raeburn  6583:     }
                   6584: 
                   6585:     if ($toolstatus ne '') {
                   6586:         if ($toolstatus) {
                   6587:             $access = 1;
                   6588:         } else {
                   6589:             $access = 0;
                   6590:         }
                   6591:         return $access;
                   6592:     }
                   6593: 
1.1084    raeburn  6594:     my ($is_adv,%domdef);
                   6595:     if (ref($is_advref) eq 'HASH') {
                   6596:         $is_adv = $is_advref->{'is_adv'};
                   6597:     } else {
                   6598:         $is_adv = &is_advanced_user($udom,$uname);
                   6599:     }
                   6600:     if (ref($domdefref) eq 'HASH') {
                   6601:         %domdef = %{$domdefref};
                   6602:     } else {
                   6603:         %domdef = &get_domain_defaults($udom);
                   6604:     }
1.976     raeburn  6605:     if (ref($domdef{$tool}) eq 'HASH') {
                   6606:         if ($is_adv) {
                   6607:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6608:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6609:                     $access = 1;
                   6610:                 } else {
                   6611:                     $access = 0;
                   6612:                 }
                   6613:                 return $access;
                   6614:             }
                   6615:         }
                   6616:         if ($inststatus ne '') {
                   6617:             my ($hasaccess,$hasnoaccess);
                   6618:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6619:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6620:                     if ($domdef{$tool}{$affiliation}) {
                   6621:                         $hasaccess = 1;
                   6622:                     } else {
                   6623:                         $hasnoaccess = 1;
                   6624:                     }
                   6625:                 }
                   6626:             }
                   6627:             if ($hasaccess || $hasnoaccess) {
                   6628:                 if ($hasaccess) {
                   6629:                     $access = 1;
                   6630:                 } elsif ($hasnoaccess) {
                   6631:                     $access = 0; 
                   6632:                 }
                   6633:                 return $access;
                   6634:             }
                   6635:         } else {
                   6636:             if ($domdef{$tool}{'default'} ne '') {
                   6637:                 if ($domdef{$tool}{'default'}) {
                   6638:                     $access = 1;
                   6639:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6640:                     $access = 0;
                   6641:                 }
                   6642:                 return $access;
                   6643:             }
                   6644:         }
                   6645:     } else {
1.1172.2.6  raeburn  6646:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6647:             $access = 1;
                   6648:         } else {
                   6649:             $access = 0;
                   6650:         }
1.976     raeburn  6651:         return $access;
                   6652:     }
                   6653: }
                   6654: 
1.1050    raeburn  6655: sub is_course_owner {
                   6656:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6657:     if (($udom eq '') || ($uname eq '')) {
                   6658:         $udom = $env{'user.domain'};
                   6659:         $uname = $env{'user.name'};
                   6660:     }
                   6661:     unless (($udom eq '') || ($uname eq '')) {
                   6662:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6663:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6664:                 return 1;
                   6665:             } else {
                   6666:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6667:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6668:                     return 1;
                   6669:                 }
                   6670:             }
                   6671:         }
                   6672:     }
                   6673:     return;
                   6674: }
                   6675: 
1.976     raeburn  6676: sub is_advanced_user {
                   6677:     my ($udom,$uname) = @_;
1.1085    raeburn  6678:     if ($udom ne '' && $uname ne '') {
                   6679:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6680:             if (wantarray) {
                   6681:                 return ($env{'user.adv'},$env{'user.author'});
                   6682:             } else {
                   6683:                 return $env{'user.adv'};
                   6684:             }
1.1085    raeburn  6685:         }
                   6686:     }
1.976     raeburn  6687:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6688:     my %allroles;
1.1128    raeburn  6689:     my ($is_adv,$is_author);
1.976     raeburn  6690:     foreach my $role (keys(%roleshash)) {
                   6691:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6692:         my $area = '/'.$tdomain.'/'.$trest;
                   6693:         if ($sec ne '') {
                   6694:             $area .= '/'.$sec;
                   6695:         }
                   6696:         if (($area ne '') && ($trole ne '')) {
                   6697:             my $spec=$trole.'.'.$area;
                   6698:             if ($trole =~ /^cr\//) {
                   6699:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6700:             } elsif ($trole ne 'gr') {
                   6701:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6702:             }
1.1128    raeburn  6703:             if ($trole eq 'au') {
                   6704:                 $is_author = 1;
                   6705:             }
1.976     raeburn  6706:         }
                   6707:     }
                   6708:     foreach my $role (keys(%allroles)) {
                   6709:         last if ($is_adv);
                   6710:         foreach my $item (split(/:/,$allroles{$role})) {
                   6711:             if ($item ne '') {
                   6712:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6713:                 if ($privilege eq 'adv') {
                   6714:                     $is_adv = 1;
                   6715:                     last;
                   6716:                 }
                   6717:             }
                   6718:         }
                   6719:     }
1.1128    raeburn  6720:     if (wantarray) {
                   6721:         return ($is_adv,$is_author);
                   6722:     }
1.976     raeburn  6723:     return $is_adv;
                   6724: }
1.798     raeburn  6725: 
1.1035    raeburn  6726: sub check_can_request {
1.1036    raeburn  6727:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6728:     my $canreq = 0;
                   6729:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6730:     my @options = ('approval','validate','autolimit');
                   6731:     my $optregex = join('|',@options);
                   6732:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6733:         foreach my $type (@{$types}) {
                   6734:             if (&usertools_access($env{'user.name'},
                   6735:                                   $env{'user.domain'},
                   6736:                                   $type,undef,'requestcourses')) {
                   6737:                 $canreq ++;
1.1036    raeburn  6738:                 if (ref($request_domains) eq 'HASH') {
                   6739:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6740:                 }
1.1035    raeburn  6741:                 if ($dom eq $env{'user.domain'}) {
                   6742:                     $can_request->{$type} = 1;
                   6743:                 }
                   6744:             }
                   6745:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6746:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6747:                 if (@curr > 0) {
1.1036    raeburn  6748:                     foreach my $item (@curr) {
                   6749:                         if (ref($request_domains) eq 'HASH') {
                   6750:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6751:                             if ($otherdom ne '') {
                   6752:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6753:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6754:                                         push(@{$request_domains->{$type}},$otherdom);
                   6755:                                     }
                   6756:                                 } else {
                   6757:                                     push(@{$request_domains->{$type}},$otherdom);
                   6758:                                 }
                   6759:                             }
                   6760:                         }
                   6761:                     }
                   6762:                     unless($dom eq $env{'user.domain'}) {
                   6763:                         $canreq ++;
1.1035    raeburn  6764:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6765:                             $can_request->{$type} = 1;
                   6766:                         }
                   6767:                     }
                   6768:                 }
                   6769:             }
                   6770:         }
                   6771:     }
                   6772:     return $canreq;
                   6773: }
                   6774: 
1.341     www      6775: # ---------------------------------------------- Custom access rule evaluation
                   6776: 
                   6777: sub customaccess {
                   6778:     my ($priv,$uri)=@_;
1.807     albertel 6779:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6780:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6781:     $udom = &LONCAPA::clean_domain($udom);
                   6782:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6783:     my $access=0;
1.800     albertel 6784:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6785: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6786: 	if ($type eq 'user') {
                   6787: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6788: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6789: 		if ($tdom) {
                   6790: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6791: 		}
1.896     albertel 6792: 		if ($tuname) {
                   6793: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6794: 		}
                   6795: 		$access=($effect eq 'allow');
                   6796: 		last;
                   6797: 	    }
                   6798: 	} else {
                   6799: 	    if ($role) {
                   6800: 		if ($role ne $urole) { next; }
                   6801: 	    }
                   6802: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6803: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6804: 		if ($tdom) {
                   6805: 		    if ($tdom ne $udom) { next; }
                   6806: 		}
                   6807: 		if ($tcrs) {
                   6808: 		    if ($tcrs ne $ucrs) { next; }
                   6809: 		}
                   6810: 		if ($tsec) {
                   6811: 		    if ($tsec ne $usec) { next; }
                   6812: 		}
                   6813: 		$access=($effect eq 'allow');
                   6814: 		last;
                   6815: 	    }
                   6816: 	    if ($realm eq '' && $role eq '') {
                   6817: 		$access=($effect eq 'allow');
                   6818: 	    }
1.402     bowersj2 6819: 	}
1.341     www      6820:     }
                   6821:     return $access;
                   6822: }
                   6823: 
1.103     harris41 6824: # ------------------------------------------------- Check for a user privilege
1.12      www      6825: 
                   6826: sub allowed {
1.1172.2.65  raeburn  6827:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6828:     my $ver_orguri=$uri;
1.439     www      6829:     $uri=&deversion($uri);
1.152     www      6830:     my $orguri=$uri;
1.52      www      6831:     $uri=&declutter($uri);
1.809     raeburn  6832: 
1.810     raeburn  6833:     if ($priv eq 'evb') {
                   6834: # Evade communication block restrictions for specified role in a course
                   6835:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6836:             return $1;
                   6837:         } else {
                   6838:             return;
                   6839:         }
                   6840:     }
                   6841: 
1.620     albertel 6842:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6843: # Free bre access to adm and meta resources
1.775     albertel 6844:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6845: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6846: 	&& ($priv eq 'bre')) {
1.14      www      6847: 	return 'F';
1.159     www      6848:     }
                   6849: 
1.545     banghart 6850: # Free bre access to user's own portfolio contents
1.714     raeburn  6851:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6852:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6853: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6854:         my %setters;
                   6855:         my ($startblock,$endblock) = 
                   6856:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6857:         if ($startblock && $endblock) {
                   6858:             return 'B';
                   6859:         } else {
                   6860:             return 'F';
                   6861:         }
1.545     banghart 6862:     }
                   6863: 
1.762     raeburn  6864: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6865:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6866:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6867:         if (exists($env{'request.course.id'})) {
                   6868:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6869:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6870:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6871:                 my $courseprivid=$env{'request.course.id'};
                   6872:                 $courseprivid=~s/\_/\//;
                   6873:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6874:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6875:                     return $1; 
1.762     raeburn  6876:                 } else {
                   6877:                     if ($env{'request.course.sec'}) {
                   6878:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6879:                     }
                   6880:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6881:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6882:                         return $2;
                   6883:                     }
1.714     raeburn  6884:                 }
                   6885:             }
                   6886:         }
                   6887:     }
                   6888: 
1.159     www      6889: # Free bre to public access
                   6890: 
                   6891:     if ($priv eq 'bre') {
1.238     www      6892:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6893: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6894:            return 'F'; 
                   6895:         }
1.238     www      6896:         if ($copyright eq 'priv') {
                   6897:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6898: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6899: 		return '';
                   6900:             }
                   6901:         }
                   6902:         if ($copyright eq 'domain') {
                   6903:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6904: 	    unless (($env{'user.domain'} eq $1) ||
                   6905:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6906: 		return '';
                   6907:             }
1.262     matthew  6908:         }
1.620     albertel 6909:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6910:             # Library role, so allow browsing of resources in this domain.
                   6911:             return 'F';
1.238     www      6912:         }
1.341     www      6913:         if ($copyright eq 'custom') {
                   6914: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6915:         }
1.14      www      6916:     }
1.264     matthew  6917:     # Domain coordinator is trying to create a course
1.620     albertel 6918:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6919:         # uri is the requested domain in this case.
                   6920:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6921:         # a role of dc for the domain in question.
1.620     albertel 6922:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6923:     }
1.29      www      6924: 
1.52      www      6925:     my $thisallowed='';
                   6926:     my $statecond=0;
                   6927:     my $courseprivid='';
                   6928: 
1.1039    raeburn  6929:     my $ownaccess;
1.1043    raeburn  6930:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6931:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6932:         if ($uri eq '') {
                   6933:             $ownaccess = 1;
                   6934:         } else {
                   6935:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6936:                 my $udom = $env{'user.domain'};
                   6937:                 my $uname = $env{'user.name'};
                   6938:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6939:                     $ownaccess = 1;
1.1040    raeburn  6940:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6941:                     unless ($uri =~ m{\.\./}) {
                   6942:                         $ownaccess = 1;
                   6943:                     }
                   6944:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6945:                     my $now = time;
                   6946:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6947:                         my $adom = $1;
                   6948:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6949:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6950:                                 my ($start,$end) = split('.',$env{$key});
                   6951:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6952:                                     $ownaccess = 1;
                   6953:                                     last;
                   6954:                                 }
                   6955:                             }
                   6956:                         }
                   6957:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6958:                         my $adom = $1;
                   6959:                         my $aname = $2;
1.1042    raeburn  6960:                         foreach my $role ('ca','aa') { 
                   6961:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6962:                                 my ($start,$end) =
                   6963:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6964:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6965:                                     $ownaccess = 1;
                   6966:                                     last;
                   6967:                                 }
1.1039    raeburn  6968:                             }
                   6969:                         }
                   6970:                     }
                   6971:                 }
                   6972:             }
                   6973:         }
                   6974:     }
                   6975: 
1.52      www      6976: # Course
                   6977: 
1.620     albertel 6978:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6979:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6980:             $thisallowed.=$1;
                   6981:         }
1.52      www      6982:     }
1.29      www      6983: 
1.52      www      6984: # Domain
                   6985: 
1.620     albertel 6986:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6987:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6988:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6989:             $thisallowed.=$1;
                   6990:         }
1.12      www      6991:     }
1.52      www      6992: 
1.1141    raeburn  6993: # User who is not author or co-author might still be able to edit
                   6994: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6995:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6996:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6997:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6998:             $thisallowed.=$1;
                   6999:         }
                   7000:     }
                   7001: 
1.52      www      7002: # Course: uri itself is a course
1.66      www      7003:     my $courseuri=$uri;
                   7004:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7005:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7006: 
1.620     albertel 7007:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7008:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7009:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7010:             $thisallowed.=$1;
                   7011:         }
1.12      www      7012:     }
1.29      www      7013: 
1.665     albertel 7014: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7015: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7016:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7017: 	$thisallowed='';
1.671     raeburn  7018:         my ($match)=&is_on_map($uri);
                   7019:         if ($match) {
                   7020:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7021:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7022:                 my $value = $1;
                   7023:                 if ($noblockcheck) {
                   7024:                     $thisallowed.=$value;
1.1162    raeburn  7025:                 } else {
1.1172.2.65  raeburn  7026:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7027:                     if (@blockers > 0) {
                   7028:                         $thisallowed = 'B';
                   7029:                     } else {
                   7030:                         $thisallowed.=$value;
                   7031:                     }
1.1162    raeburn  7032:                 }
1.671     raeburn  7033:             }
                   7034:         } else {
1.705     albertel 7035:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7036:             if ($refuri) {
                   7037:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7038:                     $thisallowed='F';
1.671     raeburn  7039:                 } else {
                   7040:                     $refuri=&declutter($refuri);
                   7041:                     my ($match) = &is_on_map($refuri);
                   7042:                     if ($match) {
1.1172.2.65  raeburn  7043:                         if ($noblockcheck) {
1.1162    raeburn  7044:                             $thisallowed='F';
1.1172.2.65  raeburn  7045:                         } else {
                   7046:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7047:                             if (@blockers > 0) {
                   7048:                                 $thisallowed = 'B';
                   7049:                             } else {
                   7050:                                 $thisallowed='F';
                   7051:                             }
1.1162    raeburn  7052:                         }
1.671     raeburn  7053:                     }
1.669     raeburn  7054:                 }
1.671     raeburn  7055:             }
                   7056:         }
1.314     www      7057:     }
1.492     albertel 7058: 
1.766     albertel 7059:     if ($priv eq 'bre'
                   7060: 	&& $thisallowed ne 'F' 
                   7061: 	&& $thisallowed ne '2'
                   7062: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7063: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7064:     }
                   7065:     
1.52      www      7066: # Full access at system, domain or course-wide level? Exit.
1.29      www      7067:     if ($thisallowed=~/F/) {
                   7068: 	return 'F';
                   7069:     }
                   7070: 
1.52      www      7071: # If this is generating or modifying users, exit with special codes
1.29      www      7072: 
1.643     www      7073:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7074: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7075: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7076: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7077: 	    unless ($auname) { return $thisallowed; }
                   7078: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7079: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7080: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7081: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7082: 	}
1.52      www      7083: 	return $thisallowed;
                   7084:     }
                   7085: #
1.103     harris41 7086: # Gathered so far: system, domain and course wide privileges
1.52      www      7087: #
                   7088: # Course: See if uri or referer is an individual resource that is part of 
                   7089: # the course
                   7090: 
1.620     albertel 7091:     if ($env{'request.course.id'}) {
1.232     www      7092: 
1.620     albertel 7093:        $courseprivid=$env{'request.course.id'};
                   7094:        if ($env{'request.course.sec'}) {
                   7095:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7096:        }
                   7097:        $courseprivid=~s/\_/\//;
                   7098:        my $checkreferer=1;
1.232     www      7099:        my ($match,$cond)=&is_on_map($uri);
                   7100:        if ($match) {
                   7101:            $statecond=$cond;
1.620     albertel 7102:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7103:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7104:                my $value = $1;
                   7105:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7106:                    if ($noblockcheck) {
1.1162    raeburn  7107:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7108:                    } else {
                   7109:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7110:                        if (@blockers > 0) {
                   7111:                            $thisallowed = 'B';
                   7112:                        } else {
                   7113:                            $thisallowed.=$value;
                   7114:                        }
1.1162    raeburn  7115:                    }
                   7116:                } else {
                   7117:                    $thisallowed.=$value;
                   7118:                }
1.52      www      7119:                $checkreferer=0;
                   7120:            }
1.29      www      7121:        }
1.83      www      7122:        
1.148     www      7123:        if ($checkreferer) {
1.620     albertel 7124: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7125:             unless ($refuri) {
1.800     albertel 7126:                 foreach my $key (keys(%env)) {
                   7127: 		    if ($key=~/^httpref\..*\*/) {
                   7128: 			my $pattern=$key;
1.156     www      7129:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7130:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7131:                         $pattern=~s/\//\\\//g;
1.152     www      7132:                         if ($orguri=~/$pattern/) {
1.800     albertel 7133: 			    $refuri=$env{$key};
1.148     www      7134:                         }
                   7135:                     }
1.191     harris41 7136:                 }
1.148     www      7137:             }
1.232     www      7138: 
1.148     www      7139:          if ($refuri) { 
1.152     www      7140: 	  $refuri=&declutter($refuri);
1.232     www      7141:           my ($match,$cond)=&is_on_map($refuri);
                   7142:             if ($match) {
                   7143:               my $refstatecond=$cond;
1.620     albertel 7144:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7145:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7146:                   my $value = $1;
                   7147:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7148:                       if ($noblockcheck) {
1.1162    raeburn  7149:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7150:                       } else {
                   7151:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7152:                           if (@blockers > 0) {
                   7153:                               $thisallowed = 'B';
                   7154:                           } else {
                   7155:                               $thisallowed.=$value;
                   7156:                           }
1.1162    raeburn  7157:                       }
                   7158:                   } else {
                   7159:                       $thisallowed.=$value;
                   7160:                   }
1.53      www      7161:                   $uri=$refuri;
                   7162:                   $statecond=$refstatecond;
1.52      www      7163:               }
                   7164:           }
1.148     www      7165:         }
1.29      www      7166:        }
1.52      www      7167:    }
1.29      www      7168: 
1.52      www      7169: #
1.103     harris41 7170: # Gathered now: all privileges that could apply, and condition number
1.52      www      7171: # 
                   7172: #
                   7173: # Full or no access?
                   7174: #
1.29      www      7175: 
1.52      www      7176:     if ($thisallowed=~/F/) {
                   7177: 	return 'F';
                   7178:     }
1.29      www      7179: 
1.52      www      7180:     unless ($thisallowed) {
                   7181:         return '';
                   7182:     }
1.29      www      7183: 
1.52      www      7184: # Restrictions exist, deal with them
                   7185: #
                   7186: #   C:according to course preferences
                   7187: #   R:according to resource settings
                   7188: #   L:unless locked
                   7189: #   X:according to user session state
                   7190: #
                   7191: 
                   7192: # Possibly locked functionality, check all courses
1.54      www      7193: # Locks might take effect only after 10 minutes cache expiration for other
                   7194: # courses, and 2 minutes for current course
1.52      www      7195: 
                   7196:     my $envkey;
                   7197:     if ($thisallowed=~/L/) {
1.1000    raeburn  7198:         foreach $envkey (keys(%env)) {
1.54      www      7199:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7200:                my $courseid=$2;
                   7201:                my $roleid=$1.'.'.$2;
1.92      www      7202:                $courseid=~s/^\///;
1.54      www      7203:                my $expiretime=600;
1.620     albertel 7204:                if ($env{'request.role'} eq $roleid) {
1.54      www      7205: 		  $expiretime=120;
                   7206:                }
                   7207: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7208:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7209:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7210: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7211:                }
1.620     albertel 7212:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7213:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7214: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7215:                        &log($env{'user.domain'},$env{'user.name'},
                   7216:                             $env{'user.home'},
1.57      www      7217:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7218:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7219:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7220: 		       return '';
                   7221:                    }
                   7222:                }
1.620     albertel 7223:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7224:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7225: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7226:                        &log($env{'user.domain'},$env{'user.name'},
                   7227:                             $env{'user.home'},
1.57      www      7228:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7229:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7230:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7231: 		       return '';
                   7232:                    }
                   7233:                }
                   7234: 	   }
1.29      www      7235:        }
1.52      www      7236:     }
                   7237:    
                   7238: #
                   7239: # Rest of the restrictions depend on selected course
                   7240: #
                   7241: 
1.620     albertel 7242:     unless ($env{'request.course.id'}) {
1.766     albertel 7243: 	if ($thisallowed eq 'A') {
                   7244: 	    return 'A';
1.814     raeburn  7245:         } elsif ($thisallowed eq 'B') {
                   7246:             return 'B';
1.766     albertel 7247: 	} else {
                   7248: 	    return '1';
                   7249: 	}
1.52      www      7250:     }
1.29      www      7251: 
1.52      www      7252: #
                   7253: # Now user is definitely in a course
                   7254: #
1.53      www      7255: 
                   7256: 
                   7257: # Course preferences
                   7258: 
                   7259:    if ($thisallowed=~/C/) {
1.620     albertel 7260:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7261:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7262:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7263: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7264: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7265: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7266: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7267: 			$env{'request.course.id'});
                   7268: 	   }
1.237     www      7269:            return '';
                   7270:        }
                   7271: 
1.620     albertel 7272:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7273: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7274: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7275: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7276: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7277: 			$env{'request.course.id'});
                   7278: 	   }
1.54      www      7279:            return '';
                   7280:        }
1.53      www      7281:    }
                   7282: 
                   7283: # Resource preferences
                   7284: 
                   7285:    if ($thisallowed=~/R/) {
1.620     albertel 7286:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7287:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7288: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7289: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7290: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7291: 	   }
                   7292: 	   return '';
1.54      www      7293:        }
1.53      www      7294:    }
1.30      www      7295: 
1.246     www      7296: # Restricted by state or randomout?
1.30      www      7297: 
1.52      www      7298:    if ($thisallowed=~/X/) {
1.620     albertel 7299:       if ($env{'acc.randomout'}) {
1.579     albertel 7300: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7301:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7302:             return ''; 
                   7303:          }
1.247     www      7304:       }
                   7305:       if (&condval($statecond)) {
1.52      www      7306: 	 return '2';
                   7307:       } else {
                   7308:          return '';
                   7309:       }
                   7310:    }
1.30      www      7311: 
1.766     albertel 7312:     if ($thisallowed eq 'A') {
                   7313: 	return 'A';
1.814     raeburn  7314:     } elsif ($thisallowed eq 'B') {
                   7315:         return 'B';
1.766     albertel 7316:     }
1.52      www      7317:    return 'F';
1.232     www      7318: }
1.1162    raeburn  7319: 
1.1172.2.13  raeburn  7320: # ------------------------------------------- Check construction space access
                   7321: 
                   7322: sub constructaccess {
                   7323:     my ($url,$setpriv)=@_;
                   7324: 
                   7325: # We do not allow editing of previous versions of files
                   7326:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7327: 
                   7328: # Get username and domain from URL
                   7329:     my ($ownername,$ownerdomain,$ownerhome);
                   7330: 
                   7331:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  7332:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  7333: 
                   7334: # The URL does not really point to any authorspace, forget it
                   7335:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7336: 
                   7337: # Now we need to see if the user has access to the authorspace of
                   7338: # $ownername at $ownerdomain
                   7339: 
                   7340:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7341: # Real author for this?
                   7342:        $ownerhome = $env{'user.home'};
                   7343:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7344:           return ($ownername,$ownerdomain,$ownerhome);
                   7345:        }
                   7346:     } else {
                   7347: # Co-author for this?
                   7348:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7349:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7350:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7351:             return ($ownername,$ownerdomain,$ownerhome);
                   7352:         }
                   7353:     }
                   7354: 
                   7355: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7356: # we might as well leave
                   7357:    unless ($setpriv) { return ''; }
                   7358: 
                   7359: # Backdoor access?
                   7360:     my $allowed=&allowed('eco',$ownerdomain);
                   7361: # Nope
                   7362:     unless ($allowed) { return ''; }
                   7363: # Looks like we may have access, but could be locked by the owner of the construction space
                   7364:     if ($allowed eq 'U') {
                   7365:         my %blocked=&get('environment',['domcoord.author'],
                   7366:                          $ownerdomain,$ownername);
                   7367: # Is blocked by owner
                   7368:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7369:     }
                   7370:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7371: # Grant temporary access
                   7372:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7373:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7374:         if (!$update) { $update = $then; }
                   7375:         my $refresh=$env{'user.refresh.time'};
                   7376:         if (!$refresh) { $refresh = $update; }
                   7377:         my $now = time;
                   7378:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7379:                            $now,'ca','constructaccess');
                   7380:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7381:         return($ownername,$ownerdomain,$ownerhome);
                   7382:     }
                   7383: # No business here
                   7384:     return '';
                   7385: }
                   7386: 
1.1172.2.66  raeburn  7387: # ----------------------------------------------------------- Content Blocking
                   7388: 
                   7389: {
                   7390: # Caches for faster Course Contents display where content blocking
                   7391: # is in operation (i.e., interval param set) for timed quiz.
                   7392: #
                   7393: # User for whom data are being temporarily cached.
                   7394: my $cacheduser='';
                   7395: # Cached blockers for this user (a hash of blocking items).
                   7396: my %cachedblockers=();
                   7397: # When the data were last cached.
                   7398: my $cachedlast='';
                   7399: 
                   7400: sub load_all_blockers {
                   7401:     my ($uname,$udom,$blocks)=@_;
                   7402:     if (($uname ne '') && ($udom ne '')) {
                   7403:         if (($cacheduser eq $uname.':'.$udom) &&
                   7404:             (abs($cachedlast-time)<5)) {
                   7405:             return;
                   7406:         }
                   7407:     }
                   7408:     $cachedlast=time;
                   7409:     $cacheduser=$uname.':'.$udom;
                   7410:     %cachedblockers = &get_commblock_resources($blocks);
                   7411: }
                   7412: 
1.1162    raeburn  7413: sub get_comm_blocks {
                   7414:     my ($cdom,$cnum) = @_;
                   7415:     if ($cdom eq '' || $cnum eq '') {
                   7416:         return unless ($env{'request.course.id'});
                   7417:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7418:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7419:     }
                   7420:     my %commblocks;
                   7421:     my $hashid=$cdom.'_'.$cnum;
                   7422:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7423:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7424:         %commblocks = %{$blocksref};
                   7425:     } else {
                   7426:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7427:         my $cachetime = 600;
                   7428:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7429:     }
                   7430:     return %commblocks;
                   7431: }
                   7432: 
1.1172.2.66  raeburn  7433: sub get_commblock_resources {
                   7434:     my ($blocks) = @_;
                   7435:     my %blockers = ();
                   7436:     return %blockers unless ($env{'request.course.id'});
                   7437:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7438:     my %commblocks;
                   7439:     if (ref($blocks) eq 'HASH') {
                   7440:         %commblocks = %{$blocks};
                   7441:     } else {
                   7442:         %commblocks = &get_comm_blocks();
                   7443:     }
1.1172.2.66  raeburn  7444:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7445:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7446:     return %blockers unless (ref($navmap));
                   7447:     my $now = time;
1.1162    raeburn  7448:     foreach my $block (keys(%commblocks)) {
                   7449:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7450:             my ($start,$end) = ($1,$2);
                   7451:             if ($start <= $now && $end >= $now) {
                   7452:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7453:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7454:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7455:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7456:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7457:                             }
                   7458:                         }
                   7459:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7460:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7461:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7462:                             }
                   7463:                         }
                   7464:                     }
                   7465:                 }
                   7466:             }
                   7467:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7468:             my $item = $1;
1.1163    raeburn  7469:             my @to_test;
1.1162    raeburn  7470:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7471:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7472:                     my @interval;
                   7473:                     my $type = 'map';
                   7474:                     if ($item eq 'course') {
                   7475:                         $type = 'course';
                   7476:                         @interval=&EXT("resource.0.interval");
                   7477:                     } else {
                   7478:                         if ($item =~ /___\d+___/) {
                   7479:                             $type = 'resource';
                   7480:                             @interval=&EXT("resource.0.interval",$item);
                   7481:                             if (ref($navmap)) {
                   7482:                                 my $res = $navmap->getBySymb($item);
                   7483:                                 push(@to_test,$res);
                   7484:                             }
1.1162    raeburn  7485:                         } else {
1.1172.2.66  raeburn  7486:                             my $mapsymb = &symbread($item,1);
                   7487:                             if ($mapsymb) {
                   7488:                                 if (ref($navmap)) {
                   7489:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7490:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7491:                                     foreach my $res (@to_test) {
                   7492:                                         my $symb = $res->symb();
                   7493:                                         next if ($symb eq $mapsymb);
                   7494:                                         if ($symb ne '') {
                   7495:                                             @interval=&EXT("resource.0.interval",$symb);
                   7496:                                             if ($interval[1] eq 'map') {
                   7497:                                                 last;
1.1162    raeburn  7498:                                             }
                   7499:                                         }
                   7500:                                     }
                   7501:                                 }
                   7502:                             }
                   7503:                         }
1.1172.2.66  raeburn  7504:                     }
                   7505:                     if ($interval[0] =~ /^\d+$/) {
                   7506:                         my $first_access;
                   7507:                         if ($type eq 'resource') {
                   7508:                             $first_access=&get_first_access($interval[1],$item);
                   7509:                         } elsif ($type eq 'map') {
                   7510:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7511:                         } else {
                   7512:                             $first_access=&get_first_access($interval[1]);
                   7513:                         }
                   7514:                         if ($first_access) {
                   7515:                             my $timesup = $first_access+$interval[0];
                   7516:                             if ($timesup > $now) {
                   7517:                                 my $activeblock;
                   7518:                                 foreach my $res (@to_test) {
                   7519:                                     if ($res->answerable()) {
                   7520:                                         $activeblock = 1;
                   7521:                                         last;
                   7522:                                     }
                   7523:                                 }
                   7524:                                 if ($activeblock) {
                   7525:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7526:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7527:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7528:                                          }
                   7529:                                     }
                   7530:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7531:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7532:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7533:                                         }
1.1162    raeburn  7534:                                     }
                   7535:                                 }
                   7536:                             }
                   7537:                         }
                   7538:                     }
                   7539:                 }
                   7540:             }
                   7541:         }
                   7542:     }
1.1172.2.66  raeburn  7543:     return %blockers;
1.1162    raeburn  7544: }
                   7545: 
1.1172.2.66  raeburn  7546: sub has_comm_blocking {
                   7547:     my ($priv,$symb,$uri,$blocks) = @_;
                   7548:     my @blockers;
                   7549:     return unless ($env{'request.course.id'});
                   7550:     return unless ($priv eq 'bre');
                   7551:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7552:     return if ($env{'request.state'} eq 'construct');
                   7553:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7554:     return unless (keys(%cachedblockers) > 0);
                   7555:     my (%possibles,@symbs);
                   7556:     if (!$symb) {
                   7557:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7558:     }
1.1172.2.66  raeburn  7559:     if ($symb) {
                   7560:         @symbs = ($symb);
                   7561:     } elsif (keys(%possibles)) {
                   7562:         @symbs = keys(%possibles);
                   7563:     }
                   7564:     my $noblock;
                   7565:     foreach my $symb (@symbs) {
                   7566:         last if ($noblock);
                   7567:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7568:         foreach my $block (keys(%cachedblockers)) {
                   7569:             if ($block =~ /^firstaccess____(.+)$/) {
                   7570:                 my $item = $1;
                   7571:                 if (($item eq $map) || ($item eq $symb)) {
                   7572:                     $noblock = 1;
                   7573:                     last;
                   7574:                 }
1.1162    raeburn  7575:             }
1.1172.2.66  raeburn  7576:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7577:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7578:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7579:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7580:                             push(@blockers,$block);
                   7581:                         }
                   7582:                     }
                   7583:                 }
                   7584:             }
                   7585:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7586:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7587:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7588:                         push(@blockers,$block);
                   7589:                     }
                   7590:                 }
1.1162    raeburn  7591:             }
                   7592:         }
                   7593:     }
1.1172.2.66  raeburn  7594:     return if ($noblock);
                   7595:     return @blockers;
                   7596: }
1.1162    raeburn  7597: }
                   7598: 
1.1172.2.66  raeburn  7599: # -------------------------------- Deversion and split uri into path an filename
                   7600: 
1.1133    foxr     7601: #
1.1172.2.66  raeburn  7602: #   Removes the version from a URI and
1.1133    foxr     7603: #   splits it in to its filename and path to the filename.
                   7604: #   Seems like File::Basename could have done this more clearly.
                   7605: #   Parameters:
                   7606: #      $uri   - input URI
                   7607: #   Returns:
                   7608: #     Two element list consisting of 
                   7609: #     $pathname  - the URI up to and excluding the trailing /
                   7610: #     $filename  - The part of the URI following the last /
                   7611: #  NOTE:
                   7612: #    Another realization of this is simply:
                   7613: #    use File::Basename;
                   7614: #    ...
                   7615: #    $uri = shift;
                   7616: #    $filename = basename($uri);
                   7617: #    $path     = dirname($uri);
                   7618: #    return ($filename, $path);
                   7619: #
                   7620: #     The implementation below is probably faster however.
                   7621: #
1.710     albertel 7622: sub split_uri_for_cond {
                   7623:     my $uri=&deversion(&declutter(shift));
                   7624:     my @uriparts=split(/\//,$uri);
                   7625:     my $filename=pop(@uriparts);
                   7626:     my $pathname=join('/',@uriparts);
                   7627:     return ($pathname,$filename);
                   7628: }
1.232     www      7629: # --------------------------------------------------- Is a resource on the map?
                   7630: 
                   7631: sub is_on_map {
1.710     albertel 7632:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7633:     #Trying to find the conditional for the file
1.620     albertel 7634:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7635: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7636:     if ($match) {
1.289     bowersj2 7637: 	return (1,$1);
                   7638:     } else {
1.434     www      7639: 	return (0,0);
1.289     bowersj2 7640:     }
1.12      www      7641: }
                   7642: 
1.427     www      7643: # --------------------------------------------------------- Get symb from alias
                   7644: 
                   7645: sub get_symb_from_alias {
                   7646:     my $symb=shift;
                   7647:     my ($map,$resid,$url)=&decode_symb($symb);
                   7648: # Already is a symb
                   7649:     if ($url) { return $symb; }
                   7650: # Must be an alias
                   7651:     my $aliassymb='';
                   7652:     my %bighash;
1.620     albertel 7653:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7654:                             &GDBM_READER(),0640)) {
                   7655:         my $rid=$bighash{'mapalias_'.$symb};
                   7656: 	if ($rid) {
                   7657: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7658: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7659: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7660: 	}
                   7661:         untie %bighash;
                   7662:     }
                   7663:     return $aliassymb;
                   7664: }
                   7665: 
1.12      www      7666: # ----------------------------------------------------------------- Define Role
                   7667: 
                   7668: sub definerole {
                   7669:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  7670:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 7671:     foreach my $role (split(':',$sysrole)) {
                   7672: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7673:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7674:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7675: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7676:                return "refused:s:$crole&$cqual"; 
                   7677:             }
                   7678:         }
1.191     harris41 7679:     }
1.800     albertel 7680:     foreach my $role (split(':',$domrole)) {
                   7681: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7682:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7683:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7684: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7685:                return "refused:d:$crole&$cqual"; 
                   7686:             }
                   7687:         }
1.191     harris41 7688:     }
1.800     albertel 7689:     foreach my $role (split(':',$courole)) {
                   7690: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7691:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7692:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7693: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7694:                return "refused:c:$crole&$cqual"; 
                   7695:             }
                   7696:         }
1.191     harris41 7697:     }
1.1172.2.84  raeburn  7698:     my $uhome;
                   7699:     if (($uname ne '') && ($udom ne '')) {
                   7700:         $uhome = &homeserver($uname,$udom);
                   7701:         return $uhome if ($uhome eq 'no_host');
                   7702:     } else {
                   7703:         $uname = $env{'user.name'};
                   7704:         $udom = $env{'user.domain'};
                   7705:         $uhome = $env{'user.home'};
                   7706:     }
1.620     albertel 7707:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  7708:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      7709:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  7710:     return reply($command,$uhome);
1.12      www      7711:   } else {
                   7712:     return 'refused';
                   7713:   }
1.105     harris41 7714: }
                   7715: 
                   7716: # ---------------- Make a metadata query against the network of library servers
                   7717: 
                   7718: sub metadata_query {
1.1172.2.33  raeburn  7719:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7720:     my %rhash;
1.845     albertel 7721:     my %libserv = &all_library();
1.244     matthew  7722:     my @server_list = (defined($server_array) ? @$server_array
                   7723:                                               : keys(%libserv) );
                   7724:     for my $server (@server_list) {
1.1172.2.33  raeburn  7725:         my $domains = '';
                   7726:         if (ref($domains_hash) eq 'HASH') {
                   7727:             $domains = $domains_hash->{$server};    
                   7728:         }
1.118     harris41 7729: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  7730: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7731: 	    $rhash{$server}=$reply;
                   7732: 	}
                   7733: 	else {
                   7734: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  7735: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7736: 			     $server);
                   7737: 	    $rhash{$server}=$reply;
                   7738: 	}
1.112     harris41 7739:     }
1.118     harris41 7740:     return \%rhash;
1.240     www      7741: }
                   7742: 
                   7743: # ----------------------------------------- Send log queries and wait for reply
                   7744: 
                   7745: sub log_query {
                   7746:     my ($uname,$udom,$query,%filters)=@_;
                   7747:     my $uhome=&homeserver($uname,$udom);
                   7748:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7749:     my $uhost=&hostname($uhome);
1.800     albertel 7750:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7751:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7752:                        $uhome);
1.479     albertel 7753:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7754:     return get_query_reply($queryid);
                   7755: }
                   7756: 
1.818     raeburn  7757: # -------------------------- Update MySQL table for portfolio file
                   7758: 
                   7759: sub update_portfolio_table {
1.821     raeburn  7760:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7761:     if ($group ne '') {
                   7762:         $file_name =~s /^\Q$group\E//;
                   7763:     }
1.818     raeburn  7764:     my $homeserver = &homeserver($uname,$udom);
                   7765:     my $queryid=
1.821     raeburn  7766:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7767:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7768:     my $reply = &get_query_reply($queryid);
                   7769:     return $reply;
                   7770: }
                   7771: 
1.899     raeburn  7772: # -------------------------- Update MySQL allusers table
                   7773: 
                   7774: sub update_allusers_table {
                   7775:     my ($uname,$udom,$names) = @_;
                   7776:     my $homeserver = &homeserver($uname,$udom);
                   7777:     my $queryid=
                   7778:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7779:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7780:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7781:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7782:                'generation='.&escape($names->{'generation'}).'%%'.
                   7783:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7784:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7785:     return;
1.899     raeburn  7786: }
                   7787: 
1.508     raeburn  7788: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7789: 
                   7790: sub fetch_enrollment_query {
1.511     raeburn  7791:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  7792:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  7793:     my $maxtries = 1;
1.508     raeburn  7794:     if ($context eq 'automated') {
                   7795:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  7796:         $sleep = 2;
                   7797:         $loopmax = 100;
1.547     raeburn  7798:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7799:     } else {
                   7800:         $homeserver = &homeserver($cnum,$dom);
                   7801:     }
1.838     albertel 7802:     my $host=&hostname($homeserver);
1.506     raeburn  7803:     my $cmd = '';
1.1000    raeburn  7804:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7805:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7806:     }
                   7807:     $cmd =~ s/%%$//;
                   7808:     $cmd = &escape($cmd);
                   7809:     my $query = 'fetchenrollment';
1.620     albertel 7810:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7811:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7812:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7813:         return 'error: '.$queryid;
                   7814:     }
1.1172.2.79  raeburn  7815:     my $reply = &get_query_reply($queryid,$sleep.$loopmax);
1.547     raeburn  7816:     my $tries = 1;
                   7817:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  7818:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  7819:         $tries ++;
                   7820:     }
1.526     raeburn  7821:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7822:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7823:     } else {
1.901     albertel 7824:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  7825:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 7826:             foreach my $line (@responses) {
                   7827:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7828:                 $$replyref{$key} = $value;
                   7829:             }
                   7830:         } else {
1.1117    foxr     7831:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7832:             foreach my $line (@responses) {
                   7833:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7834:                 $$replyref{$key} = $value;
                   7835:                 if ($value > 0) {
1.800     albertel 7836:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7837:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7838:                         my $destname = $pathname.'/'.$filename;
                   7839:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7840:                         if ($xml_classlist =~ /^error/) {
                   7841:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7842:                         } else {
1.506     raeburn  7843:                             if ( open(FILE,">$destname") ) {
                   7844:                                 print FILE &unescape($xml_classlist);
                   7845:                                 close(FILE);
1.526     raeburn  7846:                             } else {
                   7847:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7848:                             }
                   7849:                         }
                   7850:                     }
                   7851:                 }
                   7852:             }
                   7853:         }
                   7854:         return 'ok';
                   7855:     }
                   7856:     return 'error';
                   7857: }
                   7858: 
1.242     www      7859: sub get_query_reply {
1.1172.2.79  raeburn  7860:     my ($queryid,$sleep,$loopmax) = @_;
                   7861:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   7862:         $sleep = 0.2;
                   7863:     }
                   7864:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   7865:         $loopmax = 100;
                   7866:     }
1.1117    foxr     7867:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7868:     my $reply='';
1.1172.2.79  raeburn  7869:     for (1..$loopmax) {
                   7870: 	sleep($sleep);
1.240     www      7871:         if (-e $replyfile.'.end') {
1.448     albertel 7872: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7873: 		$reply = join('',<$fh>);
                   7874: 		close($fh);
1.240     www      7875: 	   } else { return 'error: reply_file_error'; }
1.242     www      7876:            return &unescape($reply);
                   7877: 	}
1.240     www      7878:     }
1.242     www      7879:     return 'timeout:'.$queryid;
1.240     www      7880: }
                   7881: 
                   7882: sub courselog_query {
1.241     www      7883: #
                   7884: # possible filters:
                   7885: # url: url or symb
                   7886: # username
                   7887: # domain
                   7888: # action: view, submit, grade
                   7889: # start: timestamp
                   7890: # end: timestamp
                   7891: #
1.240     www      7892:     my (%filters)=@_;
1.620     albertel 7893:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7894:     if ($filters{'url'}) {
                   7895: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7896:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7897:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7898:     }
1.620     albertel 7899:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7900:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7901:     return &log_query($cname,$cdom,'courselog',%filters);
                   7902: }
                   7903: 
                   7904: sub userlog_query {
1.858     raeburn  7905: #
                   7906: # possible filters:
                   7907: # action: log check role
                   7908: # start: timestamp
                   7909: # end: timestamp
                   7910: #
1.240     www      7911:     my ($uname,$udom,%filters)=@_;
                   7912:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7913: }
                   7914: 
1.506     raeburn  7915: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7916: 
                   7917: sub auto_run {
1.508     raeburn  7918:     my ($cnum,$cdom) = @_;
1.876     raeburn  7919:     my $response = 0;
                   7920:     my $settings;
                   7921:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7922:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7923:         $settings = $domconfig{'autoenroll'};
                   7924:         if ($settings->{'run'} eq '1') {
                   7925:             $response = 1;
                   7926:         }
                   7927:     } else {
1.934     raeburn  7928:         my $homeserver;
                   7929:         if (&is_course($cdom,$cnum)) {
                   7930:             $homeserver = &homeserver($cnum,$cdom);
                   7931:         } else {
                   7932:             $homeserver = &domain($cdom,'primary');
                   7933:         }
                   7934:         if ($homeserver ne 'no_host') {
                   7935:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7936:         }
1.876     raeburn  7937:     }
1.506     raeburn  7938:     return $response;
                   7939: }
1.776     albertel 7940: 
1.506     raeburn  7941: sub auto_get_sections {
1.508     raeburn  7942:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7943:     my $homeserver;
                   7944:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7945:         $homeserver = &homeserver($cnum,$cdom);
                   7946:     }
                   7947:     if (!defined($homeserver)) { 
                   7948:         if ($cdom =~ /^$match_domain$/) {
                   7949:             $homeserver = &domain($cdom,'primary');
                   7950:         }
                   7951:     }
                   7952:     my @secs;
                   7953:     if (defined($homeserver)) {
                   7954:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7955:         unless ($response eq 'refused') {
                   7956:             @secs = split(/:/,$response);
                   7957:         }
1.506     raeburn  7958:     }
                   7959:     return @secs;
                   7960: }
1.776     albertel 7961: 
1.506     raeburn  7962: sub auto_new_course {
1.1099    raeburn  7963:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7964:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7965:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7966:     return $response;
                   7967: }
1.776     albertel 7968: 
1.506     raeburn  7969: sub auto_validate_courseID {
1.508     raeburn  7970:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7971:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7972:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7973:     return $response;
                   7974: }
1.776     albertel 7975: 
1.1007    raeburn  7976: sub auto_validate_instcode {
1.1020    raeburn  7977:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7978:     my ($homeserver,$response);
                   7979:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7980:         $homeserver = &homeserver($cnum,$cdom);
                   7981:     }
                   7982:     if (!defined($homeserver)) {
                   7983:         if ($cdom =~ /^$match_domain$/) {
                   7984:             $homeserver = &domain($cdom,'primary');
                   7985:         }
                   7986:     }
1.1065    raeburn  7987:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7988:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7989:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7990:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7991: }
                   7992: 
1.506     raeburn  7993: sub auto_create_password {
1.873     raeburn  7994:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7995:     my ($homeserver,$response);
1.506     raeburn  7996:     my $create_passwd = 0;
                   7997:     my $authchk = '';
1.873     raeburn  7998:     if ($udom =~ /^$match_domain$/) {
                   7999:         $homeserver = &domain($udom,'primary');
                   8000:     }
                   8001:     if ($homeserver eq '') {
                   8002:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8003:             $homeserver = &homeserver($cnum,$cdom);
                   8004:         }
                   8005:     }
                   8006:     if ($homeserver eq '') {
                   8007:         $authchk = 'nodomain';
1.506     raeburn  8008:     } else {
1.873     raeburn  8009:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8010:         if ($response eq 'refused') {
                   8011:             $authchk = 'refused';
                   8012:         } else {
1.901     albertel 8013:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8014:         }
1.506     raeburn  8015:     }
                   8016:     return ($authparam,$create_passwd,$authchk);
                   8017: }
                   8018: 
1.706     raeburn  8019: sub auto_photo_permission {
                   8020:     my ($cnum,$cdom,$students) = @_;
                   8021:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8022:     my ($outcome,$perm_reqd,$conditions) = 
                   8023: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8024:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8025: 	return (undef,undef);
                   8026:     }
1.706     raeburn  8027:     return ($outcome,$perm_reqd,$conditions);
                   8028: }
                   8029: 
                   8030: sub auto_checkphotos {
                   8031:     my ($uname,$udom,$pid) = @_;
                   8032:     my $homeserver = &homeserver($uname,$udom);
                   8033:     my ($result,$resulttype);
                   8034:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8035: 				   &escape($uname).':'.&escape($pid),
                   8036: 				   $homeserver));
1.709     albertel 8037:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8038: 	return (undef,undef);
                   8039:     }
1.706     raeburn  8040:     if ($outcome) {
                   8041:         ($result,$resulttype) = split(/:/,$outcome);
                   8042:     } 
                   8043:     return ($result,$resulttype);
                   8044: }
                   8045: 
                   8046: sub auto_photochoice {
                   8047:     my ($cnum,$cdom) = @_;
                   8048:     my $homeserver = &homeserver($cnum,$cdom);
                   8049:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8050: 						       &escape($cdom),
                   8051: 						       $homeserver)));
1.709     albertel 8052:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8053: 	return (undef,undef);
                   8054:     }
1.706     raeburn  8055:     return ($update,$comment);
                   8056: }
                   8057: 
                   8058: sub auto_photoupdate {
                   8059:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8060:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8061:     my $host=&hostname($homeserver);
1.706     raeburn  8062:     my $cmd = '';
                   8063:     my $maxtries = 1;
1.800     albertel 8064:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8065:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8066:     }
                   8067:     $cmd =~ s/%%$//;
                   8068:     $cmd = &escape($cmd);
                   8069:     my $query = 'institutionalphotos';
                   8070:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8071:     unless ($queryid=~/^\Q$host\E\_/) {
                   8072:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8073:         return 'error: '.$queryid;
                   8074:     }
                   8075:     my $reply = &get_query_reply($queryid);
                   8076:     my $tries = 1;
                   8077:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8078:         $reply = &get_query_reply($queryid);
                   8079:         $tries ++;
                   8080:     }
                   8081:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8082:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8083:     } else {
                   8084:         my @responses = split(/:/,$reply);
                   8085:         my $outcome = shift(@responses); 
                   8086:         foreach my $item (@responses) {
                   8087:             my ($key,$value) = split(/=/,$item);
                   8088:             $$photo{$key} = $value;
                   8089:         }
                   8090:         return $outcome;
                   8091:     }
                   8092:     return 'error';
                   8093: }
                   8094: 
1.521     raeburn  8095: sub auto_instcode_format {
1.793     albertel 8096:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8097: 	$cat_order) = @_;
1.521     raeburn  8098:     my $courses = '';
1.772     raeburn  8099:     my @homeservers;
1.521     raeburn  8100:     if ($caller eq 'global') {
1.841     albertel 8101: 	my %servers = &get_servers($codedom,'library');
                   8102: 	foreach my $tryserver (keys(%servers)) {
                   8103: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8104: 		push(@homeservers,$tryserver);
                   8105: 	    }
1.584     raeburn  8106:         }
1.1022    raeburn  8107:     } elsif ($caller eq 'requests') {
                   8108:         if ($codedom =~ /^$match_domain$/) {
                   8109:             my $chome = &domain($codedom,'primary');
                   8110:             unless ($chome eq 'no_host') {
                   8111:                 push(@homeservers,$chome);
                   8112:             }
                   8113:         }
1.521     raeburn  8114:     } else {
1.772     raeburn  8115:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8116:     }
1.793     albertel 8117:     foreach my $code (keys(%{$instcodes})) {
                   8118:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8119:     }
                   8120:     chop($courses);
1.772     raeburn  8121:     my $ok_response = 0;
                   8122:     my $response;
                   8123:     while (@homeservers > 0 && $ok_response == 0) {
                   8124:         my $server = shift(@homeservers); 
                   8125:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8126:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8127:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8128: 		split(/:/,$response);
1.772     raeburn  8129:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8130:             push(@{$codetitles},&str2array($codetitles_str));
                   8131:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8132:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8133:             $ok_response = 1;
                   8134:         }
                   8135:     }
                   8136:     if ($ok_response) {
1.521     raeburn  8137:         return 'ok';
1.772     raeburn  8138:     } else {
                   8139:         return $response;
1.521     raeburn  8140:     }
                   8141: }
                   8142: 
1.792     raeburn  8143: sub auto_instcode_defaults {
                   8144:     my ($domain,$returnhash,$code_order) = @_;
                   8145:     my @homeservers;
1.841     albertel 8146: 
                   8147:     my %servers = &get_servers($domain,'library');
                   8148:     foreach my $tryserver (keys(%servers)) {
                   8149: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8150: 	    push(@homeservers,$tryserver);
                   8151: 	}
1.792     raeburn  8152:     }
1.841     albertel 8153: 
1.792     raeburn  8154:     my $response;
1.841     albertel 8155:     foreach my $server (@homeservers) {
1.792     raeburn  8156:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8157:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8158: 	
                   8159: 	foreach my $pair (split(/\&/,$response)) {
                   8160: 	    my ($name,$value)=split(/\=/,$pair);
                   8161: 	    if ($name eq 'code_order') {
                   8162: 		@{$code_order} = split(/\&/,&unescape($value));
                   8163: 	    } else {
                   8164: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8165: 	    }
                   8166: 	}
                   8167: 	return 'ok';
1.792     raeburn  8168:     }
1.841     albertel 8169: 
                   8170:     return $response;
1.1003    raeburn  8171: }
                   8172: 
                   8173: sub auto_possible_instcodes {
1.1007    raeburn  8174:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8175:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8176:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8177:         return;
                   8178:     }
1.1003    raeburn  8179:     my (@homeservers,$uhome);
                   8180:     if (defined(&domain($domain,'primary'))) {
                   8181:         $uhome=&domain($domain,'primary');
                   8182:         push(@homeservers,&domain($domain,'primary'));
                   8183:     } else {
                   8184:         my %servers = &get_servers($domain,'library');
                   8185:         foreach my $tryserver (keys(%servers)) {
                   8186:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8187:                 push(@homeservers,$tryserver);
                   8188:             }
                   8189:         }
                   8190:     }
                   8191:     my $response;
                   8192:     foreach my $server (@homeservers) {
                   8193:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8194:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8195:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8196:             split(':',$response);
                   8197:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8198:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8199:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8200:             my ($name,$value)=split('=',$item);
                   8201:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8202:         }
                   8203:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8204:             my ($name,$value)=split('=',$item);
                   8205:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8206:         }
                   8207:         return 'ok';
                   8208:     }
                   8209:     return $response;
                   8210: }
1.792     raeburn  8211: 
1.1010    raeburn  8212: sub auto_courserequest_checks {
                   8213:     my ($dom) = @_;
1.1020    raeburn  8214:     my ($homeserver,%validations);
                   8215:     if ($dom =~ /^$match_domain$/) {
                   8216:         $homeserver = &domain($dom,'primary');
                   8217:     }
                   8218:     unless ($homeserver eq 'no_host') {
                   8219:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8220:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8221:             my @items = split(/&/,$response);
                   8222:             foreach my $item (@items) {
                   8223:                 my ($key,$value) = split('=',$item);
                   8224:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8225:             }
                   8226:         }
                   8227:     }
1.1010    raeburn  8228:     return %validations; 
                   8229: }
                   8230: 
1.1020    raeburn  8231: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8232:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8233:     my ($homeserver,$response);
                   8234:     if ($dom =~ /^$match_domain$/) {
                   8235:         $homeserver = &domain($dom,'primary');
                   8236:     }
1.1172.2.43  raeburn  8237:     unless ($homeserver eq 'no_host') {
                   8238:         my $customdata;
                   8239:         if (ref($custominfo) eq 'HASH') {
                   8240:             $customdata = &freeze_escape($custominfo);
                   8241:         }
1.1020    raeburn  8242:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8243:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8244:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8245:                                     $customdata,$homeserver));
1.1020    raeburn  8246:     }
                   8247:     return $response;
                   8248: }
                   8249: 
1.777     albertel 8250: sub auto_validate_class_sec {
1.918     raeburn  8251:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8252:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8253:     my $ownerlist;
                   8254:     if (ref($owners) eq 'ARRAY') {
                   8255:         $ownerlist = join(',',@{$owners});
                   8256:     } else {
                   8257:         $ownerlist = $owners;
                   8258:     }
1.773     raeburn  8259:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8260:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8261:     return $response;
                   8262: }
                   8263: 
1.1172.2.38  raeburn  8264: sub auto_crsreq_update {
                   8265:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8266:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8267:     my ($homeserver,%crsreqresponse);
                   8268:     if ($cdom =~ /^$match_domain$/) {
                   8269:         $homeserver = &domain($cdom,'primary');
                   8270:     }
                   8271:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8272:         my $info;
                   8273:         if (ref($inbound) eq 'HASH') {
                   8274:             $info = &freeze_escape($inbound);
                   8275:         }
                   8276:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8277:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8278:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8279:                             &escape($title).':'.&escape($code).':'.
                   8280:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8281:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8282:             my @items = split(/&/,$response);
                   8283:             foreach my $item (@items) {
                   8284:                 my ($key,$value) = split('=',$item);
                   8285:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8286:             }
                   8287:         }
                   8288:     }
                   8289:     return \%crsreqresponse;
                   8290: }
                   8291: 
1.1172.2.78  raeburn  8292: sub auto_export_grades {
                   8293:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8294:     my ($homeserver,%exportresponse);
                   8295:     if ($cdom =~ /^$match_domain$/) {
                   8296:         $homeserver = &domain($cdom,'primary');
                   8297:     }
                   8298:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8299:         my $info;
                   8300:         if (ref($inforef) eq 'HASH') {
                   8301:             $info = &freeze_escape($inforef);
                   8302:         }
                   8303:         if (ref($gradesref) eq 'HASH') {
                   8304:             my $grades = &freeze_escape($gradesref);
                   8305:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8306:                                 $info.':'.$grades,$homeserver);
                   8307:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8308:                 my @items = split(/&/,$response);
                   8309:                 foreach my $item (@items) {
                   8310:                     my ($key,$value) = split('=',$item);
                   8311:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8312:                 }
                   8313:             }
                   8314:         }
                   8315:     }
                   8316:     return \%exportresponse;
                   8317: }
                   8318: 
1.1172.2.68  raeburn  8319: sub check_instcode_cloning {
                   8320:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8321:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8322:         return;
                   8323:     }
                   8324:     my $canclone;
                   8325:     if (@{$code_order} > 0) {
                   8326:         my $instcoderegexp ='^';
                   8327:         my @clonecodes = split(/\&/,$cloner);
                   8328:         foreach my $item (@{$code_order}) {
                   8329:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8330:                 foreach my $pair (@clonecodes) {
                   8331:                     my ($key,$val) = split(/\=/,$pair,2);
                   8332:                     $val = &unescape($val);
                   8333:                     if ($key eq $item) {
                   8334:                         $instcoderegexp .= '('.$val.')';
                   8335:                         last;
                   8336:                     }
                   8337:                 }
                   8338:             } else {
                   8339:                 $instcoderegexp .= $codedefaults->{$item};
                   8340:             }
                   8341:         }
                   8342:         $instcoderegexp .= '$';
                   8343:         my (@from,@to);
                   8344:         eval {
                   8345:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8346:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8347:         };
                   8348:         if ((@from > 0) && (@to > 0)) {
                   8349:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8350:             if (!@diffs) {
                   8351:                 $canclone = 1;
                   8352:             }
                   8353:         }
                   8354:     }
                   8355:     return $canclone;
                   8356: }
                   8357: 
                   8358: sub default_instcode_cloning {
                   8359:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8360:     my (%codedefaults,@code_order,$canclone);
                   8361:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8362:         %codedefaults = %{$codedefaultsref};
                   8363:         @code_order = @{$codeorderref};
                   8364:     } elsif ($clonedom) {
                   8365:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8366:     }
                   8367:     if (($domdefclone) && (@code_order)) {
                   8368:         my @clonecodes = split(/\+/,$domdefclone);
                   8369:         my $instcoderegexp ='^';
                   8370:         foreach my $item (@code_order) {
                   8371:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8372:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8373:             } else {
                   8374:                 $instcoderegexp .= $codedefaults{$item};
                   8375:             }
                   8376:         }
                   8377:         $instcoderegexp .= '$';
                   8378:         my (@from,@to);
                   8379:         eval {
                   8380:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8381:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8382:         };
                   8383:         if ((@from > 0) && (@to > 0)) {
                   8384:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8385:             if (!@diffs) {
                   8386:                 $canclone = 1;
                   8387:             }
                   8388:         }
                   8389:     }
                   8390:     return $canclone;
                   8391: }
                   8392: 
1.679     raeburn  8393: # ------------------------------------------------------- Course Group routines
                   8394: 
                   8395: sub get_coursegroups {
1.809     raeburn  8396:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8397:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8398: }
                   8399: 
1.679     raeburn  8400: sub modify_coursegroup {
                   8401:     my ($cdom,$cnum,$groupsettings) = @_;
                   8402:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8403: }
                   8404: 
1.809     raeburn  8405: sub toggle_coursegroup_status {
                   8406:     my ($cdom,$cnum,$group,$action) = @_;
                   8407:     my ($from_namespace,$to_namespace);
                   8408:     if ($action eq 'delete') {
                   8409:         $from_namespace = 'coursegroups';
                   8410:         $to_namespace = 'deleted_groups';
                   8411:     } else {
                   8412:         $from_namespace = 'deleted_groups';
                   8413:         $to_namespace = 'coursegroups';
                   8414:     }
                   8415:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8416:     if (my $tmp = &error(%curr_group)) {
                   8417:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8418:         return ('read error',$tmp);
                   8419:     } else {
                   8420:         my %savedsettings = %curr_group; 
1.809     raeburn  8421:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8422:         my $deloutcome;
                   8423:         if ($result eq 'ok') {
1.809     raeburn  8424:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8425:         } else {
                   8426:             return ('write error',$result);
                   8427:         }
                   8428:         if ($deloutcome eq 'ok') {
                   8429:             return 'ok';
                   8430:         } else {
                   8431:             return ('delete error',$deloutcome);
                   8432:         }
                   8433:     }
                   8434: }
                   8435: 
1.679     raeburn  8436: sub modify_group_roles {
1.957     raeburn  8437:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8438:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8439:     my $role = 'gr/'.&escape($userprivs);
                   8440:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8441:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8442:     if ($result eq 'ok') {
                   8443:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8444:     }
1.679     raeburn  8445:     return $result;
                   8446: }
                   8447: 
                   8448: sub modify_coursegroup_membership {
                   8449:     my ($cdom,$cnum,$membership) = @_;
                   8450:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8451:     return $result;
                   8452: }
                   8453: 
1.682     raeburn  8454: sub get_active_groups {
                   8455:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8456:     my $now = time;
                   8457:     my %groups = ();
                   8458:     foreach my $key (keys(%env)) {
1.811     albertel 8459:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8460:             my ($start,$end) = split(/\./,$env{$key});
                   8461:             if (($end!=0) && ($end<$now)) { next; }
                   8462:             if (($start!=0) && ($start>$now)) { next; }
                   8463:             if ($1 eq $cdom && $2 eq $cnum) {
                   8464:                 $groups{$3} = $env{$key} ;
                   8465:             }
                   8466:         }
                   8467:     }
                   8468:     return %groups;
                   8469: }
                   8470: 
1.683     raeburn  8471: sub get_group_membership {
                   8472:     my ($cdom,$cnum,$group) = @_;
                   8473:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8474: }
                   8475: 
                   8476: sub get_users_groups {
                   8477:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8478:     my @usersgroups;
1.683     raeburn  8479:     my $cachetime=1800;
                   8480: 
                   8481:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8482:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8483:     if (defined($cached)) {
1.734     albertel 8484:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8485:     } else {  
                   8486:         $grouplist = '';
1.816     raeburn  8487:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8488:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8489:         my $access_end = $env{'course.'.$courseid.
                   8490:                               '.default_enrollment_end_date'};
                   8491:         my $now = time;
                   8492:         foreach my $key (keys(%roleshash)) {
                   8493:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8494:                 my $group = $1;
                   8495:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8496:                     my $start = $2;
                   8497:                     my $end = $1;
                   8498:                     if ($start == -1) { next; } # deleted from group
                   8499:                     if (($start!=0) && ($start>$now)) { next; }
                   8500:                     if (($end!=0) && ($end<$now)) {
                   8501:                         if ($access_end && $access_end < $now) {
                   8502:                             if ($access_end - $end < 86400) {
                   8503:                                 push(@usersgroups,$group);
1.733     raeburn  8504:                             }
                   8505:                         }
1.817     raeburn  8506:                         next;
1.733     raeburn  8507:                     }
1.817     raeburn  8508:                     push(@usersgroups,$group);
1.683     raeburn  8509:                 }
                   8510:             }
                   8511:         }
1.817     raeburn  8512:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8513:         $grouplist = join(':',@usersgroups);
                   8514:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8515:     }
1.733     raeburn  8516:     return @usersgroups;
1.683     raeburn  8517: }
                   8518: 
                   8519: sub devalidate_getgroups_cache {
                   8520:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8521:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8522: 
1.683     raeburn  8523:     my $hashid="$udom:$uname:$courseid";
                   8524:     &devalidate_cache_new('getgroups',$hashid);
                   8525: }
                   8526: 
1.12      www      8527: # ------------------------------------------------------------------ Plain Text
                   8528: 
                   8529: sub plaintext {
1.988     raeburn  8530:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8531:     if ($short =~ m{^cr/}) {
1.758     albertel 8532: 	return (split('/',$short))[-1];
                   8533:     }
1.742     raeburn  8534:     if (!defined($cid)) {
                   8535:         $cid = $env{'request.course.id'};
                   8536:     }
                   8537:     my %rolenames = (
1.1008    raeburn  8538:                       Course    => 'std',
                   8539:                       Community => 'alt1',
1.742     raeburn  8540:                     );
1.1037    raeburn  8541:     if ($cid ne '') {
                   8542:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8543:             unless ($forcedefault) {
                   8544:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8545:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8546:                 return &Apache::lonlocal::mt($roletext);
                   8547:             }
                   8548:         }
                   8549:     }
                   8550:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8551:         (defined($rolenames{$type})) && 
                   8552:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8553:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8554:     } elsif ($cid ne '') {
                   8555:         my $crstype = $env{'course.'.$cid.'.type'};
                   8556:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8557:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8558:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8559:         }
1.742     raeburn  8560:     }
1.1037    raeburn  8561:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8562: }
                   8563: 
                   8564: # ----------------------------------------------------------------- Assign Role
                   8565: 
                   8566: sub assignrole {
1.957     raeburn  8567:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8568:         $context)=@_;
1.21      www      8569:     my $mrole;
                   8570:     if ($role =~ /^cr\//) {
1.393     www      8571:         my $cwosec=$url;
1.811     albertel 8572:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8573: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8574:            my $refused = 1;
                   8575:            if ($context eq 'requestcourses') {
                   8576:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8577:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8578:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8579:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8580:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8581:                            if ($crsenv{'internal.courseowner'} eq
                   8582:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8583:                                $refused = '';
                   8584:                            }
                   8585:                        }
                   8586:                    }
                   8587:                }
                   8588:            }
                   8589:            if ($refused) {
                   8590:                &logthis('Refused custom assignrole: '.
                   8591:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8592:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8593:                return 'refused';
                   8594:            }
1.104     www      8595:         }
1.21      www      8596:         $mrole='cr';
1.678     raeburn  8597:     } elsif ($role =~ /^gr\//) {
                   8598:         my $cwogrp=$url;
1.811     albertel 8599:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8600:         unless (&allowed('mdg',$cwogrp)) {
                   8601:             &logthis('Refused group assignrole: '.
                   8602:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8603:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8604:             return 'refused';
                   8605:         }
                   8606:         $mrole='gr';
1.21      www      8607:     } else {
1.82      www      8608:         my $cwosec=$url;
1.811     albertel 8609:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8610:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8611:             my $refused;
                   8612:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8613:                 if (!(&allowed('c'.$role,$url))) {
                   8614:                     $refused = 1;
                   8615:                 }
                   8616:             } else {
                   8617:                 $refused = 1;
                   8618:             }
1.947     raeburn  8619:             if ($refused) {
1.1045    raeburn  8620:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8621:                 if (!$selfenroll && $context eq 'course') {
                   8622:                     my %crsenv;
                   8623:                     if ($role eq 'cc' || $role eq 'co') {
                   8624:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8625:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8626:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8627:                                 if ($crsenv{'internal.courseowner'} eq 
                   8628:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8629:                                     $refused = '';
                   8630:                                 }
                   8631:                             }
                   8632:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8633:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8634:                                 if ($crsenv{'internal.courseowner'} eq 
                   8635:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8636:                                     $refused = '';
                   8637:                                 }
                   8638:                             }
                   8639:                         }
                   8640:                     }
                   8641:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8642:                     $refused = '';
1.1017    raeburn  8643:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8644:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8645:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8646:                         my $wrongcc;
                   8647:                         if ($cnum =~ /^$match_community$/) {
                   8648:                             $wrongcc = 1 if ($role eq 'cc');
                   8649:                         } else {
                   8650:                             $wrongcc = 1 if ($role eq 'co');
                   8651:                         }
                   8652:                         unless ($wrongcc) {
                   8653:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8654:                             if ($crsenv{'internal.courseowner'} eq 
                   8655:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8656:                                 $refused = '';
                   8657:                             }
1.1017    raeburn  8658:                         }
                   8659:                     }
1.1172.2.9  raeburn  8660:                 } elsif ($context eq 'requestauthor') {
                   8661:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8662:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8663:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8664:                             $refused = '';
                   8665:                         } else {
                   8666:                             my %domdefaults = &get_domain_defaults($udom);
                   8667:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8668:                                 my $checkbystatus;
                   8669:                                 if ($env{'user.adv'}) {
                   8670:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8671:                                     if ($disposition eq 'automatic') {
                   8672:                                         $refused = '';
                   8673:                                     } elsif ($disposition eq '') {
                   8674:                                         $checkbystatus = 1;
                   8675:                                     }
                   8676:                                 } else {
                   8677:                                     $checkbystatus = 1;
                   8678:                                 }
                   8679:                                 if ($checkbystatus) {
                   8680:                                     if ($env{'environment.inststatus'}) {
                   8681:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8682:                                         foreach my $type (@inststatuses) {
                   8683:                                             if (($type ne '') &&
                   8684:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8685:                                                 $refused = '';
                   8686:                                             }
                   8687:                                         }
                   8688:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8689:                                         $refused = '';
                   8690:                                     }
                   8691:                                 }
                   8692:                             }
                   8693:                         }
                   8694:                     }
1.1017    raeburn  8695:                 }
                   8696:                 if ($refused) {
1.947     raeburn  8697:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8698:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8699: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8700:                     return 'refused';
                   8701:                 }
1.932     raeburn  8702:             }
1.1131    raeburn  8703:         } elsif ($role eq 'au') {
                   8704:             if ($url ne '/'.$udom.'/') {
                   8705:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8706:                          ' to assign author role for '.$uname.':'.$udom.
                   8707:                          ' in domain: '.$url.' refused (wrong domain).');
                   8708:                 return 'refused';
                   8709:             }
1.104     www      8710:         }
1.21      www      8711:         $mrole=$role;
                   8712:     }
1.620     albertel 8713:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8714:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8715:     if ($end) { $command.='_'.$end; }
1.21      www      8716:     if ($start) {
                   8717: 	if ($end) { 
1.81      www      8718:            $command.='_'.$start; 
1.21      www      8719:         } else {
1.81      www      8720:            $command.='_0_'.$start;
1.21      www      8721:         }
                   8722:     }
1.739     raeburn  8723:     my $origstart = $start;
                   8724:     my $origend = $end;
1.957     raeburn  8725:     my $delflag;
1.357     www      8726: # actually delete
                   8727:     if ($deleteflag) {
1.373     www      8728: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8729: # modify command to delete the role
1.620     albertel 8730:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8731:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8732: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8733: # set start and finish to negative values for userrolelog
                   8734:            $start=-1;
                   8735:            $end=-1;
1.957     raeburn  8736:            $delflag = 1;
1.357     www      8737:         }
                   8738:     }
                   8739: # send command
1.349     www      8740:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8741: # log new user role if status is ok
1.349     www      8742:     if ($answer eq 'ok') {
1.663     raeburn  8743: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8744:         if (($role eq 'cc') || ($role eq 'in') ||
                   8745:             ($role eq 'ep') || ($role eq 'ad') ||
                   8746:             ($role eq 'ta') || ($role eq 'st') ||
                   8747:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8748:             ($role eq 'co')) {
1.1172.2.13  raeburn  8749: # for course roles, perform group memberships changes triggered by role change.
                   8750:             unless ($role =~ /^gr/) {
                   8751:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8752:                                                  $origstart,$selfenroll,$context);
                   8753:             }
1.1172.2.9  raeburn  8754:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8755:                            $selfenroll,$context);
                   8756:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.84  raeburn  8757:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh')) {
1.1172.2.9  raeburn  8758:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8759:                            $context);
                   8760:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8761:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8762:                              $context);
                   8763:         }
1.1053    raeburn  8764:         if ($role eq 'cc') {
                   8765:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8766:         }
1.349     www      8767:     }
                   8768:     return $answer;
1.169     harris41 8769: }
                   8770: 
1.1053    raeburn  8771: sub autoupdate_coowners {
                   8772:     my ($url,$end,$start,$uname,$udom) = @_;
                   8773:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8774:     if (($cdom ne '') && ($cnum ne '')) {
                   8775:         my $now = time;
                   8776:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8777:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8778:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8779:             my $instcode = $coursehash{'internal.coursecode'};
                   8780:             if ($instcode ne '') {
1.1056    raeburn  8781:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8782:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8783:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8784:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8785:                         if ($result eq 'valid') {
                   8786:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8787:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8788:                                     push(@newcoowners,$coowner);
                   8789:                                 }
                   8790:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8791:                                     push(@newcoowners,$uname.':'.$udom);
                   8792:                                 }
                   8793:                                 @newcoowners = sort(@newcoowners);
                   8794:                             } else {
                   8795:                                 push(@newcoowners,$uname.':'.$udom);
                   8796:                             }
                   8797:                         } else {
                   8798:                             if ($coursehash{'internal.co-owners'}) {
                   8799:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8800:                                     unless ($coowner eq $uname.':'.$udom) {
                   8801:                                         push(@newcoowners,$coowner);
                   8802:                                     }
                   8803:                                 }
                   8804:                                 unless (@newcoowners > 0) {
                   8805:                                     $delcoowners = 1;
                   8806:                                     $coowners = '';
                   8807:                                 }
                   8808:                             }
                   8809:                         }
                   8810:                         if (@newcoowners || $delcoowners) {
                   8811:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8812:                                             $delcoowners,@newcoowners);
                   8813:                         }
                   8814:                     }
                   8815:                 }
                   8816:             }
                   8817:         }
                   8818:     }
                   8819: }
                   8820: 
                   8821: sub store_coowners {
                   8822:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8823:     my $cid = $cdom.'_'.$cnum;
                   8824:     my ($coowners,$delresult,$putresult);
                   8825:     if (@newcoowners) {
                   8826:         $coowners = join(',',@newcoowners);
                   8827:         my %coownershash = (
                   8828:                             'internal.co-owners' => $coowners,
                   8829:                            );
                   8830:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8831:         if ($putresult eq 'ok') {
                   8832:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8833:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8834:             }
                   8835:         }
                   8836:     }
                   8837:     if ($delcoowners) {
                   8838:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8839:         if ($delresult eq 'ok') {
                   8840:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8841:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8842:             }
                   8843:         }
                   8844:     }
                   8845:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8846:         my %crsinfo =
                   8847:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8848:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8849:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8850:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8851:         }
                   8852:     }
                   8853: }
                   8854: 
1.169     harris41 8855: # -------------------------------------------------- Modify user authentication
1.197     www      8856: # Overrides without validation
                   8857: 
1.169     harris41 8858: sub modifyuserauth {
                   8859:     my ($udom,$uname,$umode,$upass)=@_;
                   8860:     my $uhome=&homeserver($uname,$udom);
1.197     www      8861:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8862:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8863:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8864:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8865:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8866: 		     &escape($upass),$uhome);
1.620     albertel 8867:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8868:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8869:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8870:     &log($udom,,$uname,$uhome,
1.620     albertel 8871:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8872:                                      $env{'user.name'}.', '.$umode.
1.197     www      8873:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8874:     unless ($reply eq 'ok') {
1.197     www      8875:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8876: 	return 'error: '.$reply;
                   8877:     }   
1.170     harris41 8878:     return 'ok';
1.80      www      8879: }
                   8880: 
1.81      www      8881: # --------------------------------------------------------------- Modify a user
1.80      www      8882: 
1.81      www      8883: sub modifyuser {
1.206     matthew  8884:     my ($udom,    $uname, $uid,
                   8885:         $umode,   $upass, $first,
                   8886:         $middle,  $last,  $gene,
1.1058    raeburn  8887:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8888:     $udom= &LONCAPA::clean_domain($udom);
                   8889:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8890:     my $showcandelete = 'none';
                   8891:     if (ref($candelete) eq 'ARRAY') {
                   8892:         if (@{$candelete} > 0) {
                   8893:             $showcandelete = join(', ',@{$candelete});
                   8894:         }
                   8895:     }
1.81      www      8896:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8897:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8898: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8899:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8900:                                      ' desiredhome not specified'). 
1.620     albertel 8901:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8902:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8903:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8904:     my $newuser;
                   8905:     if ($uhome eq 'no_host') {
                   8906:         $newuser = 1;
                   8907:     }
1.80      www      8908: # ----------------------------------------------------------------- Create User
1.406     albertel 8909:     if (($uhome eq 'no_host') && 
                   8910: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8911:         my $unhome='';
1.844     albertel 8912:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8913:             $unhome = $desiredhome;
1.620     albertel 8914: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8915: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8916:         } else { # load balancing routine for determining $unhome
1.81      www      8917:             my $loadm=10000000;
1.841     albertel 8918: 	    my %servers = &get_servers($udom,'library');
                   8919: 	    foreach my $tryserver (keys(%servers)) {
                   8920: 		my $answer=reply('load',$tryserver);
                   8921: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8922: 		    $loadm=$answer;
                   8923: 		    $unhome=$tryserver;
                   8924: 		}
1.80      www      8925: 	    }
                   8926:         }
                   8927:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8928: 	    return 'error: unable to find a home server for '.$uname.
                   8929:                    ' in domain '.$udom;
1.80      www      8930:         }
                   8931:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8932:                          &escape($upass),$unhome);
                   8933: 	unless ($reply eq 'ok') {
                   8934:             return 'error: '.$reply;
                   8935:         }   
1.230     stredwic 8936:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8937:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8938: 	    return 'error: unable verify users home machine.';
1.80      www      8939:         }
1.209     matthew  8940:     }   # End of creation of new user
1.80      www      8941: # ---------------------------------------------------------------------- Add ID
                   8942:     if ($uid) {
                   8943:        $uid=~tr/A-Z/a-z/;
                   8944:        my %uidhash=&idrget($udom,$uname);
1.196     www      8945:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8946:          && (!$forceid)) {
1.80      www      8947: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8948: 	      return 'error: user id "'.$uid.'" does not match '.
                   8949:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8950:           }
                   8951:        } else {
                   8952: 	  &idput($udom,($uname => $uid));
                   8953:        }
                   8954:     }
                   8955: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8956:     my @tmp=&get('environment',
1.899     raeburn  8957: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8958:                     'permanentemail','inststatus'],
1.134     albertel 8959: 		   $udom,$uname);
1.1075    raeburn  8960:     my (%names,%oldnames);
1.313     matthew  8961:     if ($tmp[0] =~ m/^error:.*/) { 
                   8962:         %names=(); 
                   8963:     } else {
                   8964:         %names = @tmp;
1.1075    raeburn  8965:         %oldnames = %names;
1.313     matthew  8966:     }
1.388     www      8967: #
1.1058    raeburn  8968: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8969: # of users did not contain them), do not overwrite existing values
                   8970: # unless field is in $candelete array ref.  
                   8971: #
                   8972: 
                   8973:     my @fields = ('firstname','middlename','lastname','generation',
                   8974:                   'permanentemail','id');
                   8975:     my %newvalues;
                   8976:     if (ref($candelete) eq 'ARRAY') {
                   8977:         foreach my $field (@fields) {
                   8978:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8979:                 if ($field eq 'firstname') {
                   8980:                     $names{$field} = $first;
                   8981:                 } elsif ($field eq 'middlename') {
                   8982:                     $names{$field} = $middle;
                   8983:                 } elsif ($field eq 'lastname') {
                   8984:                     $names{$field} = $last;
                   8985:                 } elsif ($field eq 'generation') { 
                   8986:                     $names{$field} = $gene;
                   8987:                 } elsif ($field eq 'permanentemail') {
                   8988:                     $names{$field} = $email;
                   8989:                 } elsif ($field eq 'id') {
                   8990:                     $names{$field}  = $uid;
                   8991:                 }
                   8992:             }
                   8993:         }
                   8994:     }
1.388     www      8995:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8996:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8997:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8998:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8999:     if ($email) {
                   9000:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9001:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9002:     }
1.899     raeburn  9003:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9004:     if (defined($inststatus)) {
                   9005:         $names{'inststatus'} = '';
                   9006:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9007:         if (ref($usertypes) eq 'HASH') {
                   9008:             my @okstatuses; 
                   9009:             foreach my $item (split(/:/,$inststatus)) {
                   9010:                 if (defined($usertypes->{$item})) {
                   9011:                     push(@okstatuses,$item);  
                   9012:                 }
                   9013:             }
                   9014:             if (@okstatuses) {
                   9015:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9016:             }
                   9017:         }
                   9018:     }
1.1075    raeburn  9019:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9020:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9021:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9022:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9023:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9024:     } else {
                   9025:         $logmsg .= ' during self creation';
                   9026:     }
1.1075    raeburn  9027:     my $changed;
                   9028:     if ($newuser) {
                   9029:         $changed = 1;
                   9030:     } else {
                   9031:         foreach my $field (@fields) {
                   9032:             if ($names{$field} ne $oldnames{$field}) {
                   9033:                 $changed = 1;
                   9034:                 last;
                   9035:             }
                   9036:         }
                   9037:     }
                   9038:     unless ($changed) {
                   9039:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9040:         &logthis($logmsg);
                   9041:         return 'ok';
                   9042:     }
                   9043:     my $reply = &put('environment', \%names, $udom,$uname);
                   9044:     if ($reply ne 'ok') { 
                   9045:         return 'error: '.$reply;
                   9046:     }
1.1087    raeburn  9047:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9048:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9049:     }
1.1075    raeburn  9050:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9051:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9052:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9053:     &logthis($logmsg);
1.134     albertel 9054:     return 'ok';
1.80      www      9055: }
                   9056: 
1.81      www      9057: # -------------------------------------------------------------- Modify student
1.80      www      9058: 
1.81      www      9059: sub modifystudent {
                   9060:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9061:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9062:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9063:     if (!$cid) {
1.620     albertel 9064: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9065: 	    return 'not_in_class';
                   9066: 	}
1.80      www      9067:     }
                   9068: # --------------------------------------------------------------- Make the user
1.81      www      9069:     my $reply=&modifyuser
1.209     matthew  9070: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9071:          $desiredhome,$email,$inststatus);
1.80      www      9072:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9073:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9074:     # student's environment
1.297     matthew  9075:     $uid = undef if (!$forceid);
1.455     albertel 9076:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9077: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9078:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9079:     return $reply;
                   9080: }
                   9081: 
                   9082: sub modify_student_enrollment {
1.1172.2.23  raeburn  9083:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9084:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9085:     my ($cdom,$cnum,$chome);
                   9086:     if (!$cid) {
1.620     albertel 9087: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9088: 	    return 'not_in_class';
                   9089: 	}
1.620     albertel 9090: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9091: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9092:     } else {
                   9093: 	($cdom,$cnum)=split(/_/,$cid);
                   9094:     }
1.620     albertel 9095:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9096:     if (!$chome) {
1.457     raeburn  9097: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9098:     }
1.455     albertel 9099:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9100:     # Make sure the user exists
1.81      www      9101:     my $uhome=&homeserver($uname,$udom);
                   9102:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9103: 	return 'error: no such user';
                   9104:     }
1.297     matthew  9105:     # Get student data if we were not given enough information
                   9106:     if (!defined($first)  || $first  eq '' || 
                   9107:         !defined($last)   || $last   eq '' || 
                   9108:         !defined($uid)    || $uid    eq '' || 
                   9109:         !defined($middle) || $middle eq '' || 
                   9110:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9111:         # They did not supply us with enough data to enroll the student, so
                   9112:         # we need to pick up more information.
1.297     matthew  9113:         my %tmp = &get('environment',
1.294     matthew  9114:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9115:                        ,$udom,$uname);
                   9116: 
1.800     albertel 9117:         #foreach my $key (keys(%tmp)) {
                   9118:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9119:         #}
1.294     matthew  9120:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9121:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9122:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9123:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9124:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9125:     }
1.556     albertel 9126:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9127:     my $user = "$uname:$udom";
                   9128:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9129:     my $reply=cput('classlist',
1.1148    raeburn  9130: 		   {$user => 
1.1172.2.76  raeburn  9131: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9132: 		   $cdom,$cnum);
1.1148    raeburn  9133:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9134:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9135:     } else { 
1.81      www      9136: 	return 'error: '.$reply;
                   9137:     }
1.297     matthew  9138:     # Add student role to user
1.83      www      9139:     my $uurl='/'.$cid;
1.81      www      9140:     $uurl=~s/\_/\//g;
                   9141:     if ($usec) {
                   9142: 	$uurl.='/'.$usec;
                   9143:     }
1.1148    raeburn  9144:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9145:                              $selfenroll,$context);
                   9146:     if ($result ne 'ok') {
                   9147:         if ($old_entry{$user} ne '') {
                   9148:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9149:         } else {
                   9150:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9151:         }
                   9152:     }
                   9153:     return $result; 
1.21      www      9154: }
                   9155: 
1.556     albertel 9156: sub format_name {
                   9157:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9158:     my $name;
                   9159:     if ($first ne 'lastname') {
                   9160: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9161:     } else {
                   9162: 	if ($lastname=~/\S/) {
                   9163: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9164: 	    $name=~s/\s+,/,/;
                   9165: 	} else {
                   9166: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9167: 	}
                   9168:     }
                   9169:     $name=~s/^\s+//;
                   9170:     $name=~s/\s+$//;
                   9171:     $name=~s/\s+/ /g;
                   9172:     return $name;
                   9173: }
                   9174: 
1.84      www      9175: # ------------------------------------------------- Write to course preferences
                   9176: 
                   9177: sub writecoursepref {
                   9178:     my ($courseid,%prefs)=@_;
                   9179:     $courseid=~s/^\///;
                   9180:     $courseid=~s/\_/\//g;
                   9181:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9182:     my $chome=homeserver($cnum,$cdomain);
                   9183:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9184: 	return 'error: no such course';
                   9185:     }
                   9186:     my $cstring='';
1.800     albertel 9187:     foreach my $pref (keys(%prefs)) {
                   9188: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9189:     }
1.84      www      9190:     $cstring=~s/\&$//;
                   9191:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9192: }
                   9193: 
                   9194: # ---------------------------------------------------------- Make/modify course
                   9195: 
                   9196: sub createcourse {
1.741     raeburn  9197:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9198:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9199:     $url=&declutter($url);
                   9200:     my $cid='';
1.1028    raeburn  9201:     if ($context eq 'requestcourses') {
                   9202:         my $can_create = 0;
                   9203:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9204:         if ($udom eq $ownerdom) {
                   9205:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9206:                                   $context)) {
                   9207:                 $can_create = 1;
                   9208:             }
                   9209:         } else {
                   9210:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9211:                                            $category);
                   9212:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9213:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9214:                 if (@curr > 0) {
                   9215:                     my @options = qw(approval validate autolimit);
                   9216:                     my $optregex = join('|',@options);
                   9217:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9218:                         $can_create = 1;
                   9219:                     }
                   9220:                 }
                   9221:             }
                   9222:         }
                   9223:         if ($can_create) {
                   9224:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9225:                 unless (&allowed('ccc',$udom)) {
                   9226:                     return 'refused'; 
                   9227:                 }
1.1017    raeburn  9228:             }
                   9229:         } else {
                   9230:             return 'refused';
                   9231:         }
1.1028    raeburn  9232:     } elsif (!&allowed('ccc',$udom)) {
                   9233:         return 'refused';
1.84      www      9234:     }
1.1011    raeburn  9235: # --------------------------------------------------------------- Get Unique ID
                   9236:     my $uname;
                   9237:     if ($cnum =~ /^$match_courseid$/) {
                   9238:         my $chome=&homeserver($cnum,$udom,'true');
                   9239:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9240:             $uname = $cnum;
                   9241:         } else {
1.1038    raeburn  9242:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9243:         }
                   9244:     } else {
1.1038    raeburn  9245:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9246:     }
                   9247:     return $uname if ($uname =~ /^error/);
                   9248: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9249:     if (!defined($course_server)) {
                   9250:         if (defined(&domain($udom,'primary'))) {
                   9251:             $course_server = &domain($udom,'primary');
                   9252:         } else {
                   9253:             $course_server = $env{'user.home'}; 
                   9254:         }
                   9255:     }
                   9256:     my %host_servers =
                   9257:         &Apache::lonnet::get_servers($udom,'library');
                   9258:     unless ($host_servers{$course_server}) {
                   9259:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9260:     }
1.84      www      9261: # ------------------------------------------------------------- Make the course
                   9262:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9263:                       $course_server);
1.84      www      9264:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9265:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9266:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9267: 	return 'error: no such course';
                   9268:     }
1.271     www      9269: # ----------------------------------------------------------------- Course made
1.516     raeburn  9270: # log existence
1.1029    raeburn  9271:     my $now = time;
1.918     raeburn  9272:     my $newcourse = {
                   9273:                     $udom.'_'.$uname => {
1.921     raeburn  9274:                                      description => $description,
                   9275:                                      inst_code   => $inst_code,
                   9276:                                      owner       => $course_owner,
                   9277:                                      type        => $crstype,
1.1029    raeburn  9278:                                      creator     => $env{'user.name'}.':'.
                   9279:                                                     $env{'user.domain'},
                   9280:                                      created     => $now,
                   9281:                                      context     => $context,
1.918     raeburn  9282:                                                 },
                   9283:                     };
1.921     raeburn  9284:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9285: # set toplevel url
1.271     www      9286:     my $topurl=$url;
                   9287:     unless ($nonstandard) {
                   9288: # ------------------------------------------ For standard courses, make top url
                   9289:         my $mapurl=&clutter($url);
1.278     www      9290:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9291:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9292: <map>
                   9293: <resource id="1" type="start"></resource>
                   9294: <resource id="2" src="$mapurl"></resource>
                   9295: <resource id="3" type="finish"></resource>
                   9296: <link index="1" from="1" to="2"></link>
                   9297: <link index="2" from="2" to="3"></link>
                   9298: </map>
                   9299: ENDINITMAP
                   9300:         $topurl=&declutter(
1.638     albertel 9301:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9302:                           );
                   9303:     }
                   9304: # ----------------------------------------------------------- Write preferences
1.84      www      9305:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9306:                      ('description'              => $description,
                   9307:                       'url'                      => $topurl,
                   9308:                       'internal.creator'         => $env{'user.name'}.':'.
                   9309:                                                     $env{'user.domain'},
                   9310:                       'internal.created'         => $now,
                   9311:                       'internal.creationcontext' => $context)
                   9312:                     );
1.84      www      9313:     return '/'.$udom.'/'.$uname;
                   9314: }
                   9315: 
1.1011    raeburn  9316: # ------------------------------------------------------------------- Create ID
                   9317: sub generate_coursenum {
1.1038    raeburn  9318:     my ($udom,$crstype) = @_;
1.1011    raeburn  9319:     my $domdesc = &domain($udom);
                   9320:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9321:     my $first;
                   9322:     if ($crstype eq 'Community') {
                   9323:         $first = '0';
                   9324:     } else {
                   9325:         $first = int(1+rand(9)); 
                   9326:     } 
                   9327:     my $uname=$first.
1.1011    raeburn  9328:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9329:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9330:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9331: # ----------------------------------------------- Make sure that does not exist
                   9332:     my $uhome=&homeserver($uname,$udom,'true');
                   9333:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9334:         if ($crstype eq 'Community') {
                   9335:             $first = '0';
                   9336:         } else {
                   9337:             $first = int(1+rand(9));
                   9338:         }
                   9339:         $uname=$first.
1.1011    raeburn  9340:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9341:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9342:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9343:         $uhome=&homeserver($uname,$udom,'true');
                   9344:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9345:             return 'error: unable to generate unique course-ID';
                   9346:         }
                   9347:     }
                   9348:     return $uname;
                   9349: }
                   9350: 
1.813     albertel 9351: sub is_course {
1.1167    droeschl 9352:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9353:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9354: 
                   9355:     return unless $cdom and $cnum;
                   9356: 
                   9357:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9358:         '.');
                   9359: 
1.1172.2.23  raeburn  9360:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9361:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9362: }
                   9363: 
1.1015    raeburn  9364: sub store_userdata {
                   9365:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9366:     my $result;
1.1016    raeburn  9367:     if ($datakey ne '') {
1.1013    raeburn  9368:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9369:             if ($udom eq '' || $uname eq '') {
                   9370:                 $udom = $env{'user.domain'};
                   9371:                 $uname = $env{'user.name'};
                   9372:             }
                   9373:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9374:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9375:                 $result = 'error: no_host';
                   9376:             } else {
                   9377:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9378:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9379: 
                   9380:                 my $namevalue='';
                   9381:                 foreach my $key (keys(%{$storehash})) {
                   9382:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9383:                 }
                   9384:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9385:                 unless ($namespace eq 'courserequests') {
                   9386:                     $datakey = &escape($datakey);
                   9387:                 }
1.1105    raeburn  9388:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9389:                                   $namevalue,$uhome);
1.1013    raeburn  9390:             }
                   9391:         } else {
                   9392:             $result = 'error: data to store was not a hash reference'; 
                   9393:         }
                   9394:     } else {
                   9395:         $result= 'error: invalid requestkey'; 
                   9396:     }
                   9397:     return $result;
                   9398: }
                   9399: 
1.21      www      9400: # ---------------------------------------------------------- Assign Custom Role
                   9401: 
                   9402: sub assigncustomrole {
1.957     raeburn  9403:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9404:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9405:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9406: }
                   9407: 
                   9408: # ----------------------------------------------------------------- Revoke Role
                   9409: 
                   9410: sub revokerole {
1.957     raeburn  9411:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9412:     my $now=time;
1.965     raeburn  9413:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9414: }
                   9415: 
                   9416: # ---------------------------------------------------------- Revoke Custom Role
                   9417: 
                   9418: sub revokecustomrole {
1.957     raeburn  9419:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9420:     my $now=time;
1.357     www      9421:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9422:            $deleteflag,$selfenroll,$context);
1.17      www      9423: }
                   9424: 
1.533     banghart 9425: # ------------------------------------------------------------ Disk usage
1.535     albertel 9426: sub diskusage {
1.955     raeburn  9427:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9428:     $directorypath =~ s/\/$//;
                   9429:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9430:                        .&escape($getpropath).':'.&escape($uname).':'
                   9431:                        .&escape($udom),homeserver($uname,$udom));
                   9432:     if ($listing eq 'unknown_cmd') {
                   9433:         if ($getpropath) {
                   9434:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9435:         }
                   9436:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9437:     }
1.514     albertel 9438:     return $listing;
1.512     banghart 9439: }
                   9440: 
1.566     banghart 9441: sub is_locked {
1.1096    raeburn  9442:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9443:     my @check;
                   9444:     my $is_locked;
1.1093    raeburn  9445:     push (@check,$file_name);
1.613     albertel 9446:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9447: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9448:     my ($tmp)=keys(%locked);
                   9449:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9450:     
1.566     banghart 9451:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9452:         $is_locked = 'false';
                   9453:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9454:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9455:                $is_locked = 'true';
1.1096    raeburn  9456:                if (ref($which) eq 'ARRAY') {
                   9457:                    push(@{$which},$entry);
                   9458:                } else {
                   9459:                    last;
                   9460:                }
1.745     raeburn  9461:            }
                   9462:        }
1.566     banghart 9463:     } else {
                   9464:         $is_locked = 'false';
                   9465:     }
1.1093    raeburn  9466:     return $is_locked;
1.566     banghart 9467: }
                   9468: 
1.759     albertel 9469: sub declutter_portfile {
                   9470:     my ($file) = @_;
1.833     albertel 9471:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9472:     return $file;
                   9473: }
                   9474: 
1.559     banghart 9475: # ------------------------------------------------------------- Mark as Read Only
                   9476: 
                   9477: sub mark_as_readonly {
                   9478:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9479:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9480:     my ($tmp)=keys(%current_permissions);
                   9481:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9482:     foreach my $file (@{$files}) {
1.759     albertel 9483: 	$file = &declutter_portfile($file);
1.561     banghart 9484:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9485:     }
1.613     albertel 9486:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9487:     return;
                   9488: }
                   9489: 
1.572     banghart 9490: # ------------------------------------------------------------Save Selected Files
                   9491: 
                   9492: sub save_selected_files {
                   9493:     my ($user, $path, @files) = @_;
                   9494:     my $filename = $user."savedfiles";
1.573     banghart 9495:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9496:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9497:     foreach my $file (@files) {
1.620     albertel 9498:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9499:     }
                   9500:     foreach my $file (@other_files) {
1.574     banghart 9501:         print (OUT $file."\n");
1.572     banghart 9502:     }
1.574     banghart 9503:     close (OUT);
1.572     banghart 9504:     return 'ok';
                   9505: }
                   9506: 
1.574     banghart 9507: sub clear_selected_files {
                   9508:     my ($user) = @_;
                   9509:     my $filename = $user."savedfiles";
1.1117    foxr     9510:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9511:     print (OUT undef);
                   9512:     close (OUT);
                   9513:     return ("ok");    
                   9514: }
                   9515: 
1.572     banghart 9516: sub files_in_path {
                   9517:     my ($user, $path) = @_;
                   9518:     my $filename = $user."savedfiles";
                   9519:     my %return_files;
1.1117    foxr     9520:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9521:     while (my $line_in = <IN>) {
1.574     banghart 9522:         chomp ($line_in);
                   9523:         my @paths_and_file = split (m!/!, $line_in);
                   9524:         my $file_part = pop (@paths_and_file);
                   9525:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9526:         $path_part.='/';
                   9527:         my $path_and_file = $path_part.$file_part;
                   9528:         if ($path_part eq $path) {
                   9529:             $return_files{$file_part}= 'selected';
                   9530:         }
                   9531:     }
1.574     banghart 9532:     close (IN);
                   9533:     return (\%return_files);
1.572     banghart 9534: }
                   9535: 
                   9536: # called in portfolio select mode, to show files selected NOT in current directory
                   9537: sub files_not_in_path {
                   9538:     my ($user, $path) = @_;
                   9539:     my $filename = $user."savedfiles";
                   9540:     my @return_files;
                   9541:     my $path_part;
1.1117    foxr     9542:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9543:     while (my $line = <IN>) {
1.572     banghart 9544:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9545:         my @paths_and_file = split(m|/|, $line);
                   9546:         my $file_part = pop(@paths_and_file);
                   9547:         chomp($file_part);
                   9548:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9549:         $path_part .= '/';
                   9550:         my $path_and_file = $path_part.$file_part;
                   9551:         if ($path_part ne $path) {
1.800     albertel 9552:             push(@return_files, ($path_and_file));
1.572     banghart 9553:         }
                   9554:     }
1.800     albertel 9555:     close(OUT);
1.574     banghart 9556:     return (@return_files);
1.572     banghart 9557: }
                   9558: 
1.745     raeburn  9559: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9560: 
1.745     raeburn  9561: sub get_portfile_permissions {
                   9562:     my ($domain,$user) = @_;
1.613     albertel 9563:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9564:     my ($tmp)=keys(%current_permissions);
                   9565:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9566:     return \%current_permissions;
                   9567: }
                   9568: 
                   9569: #---------------------------------------------Get portfolio file access controls
                   9570: 
1.749     raeburn  9571: sub get_access_controls {
1.745     raeburn  9572:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9573:     my %access;
                   9574:     my $real_file = $file;
                   9575:     $file =~ s/\.meta$//;
1.745     raeburn  9576:     if (defined($file)) {
1.749     raeburn  9577:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9578:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9579:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9580:             }
                   9581:         }
1.745     raeburn  9582:     } else {
1.749     raeburn  9583:         foreach my $key (keys(%{$current_permissions})) {
                   9584:             if ($key =~ /\0accesscontrol$/) {
                   9585:                 if (defined($group)) {
                   9586:                     if ($key !~ m-^\Q$group\E/-) {
                   9587:                         next;
                   9588:                     }
                   9589:                 }
                   9590:                 my ($fullpath) = split(/\0/,$key);
                   9591:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9592:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9593:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9594:                     }
                   9595:                 }
                   9596:             }
                   9597:         }
                   9598:     }
                   9599:     return %access;
                   9600: }
                   9601: 
                   9602: sub modify_access_controls {
                   9603:     my ($file_name,$changes,$domain,$user)=@_;
                   9604:     my ($outcome,$deloutcome);
                   9605:     my %store_permissions;
                   9606:     my %new_values;
                   9607:     my %new_control;
                   9608:     my %translation;
                   9609:     my @deletions = ();
                   9610:     my $now = time;
                   9611:     if (exists($$changes{'activate'})) {
                   9612:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9613:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9614:             my $numnew = scalar(@newitems);
                   9615:             for (my $i=0; $i<$numnew; $i++) {
                   9616:                 my $newkey = $newitems[$i];
                   9617:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9618:                 if ($newkey =~ /^\d+:/) { 
                   9619:                     $newkey =~ s/^(\d+)/$newid/;
                   9620:                     $translation{$1} = $newid;
                   9621:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9622:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9623:                     $translation{$1} = $newid;
                   9624:                 }
1.749     raeburn  9625:                 $new_values{$file_name."\0".$newkey} = 
                   9626:                                           $$changes{'activate'}{$newitems[$i]};
                   9627:                 $new_control{$newkey} = $now;
                   9628:             }
                   9629:         }
                   9630:     }
                   9631:     my %todelete;
                   9632:     my %changed_items;
                   9633:     foreach my $action ('delete','update') {
                   9634:         if (exists($$changes{$action})) {
                   9635:             if (ref($$changes{$action}) eq 'HASH') {
                   9636:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9637:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9638:                     if ($action eq 'delete') { 
                   9639:                         $todelete{$itemnum} = 1;
                   9640:                     } else {
                   9641:                         $changed_items{$itemnum} = $key;
                   9642:                     }
                   9643:                 }
1.745     raeburn  9644:             }
                   9645:         }
1.749     raeburn  9646:     }
                   9647:     # get lock on access controls for file.
                   9648:     my $lockhash = {
                   9649:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9650:                                                        ':'.$env{'user.domain'},
                   9651:                    }; 
                   9652:     my $tries = 0;
                   9653:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9654:    
1.1172.2.79  raeburn  9655:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9656:         $tries ++;
1.1172.2.79  raeburn  9657:         sleep(0.1);
1.749     raeburn  9658:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9659:     }
                   9660:     if ($gotlock eq 'ok') {
                   9661:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9662:         my ($tmp)=keys(%curr_permissions);
                   9663:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9664:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9665:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9666:             if (ref($curr_controls) eq 'HASH') {
                   9667:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9668:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9669:                     if (defined($todelete{$itemnum})) {
                   9670:                         push(@deletions,$file_name."\0".$control_item);
                   9671:                     } else {
                   9672:                         if (defined($changed_items{$itemnum})) {
                   9673:                             $new_control{$changed_items{$itemnum}} = $now;
                   9674:                             push(@deletions,$file_name."\0".$control_item);
                   9675:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9676:                         } else {
                   9677:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9678:                         }
                   9679:                     }
1.745     raeburn  9680:                 }
                   9681:             }
                   9682:         }
1.970     raeburn  9683:         my ($group);
                   9684:         if (&is_course($domain,$user)) {
                   9685:             ($group,my $file) = split(/\//,$file_name,2);
                   9686:         }
1.749     raeburn  9687:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9688:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9689:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9690:         #  remove lock
                   9691:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9692:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9693:         my $sqlresult =
1.970     raeburn  9694:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9695:                                     $group);
1.749     raeburn  9696:     } else {
                   9697:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9698:     }
1.749     raeburn  9699:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9700: }
                   9701: 
1.827     raeburn  9702: sub make_public_indefinitely {
                   9703:     my ($requrl) = @_;
                   9704:     my $now = time;
                   9705:     my $action = 'activate';
                   9706:     my $aclnum = 0;
                   9707:     if (&is_portfolio_url($requrl)) {
                   9708:         my (undef,$udom,$unum,$file_name,$group) =
                   9709:             &parse_portfolio_url($requrl);
                   9710:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9711:         my %access_controls = &get_access_controls($current_perms,
                   9712:                                                    $group,$file_name);
                   9713:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9714:             my ($num,$scope,$end,$start) = 
                   9715:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9716:             if ($scope eq 'public') {
                   9717:                 if ($start <= $now && $end == 0) {
                   9718:                     $action = 'none';
                   9719:                 } else {
                   9720:                     $action = 'update';
                   9721:                     $aclnum = $num;
                   9722:                 }
                   9723:                 last;
                   9724:             }
                   9725:         }
                   9726:         if ($action eq 'none') {
                   9727:              return 'ok';
                   9728:         } else {
                   9729:             my %changes;
                   9730:             my $newend = 0;
                   9731:             my $newstart = $now;
                   9732:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9733:             $changes{$action}{$newkey} = {
                   9734:                 type => 'public',
                   9735:                 time => {
                   9736:                     start => $newstart,
                   9737:                     end   => $newend,
                   9738:                 },
                   9739:             };
                   9740:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9741:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9742:             return $outcome;
                   9743:         }
                   9744:     } else {
                   9745:         return 'invalid';
                   9746:     }
                   9747: }
                   9748: 
1.745     raeburn  9749: #------------------------------------------------------Get Marked as Read Only
                   9750: 
                   9751: sub get_marked_as_readonly {
                   9752:     my ($domain,$user,$what,$group) = @_;
                   9753:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9754:     my @readonly_files;
1.629     banghart 9755:     my $cmp1=$what;
                   9756:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9757:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9758:         if (defined($group)) {
                   9759:             if ($file_name !~ m-^\Q$group\E/-) {
                   9760:                 next;
                   9761:             }
                   9762:         }
1.561     banghart 9763:         if (ref($value) eq "ARRAY"){
                   9764:             foreach my $stored_what (@{$value}) {
1.629     banghart 9765:                 my $cmp2=$stored_what;
1.759     albertel 9766:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9767:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9768:                 }
1.629     banghart 9769:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9770:                     push(@readonly_files, $file_name);
1.745     raeburn  9771:                     last;
1.563     banghart 9772:                 } elsif (!defined($what)) {
                   9773:                     push(@readonly_files, $file_name);
1.745     raeburn  9774:                     last;
1.561     banghart 9775:                 }
                   9776:             }
1.745     raeburn  9777:         }
1.561     banghart 9778:     }
                   9779:     return @readonly_files;
                   9780: }
1.577     banghart 9781: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9782: 
1.577     banghart 9783: sub get_marked_as_readonly_hash {
1.745     raeburn  9784:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9785:     my %readonly_files;
1.745     raeburn  9786:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9787:         if (defined($group)) {
                   9788:             if ($file_name !~ m-^\Q$group\E/-) {
                   9789:                 next;
                   9790:             }
                   9791:         }
1.577     banghart 9792:         if (ref($value) eq "ARRAY"){
                   9793:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9794:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9795:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9796:                         if ($lock_descriptor eq 'graded') {
                   9797:                             $readonly_files{$file_name} = 'graded';
                   9798:                         } elsif ($lock_descriptor eq 'handback') {
                   9799:                             $readonly_files{$file_name} = 'handback';
                   9800:                         } else {
                   9801:                             if (!exists($readonly_files{$file_name})) {
                   9802:                                 $readonly_files{$file_name} = 'locked';
                   9803:                             }
                   9804:                         }
1.745     raeburn  9805:                     }
1.750     banghart 9806:                 } 
1.577     banghart 9807:             }
                   9808:         } 
                   9809:     }
                   9810:     return %readonly_files;
                   9811: }
1.559     banghart 9812: # ------------------------------------------------------------ Unmark as Read Only
                   9813: 
                   9814: sub unmark_as_readonly {
1.629     banghart 9815:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9816:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9817:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9818:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9819:     my $symb_crs = $what;
                   9820:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9821:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9822:     my ($tmp)=keys(%current_permissions);
                   9823:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9824:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9825:     foreach my $file (@readonly_files) {
1.759     albertel 9826: 	my $clean_file = &declutter_portfile($file);
                   9827: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9828: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9829:         my @new_locks;
                   9830:         my @del_keys;
                   9831:         if (ref($current_locks) eq "ARRAY"){
                   9832:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9833:                 my $compare=$locker;
1.749     raeburn  9834:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9835:                     $compare=join('',@{$locker});
1.746     raeburn  9836:                     if ($compare ne $symb_crs) {
                   9837:                         push(@new_locks, $locker);
                   9838:                     }
1.563     banghart 9839:                 }
                   9840:             }
1.650     albertel 9841:             if (scalar(@new_locks) > 0) {
1.563     banghart 9842:                 $current_permissions{$file} = \@new_locks;
                   9843:             } else {
                   9844:                 push(@del_keys, $file);
1.613     albertel 9845:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9846:                 delete($current_permissions{$file});
1.563     banghart 9847:             }
                   9848:         }
1.561     banghart 9849:     }
1.613     albertel 9850:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9851:     return;
                   9852: }
1.512     banghart 9853: 
1.17      www      9854: # ------------------------------------------------------------ Directory lister
                   9855: 
                   9856: sub dirlist {
1.955     raeburn  9857:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9858:     $uri=~s/^\///;
                   9859:     $uri=~s/\/$//;
1.253     stredwic 9860:     my ($udom, $uname);
1.955     raeburn  9861:     if ($getuserdir) {
1.253     stredwic 9862:         $udom = $userdomain;
                   9863:         $uname = $username;
1.955     raeburn  9864:     } else {
                   9865:         (undef,$udom,$uname)=split(/\//,$uri);
                   9866:         if(defined($userdomain)) {
                   9867:             $udom = $userdomain;
                   9868:         }
                   9869:         if(defined($username)) {
                   9870:             $uname = $username;
                   9871:         }
1.253     stredwic 9872:     }
1.955     raeburn  9873:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9874: 
1.955     raeburn  9875:     $dirRoot = $perlvar{'lonDocRoot'};
                   9876:     if (defined($getpropath)) {
                   9877:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9878:         $dirRoot =~ s/\/$//;
1.955     raeburn  9879:     } elsif (defined($getuserdir)) {
                   9880:         my $subdir=$uname.'__';
                   9881:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9882:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9883:                    ."/$udom/$subdir/$uname";
                   9884:     } elsif (defined($alternateRoot)) {
                   9885:         $dirRoot = $alternateRoot;
1.751     banghart 9886:     }
1.253     stredwic 9887: 
                   9888:     if($udom) {
                   9889:         if($uname) {
1.1135    raeburn  9890:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9891:             if ($uhome eq 'no_host') {
                   9892:                 return ([],'no_host');
                   9893:             }
1.955     raeburn  9894:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9895:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9896:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9897:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9898:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9899:             } else {
                   9900:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9901:             }
1.605     matthew  9902:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9903:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9904:                 @listing_results = split(/:/,$listing);
                   9905:             } else {
                   9906:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9907:             }
1.1135    raeburn  9908:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9909:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9910:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9911:                 return ([],$listing);
                   9912:             } else {
                   9913:                 return (\@listing_results);
1.1135    raeburn  9914:             }
1.955     raeburn  9915:         } elsif(!$alternateRoot) {
1.1136    raeburn  9916:             my (%allusers,%listerror);
1.841     albertel 9917: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9918:  	    foreach my $tryserver (keys(%servers)) {
                   9919:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9920:                                   &escape($udom),$tryserver);
                   9921:                 if ($listing eq 'unknown_cmd') {
                   9922: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9923: 				      $udom, $tryserver);
                   9924:                 } else {
                   9925:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9926:                 }
1.841     albertel 9927: 		if ($listing eq 'unknown_cmd') {
                   9928: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9929: 				      $udom, $tryserver);
                   9930: 		    @listing_results = split(/:/,$listing);
                   9931: 		} else {
                   9932: 		    @listing_results =
                   9933: 			map { &unescape($_); } split(/:/,$listing);
                   9934: 		}
1.1136    raeburn  9935:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9936:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9937:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9938:                     $listerror{$tryserver} = $listing;
                   9939:                 } else {
1.841     albertel 9940: 		    foreach my $line (@listing_results) {
                   9941: 			my ($entry) = split(/&/,$line,2);
                   9942: 			$allusers{$entry} = 1;
                   9943: 		    }
                   9944: 		}
1.253     stredwic 9945:             }
1.1136    raeburn  9946:             my @alluserslist=();
1.800     albertel 9947:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9948:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9949:             }
1.1172.2.80  raeburn  9950:             if (!%listerror) {
                   9951:                 # no errors
                   9952:                 return (\@alluserslist);
                   9953:             } elsif (scalar(keys(%servers)) == 1) {
                   9954:                 # one library server, one error
                   9955:                 my ($key) = keys(%listerror);
                   9956:                 return (\@alluserslist, $listerror{$key});
                   9957:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   9958:                 # con_lost indicates that we might miss data from at least one
                   9959:                 # library server
                   9960:                 return (\@alluserslist, 'con_lost');
                   9961:             } else {
                   9962:                 # multiple library servers and no con_lost -> data should be
                   9963:                 # complete.
                   9964:                 return (\@alluserslist);
                   9965:             }
                   9966: 
1.253     stredwic 9967:         } else {
1.1136    raeburn  9968:             return ([],'missing username');
1.253     stredwic 9969:         }
1.955     raeburn  9970:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9971:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9972:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9973:         return (\@all_domains);
1.955     raeburn  9974:     } else {
1.1136    raeburn  9975:         return ([],'missing domain');
1.275     stredwic 9976:     }
                   9977: }
                   9978: 
                   9979: # --------------------------------------------- GetFileTimestamp
                   9980: # This function utilizes dirlist and returns the date stamp for
                   9981: # when it was last modified.  It will also return an error of -1
                   9982: # if an error occurs
                   9983: 
                   9984: sub GetFileTimestamp {
1.955     raeburn  9985:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9986:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9987:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9988:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9989:                                     undef,$getuserdir);
                   9990:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9991:         return -1;
                   9992:     }
                   9993:     if (ref($fileref) eq 'ARRAY') {
                   9994:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9995:         # @stats contains first the filename, then the stat output
                   9996:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9997:     } else {
                   9998:         return -1;
1.253     stredwic 9999:     }
1.26      www      10000: }
                   10001: 
1.712     albertel 10002: sub stat_file {
                   10003:     my ($uri) = @_;
1.787     albertel 10004:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10005: 
1.955     raeburn  10006:     my ($udom,$uname,$file);
1.712     albertel 10007:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10008: 	($udom,$uname,$file) =
1.811     albertel 10009: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10010: 	$file = 'userfiles/'.$file;
                   10011:     }
                   10012:     if ($uri =~ m-^/res/-) {
                   10013: 	($udom,$uname) = 
1.807     albertel 10014: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10015: 	$file = $uri;
                   10016:     }
                   10017: 
                   10018:     if (!$udom || !$uname || !$file) {
                   10019: 	# unable to handle the uri
                   10020: 	return ();
                   10021:     }
1.956     raeburn  10022:     my $getpropath;
                   10023:     if ($file =~ /^userfiles\//) {
                   10024:         $getpropath = 1;
                   10025:     }
1.1136    raeburn  10026:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10027:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10028:         return ();
                   10029:     } else {
                   10030:         if (ref($listref) eq 'ARRAY') {
                   10031:             my @stats = split('&',$listref->[0]);
                   10032: 	    shift(@stats); #filename is first
                   10033: 	    return @stats;
                   10034:         }
1.712     albertel 10035:     }
                   10036:     return ();
                   10037: }
                   10038: 
1.26      www      10039: # -------------------------------------------------------- Value of a Condition
                   10040: 
1.713     albertel 10041: # gets the value of a specific preevaluated condition
                   10042: #    stored in the string  $env{user.state.<cid>}
                   10043: # or looks up a condition reference in the bighash and if if hasn't
                   10044: # already been evaluated recurses into docondval to get the value of
                   10045: # the condition, then memoizing it to 
                   10046: #   $env{user.state.<cid>.<condition>}
1.40      www      10047: sub directcondval {
                   10048:     my $number=shift;
1.620     albertel 10049:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10050: 	&Apache::lonuserstate::evalstate();
                   10051:     }
1.713     albertel 10052:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10053: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10054:     } elsif ($number =~ /^_/) {
                   10055: 	my $sub_condition;
                   10056: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10057: 		&GDBM_READER(),0640)) {
                   10058: 	    $sub_condition=$bighash{'conditions'.$number};
                   10059: 	    untie(%bighash);
                   10060: 	}
                   10061: 	my $value = &docondval($sub_condition);
1.949     raeburn  10062: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10063: 	return $value;
                   10064:     }
1.620     albertel 10065:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10066:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10067:     } else {
                   10068:        return 2;
                   10069:     }
                   10070: }
                   10071: 
1.713     albertel 10072: # get the collection of conditions for this resource
1.26      www      10073: sub condval {
                   10074:     my $condidx=shift;
1.54      www      10075:     my $allpathcond='';
1.713     albertel 10076:     foreach my $cond (split(/\|/,$condidx)) {
                   10077: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10078: 	    $allpathcond.=
                   10079: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10080: 	}
1.191     harris41 10081:     }
1.54      www      10082:     $allpathcond=~s/\|$//;
1.713     albertel 10083:     return &docondval($allpathcond);
                   10084: }
                   10085: 
                   10086: #evaluates an expression of conditions
                   10087: sub docondval {
                   10088:     my ($allpathcond) = @_;
                   10089:     my $result=0;
                   10090:     if ($env{'request.course.id'}
                   10091: 	&& defined($allpathcond)) {
                   10092: 	my $operand='|';
                   10093: 	my @stack;
                   10094: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10095: 	    if ($chunk eq '(') {
                   10096: 		push @stack,($operand,$result);
                   10097: 	    } elsif ($chunk eq ')') {
                   10098: 		my $before=pop @stack;
                   10099: 		if (pop @stack eq '&') {
                   10100: 		    $result=$result>$before?$before:$result;
                   10101: 		} else {
                   10102: 		    $result=$result>$before?$result:$before;
                   10103: 		}
                   10104: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10105: 		$operand=$chunk;
                   10106: 	    } else {
                   10107: 		my $new=directcondval($chunk);
                   10108: 		if ($operand eq '&') {
                   10109: 		    $result=$result>$new?$new:$result;
                   10110: 		} else {
                   10111: 		    $result=$result>$new?$result:$new;
                   10112: 		}
                   10113: 	    }
                   10114: 	}
1.26      www      10115:     }
                   10116:     return $result;
1.421     albertel 10117: }
                   10118: 
                   10119: # ---------------------------------------------------- Devalidate courseresdata
                   10120: 
                   10121: sub devalidatecourseresdata {
                   10122:     my ($coursenum,$coursedomain)=@_;
                   10123:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10124:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10125: }
                   10126: 
1.763     www      10127: 
1.200     www      10128: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10129: #
                   10130: #  Parameters:
                   10131: #      $coursenum    - Number of the course.
                   10132: #      $coursedomain - Domain at which the course was created.
                   10133: #  Returns:
                   10134: #     A hash of the course parameters along (I think) with timestamps
                   10135: #     and version info.
1.877     foxr     10136: 
1.624     albertel 10137: sub get_courseresdata {
                   10138:     my ($coursenum,$coursedomain)=@_;
1.200     www      10139:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10140:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10141:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10142:     my %dumpreply;
1.417     albertel 10143:     unless (defined($cached)) {
1.624     albertel 10144: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10145: 	$result=\%dumpreply;
1.251     albertel 10146: 	my ($tmp) = keys(%dumpreply);
                   10147: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10148: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10149: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10150: 	    return $tmp;
1.416     albertel 10151: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10152: 	    $result=undef;
1.599     albertel 10153: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10154: 	}
                   10155:     }
1.624     albertel 10156:     return $result;
                   10157: }
                   10158: 
1.633     albertel 10159: sub devalidateuserresdata {
                   10160:     my ($uname,$udom)=@_;
                   10161:     my $hashid="$udom:$uname";
                   10162:     &devalidate_cache_new('userres',$hashid);
                   10163: }
                   10164: 
1.624     albertel 10165: sub get_userresdata {
                   10166:     my ($uname,$udom)=@_;
                   10167:     #most student don\'t have any data set, check if there is some data
                   10168:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10169: 
                   10170:     my $hashid="$udom:$uname";
                   10171:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10172:     if (!defined($cached)) {
                   10173: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10174: 	$result=\%resourcedata;
                   10175: 	&do_cache_new('userres',$hashid,$result,600);
                   10176:     }
                   10177:     my ($tmp)=keys(%$result);
                   10178:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10179: 	return $result;
                   10180:     }
                   10181:     #error 2 occurs when the .db doesn't exist
                   10182:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10183:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10184: 	    &logthis("<font color=\"blue\">WARNING:".
                   10185: 		     " Trying to get resource data for ".
                   10186: 		     $uname." at ".$udom.": ".
                   10187: 		     $tmp."</font>");
                   10188:         }
1.624     albertel 10189:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10190: 	#&EXT_cache_set($udom,$uname);
                   10191: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10192: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10193:     }
                   10194:     return $tmp;
                   10195: }
1.879     foxr     10196: #----------------------------------------------- resdata - return resource data
                   10197: #  Purpose:
                   10198: #    Return resource data for either users or for a course.
                   10199: #  Parameters:
                   10200: #     $name      - Course/user name.
                   10201: #     $domain    - Name of the domain the user/course is registered on.
                   10202: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10203: #     @which     - Array of names of resources desired.
                   10204: #  Returns:
                   10205: #     The value of the first reasource in @which that is found in the
                   10206: #     resource hash.
                   10207: #  Exceptional Conditions:
                   10208: #     If the $type passed in is not valid (not the string 'course' or 
                   10209: #     'user', an undefined  reference is returned.
                   10210: #     If none of the resources are found, an undef is returned
1.624     albertel 10211: sub resdata {
                   10212:     my ($name,$domain,$type,@which)=@_;
                   10213:     my $result;
                   10214:     if ($type eq 'course') {
                   10215: 	$result=&get_courseresdata($name,$domain);
                   10216:     } elsif ($type eq 'user') {
                   10217: 	$result=&get_userresdata($name,$domain);
                   10218:     }
                   10219:     if (!ref($result)) { return $result; }    
1.251     albertel 10220:     foreach my $item (@which) {
1.927     albertel 10221: 	if (defined($result->{$item->[0]})) {
                   10222: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10223: 	}
1.250     albertel 10224:     }
1.291     albertel 10225:     return undef;
1.200     www      10226: }
                   10227: 
1.1172.2.31  raeburn  10228: sub get_numsuppfiles {
                   10229:     my ($cnum,$cdom,$ignorecache)=@_;
                   10230:     my $hashid=$cnum.':'.$cdom;
                   10231:     my ($suppcount,$cached);
                   10232:     unless ($ignorecache) {
                   10233:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10234:     }
                   10235:     unless (defined($cached)) {
                   10236:         my $chome=&homeserver($cnum,$cdom);
                   10237:         unless ($chome eq 'no_host') {
                   10238:             ($suppcount,my $errors) = (0,0);
                   10239:             my $suppmap = 'supplemental.sequence';
                   10240:             ($suppcount,$errors) =
                   10241:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10242:         }
                   10243:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10244:     }
                   10245:     return $suppcount;
                   10246: }
                   10247: 
1.379     matthew  10248: #
                   10249: # EXT resource caching routines
                   10250: #
                   10251: 
                   10252: sub clear_EXT_cache_status {
1.383     albertel 10253:     &delenv('cache.EXT.');
1.379     matthew  10254: }
                   10255: 
                   10256: sub EXT_cache_status {
                   10257:     my ($target_domain,$target_user) = @_;
1.383     albertel 10258:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10259:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10260:         # We know already the user has no data
                   10261:         return 1;
                   10262:     } else {
                   10263:         return 0;
                   10264:     }
                   10265: }
                   10266: 
                   10267: sub EXT_cache_set {
                   10268:     my ($target_domain,$target_user) = @_;
1.383     albertel 10269:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10270:     #&appenv({$cachename => time});
1.379     matthew  10271: }
                   10272: 
1.28      www      10273: # --------------------------------------------------------- Value of a Variable
1.58      www      10274: sub EXT {
1.715     albertel 10275: 
1.1172.2.28  raeburn  10276:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10277:     unless ($varname) { return ''; }
1.218     albertel 10278:     #get real user name/domain, courseid and symb
                   10279:     my $courseid;
1.359     albertel 10280:     my $publicuser;
1.427     www      10281:     if ($symbparm) {
                   10282: 	$symbparm=&get_symb_from_alias($symbparm);
                   10283:     }
1.218     albertel 10284:     if (!($uname && $udom)) {
1.790     albertel 10285:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10286:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10287:     } else {
1.620     albertel 10288: 	$courseid=$env{'request.course.id'};
1.218     albertel 10289:     }
1.48      www      10290:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10291:     my $rest;
1.320     albertel 10292:     if (defined($therest[0])) {
1.48      www      10293:        $rest=join('.',@therest);
                   10294:     } else {
                   10295:        $rest='';
                   10296:     }
1.320     albertel 10297: 
1.57      www      10298:     my $qualifierrest=$qualifier;
                   10299:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10300:     my $spacequalifierrest=$space;
                   10301:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10302:     if ($realm eq 'user') {
1.48      www      10303: # --------------------------------------------------------------- user.resource
                   10304: 	if ($space eq 'resource') {
1.651     albertel 10305: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10306: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10307: 		 &&
1.744     albertel 10308: 		 ($symbparm eq &symbread()) ) {	
                   10309: 		# if we are in the middle of processing the resource the
                   10310: 		# get the value we are planning on committing
                   10311:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10312:                     return $Apache::lonhomework::results{$qualifierrest};
                   10313:                 } else {
                   10314:                     return $Apache::lonhomework::history{$qualifierrest};
                   10315:                 }
1.335     albertel 10316: 	    } else {
1.359     albertel 10317: 		my %restored;
1.620     albertel 10318: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10319: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10320: 		} else {
                   10321: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10322: 		}
1.335     albertel 10323: 		return $restored{$qualifierrest};
                   10324: 	    }
1.48      www      10325: # ----------------------------------------------------------------- user.access
                   10326:         } elsif ($space eq 'access') {
1.218     albertel 10327: 	    # FIXME - not supporting calls for a specific user
1.48      www      10328:             return &allowed($qualifier,$rest);
                   10329: # ------------------------------------------ user.preferences, user.environment
                   10330:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10331: 	    if (($uname eq $env{'user.name'}) &&
                   10332: 		($udom eq $env{'user.domain'})) {
                   10333: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10334: 	    } else {
1.359     albertel 10335: 		my %returnhash;
                   10336: 		if (!$publicuser) {
                   10337: 		    %returnhash=&userenvironment($udom,$uname,
                   10338: 						 $qualifierrest);
                   10339: 		}
1.218     albertel 10340: 		return $returnhash{$qualifierrest};
                   10341: 	    }
1.48      www      10342: # ----------------------------------------------------------------- user.course
                   10343:         } elsif ($space eq 'course') {
1.218     albertel 10344: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10345:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10346: # ------------------------------------------------------------------- user.role
                   10347:         } elsif ($space eq 'role') {
1.218     albertel 10348: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10349:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10350:             if ($qualifier eq 'value') {
                   10351: 		return $role;
                   10352:             } elsif ($qualifier eq 'extent') {
                   10353:                 return $where;
                   10354:             }
                   10355: # ----------------------------------------------------------------- user.domain
                   10356:         } elsif ($space eq 'domain') {
1.218     albertel 10357:             return $udom;
1.48      www      10358: # ------------------------------------------------------------------- user.name
                   10359:         } elsif ($space eq 'name') {
1.218     albertel 10360:             return $uname;
1.48      www      10361: # ---------------------------------------------------- Any other user namespace
1.29      www      10362:         } else {
1.359     albertel 10363: 	    my %reply;
                   10364: 	    if (!$publicuser) {
                   10365: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10366: 	    }
                   10367: 	    return $reply{$qualifierrest};
1.48      www      10368:         }
1.236     www      10369:     } elsif ($realm eq 'query') {
                   10370: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10371:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10372: 						[$spacequalifierrest]);
1.620     albertel 10373: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10374:    } elsif ($realm eq 'request') {
1.48      www      10375: # ------------------------------------------------------------- request.browser
                   10376:         if ($space eq 'browser') {
1.1145    bisitz   10377:             return $env{'browser.'.$qualifier};
1.57      www      10378: # ------------------------------------------------------------ request.filename
                   10379:         } else {
1.620     albertel 10380:             return $env{'request.'.$spacequalifierrest};
1.29      www      10381:         }
1.28      www      10382:     } elsif ($realm eq 'course') {
1.48      www      10383: # ---------------------------------------------------------- course.description
1.620     albertel 10384:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10385:     } elsif ($realm eq 'resource') {
1.165     www      10386: 
1.620     albertel 10387: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10388: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10389: 	}
1.693     albertel 10390: 
1.1172.2.30  raeburn  10391:         if ($qualifier eq '') {
                   10392: 	    if ($space eq 'title') {
                   10393: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10394: 	        return &gettitle($symbparm);
                   10395: 	    }
1.693     albertel 10396: 	
1.1172.2.30  raeburn  10397: 	    if ($space eq 'map') {
                   10398: 	        my ($map) = &decode_symb($symbparm);
                   10399: 	        return &symbread($map);
                   10400: 	    }
                   10401:             if ($space eq 'maptitle') {
                   10402:                 my ($map) = &decode_symb($symbparm);
                   10403:                 return &gettitle($map);
                   10404:             }
                   10405: 	    if ($space eq 'filename') {
                   10406: 	        if ($symbparm) {
                   10407: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10408: 	        }
                   10409: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10410: 	    }
1.1172.2.30  raeburn  10411: 
                   10412:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10413:                 if ($space eq 'visibleparts') {
                   10414:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10415:                     my $item;
                   10416:                     if (ref($navmap)) {
                   10417:                         my $res = $navmap->getBySymb($symbparm);
                   10418:                         my $parts = $res->parts();
                   10419:                         if (ref($parts) eq 'ARRAY') {
                   10420:                             $item = join(',',@{$parts});
                   10421:                         }
                   10422:                         undef($navmap);
                   10423:                     }
                   10424:                     return $item;
                   10425:                 }
                   10426:             }
                   10427:         }
1.693     albertel 10428: 
                   10429: 	my ($section, $group, @groups);
1.593     albertel 10430: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10431:         if (($courseid eq '') && ($cid)) {
                   10432:             $courseid = $cid;
                   10433:         }
                   10434: 	if (($symbparm && $courseid) && 
                   10435: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10436: 
1.218     albertel 10437: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10438: 
1.60      www      10439: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10440: 	    my $symbp=$symbparm;
1.735     albertel 10441: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10442: 
                   10443: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10444: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10445: 
1.620     albertel 10446: 	    if (($env{'user.name'} eq $uname) &&
                   10447: 		($env{'user.domain'} eq $udom)) {
                   10448: 		$section=$env{'request.course.sec'};
1.733     raeburn  10449:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10450:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10451: 	    } else {
1.539     albertel 10452: 		if (! defined($usection)) {
1.551     albertel 10453: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10454: 		} else {
                   10455: 		    $section = $usection;
                   10456: 		}
1.733     raeburn  10457:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10458: 	    }
                   10459: 
                   10460: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10461: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10462: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10463: 
1.593     albertel 10464: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10465: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10466: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10467: 
1.60      www      10468: # ----------------------------------------------------------- first, check user
1.624     albertel 10469: 
                   10470: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10471: 				       ([$courselevelr,'resource'],
                   10472: 					[$courselevelm,'map'     ],
                   10473: 					[$courselevel, 'course'  ]));
1.931     albertel 10474: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10475: 
1.594     albertel 10476: # ------------------------------------------------ second, check some of course
1.684     raeburn  10477:             my $coursereply;
1.691     raeburn  10478:             if (@groups > 0) {
                   10479:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10480:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10481:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10482:             }
1.96      www      10483: 
1.684     raeburn  10484: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10485: 				  $env{'course.'.$courseid.'.domain'},
                   10486: 				  'course',
                   10487: 				  ([$seclevelr,   'resource'],
                   10488: 				   [$seclevelm,   'map'     ],
                   10489: 				   [$seclevel,    'course'  ],
                   10490: 				   [$courselevelr,'resource']));
                   10491: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10492: 
1.60      www      10493: # ------------------------------------------------------ third, check map parms
1.218     albertel 10494: 	    my %parmhash=();
                   10495: 	    my $thisparm='';
                   10496: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10497: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10498: 		    &GDBM_READER(),0640)) {
1.218     albertel 10499: 		$thisparm=$parmhash{$symbparm};
                   10500: 		untie(%parmhash);
                   10501: 	    }
1.927     albertel 10502: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10503: 	}
1.594     albertel 10504: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10505: 
1.218     albertel 10506: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10507: 	my $filename;
                   10508: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10509: 	if ($symbparm) {
1.409     www      10510: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10511: 	} else {
1.620     albertel 10512: 	    $filename=$env{'request.filename'};
1.282     albertel 10513: 	}
                   10514: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10515: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10516: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10517: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10518: 
1.927     albertel 10519: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10520: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10521: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10522: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10523: 				     $env{'course.'.$courseid.'.domain'},
                   10524: 				     'course',
1.927     albertel 10525: 				     ([$courselevelm,'map'   ],
                   10526: 				      [$courselevel, 'course']));
                   10527: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10528: 	}
1.145     www      10529: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10530: 	unless ($space eq '0') {
1.336     albertel 10531: 	    my @parts=split(/_/,$space);
                   10532: 	    my $id=pop(@parts);
                   10533: 	    my $part=join('_',@parts);
                   10534: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10535: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10536: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10537: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10538: 	}
1.395     albertel 10539: 	if ($recurse) { return undef; }
                   10540: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10541: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10542: # ---------------------------------------------------- Any other user namespace
                   10543:     } elsif ($realm eq 'environment') {
                   10544: # ----------------------------------------------------------------- environment
1.620     albertel 10545: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10546: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10547: 	} else {
1.770     albertel 10548: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10549: 		return '';
                   10550: 	    }
1.219     albertel 10551: 	    my %returnhash=&userenvironment($udom,$uname,
                   10552: 					    $spacequalifierrest);
                   10553: 	    return $returnhash{$spacequalifierrest};
                   10554: 	}
1.28      www      10555:     } elsif ($realm eq 'system') {
1.48      www      10556: # ----------------------------------------------------------------- system.time
                   10557: 	if ($space eq 'time') {
                   10558: 	    return time;
                   10559:         }
1.696     albertel 10560:     } elsif ($realm eq 'server') {
                   10561: # ----------------------------------------------------------------- system.time
                   10562: 	if ($space eq 'name') {
                   10563: 	    return $ENV{'SERVER_NAME'};
                   10564:         }
1.28      www      10565:     }
1.48      www      10566:     return '';
1.61      www      10567: }
                   10568: 
1.927     albertel 10569: sub get_reply {
                   10570:     my ($reply_value) = @_;
1.940     raeburn  10571:     if (ref($reply_value) eq 'ARRAY') {
                   10572:         if (wantarray) {
                   10573: 	    return @$reply_value;
                   10574:         }
                   10575:         return $reply_value->[0];
                   10576:     } else {
                   10577:         return $reply_value;
1.927     albertel 10578:     }
                   10579: }
                   10580: 
1.691     raeburn  10581: sub check_group_parms {
                   10582:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10583:     my @groupitems = ();
                   10584:     my $resultitem;
1.927     albertel 10585:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10586:     foreach my $group (@{$groups}) {
                   10587:         foreach my $level (@levels) {
1.927     albertel 10588:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10589:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10590:         }
                   10591:     }
                   10592:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10593:                             $env{'course.'.$courseid.'.domain'},
                   10594:                                      'course',@groupitems);
                   10595:     return $coursereply;
                   10596: }
                   10597: 
                   10598: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10599:     my ($courseid,@groups) = @_;
                   10600:     @groups = sort(@groups);
1.691     raeburn  10601:     return @groups;
                   10602: }
                   10603: 
1.395     albertel 10604: sub packages_tab_default {
                   10605:     my ($uri,$varname)=@_;
                   10606:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10607: 
                   10608:     my (@extension,@specifics,$do_default);
                   10609:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10610: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10611: 	if ($pack_type eq 'default') {
                   10612: 	    $do_default=1;
                   10613: 	} elsif ($pack_type eq 'extension') {
                   10614: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10615: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10616: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10617: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10618: 	}
                   10619:     }
                   10620:     # first look for a package that matches the requested part id
                   10621:     foreach my $package (@specifics) {
                   10622: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10623: 	next if ($pack_part ne $part);
                   10624: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10625: 	    return $packagetab{"$pack_type&$name&default"};
                   10626: 	}
                   10627:     }
                   10628:     # look for any possible matching non extension_ package
                   10629:     foreach my $package (@specifics) {
                   10630: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10631: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10632: 	    return $packagetab{"$pack_type&$name&default"};
                   10633: 	}
1.585     albertel 10634: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10635: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10636: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10637: 	}
                   10638:     }
1.738     albertel 10639:     # look for any posible extension_ match
                   10640:     foreach my $package (@extension) {
                   10641: 	my ($package,$pack_type)=@{$package};
                   10642: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10643: 	    return $packagetab{"$pack_type&$name&default"};
                   10644: 	}
                   10645: 	if (defined($packagetab{$package."&$name&default"})) {
                   10646: 	    return $packagetab{$package."&$name&default"};
                   10647: 	}
                   10648:     }
                   10649:     # look for a global default setting
                   10650:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10651: 	return $packagetab{"default&$name&default"};
                   10652:     }
1.395     albertel 10653:     return undef;
                   10654: }
                   10655: 
1.334     albertel 10656: sub add_prefix_and_part {
                   10657:     my ($prefix,$part)=@_;
                   10658:     my $keyroot;
                   10659:     if (defined($prefix) && $prefix !~ /^__/) {
                   10660: 	# prefix that has a part already
                   10661: 	$keyroot=$prefix;
                   10662:     } elsif (defined($prefix)) {
                   10663: 	# prefix that is missing a part
                   10664: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10665:     } else {
                   10666: 	# no prefix at all
                   10667: 	if (defined($part)) { $keyroot='_'.$part; }
                   10668:     }
                   10669:     return $keyroot;
                   10670: }
                   10671: 
1.71      www      10672: # ---------------------------------------------------------------- Get metadata
                   10673: 
1.599     albertel 10674: my %metaentry;
1.1070    www      10675: my %importedpartids;
1.71      www      10676: sub metadata {
1.176     www      10677:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10678:     $uri=&declutter($uri);
1.288     albertel 10679:     # if it is a non metadata possible uri return quickly
1.529     albertel 10680:     if (($uri eq '') || 
                   10681: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10682: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10683:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10684: 	return undef;
                   10685:     }
1.1172.2.49  raeburn  10686:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10687: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10688: 	return undef;
1.288     albertel 10689:     }
1.73      www      10690:     my $filename=$uri;
                   10691:     $uri=~s/\.meta$//;
1.172     www      10692: #
                   10693: # Is the metadata already cached?
1.177     www      10694: # Look at timestamp of caching
1.172     www      10695: # Everything is cached by the main uri, libraries are never directly cached
                   10696: #
1.428     albertel 10697:     if (!defined($liburi)) {
1.599     albertel 10698: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10699: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10700:     }
                   10701:     {
1.1069    www      10702: # Imported parts would go here
1.1070    www      10703:         my %importedids=();
                   10704:         my @origfileimportpartids=();
1.1069    www      10705:         my $importedparts=0;
1.172     www      10706: #
                   10707: # Is this a recursive call for a library?
                   10708: #
1.599     albertel 10709: #	if (! exists($metacache{$uri})) {
                   10710: #	    $metacache{$uri}={};
                   10711: #	}
1.924     albertel 10712: 	my $cachetime = 60*60;
1.171     www      10713:         if ($liburi) {
                   10714: 	    $liburi=&declutter($liburi);
                   10715:             $filename=$liburi;
1.401     bowersj2 10716:         } else {
1.599     albertel 10717: 	    &devalidate_cache_new('meta',$uri);
                   10718: 	    undef(%metaentry);
1.401     bowersj2 10719: 	}
1.140     www      10720:         my %metathesekeys=();
1.73      www      10721:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10722: 	my $metastring;
1.1140    www      10723: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10724: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10725: 	    $metastring = 
1.929     albertel 10726: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10727: 					  ('grade_target' => 'meta'));
                   10728: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10729: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10730:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10731: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10732: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10733: 	    $metastring=&getfile($file);
1.489     albertel 10734: 	}
1.208     albertel 10735:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10736:         my $token;
1.140     www      10737:         undef %metathesekeys;
1.71      www      10738:         while ($token=$parser->get_token) {
1.339     albertel 10739: 	    if ($token->[0] eq 'S') {
                   10740: 		if (defined($token->[2]->{'package'})) {
1.172     www      10741: #
                   10742: # This is a package - get package info
                   10743: #
1.339     albertel 10744: 		    my $package=$token->[2]->{'package'};
                   10745: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10746: 		    if (defined($token->[2]->{'id'})) { 
                   10747: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10748: 		    }
1.599     albertel 10749: 		    if ($metaentry{':packages'}) {
                   10750: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10751: 		    } else {
1.599     albertel 10752: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10753: 		    }
1.736     albertel 10754: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10755: 			my $part=$keyroot;
                   10756: 			$part=~s/^\_//;
1.736     albertel 10757: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10758: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10759: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10760: 			    # ignore package.tab specified default values
                   10761:                             # here &package_tab_default() will fetch those
                   10762: 			    if ($subp eq 'default') { next; }
1.736     albertel 10763: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10764: 			    my $unikey;
                   10765: 			    if ($pack =~ /_0$/) {
                   10766: 				$unikey='parameter_0_'.$name;
                   10767: 				$part=0;
                   10768: 			    } else {
                   10769: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10770: 			    }
1.339     albertel 10771: 			    if ($subp eq 'display') {
                   10772: 				$value.=' [Part: '.$part.']';
                   10773: 			    }
1.599     albertel 10774: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10775: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10776: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10777: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10778: 			    }
1.599     albertel 10779: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10780: 				$metaentry{':'.$unikey}=
                   10781: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10782: 			    }
1.339     albertel 10783: 			}
                   10784: 		    }
                   10785: 		} else {
1.172     www      10786: #
                   10787: # This is not a package - some other kind of start tag
1.339     albertel 10788: #
                   10789: 		    my $entry=$token->[1];
1.1068    www      10790: 		    my $unikey='';
1.175     www      10791: 
1.339     albertel 10792: 		    if ($entry eq 'import') {
1.175     www      10793: #
                   10794: # Importing a library here
1.339     albertel 10795: #
1.1067    www      10796:                         my $location=$parser->get_text('/import');
                   10797:                         my $dir=$filename;
                   10798:                         $dir=~s|[^/]*$||;
                   10799:                         $location=&filelocation($dir,$location);
1.1069    www      10800:                        
1.1068    www      10801:                         my $importmode=$token->[2]->{'importmode'};
                   10802:                         if ($importmode eq 'problem') {
1.1069    www      10803: # Import as problem/response
1.1068    www      10804:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10805:                         } elsif ($importmode eq 'part') {
                   10806: # Import as part(s)
1.1069    www      10807:                            $importedparts=1;
                   10808: # We need to get the original file and the imported file to get the part order correct
                   10809: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10810: # Load and inspect original file
1.1070    www      10811:                            if ($#origfileimportpartids<0) {
                   10812:                               undef(%importedpartids);
                   10813:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10814:                               my $origfile=&getfile($origfilelocation);
                   10815:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10816:                            }
                   10817: 
1.1069    www      10818: # Load and inspect imported file
                   10819:                            my $impfile=&getfile($location);
                   10820:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10821:                            if ($#impfilepartids>=0) {
                   10822: # This problem had parts
1.1070    www      10823:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10824:                            } else {
                   10825: # Importing by turning a single problem into a problem part
                   10826: # It gets the import-tags ID as part-ID
                   10827:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10828:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10829:                            }
1.1068    www      10830:                         } else {
                   10831: # Normal import
                   10832:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10833:                            if (defined($token->[2]->{'id'})) {
                   10834:                               $unikey.='_'.$token->[2]->{'id'};
                   10835:                            }
1.1067    www      10836:                         }
                   10837: 
1.339     albertel 10838: 			if ($depthcount<20) {
1.736     albertel 10839: 			    my $metadata = 
                   10840: 				&metadata($uri,'keys', $location,$unikey,
                   10841: 					  $depthcount+1);
                   10842: 			    foreach my $meta (split(',',$metadata)) {
                   10843: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10844: 				$metathesekeys{$meta}=1;
1.339     albertel 10845: 			    }
1.1068    www      10846: 			
                   10847:                         }
1.1067    www      10848: 		    } else {
                   10849: #
                   10850: # Not importing, some other kind of non-package, non-library start tag
                   10851: # 
                   10852:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10853:                         if (defined($token->[2]->{'id'})) {
                   10854:                             $unikey.='_'.$token->[2]->{'id'};
                   10855:                         }
1.339     albertel 10856: 			if (defined($token->[2]->{'name'})) { 
                   10857: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10858: 			}
                   10859: 			$metathesekeys{$unikey}=1;
1.736     albertel 10860: 			foreach my $param (@{$token->[3]}) {
                   10861: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10862: 				$token->[2]->{$param};
1.339     albertel 10863: 			}
                   10864: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10865: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10866: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10867: 		 # only ws inside the tag, and not in default, so use default
                   10868: 		 # as value
1.599     albertel 10869: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10870: 			} elsif ( $internaltext =~ /\S/ ) {
                   10871: 		  # something interesting inside the tag
                   10872: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10873: 			} else {
1.908     albertel 10874: 		  # no interesting values, don't set a default
1.339     albertel 10875: 			}
1.172     www      10876: # end of not-a-package not-a-library import
1.339     albertel 10877: 		    }
1.172     www      10878: # end of not-a-package start tag
1.339     albertel 10879: 		}
1.172     www      10880: # the next is the end of "start tag"
1.339     albertel 10881: 	    }
                   10882: 	}
1.483     albertel 10883: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10884: 	$extension = lc($extension);
                   10885: 	if ($extension eq 'htm') { $extension='html'; }
                   10886: 
1.737     albertel 10887: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10888: 	    #no specific packages #how's our extension
                   10889: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10890: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10891: 					 \%metathesekeys);
                   10892: 	}
1.883     albertel 10893: 
                   10894: 	if (!exists($metaentry{':packages'})
                   10895: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10896: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10897: 		#no specific packages well let's get default then
                   10898: 		if ($key!~/^default&/) { next; }
1.488     albertel 10899: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10900: 					     \%metathesekeys);
                   10901: 	    }
                   10902: 	}
1.338     www      10903: # are there custom rights to evaluate
1.599     albertel 10904: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10905: 
1.338     www      10906:     #
                   10907:     # Importing a rights file here
1.339     albertel 10908:     #
                   10909: 	    unless ($depthcount) {
1.599     albertel 10910: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10911: 		my $dir=$filename;
                   10912: 		$dir=~s|[^/]*$||;
                   10913: 		$location=&filelocation($dir,$location);
1.736     albertel 10914: 		my $rights_metadata =
                   10915: 		    &metadata($uri,'keys',$location,'_rights',
                   10916: 			      $depthcount+1);
                   10917: 		foreach my $rights (split(',',$rights_metadata)) {
                   10918: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10919: 		    $metathesekeys{$rights}=1;
1.339     albertel 10920: 		}
                   10921: 	    }
                   10922: 	}
1.737     albertel 10923: 	# uniqifiy package listing
                   10924: 	my %seen;
                   10925: 	my @uniq_packages =
                   10926: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10927: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10928: 
1.1070    www      10929:         if ($importedparts) {
                   10930: # We had imported parts and need to rebuild partorder
                   10931:            $metaentry{':partorder'}='';
                   10932:            $metathesekeys{'partorder'}=1;
                   10933:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10934:                if ($origfileimportpartids[$index] eq 'part') {
                   10935: # original part, part of the problem
                   10936:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10937:                } else {
                   10938: # we have imported parts at this position
                   10939:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10940:                }
                   10941:            }
                   10942:            $metaentry{':partorder'}=~s/^\,//;
                   10943:         }
                   10944: 
1.737     albertel 10945: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10946: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  10947: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 10948: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10949: # this is the end of "was not already recently cached
1.71      www      10950:     }
1.599     albertel 10951:     return $metaentry{':'.$what};
1.261     albertel 10952: }
                   10953: 
1.488     albertel 10954: sub metadata_create_package_def {
1.483     albertel 10955:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10956:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10957:     if ($subp eq 'default') { next; }
                   10958:     
1.599     albertel 10959:     if (defined($metaentry{':packages'})) {
                   10960: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10961:     } else {
1.599     albertel 10962: 	$metaentry{':packages'}=$package;
1.483     albertel 10963:     }
                   10964:     my $value=$packagetab{$key};
                   10965:     my $unikey;
                   10966:     $unikey='parameter_0_'.$name;
1.599     albertel 10967:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10968:     $$metathesekeys{$unikey}=1;
1.599     albertel 10969:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10970: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10971:     }
1.599     albertel 10972:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10973: 	$metaentry{':'.$unikey}=
                   10974: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10975:     }
                   10976: }
                   10977: 
1.261     albertel 10978: sub metadata_generate_part0 {
                   10979:     my ($metadata,$metacache,$uri) = @_;
                   10980:     my %allnames;
1.737     albertel 10981:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10982: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10983: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10984: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10985: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10986: 	    $allnames{$name}=$part;
                   10987: 	  }
                   10988: 	}
                   10989:     }
                   10990:     foreach my $name (keys(%allnames)) {
                   10991:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10992:       my $key=":parameter_0_$name";
1.261     albertel 10993:       $$metacache{"$key.part"}='0';
                   10994:       $$metacache{"$key.name"}=$name;
1.428     albertel 10995:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10996: 					   $allnames{$name}.'_'.$name.
                   10997: 					   '.type'};
1.428     albertel 10998:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10999: 			     '.display'};
1.644     www      11000:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11001:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11002:       $$metacache{"$key.display"}=$olddis;
                   11003:     }
1.71      www      11004: }
                   11005: 
1.764     albertel 11006: # ------------------------------------------------------ Devalidate title cache
                   11007: 
                   11008: sub devalidate_title_cache {
                   11009:     my ($url)=@_;
                   11010:     if (!$env{'request.course.id'}) { return; }
                   11011:     my $symb=&symbread($url);
                   11012:     if (!$symb) { return; }
                   11013:     my $key=$env{'request.course.id'}."\0".$symb;
                   11014:     &devalidate_cache_new('title',$key);
                   11015: }
                   11016: 
1.1014    droeschl 11017: # ------------------------------------------------- Get the title of a course
                   11018: 
                   11019: sub current_course_title {
                   11020:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11021: }
1.301     www      11022: # ------------------------------------------------- Get the title of a resource
                   11023: 
                   11024: sub gettitle {
                   11025:     my $urlsymb=shift;
                   11026:     my $symb=&symbread($urlsymb);
1.534     albertel 11027:     if ($symb) {
1.620     albertel 11028: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11029: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11030: 	if (defined($cached)) { 
                   11031: 	    return $result;
                   11032: 	}
1.534     albertel 11033: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11034: 	my $title='';
1.907     albertel 11035: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11036: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11037: 	} else {
                   11038: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11039: 		    &GDBM_READER(),0640)) {
                   11040: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11041: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11042: 		untie(%bighash);
                   11043: 	    }
1.534     albertel 11044: 	}
                   11045: 	$title=~s/\&colon\;/\:/gs;
                   11046: 	if ($title) {
1.1159    www      11047: # Remember both $symb and $title for dynamic metadata
                   11048:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11049:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11050: # Cache this title and then return it
1.599     albertel 11051: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11052: 	}
                   11053: 	$urlsymb=$url;
                   11054:     }
                   11055:     my $title=&metadata($urlsymb,'title');
                   11056:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11057:     return $title;
1.301     www      11058: }
1.613     albertel 11059: 
1.614     albertel 11060: sub get_slot {
                   11061:     my ($which,$cnum,$cdom)=@_;
                   11062:     if (!$cnum || !$cdom) {
1.790     albertel 11063: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11064: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11065: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11066:     }
1.703     albertel 11067:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11068:     my %slotinfo;
                   11069:     if (exists($remembered{$key})) {
                   11070: 	$slotinfo{$which} = $remembered{$key};
                   11071:     } else {
                   11072: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11073: 	&Apache::lonhomework::showhash(%slotinfo);
                   11074: 	my ($tmp)=keys(%slotinfo);
                   11075: 	if ($tmp=~/^error:/) { return (); }
                   11076: 	$remembered{$key} = $slotinfo{$which};
                   11077:     }
1.616     albertel 11078:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11079: 	return %{$slotinfo{$which}};
                   11080:     }
                   11081:     return $slotinfo{$which};
1.614     albertel 11082: }
1.1150    raeburn  11083: 
                   11084: sub get_reservable_slots {
                   11085:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11086:     my $now = time;
                   11087:     my $reservable_info;
                   11088:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11089:     if (exists($remembered{$key})) {
                   11090:         $reservable_info = $remembered{$key};
                   11091:     } else {
                   11092:         my %resv;
                   11093:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11094:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11095:         $reservable_info = \%resv;
                   11096:         $remembered{$key} = $reservable_info;
                   11097:     }
                   11098:     return $reservable_info;
                   11099: }
                   11100: 
                   11101: sub get_course_slots {
                   11102:     my ($cnum,$cdom) = @_;
                   11103:     my $hashid=$cnum.':'.$cdom;
                   11104:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11105:     if (defined($cached)) {
                   11106:         if (ref($result) eq 'HASH') {
                   11107:             return %{$result};
                   11108:         }
                   11109:     } else {
                   11110:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11111:         my ($tmp) = keys(%slots);
                   11112:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11113:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11114:             return %slots;
                   11115:         }
                   11116:     }
                   11117:     return;
                   11118: }
                   11119: 
                   11120: sub devalidate_slots_cache {
                   11121:     my ($cnum,$cdom)=@_;
                   11122:     my $hashid=$cnum.':'.$cdom;
                   11123:     &devalidate_cache_new('allslots',$hashid);
                   11124: }
                   11125: 
1.1172.2.8  raeburn  11126: sub get_coursechange {
                   11127:     my ($cdom,$cnum) = @_;
                   11128:     if ($cdom eq '' || $cnum eq '') {
                   11129:         return unless ($env{'request.course.id'});
                   11130:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11131:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11132:     }
                   11133:     my $hashid=$cdom.'_'.$cnum;
                   11134:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11135:     if ((defined($cached)) && ($change ne '')) {
                   11136:         return $change;
                   11137:     } else {
                   11138:         my %crshash;
                   11139:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11140:         if ($crshash{'internal.contentchange'} eq '') {
                   11141:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11142:             if ($change eq '') {
                   11143:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11144:                 $change = $crshash{'internal.created'};
                   11145:             }
                   11146:         } else {
                   11147:             $change = $crshash{'internal.contentchange'};
                   11148:         }
                   11149:         my $cachetime = 600;
                   11150:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11151:     }
                   11152:     return $change;
                   11153: }
                   11154: 
                   11155: sub devalidate_coursechange_cache {
                   11156:     my ($cnum,$cdom)=@_;
                   11157:     my $hashid=$cnum.':'.$cdom;
                   11158:     &devalidate_cache_new('crschange',$hashid);
                   11159: }
                   11160: 
1.31      www      11161: # ------------------------------------------------- Update symbolic store links
                   11162: 
                   11163: sub symblist {
                   11164:     my ($mapname,%newhash)=@_;
1.438     www      11165:     $mapname=&deversion(&declutter($mapname));
1.31      www      11166:     my %hash;
1.620     albertel 11167:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11168:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11169:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11170: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11171: 		next if ($url eq 'last_known'
                   11172: 			 && $env{'form.no_update_last_known'});
                   11173: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11174: 						    $newhash{$url}->[1],
                   11175: 						    $newhash{$url}->[0]);
1.191     harris41 11176:             }
1.31      www      11177:             if (untie(%hash)) {
                   11178: 		return 'ok';
                   11179:             }
                   11180:         }
                   11181:     }
                   11182:     return 'error';
1.212     www      11183: }
                   11184: 
                   11185: # --------------------------------------------------------------- Verify a symb
                   11186: 
                   11187: sub symbverify {
1.1172.2.11  raeburn  11188:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11189:     my $thisfn=$thisurl;
1.439     www      11190:     $thisfn=&declutter($thisfn);
1.215     www      11191: # direct jump to resource in page or to a sequence - will construct own symbs
                   11192:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11193: # check URL part
1.409     www      11194:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11195: 
1.431     www      11196:     unless ($url eq $thisfn) { return 0; }
1.213     www      11197: 
1.216     www      11198:     $symb=&symbclean($symb);
1.510     www      11199:     $thisurl=&deversion($thisurl);
1.439     www      11200:     $thisfn=&deversion($thisfn);
1.213     www      11201: 
                   11202:     my %bighash;
                   11203:     my $okay=0;
1.431     www      11204: 
1.620     albertel 11205:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11206:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11207:         my $noclutter;
1.1032    raeburn  11208:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11209:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11210:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11211:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11212:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11213:                 $noclutter = 1;
                   11214:             }
                   11215:         }
                   11216:         my $ids;
                   11217:         if ($noclutter) {
                   11218:             $ids=$bighash{'ids_'.$thisurl};
                   11219:         } else {
                   11220:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11221:         }
1.1102    raeburn  11222:         unless ($ids) {
1.1172.2.13  raeburn  11223:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11224:             $ids=$bighash{$idkey};
1.216     www      11225:         }
                   11226:         if ($ids) {
                   11227: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11228:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11229:                 $symb =~ s/\?.+$//;
                   11230:             }
1.800     albertel 11231: 	    foreach my $id (split(/\,/,$ids)) {
                   11232: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11233:                if (
                   11234:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11235:    eq $symb) {
1.1172.2.11  raeburn  11236:                    if (ref($encstate)) {
                   11237:                        $$encstate = $bighash{'encrypted_'.$id};
                   11238:                    }
1.1172.2.13  raeburn  11239:                    if (($env{'request.role.adv'}) ||
                   11240:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11241:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11242:                        $okay=1;
                   11243:                        last;
                   11244:                    }
                   11245:                }
                   11246:            }
1.216     www      11247:         }
1.213     www      11248: 	untie(%bighash);
                   11249:     }
                   11250:     return $okay;
1.31      www      11251: }
                   11252: 
1.210     www      11253: # --------------------------------------------------------------- Clean-up symb
                   11254: 
                   11255: sub symbclean {
                   11256:     my $symb=shift;
1.568     albertel 11257:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11258: # remove version from map
                   11259:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11260: 
1.210     www      11261: # remove version from URL
                   11262:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11263: 
1.507     www      11264: # remove wrapper
                   11265: 
1.510     www      11266:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11267:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11268:     return $symb;
1.409     www      11269: }
                   11270: 
                   11271: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11272: 
                   11273: sub encode_symb {
                   11274:     my ($map,$resid,$url)=@_;
                   11275:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11276: }
1.409     www      11277: 
                   11278: sub decode_symb {
1.568     albertel 11279:     my $symb=shift;
                   11280:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11281:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11282:     return (&fixversion($map),$resid,&fixversion($url));
                   11283: }
                   11284: 
                   11285: sub fixversion {
                   11286:     my $fn=shift;
1.609     banghart 11287:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11288:     my %bighash;
                   11289:     my $uri=&clutter($fn);
1.620     albertel 11290:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11291: # is this cached?
1.599     albertel 11292:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11293:     if (defined($cached)) { return $result; }
                   11294: # unfortunately not cached, or expired
1.620     albertel 11295:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11296: 	    &GDBM_READER(),0640)) {
                   11297:  	if ($bighash{'version_'.$uri}) {
                   11298:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11299:  	    unless (($version eq 'mostrecent') || 
                   11300: 		    ($version==&getversion($uri))) {
1.440     www      11301:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11302:  	    }
                   11303:  	}
                   11304:  	untie %bighash;
1.413     www      11305:     }
1.599     albertel 11306:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11307: }
                   11308: 
                   11309: sub deversion {
                   11310:     my $url=shift;
                   11311:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11312:     return $url;
1.210     www      11313: }
                   11314: 
1.31      www      11315: # ------------------------------------------------------ Return symb list entry
                   11316: 
                   11317: sub symbread {
1.1172.2.66  raeburn  11318:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11319:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11320:     if (defined($env{$cache_str})) {
                   11321:         if ($ignorecachednull) {
                   11322:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11323:         } else {
                   11324:             return $env{$cache_str};
                   11325:         }
                   11326:     }
1.242     www      11327: # no filename provided? try from environment
1.1172.2.54  raeburn  11328:     unless ($thisfn) {
1.620     albertel 11329:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11330:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11331:         }
                   11332:         $thisfn=$env{'request.filename'};
1.44      www      11333:     }
1.569     albertel 11334:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11335: # is that filename actually a symb? Verify, clean, and return
                   11336:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11337: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11338: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11339: 	}
1.242     www      11340:     }
1.44      www      11341:     $thisfn=declutter($thisfn);
1.31      www      11342:     my %hash;
1.37      www      11343:     my %bighash;
                   11344:     my $syval='';
1.620     albertel 11345:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11346:         my $targetfn = $thisfn;
1.609     banghart 11347:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11348:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11349:         }
1.687     albertel 11350: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11351: 	    $targetfn=$1;
                   11352: 	}
1.620     albertel 11353:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11354:                       &GDBM_READER(),0640)) {
1.481     raeburn  11355: 	    $syval=$hash{$targetfn};
1.37      www      11356:             untie(%hash);
                   11357:         }
                   11358: # ---------------------------------------------------------- There was an entry
                   11359:         if ($syval) {
1.601     albertel 11360: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11361: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11362: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11363: 		    #return $env{$cache_str}='';
1.601     albertel 11364: 		#}    
                   11365: 		#$syval.=$1;
                   11366: 	    #}
1.37      www      11367:         } else {
                   11368: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11369:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11370:                             &GDBM_READER(),0640)) {
1.37      www      11371: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11372:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11373:               unless ($ids) { 
                   11374:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11375:               }
                   11376:               unless ($ids) {
                   11377: # alias?
                   11378: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11379:               }
1.37      www      11380:               if ($ids) {
                   11381: # ------------------------------------------------------------------- Has ID(s)
                   11382:                  my @possibilities=split(/\,/,$ids);
1.39      www      11383:                  if ($#possibilities==0) {
                   11384: # ----------------------------------------------- There is only one possibility
1.37      www      11385: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11386: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11387: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11388:                      if (ref($possibles) eq 'HASH') {
                   11389:                          $possibles->{$syval} = 1;
                   11390:                      }
                   11391:                      if ($checkforblock) {
                   11392:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11393:                          if (@blockers) {
                   11394:                              $syval = '';
                   11395:                              return;
                   11396:                          }
                   11397:                      }
                   11398:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11399: # ------------------------------------------ There is more than one possibility
                   11400:                      my $realpossible=0;
1.800     albertel 11401:                      foreach my $id (@possibilities) {
                   11402: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11403:                          my $canaccess;
                   11404:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11405:                              $canaccess = 1;
                   11406:                          } else {
                   11407:                              $canaccess = &allowed('bre',$file);
                   11408:                          }
                   11409:                          if ($canaccess) {
                   11410:          		     my ($mapid,$resid)=split(/\./,$id);
                   11411:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11412:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11413:                                                              $resid,$thisfn);
                   11414:                                  if (ref($possibles) eq 'HASH') {
                   11415:                                      $possibles->{$syval} = 1;
                   11416:                                  }
                   11417:                                  if ($checkforblock) {
                   11418:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11419:                                      unless (@blockers > 0) {
                   11420:                                          $syval = $poss_syval;
                   11421:                                          $realpossible++;
                   11422:                                      }
                   11423:                                  } else {
                   11424:                                      $syval = $poss_syval;
                   11425:                                      $realpossible++;
                   11426:                                  }
                   11427:                              }
1.39      www      11428: 			 }
1.191     harris41 11429:                      }
1.39      www      11430: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11431:                  } else {
                   11432:                      $syval='';
1.37      www      11433:                  }
                   11434: 	      }
1.1172.2.66  raeburn  11435:               untie(%bighash);
1.481     raeburn  11436:            }
1.31      www      11437:         }
1.62      www      11438:         if ($syval) {
1.620     albertel 11439: 	    return $env{$cache_str}=$syval;
1.62      www      11440:         }
1.31      www      11441:     }
1.949     raeburn  11442:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11443:     return $env{$cache_str}='';
1.31      www      11444: }
                   11445: 
                   11446: # ---------------------------------------------------------- Return random seed
                   11447: 
1.32      www      11448: sub numval {
                   11449:     my $txt=shift;
                   11450:     $txt=~tr/A-J/0-9/;
                   11451:     $txt=~tr/a-j/0-9/;
                   11452:     $txt=~tr/K-T/0-9/;
                   11453:     $txt=~tr/k-t/0-9/;
                   11454:     $txt=~tr/U-Z/0-5/;
                   11455:     $txt=~tr/u-z/0-5/;
                   11456:     $txt=~s/\D//g;
1.564     albertel 11457:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11458:     return int($txt);
1.368     albertel 11459: }
                   11460: 
1.484     albertel 11461: sub numval2 {
                   11462:     my $txt=shift;
                   11463:     $txt=~tr/A-J/0-9/;
                   11464:     $txt=~tr/a-j/0-9/;
                   11465:     $txt=~tr/K-T/0-9/;
                   11466:     $txt=~tr/k-t/0-9/;
                   11467:     $txt=~tr/U-Z/0-5/;
                   11468:     $txt=~tr/u-z/0-5/;
                   11469:     $txt=~s/\D//g;
                   11470:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11471:     my $total;
                   11472:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11473:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11474:     return int($total);
                   11475: }
                   11476: 
1.575     albertel 11477: sub numval3 {
                   11478:     use integer;
                   11479:     my $txt=shift;
                   11480:     $txt=~tr/A-J/0-9/;
                   11481:     $txt=~tr/a-j/0-9/;
                   11482:     $txt=~tr/K-T/0-9/;
                   11483:     $txt=~tr/k-t/0-9/;
                   11484:     $txt=~tr/U-Z/0-5/;
                   11485:     $txt=~tr/u-z/0-5/;
                   11486:     $txt=~s/\D//g;
                   11487:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11488:     my $total;
                   11489:     foreach my $val (@txts) { $total+=$val; }
                   11490:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11491:     return $total;
                   11492: }
                   11493: 
1.675     albertel 11494: sub digest {
                   11495:     my ($data)=@_;
                   11496:     my $digest=&Digest::MD5::md5($data);
                   11497:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11498:     my ($e,$f);
                   11499:     {
                   11500:         use integer;
                   11501:         $e=($a+$b);
                   11502:         $f=($c+$d);
                   11503:         if ($_64bit) {
                   11504:             $e=(($e<<32)>>32);
                   11505:             $f=(($f<<32)>>32);
                   11506:         }
                   11507:     }
                   11508:     if (wantarray) {
                   11509: 	return ($e,$f);
                   11510:     } else {
                   11511: 	my $g;
                   11512: 	{
                   11513: 	    use integer;
                   11514: 	    $g=($e+$f);
                   11515: 	    if ($_64bit) {
                   11516: 		$g=(($g<<32)>>32);
                   11517: 	    }
                   11518: 	}
                   11519: 	return $g;
                   11520:     }
                   11521: }
                   11522: 
1.368     albertel 11523: sub latest_rnd_algorithm_id {
1.675     albertel 11524:     return '64bit5';
1.366     albertel 11525: }
1.32      www      11526: 
1.503     albertel 11527: sub get_rand_alg {
                   11528:     my ($courseid)=@_;
1.790     albertel 11529:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11530:     if ($courseid) {
1.620     albertel 11531: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11532:     }
                   11533:     return &latest_rnd_algorithm_id();
                   11534: }
                   11535: 
1.562     albertel 11536: sub validCODE {
                   11537:     my ($CODE)=@_;
                   11538:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11539:     return 0;
                   11540: }
                   11541: 
1.491     albertel 11542: sub getCODE {
1.620     albertel 11543:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11544:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11545: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11546: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11547: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11548:     }
                   11549:     return undef;
                   11550: }
1.1133    foxr     11551: #
                   11552: #  Determines the random seed for a specific context:
                   11553: #
                   11554: # parameters:
                   11555: #   symb      - in course context the symb for the seed.
                   11556: #   course_id - The course id of the form domain_coursenum.
                   11557: #   domain    - Domain for the user.
                   11558: #   course    - Course for the user.
                   11559: #   cenv      - environment of the course.
                   11560: #
                   11561: # NOTE:
                   11562: #   All parameters are picked out of the environment if missing
                   11563: #   or not defined.
                   11564: #   If a symb cannot be determined the current time is used instead.
                   11565: #
                   11566: #  For a given well defined symb, courside, domain, username,
                   11567: #  and course environment, the seed is reproducible.
                   11568: #
1.31      www      11569: sub rndseed {
1.1133    foxr     11570:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11571:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11572:     if (!defined($symb)) {
1.366     albertel 11573: 	unless ($symb=$wsymb) { return time; }
                   11574:     }
1.1146    foxr     11575:     if (!defined $courseid) { 
                   11576: 	$courseid=$wcourseid; 
                   11577:     }
                   11578:     if (!defined $domain) { $domain=$wdomain; }
                   11579:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11580: 
                   11581:     my $which;
                   11582:     if (defined($cenv->{'rndseed'})) {
                   11583: 	$which = $cenv->{'rndseed'};
                   11584:     } else {
                   11585: 	$which =&get_rand_alg($courseid);
                   11586:     }
1.491     albertel 11587:     if (defined(&getCODE())) {
1.675     albertel 11588: 	if ($which eq '64bit5') {
                   11589: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11590: 	} elsif ($which eq '64bit4') {
1.575     albertel 11591: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11592: 	} else {
                   11593: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11594: 	}
1.675     albertel 11595:     } elsif ($which eq '64bit5') {
                   11596: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11597:     } elsif ($which eq '64bit4') {
                   11598: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11599:     } elsif ($which eq '64bit3') {
                   11600: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11601:     } elsif ($which eq '64bit2') {
                   11602: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11603:     } elsif ($which eq '64bit') {
                   11604: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11605:     }
                   11606:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11607: }
                   11608: 
                   11609: sub rndseed_32bit {
                   11610:     my ($symb,$courseid,$domain,$username)=@_;
                   11611:     {
                   11612: 	use integer;
                   11613: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11614: 	my $symbseed=numval($symb) << 22;
                   11615: 	my $namechck=unpack("%32C*",$username) << 17;
                   11616: 	my $nameseed=numval($username) << 12;
                   11617: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11618: 	my $courseseed=unpack("%32C*",$courseid);
                   11619: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11620: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11621: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11622: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11623: 	return $num;
                   11624:     }
                   11625: }
                   11626: 
                   11627: sub rndseed_64bit {
                   11628:     my ($symb,$courseid,$domain,$username)=@_;
                   11629:     {
                   11630: 	use integer;
                   11631: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11632: 	my $symbseed=numval($symb) << 10;
                   11633: 	my $namechck=unpack("%32S*",$username);
                   11634: 	
                   11635: 	my $nameseed=numval($username) << 21;
                   11636: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11637: 	my $courseseed=unpack("%32S*",$courseid);
                   11638: 	
                   11639: 	my $num1=$symbchck+$symbseed+$namechck;
                   11640: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11641: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11642: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11643: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11644: 	return "$num1,$num2";
1.155     albertel 11645:     }
1.366     albertel 11646: }
                   11647: 
1.443     albertel 11648: sub rndseed_64bit2 {
                   11649:     my ($symb,$courseid,$domain,$username)=@_;
                   11650:     {
                   11651: 	use integer;
                   11652: 	# strings need to be an even # of cahracters long, it it is odd the
                   11653:         # last characters gets thrown away
                   11654: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11655: 	my $symbseed=numval($symb) << 10;
                   11656: 	my $namechck=unpack("%32S*",$username.' ');
                   11657: 	
                   11658: 	my $nameseed=numval($username) << 21;
1.501     albertel 11659: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11660: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11661: 	
                   11662: 	my $num1=$symbchck+$symbseed+$namechck;
                   11663: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11664: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11665: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11666: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11667: 	return "$num1,$num2";
                   11668:     }
                   11669: }
                   11670: 
                   11671: sub rndseed_64bit3 {
                   11672:     my ($symb,$courseid,$domain,$username)=@_;
                   11673:     {
                   11674: 	use integer;
                   11675: 	# strings need to be an even # of cahracters long, it it is odd the
                   11676:         # last characters gets thrown away
                   11677: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11678: 	my $symbseed=numval2($symb) << 10;
                   11679: 	my $namechck=unpack("%32S*",$username.' ');
                   11680: 	
                   11681: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11682: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11683: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11684: 	
                   11685: 	my $num1=$symbchck+$symbseed+$namechck;
                   11686: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11687: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11688: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11689: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11690: 	
1.503     albertel 11691: 	return "$num1:$num2";
1.443     albertel 11692:     }
                   11693: }
                   11694: 
1.575     albertel 11695: sub rndseed_64bit4 {
                   11696:     my ($symb,$courseid,$domain,$username)=@_;
                   11697:     {
                   11698: 	use integer;
                   11699: 	# strings need to be an even # of cahracters long, it it is odd the
                   11700:         # last characters gets thrown away
                   11701: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11702: 	my $symbseed=numval3($symb) << 10;
                   11703: 	my $namechck=unpack("%32S*",$username.' ');
                   11704: 	
                   11705: 	my $nameseed=numval3($username) << 21;
                   11706: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11707: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11708: 	
                   11709: 	my $num1=$symbchck+$symbseed+$namechck;
                   11710: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11711: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11712: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11713: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11714: 	
1.575     albertel 11715: 	return "$num1:$num2";
                   11716:     }
                   11717: }
                   11718: 
1.675     albertel 11719: sub rndseed_64bit5 {
                   11720:     my ($symb,$courseid,$domain,$username)=@_;
                   11721:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11722:     return "$num1:$num2";
                   11723: }
                   11724: 
1.366     albertel 11725: sub rndseed_CODE_64bit {
                   11726:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11727:     {
1.366     albertel 11728: 	use integer;
1.443     albertel 11729: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11730: 	my $symbseed=numval2($symb);
1.491     albertel 11731: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11732: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11733: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11734: 	my $num1=$symbseed+$CODEchck;
                   11735: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11736: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11737: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11738: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11739: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11740: 	return "$num1:$num2";
1.366     albertel 11741:     }
                   11742: }
                   11743: 
1.575     albertel 11744: sub rndseed_CODE_64bit4 {
                   11745:     my ($symb,$courseid,$domain,$username)=@_;
                   11746:     {
                   11747: 	use integer;
                   11748: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11749: 	my $symbseed=numval3($symb);
                   11750: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11751: 	my $CODEseed=numval3(&getCODE());
                   11752: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11753: 	my $num1=$symbseed+$CODEchck;
                   11754: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11755: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11756: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11757: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11758: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11759: 	return "$num1:$num2";
                   11760:     }
                   11761: }
                   11762: 
1.675     albertel 11763: sub rndseed_CODE_64bit5 {
                   11764:     my ($symb,$courseid,$domain,$username)=@_;
                   11765:     my $code = &getCODE();
                   11766:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11767:     return "$num1:$num2";
                   11768: }
                   11769: 
1.366     albertel 11770: sub setup_random_from_rndseed {
                   11771:     my ($rndseed)=@_;
1.503     albertel 11772:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  11773: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11774:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11775:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11776:         } else {
                   11777:             &Math::Random::random_set_seed($num1,$num2);
                   11778:         }
1.366     albertel 11779:     } else {
                   11780: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11781:     }
1.36      albertel 11782: }
                   11783: 
1.474     albertel 11784: sub latest_receipt_algorithm_id {
1.835     albertel 11785:     return 'receipt3';
1.474     albertel 11786: }
                   11787: 
1.480     www      11788: sub recunique {
                   11789:     my $fucourseid=shift;
                   11790:     my $unique;
1.835     albertel 11791:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11792: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11793: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11794:     } else {
                   11795: 	$unique=$perlvar{'lonReceipt'};
                   11796:     }
                   11797:     return unpack("%32C*",$unique);
                   11798: }
                   11799: 
                   11800: sub recprefix {
                   11801:     my $fucourseid=shift;
                   11802:     my $prefix;
1.835     albertel 11803:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11804: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11805: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11806:     } else {
                   11807: 	$prefix=$perlvar{'lonHostID'};
                   11808:     }
                   11809:     return unpack("%32C*",$prefix);
                   11810: }
                   11811: 
1.76      www      11812: sub ireceipt {
1.474     albertel 11813:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11814: 
                   11815:     my $return =&recprefix($fucourseid).'-';
                   11816: 
                   11817:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11818: 	$env{'request.state'} eq 'construct') {
                   11819: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11820: 	return $return;
                   11821:     }
                   11822: 
1.76      www      11823:     my $cuname=unpack("%32C*",$funame);
                   11824:     my $cudom=unpack("%32C*",$fudom);
                   11825:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11826:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11827:     my $cunique=&recunique($fucourseid);
1.474     albertel 11828:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11829:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11830: 
1.790     albertel 11831: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11832: 			       
                   11833: 	$return.= ($cunique%$cuname+
                   11834: 		   $cunique%$cudom+
                   11835: 		   $cusymb%$cuname+
                   11836: 		   $cusymb%$cudom+
                   11837: 		   $cucourseid%$cuname+
                   11838: 		   $cucourseid%$cudom+
                   11839: 		   $cpart%$cuname+
                   11840: 		   $cpart%$cudom);
                   11841:     } else {
                   11842: 	$return.= ($cunique%$cuname+
                   11843: 		   $cunique%$cudom+
                   11844: 		   $cusymb%$cuname+
                   11845: 		   $cusymb%$cudom+
                   11846: 		   $cucourseid%$cuname+
                   11847: 		   $cucourseid%$cudom);
                   11848:     }
                   11849:     return $return;
1.76      www      11850: }
                   11851: 
                   11852: sub receipt {
1.474     albertel 11853:     my ($part)=@_;
1.790     albertel 11854:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11855:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11856: }
1.260     ng       11857: 
1.790     albertel 11858: sub whichuser {
                   11859:     my ($passedsymb)=@_;
                   11860:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11861:     if (defined($env{'form.grade_symb'})) {
                   11862: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11863: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11864: 	if (!$allowed &&
                   11865: 	    exists($env{'request.course.sec'}) &&
                   11866: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11867: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11868: 			      '/'.$env{'request.course.sec'});
                   11869: 	}
                   11870: 	if ($allowed) {
                   11871: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11872: 	    $courseid=$tmp_courseid;
                   11873: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11874: 	    ($name)=&get_env_multiple('form.grade_username');
                   11875: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11876: 	}
                   11877:     }
                   11878:     if (!$passedsymb) {
                   11879: 	$symb=&symbread();
                   11880:     } else {
                   11881: 	$symb=$passedsymb;
                   11882:     }
                   11883:     $courseid=$env{'request.course.id'};
                   11884:     $domain=$env{'user.domain'};
                   11885:     $name=$env{'user.name'};
                   11886:     if ($name eq 'public' && $domain eq 'public') {
                   11887: 	if (!defined($env{'form.username'})) {
                   11888: 	    $env{'form.username'}.=time.rand(10000000);
                   11889: 	}
                   11890: 	$name.=$env{'form.username'};
                   11891:     }
                   11892:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11893: 
                   11894: }
                   11895: 
1.36      albertel 11896: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11897: # returns either the contents of the file or 
                   11898: # -1 if the file doesn't exist
1.481     raeburn  11899: #
                   11900: # if the target is a file that was uploaded via DOCS, 
                   11901: # a check will be made to see if a current copy exists on the local server,
                   11902: # if it does this will be served, otherwise a copy will be retrieved from
                   11903: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11904: # the local server.   
1.472     albertel 11905: 
1.36      albertel 11906: sub getfile {
1.538     albertel 11907:     my ($file) = @_;
1.609     banghart 11908:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11909:     &repcopy($file);
                   11910:     return &readfile($file);
                   11911: }
                   11912: 
                   11913: sub repcopy_userfile {
                   11914:     my ($file)=@_;
1.1142    raeburn  11915:     my $londocroot = $perlvar{'lonDocRoot'};
                   11916:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11917:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11918:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11919: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11920:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11921:     if (-e "$file") {
1.828     www      11922: # we already have a local copy, check it out
1.538     albertel 11923: 	my @fileinfo = stat($file);
1.828     www      11924: 	my $rtncode;
                   11925: 	my $info;
1.538     albertel 11926: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11927: 	if ($lwpresp ne 'ok') {
1.828     www      11928: # there is no such file anymore, even though we had a local copy
1.482     albertel 11929: 	    if ($rtncode eq '404') {
1.538     albertel 11930: 		unlink($file);
1.482     albertel 11931: 	    }
                   11932: 	    return -1;
                   11933: 	}
                   11934: 	if ($info < $fileinfo[9]) {
1.828     www      11935: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11936: 	    return 'ok';
1.828     www      11937: 	} else {
                   11938: # the file is outdated, get rid of it
                   11939: 	    unlink($file);
1.482     albertel 11940: 	}
1.828     www      11941:     }
                   11942: # one way or the other, at this point, we don't have the file
                   11943: # construct the correct path for the file
                   11944:     my @parts = ($cdom,$cnum); 
                   11945:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11946: 	push @parts, split(/\//,$1);
                   11947:     }
                   11948:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11949:     foreach my $part (@parts) {
                   11950: 	$path .= '/'.$part;
                   11951: 	if (!-e $path) {
                   11952: 	    mkdir($path,0770);
1.482     albertel 11953: 	}
                   11954:     }
1.828     www      11955: # now the path exists for sure
                   11956: # get a user agent
                   11957:     my $ua=new LWP::UserAgent;
                   11958:     my $transferfile=$file.'.in.transfer';
                   11959: # FIXME: this should flock
                   11960:     if (-e $transferfile) { return 'ok'; }
                   11961:     my $request;
                   11962:     $uri=~s/^\///;
1.980     raeburn  11963:     my $homeserver = &homeserver($cnum,$cdom);
                   11964:     my $protocol = $protocol{$homeserver};
                   11965:     $protocol = 'http' if ($protocol ne 'https');
                   11966:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11967:     my $response=$ua->request($request,$transferfile);
                   11968: # did it work?
                   11969:     if ($response->is_error()) {
                   11970: 	unlink($transferfile);
                   11971: 	&logthis("Userfile repcopy failed for $uri");
                   11972: 	return -1;
                   11973:     }
                   11974: # worked, rename the transfer file
                   11975:     rename($transferfile,$file);
1.607     raeburn  11976:     return 'ok';
1.481     raeburn  11977: }
                   11978: 
1.517     albertel 11979: sub tokenwrapper {
                   11980:     my $uri=shift;
1.980     raeburn  11981:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11982:     $uri=~s|^/||;
1.620     albertel 11983:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11984:     my $token=$1;
1.552     albertel 11985:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11986:     if ($udom && $uname && $file) {
                   11987: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11988:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11989:         my $homeserver = &homeserver($uname,$udom);
                   11990:         my $protocol = $protocol{$homeserver};
                   11991:         $protocol = 'http' if ($protocol ne 'https');
                   11992:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11993:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11994:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11995:     } else {
                   11996:         return '/adm/notfound.html';
                   11997:     }
                   11998: }
                   11999: 
1.828     www      12000: # call with reqtype HEAD: get last modification time
                   12001: # call with reqtype GET: get the file contents
                   12002: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12003: #
1.481     raeburn  12004: sub getuploaded {
                   12005:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12006:     $uri=~s/^\///;
1.980     raeburn  12007:     my $homeserver = &homeserver($cnum,$cdom);
                   12008:     my $protocol = $protocol{$homeserver};
                   12009:     $protocol = 'http' if ($protocol ne 'https');
                   12010:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12011:     my $ua=new LWP::UserAgent;
                   12012:     my $request=new HTTP::Request($reqtype,$uri);
                   12013:     my $response=$ua->request($request);
                   12014:     $$rtncode = $response->code;
1.482     albertel 12015:     if (! $response->is_success()) {
                   12016: 	return 'failed';
                   12017:     }      
                   12018:     if ($reqtype eq 'HEAD') {
1.486     www      12019: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12020:     } elsif ($reqtype eq 'GET') {
                   12021: 	$$info = $response->content;
1.472     albertel 12022:     }
1.482     albertel 12023:     return 'ok';
1.36      albertel 12024: }
                   12025: 
1.481     raeburn  12026: sub readfile {
                   12027:     my $file = shift;
                   12028:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12029:     my $fh;
                   12030:     open($fh,"<$file");
                   12031:     my $a='';
1.800     albertel 12032:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12033:     return $a;
                   12034: }
                   12035: 
1.36      albertel 12036: sub filelocation {
1.590     banghart 12037:     my ($dir,$file) = @_;
                   12038:     my $location;
                   12039:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12040: 
                   12041:     if ($file =~ m-^/adm/-) {
                   12042: 	$file=~s-^/adm/wrapper/-/-;
                   12043: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12044:     }
1.882     albertel 12045: 
1.1139    www      12046:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12047:         $location = $file;
1.609     banghart 12048:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12049:         my ($udom,$uname,$filename)=
1.811     albertel 12050:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12051:         my $home=&homeserver($uname,$udom);
                   12052:         my $is_me=0;
                   12053:         my @ids=&current_machine_ids();
                   12054:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12055:         if ($is_me) {
1.1117    foxr     12056:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12057:         } else {
                   12058:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12059:   	      $udom.'/'.$uname.'/'.$filename;
                   12060:         }
1.882     albertel 12061:     } elsif ($file =~ m-^/adm/-) {
                   12062: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12063:     } else {
                   12064:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12065:         $file=~s:^/(res|priv)/:/:;
                   12066:         my $space=$1;
1.590     banghart 12067:         if ( !( $file =~ m:^/:) ) {
                   12068:             $location = $dir. '/'.$file;
                   12069:         } else {
1.1142    raeburn  12070:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12071:         }
1.59      albertel 12072:     }
1.590     banghart 12073:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12074:     while ($location=~m{/\.\./}) {
                   12075: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12076: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12077: 	} else {
                   12078: 	    $location=~ s{/\.\./}{/}g;
                   12079: 	}
                   12080:     } #remove dir/..
1.590     banghart 12081:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12082:     return $location;
1.46      www      12083: }
1.36      albertel 12084: 
1.46      www      12085: sub hreflocation {
                   12086:     my ($dir,$file)=@_;
1.980     raeburn  12087:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12088: 	$file=filelocation($dir,$file);
1.700     albertel 12089:     } elsif ($file=~m-^/adm/-) {
                   12090: 	$file=~s-^/adm/wrapper/-/-;
                   12091: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12092:     }
                   12093:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12094: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12095:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12096: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12097: 	        {/uploaded/$1/$2/}x;
1.46      www      12098:     }
1.913     albertel 12099:     if ($file=~ m{^/userfiles/}) {
                   12100: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12101:     }
1.462     albertel 12102:     return $file;
1.465     albertel 12103: }
                   12104: 
1.1139    www      12105: 
                   12106: 
                   12107: 
                   12108: 
1.465     albertel 12109: sub current_machine_domains {
1.853     albertel 12110:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12111: }
                   12112: 
                   12113: sub machine_domains {
                   12114:     my ($hostname) = @_;
1.465     albertel 12115:     my @domains;
1.838     albertel 12116:     my %hostname = &all_hostnames();
1.465     albertel 12117:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12118: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12119: 	if ($hostname eq $name) {
1.844     albertel 12120: 	    push(@domains,&host_domain($id));
1.465     albertel 12121: 	}
                   12122:     }
                   12123:     return @domains;
                   12124: }
                   12125: 
                   12126: sub current_machine_ids {
1.853     albertel 12127:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12128: }
                   12129: 
                   12130: sub machine_ids {
                   12131:     my ($hostname) = @_;
                   12132:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12133:     my @ids;
1.888     albertel 12134:     my %name_to_host = &all_names();
1.889     albertel 12135:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12136: 	return @{ $name_to_host{$hostname} };
                   12137:     }
                   12138:     return;
1.31      www      12139: }
                   12140: 
1.824     raeburn  12141: sub additional_machine_domains {
                   12142:     my @domains;
                   12143:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12144:     while( my $line = <$fh>) {
                   12145:         $line =~ s/\s//g;
                   12146:         push(@domains,$line);
                   12147:     }
                   12148:     return @domains;
                   12149: }
                   12150: 
                   12151: sub default_login_domain {
                   12152:     my $domain = $perlvar{'lonDefDomain'};
                   12153:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12154:     foreach my $posdom (&current_machine_domains(),
                   12155:                         &additional_machine_domains()) {
                   12156:         if (lc($posdom) eq lc($testdomain)) {
                   12157:             $domain=$posdom;
                   12158:             last;
                   12159:         }
                   12160:     }
                   12161:     return $domain;
                   12162: }
                   12163: 
1.31      www      12164: # ------------------------------------------------------------- Declutters URLs
                   12165: 
                   12166: sub declutter {
                   12167:     my $thisfn=shift;
1.569     albertel 12168:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12169:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12170:         $thisfn=~s{^/home/httpd/html}{};
                   12171:     }
1.31      www      12172:     $thisfn=~s/^\///;
1.697     albertel 12173:     $thisfn=~s|^adm/wrapper/||;
                   12174:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12175:     $thisfn=~s/^res\///;
1.1172    bisitz   12176:     $thisfn=~s/^priv\///;
1.1032    raeburn  12177:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12178:         $thisfn=~s/\?.+$//;
                   12179:     }
1.268     www      12180:     return $thisfn;
                   12181: }
                   12182: 
                   12183: # ------------------------------------------------------------- Clutter up URLs
                   12184: 
                   12185: sub clutter {
                   12186:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12187:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12188: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12189:        $thisfn='/res'.$thisfn; 
                   12190:     }
1.1031    raeburn  12191:     if ($thisfn !~m|^/adm|) {
                   12192: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12193: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12194: 	} else {
                   12195: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12196: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12197: 	    if ($embstyle eq 'ssi'
                   12198: 		|| ($embstyle eq 'hdn')
                   12199: 		|| ($embstyle eq 'rat')
                   12200: 		|| ($embstyle eq 'prv')
                   12201: 		|| ($embstyle eq 'ign')) {
                   12202: 		#do nothing with these
                   12203: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12204: 		|| ($embstyle eq 'emb')
                   12205: 		|| ($embstyle eq 'wrp')) {
                   12206: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12207: 	    } elsif ($embstyle eq 'unk'
                   12208: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12209: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12210: 	    } else {
1.718     www      12211: #		&logthis("Got a blank emb style");
1.695     albertel 12212: 	    }
1.694     albertel 12213: 	}
                   12214:     }
1.31      www      12215:     return $thisfn;
1.12      www      12216: }
                   12217: 
1.787     albertel 12218: sub clutter_with_no_wrapper {
                   12219:     my $uri = &clutter(shift);
                   12220:     if ($uri =~ m-^/adm/-) {
                   12221: 	$uri =~ s-^/adm/wrapper/-/-;
                   12222: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12223:     }
                   12224:     return $uri;
                   12225: }
                   12226: 
1.557     albertel 12227: sub freeze_escape {
                   12228:     my ($value)=@_;
                   12229:     if (ref($value)) {
                   12230: 	$value=&nfreeze($value);
                   12231: 	return '__FROZEN__'.&escape($value);
                   12232:     }
                   12233:     return &escape($value);
                   12234: }
                   12235: 
1.11      www      12236: 
1.557     albertel 12237: sub thaw_unescape {
                   12238:     my ($value)=@_;
                   12239:     if ($value =~ /^__FROZEN__/) {
                   12240: 	substr($value,0,10,undef);
                   12241: 	$value=&unescape($value);
                   12242: 	return &thaw($value);
                   12243:     }
                   12244:     return &unescape($value);
                   12245: }
                   12246: 
1.436     albertel 12247: sub correct_line_ends {
                   12248:     my ($result)=@_;
                   12249:     $$result =~s/\r\n/\n/mg;
                   12250:     $$result =~s/\r/\n/mg;
1.415     albertel 12251: }
1.1       albertel 12252: # ================================================================ Main Program
                   12253: 
1.184     www      12254: sub goodbye {
1.204     albertel 12255:    &logthis("Starting Shut down");
1.443     albertel 12256: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12257:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12258: #converted
1.599     albertel 12259: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12260:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12261: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12262: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12263: #1.1 only
1.870     albertel 12264: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12265: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12266: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12267: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12268:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12269:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12270:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12271:    &flushcourselogs();
                   12272:    &logthis("Shutting down");
                   12273: }
                   12274: 
1.852     albertel 12275: sub get_dns {
1.1172.2.17  raeburn  12276:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12277:     if (!$ignore_cache) {
                   12278: 	my ($content,$cached)=
                   12279: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12280: 	if ($cached) {
1.1172.2.17  raeburn  12281: 	    &$func($content,$hashref);
1.869     albertel 12282: 	    return;
                   12283: 	}
                   12284:     }
                   12285: 
                   12286:     my %alldns;
1.852     albertel 12287:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12288:     foreach my $dns (<$config>) {
                   12289: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12290:         my $line = $1;
                   12291:         my ($host,$protocol) = split(/:/,$line);
                   12292:         if ($protocol ne 'https') {
                   12293:             $protocol = 'http';
                   12294:         }
                   12295: 	$alldns{$host} = $protocol;
1.869     albertel 12296:     }
                   12297:     while (%alldns) {
1.1172.2.52  raeburn  12298: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12299: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12300:         $ua->timeout(30);
1.979     raeburn  12301: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12302: 	my $response=$ua->request($request);
1.979     raeburn  12303:         delete($alldns{$dns});
1.852     albertel 12304: 	next if ($response->is_error());
                   12305: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12306:         unless ($nocache) {
1.1172.2.23  raeburn  12307: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12308:         }
                   12309: 	&$func(\@content,$hashref);
1.869     albertel 12310: 	return;
1.852     albertel 12311:     }
                   12312:     close($config);
1.871     albertel 12313:     my $which = (split('/',$url))[3];
                   12314:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12315:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12316:     my @content = <$config>;
1.1172.2.17  raeburn  12317:     &$func(\@content,$hashref);
                   12318:     return;
                   12319: }
                   12320: 
                   12321: # ------------------------------------------------------Get DNS checksums file
                   12322: sub parse_dns_checksums_tab {
                   12323:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12324:     my $lonhost = $perlvar{'lonHostID'};
                   12325:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12326:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12327:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12328:     my $webconfdir = '/etc/httpd/conf';
                   12329:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12330:         $webconfdir = '/etc/apache2';
                   12331:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12332:         if ($1 >= 10) {
                   12333:             $webconfdir = '/etc/apache2';
                   12334:         }
                   12335:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12336:         if ($1 >= 10.0) {
                   12337:             $webconfdir = '/etc/apache2';
                   12338:         }
                   12339:     }
1.1172.2.17  raeburn  12340:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12341:     my (%chksum,%revnum);
                   12342:     if (ref($lines) eq 'ARRAY') {
                   12343:         chomp(@{$lines});
1.1172.2.34  raeburn  12344:         my $version = shift(@{$lines});
                   12345:         if ($version eq $release) {
1.1172.2.17  raeburn  12346:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12347:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12348:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12349:                     if ($webconfdir eq '/etc/apache2') {
                   12350:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12351:                     }
                   12352:                 }
1.1172.2.34  raeburn  12353:                 $chksum{$file} = $shasum;
                   12354:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12355:             }
                   12356:             if (ref($hashref) eq 'HASH') {
                   12357:                 %{$hashref} = (
                   12358:                                 sums     => \%chksum,
                   12359:                                 versions => \%revnum,
                   12360:                               );
                   12361:             }
                   12362:         }
                   12363:     }
1.869     albertel 12364:     return;
1.852     albertel 12365: }
1.1172.2.17  raeburn  12366: 
                   12367: sub fetch_dns_checksums {
                   12368:     my %checksums;
1.1172.2.34  raeburn  12369:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12370:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12371:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12372:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12373:              \%checksums);
                   12374:     return \%checksums;
                   12375: }
                   12376: 
1.327     albertel 12377: # ------------------------------------------------------------ Read domain file
                   12378: {
1.852     albertel 12379:     my $loaded;
1.846     albertel 12380:     my %domain;
                   12381: 
1.852     albertel 12382:     sub parse_domain_tab {
                   12383: 	my ($lines) = @_;
                   12384: 	foreach my $line (@$lines) {
                   12385: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12386: 
1.846     albertel 12387: 	    chomp($line);
1.852     albertel 12388: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12389: 	    my %this_domain;
                   12390: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12391: 			       'lang_def', 'city', 'longi', 'lati',
                   12392: 			       'primary') {
                   12393: 		$this_domain{$field} = shift(@elements);
                   12394: 	    }
                   12395: 	    $domain{$name} = \%this_domain;
1.852     albertel 12396: 	}
                   12397:     }
1.864     albertel 12398: 
                   12399:     sub reset_domain_info {
                   12400: 	undef($loaded);
                   12401: 	undef(%domain);
                   12402:     }
                   12403: 
1.852     albertel 12404:     sub load_domain_tab {
1.1172.2.70  raeburn  12405: 	my ($ignore_cache,$nocache) = @_;
                   12406: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12407: 	my $fh;
                   12408: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12409: 	    my @lines = <$fh>;
                   12410: 	    &parse_domain_tab(\@lines);
1.448     albertel 12411: 	}
1.852     albertel 12412: 	close($fh);
                   12413: 	$loaded = 1;
1.327     albertel 12414:     }
1.846     albertel 12415: 
                   12416:     sub domain {
1.852     albertel 12417: 	&load_domain_tab() if (!$loaded);
                   12418: 
1.846     albertel 12419: 	my ($name,$what) = @_;
                   12420: 	return if ( !exists($domain{$name}) );
                   12421: 
                   12422: 	if (!$what) {
                   12423: 	    return $domain{$name}{'description'};
                   12424: 	}
                   12425: 	return $domain{$name}{$what};
                   12426:     }
1.974     raeburn  12427: 
                   12428:     sub domain_info {
                   12429:         &load_domain_tab() if (!$loaded);
                   12430:         return %domain;
                   12431:     }
                   12432: 
1.327     albertel 12433: }
                   12434: 
                   12435: 
1.1       albertel 12436: # ------------------------------------------------------------- Read hosts file
                   12437: {
1.838     albertel 12438:     my %hostname;
1.844     albertel 12439:     my %hostdom;
1.845     albertel 12440:     my %libserv;
1.852     albertel 12441:     my $loaded;
1.888     albertel 12442:     my %name_to_host;
1.1074    raeburn  12443:     my %internetdom;
1.1107    raeburn  12444:     my %LC_dns_serv;
1.852     albertel 12445: 
                   12446:     sub parse_hosts_tab {
                   12447: 	my ($file) = @_;
                   12448: 	foreach my $configline (@$file) {
                   12449: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12450:             chomp($configline);
                   12451: 	    if ($configline =~ /^\^/) {
                   12452:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12453:                     $LC_dns_serv{$1} = 1;
                   12454:                 }
                   12455:                 next;
                   12456:             }
1.1074    raeburn  12457: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12458: 	    $name=~s/\s//g;
                   12459: 	    if ($id && $domain && $role && $name) {
                   12460: 		$hostname{$id}=$name;
1.888     albertel 12461: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12462: 		$hostdom{$id}=$domain;
                   12463: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12464:                 if (defined($protocol)) {
                   12465:                     if ($protocol eq 'https') {
                   12466:                         $protocol{$id} = $protocol;
                   12467:                     } else {
                   12468:                         $protocol{$id} = 'http'; 
                   12469:                     }
1.968     raeburn  12470:                 } else {
1.969     raeburn  12471:                     $protocol{$id} = 'http';
1.968     raeburn  12472:                 }
1.1074    raeburn  12473:                 if (defined($intdom)) {
                   12474:                     $internetdom{$id} = $intdom;
                   12475:                 }
1.852     albertel 12476: 	    }
                   12477: 	}
                   12478:     }
1.864     albertel 12479:     
                   12480:     sub reset_hosts_info {
1.897     albertel 12481: 	&purge_remembered();
1.864     albertel 12482: 	&reset_domain_info();
                   12483: 	&reset_hosts_ip_info();
1.892     albertel 12484: 	undef(%name_to_host);
1.864     albertel 12485: 	undef(%hostname);
                   12486: 	undef(%hostdom);
                   12487: 	undef(%libserv);
                   12488: 	undef($loaded);
                   12489:     }
1.1       albertel 12490: 
1.852     albertel 12491:     sub load_hosts_tab {
1.1172.2.70  raeburn  12492: 	my ($ignore_cache,$nocache) = @_;
                   12493: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12494: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12495: 	my @config = <$config>;
                   12496: 	&parse_hosts_tab(\@config);
                   12497: 	close($config);
                   12498: 	$loaded=1;
1.1       albertel 12499:     }
1.852     albertel 12500: 
1.838     albertel 12501:     sub hostname {
1.852     albertel 12502: 	&load_hosts_tab() if (!$loaded);
                   12503: 
1.838     albertel 12504: 	my ($lonid) = @_;
                   12505: 	return $hostname{$lonid};
                   12506:     }
1.845     albertel 12507: 
1.838     albertel 12508:     sub all_hostnames {
1.852     albertel 12509: 	&load_hosts_tab() if (!$loaded);
                   12510: 
1.838     albertel 12511: 	return %hostname;
                   12512:     }
1.845     albertel 12513: 
1.888     albertel 12514:     sub all_names {
1.1172.2.70  raeburn  12515:         my ($ignore_cache,$nocache) = @_;
                   12516: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12517: 
                   12518: 	return %name_to_host;
                   12519:     }
                   12520: 
1.974     raeburn  12521:     sub all_host_domain {
                   12522:         &load_hosts_tab() if (!$loaded);
                   12523:         return %hostdom;
                   12524:     }
                   12525: 
1.845     albertel 12526:     sub is_library {
1.852     albertel 12527: 	&load_hosts_tab() if (!$loaded);
                   12528: 
1.845     albertel 12529: 	return exists($libserv{$_[0]});
                   12530:     }
                   12531: 
                   12532:     sub all_library {
1.852     albertel 12533: 	&load_hosts_tab() if (!$loaded);
                   12534: 
1.845     albertel 12535: 	return %libserv;
                   12536:     }
                   12537: 
1.1062    droeschl 12538:     sub unique_library {
                   12539: 	#2x reverse removes all hostnames that appear more than once
                   12540:         my %unique = reverse &all_library();
                   12541:         return reverse %unique;
                   12542:     }
                   12543: 
1.841     albertel 12544:     sub get_servers {
1.852     albertel 12545: 	&load_hosts_tab() if (!$loaded);
                   12546: 
1.841     albertel 12547: 	my ($domain,$type) = @_;
                   12548: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12549: 	                                          : %hostname;
                   12550: 	my %result;
1.842     albertel 12551: 	if (ref($domain) eq 'ARRAY') {
                   12552: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12553: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12554: 		    $result{$host} = $hostname;
                   12555: 		}
                   12556: 	    }
                   12557: 	} else {
                   12558: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12559: 		if ($hostdom{$host} eq $domain) {
                   12560: 		    $result{$host} = $hostname;
                   12561: 		}
1.841     albertel 12562: 	    }
                   12563: 	}
                   12564: 	return %result;
                   12565:     }
1.845     albertel 12566: 
1.1062    droeschl 12567:     sub get_unique_servers {
                   12568:         my %unique = reverse &get_servers(@_);
                   12569: 	return reverse %unique;
                   12570:     }
                   12571: 
1.844     albertel 12572:     sub host_domain {
1.852     albertel 12573: 	&load_hosts_tab() if (!$loaded);
                   12574: 
1.844     albertel 12575: 	my ($lonid) = @_;
                   12576: 	return $hostdom{$lonid};
                   12577:     }
                   12578: 
1.841     albertel 12579:     sub all_domains {
1.852     albertel 12580: 	&load_hosts_tab() if (!$loaded);
                   12581: 
1.841     albertel 12582: 	my %seen;
                   12583: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12584: 	return @uniq;
                   12585:     }
1.1074    raeburn  12586: 
                   12587:     sub internet_dom {
                   12588:         &load_hosts_tab() if (!$loaded);
                   12589: 
                   12590:         my ($lonid) = @_;
                   12591:         return $internetdom{$lonid};
                   12592:     }
1.1107    raeburn  12593: 
                   12594:     sub is_LC_dns {
                   12595:         &load_hosts_tab() if (!$loaded);
                   12596: 
                   12597:         my ($hostname) = @_;
                   12598:         return exists($LC_dns_serv{$hostname});
                   12599:     }
                   12600: 
1.1       albertel 12601: }
                   12602: 
1.847     albertel 12603: { 
                   12604:     my %iphost;
1.856     albertel 12605:     my %name_to_ip;
                   12606:     my %lonid_to_ip;
1.869     albertel 12607: 
1.847     albertel 12608:     sub get_hosts_from_ip {
                   12609: 	my ($ip) = @_;
                   12610: 	my %iphosts = &get_iphost();
                   12611: 	if (ref($iphosts{$ip})) {
                   12612: 	    return @{$iphosts{$ip}};
                   12613: 	}
                   12614: 	return;
1.839     albertel 12615:     }
1.864     albertel 12616:     
                   12617:     sub reset_hosts_ip_info {
                   12618: 	undef(%iphost);
                   12619: 	undef(%name_to_ip);
                   12620: 	undef(%lonid_to_ip);
                   12621:     }
1.856     albertel 12622: 
                   12623:     sub get_host_ip {
                   12624: 	my ($lonid) = @_;
                   12625: 	if (exists($lonid_to_ip{$lonid})) {
                   12626: 	    return $lonid_to_ip{$lonid};
                   12627: 	}
                   12628: 	my $name=&hostname($lonid);
                   12629:    	my $ip = gethostbyname($name);
                   12630: 	return if (!$ip || length($ip) ne 4);
                   12631: 	$ip=inet_ntoa($ip);
                   12632: 	$name_to_ip{$name}   = $ip;
                   12633: 	$lonid_to_ip{$lonid} = $ip;
                   12634: 	return $ip;
                   12635:     }
1.847     albertel 12636:     
                   12637:     sub get_iphost {
1.1172.2.70  raeburn  12638: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 12639: 
1.869     albertel 12640: 	if (!$ignore_cache) {
                   12641: 	    if (%iphost) {
                   12642: 		return %iphost;
                   12643: 	    }
                   12644: 	    my ($ip_info,$cached)=
                   12645: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12646: 	    if ($cached) {
                   12647: 		%iphost      = %{$ip_info->[0]};
                   12648: 		%name_to_ip  = %{$ip_info->[1]};
                   12649: 		%lonid_to_ip = %{$ip_info->[2]};
                   12650: 		return %iphost;
                   12651: 	    }
                   12652: 	}
1.894     albertel 12653: 
                   12654: 	# get yesterday's info for fallback
                   12655: 	my %old_name_to_ip;
                   12656: 	my ($ip_info,$cached)=
                   12657: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12658: 	if ($cached) {
                   12659: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12660: 	}
                   12661: 
1.1172.2.70  raeburn  12662: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 12663: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12664: 	    my $ip;
                   12665: 	    if (!exists($name_to_ip{$name})) {
                   12666: 		$ip = gethostbyname($name);
                   12667: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12668: 		    if (defined($old_name_to_ip{$name})) {
                   12669: 			$ip = $old_name_to_ip{$name};
                   12670: 			&logthis("Can't find $name defaulting to old $ip");
                   12671: 		    } else {
                   12672: 			&logthis("Name $name no IP found");
                   12673: 			next;
                   12674: 		    }
                   12675: 		} else {
                   12676: 		    $ip=inet_ntoa($ip);
1.847     albertel 12677: 		}
                   12678: 		$name_to_ip{$name} = $ip;
                   12679: 	    } else {
                   12680: 		$ip = $name_to_ip{$name};
1.653     albertel 12681: 	    }
1.888     albertel 12682: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12683: 		$lonid_to_ip{$id} = $ip;
                   12684: 	    }
                   12685: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12686: 	}
1.1172.2.70  raeburn  12687:         unless ($nocache) {
                   12688: 	    &do_cache_new('iphost','iphost',
                   12689: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12690: 		          48*60*60);
                   12691:         }
1.869     albertel 12692: 
1.847     albertel 12693: 	return %iphost;
1.598     albertel 12694:     }
                   12695: 
1.992     raeburn  12696:     #
                   12697:     #  Given a DNS returns the loncapa host name for that DNS 
                   12698:     # 
                   12699:     sub host_from_dns {
                   12700:         my ($dns) = @_;
                   12701:         my @hosts;
                   12702:         my $ip;
                   12703: 
1.993     raeburn  12704:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12705:             $ip = $name_to_ip{$dns};
                   12706:         }
                   12707:         if (!$ip) {
                   12708:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12709:             if (length($ip) == 4) { 
                   12710: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12711:             }
                   12712:         }
                   12713:         if ($ip) {
                   12714: 	    @hosts = get_hosts_from_ip($ip);
                   12715: 	    return $hosts[0];
                   12716:         }
                   12717:         return undef;
1.986     foxr     12718:     }
1.992     raeburn  12719: 
1.1074    raeburn  12720:     sub get_internet_names {
                   12721:         my ($lonid) = @_;
                   12722:         return if ($lonid eq '');
                   12723:         my ($idnref,$cached)=
                   12724:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12725:         if ($cached) {
                   12726:             return $idnref;
                   12727:         }
                   12728:         my $ip = &get_host_ip($lonid);
                   12729:         my @hosts = &get_hosts_from_ip($ip);
                   12730:         my %iphost = &get_iphost();
                   12731:         my (@idns,%seen);
                   12732:         foreach my $id (@hosts) {
                   12733:             my $dom = &host_domain($id);
                   12734:             my $prim_id = &domain($dom,'primary');
                   12735:             my $prim_ip = &get_host_ip($prim_id);
                   12736:             next if ($seen{$prim_ip});
                   12737:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12738:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12739:                     my $intdom = &internet_dom($id);
                   12740:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12741:                         push(@idns,$intdom);
                   12742:                     }
                   12743:                 }
                   12744:             }
                   12745:             $seen{$prim_ip} = 1;
                   12746:         }
1.1172.2.23  raeburn  12747:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12748:     }
                   12749: 
1.986     foxr     12750: }
                   12751: 
1.1079    raeburn  12752: sub all_loncaparevs {
1.1172.2.39  raeburn  12753:     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  12754: }
                   12755: 
1.1172.2.27  raeburn  12756: # ------------------------------------------------------- Read loncaparev table
                   12757: {
                   12758:     sub load_loncaparevs {
                   12759:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12760:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12761:                 while (my $configline=<$config>) {
                   12762:                     chomp($configline);
                   12763:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12764:                     $loncaparevs{$hostid}=$loncaparev;
                   12765:                 }
                   12766:                 close($config);
                   12767:             }
                   12768:         }
                   12769:     }
                   12770: }
                   12771: 
                   12772: # ----------------------------------------------------- Read serverhostID table
                   12773: {
                   12774:     sub load_serverhomeIDs {
                   12775:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12776:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12777:                 while (my $configline=<$config>) {
                   12778:                     chomp($configline);
                   12779:                     my ($name,$id)=split(/:/,$configline);
                   12780:                     $serverhomeIDs{$name}=$id;
                   12781:                 }
                   12782:                 close($config);
                   12783:             }
                   12784:         }
                   12785:     }
                   12786: }
                   12787: 
                   12788: 
1.862     albertel 12789: BEGIN {
                   12790: 
                   12791: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12792:     unless ($readit) {
                   12793: {
                   12794:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12795:     %perlvar = (%perlvar,%{$configvars});
                   12796: }
                   12797: 
                   12798: 
1.1       albertel 12799: # ------------------------------------------------------ Read spare server file
                   12800: {
1.448     albertel 12801:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12802: 
                   12803:     while (my $configline=<$config>) {
                   12804:        chomp($configline);
1.284     matthew  12805:        if ($configline) {
1.784     albertel 12806: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12807: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12808: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12809:        }
                   12810:     }
1.448     albertel 12811:     close($config);
1.1       albertel 12812: }
1.11      www      12813: # ------------------------------------------------------------ Read permissions
                   12814: {
1.448     albertel 12815:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12816: 
                   12817:     while (my $configline=<$config>) {
1.448     albertel 12818: 	chomp($configline);
                   12819: 	if ($configline) {
                   12820: 	    my ($role,$perm)=split(/ /,$configline);
                   12821: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12822: 	}
1.11      www      12823:     }
1.448     albertel 12824:     close($config);
1.11      www      12825: }
                   12826: 
                   12827: # -------------------------------------------- Read plain texts for permissions
                   12828: {
1.448     albertel 12829:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12830: 
                   12831:     while (my $configline=<$config>) {
1.448     albertel 12832: 	chomp($configline);
                   12833: 	if ($configline) {
1.742     raeburn  12834: 	    my ($short,@plain)=split(/:/,$configline);
                   12835:             %{$prp{$short}} = ();
                   12836: 	    if (@plain > 0) {
                   12837:                 $prp{$short}{'std'} = $plain[0];
                   12838:                 for (my $i=1; $i<@plain; $i++) {
                   12839:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12840:                 }
                   12841:             }
1.448     albertel 12842: 	}
1.135     www      12843:     }
1.448     albertel 12844:     close($config);
1.135     www      12845: }
                   12846: 
                   12847: # ---------------------------------------------------------- Read package table
                   12848: {
1.448     albertel 12849:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12850: 
                   12851:     while (my $configline=<$config>) {
1.483     albertel 12852: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12853: 	chomp($configline);
                   12854: 	my ($short,$plain)=split(/:/,$configline);
                   12855: 	my ($pack,$name)=split(/\&/,$short);
                   12856: 	if ($plain ne '') {
                   12857: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12858: 	    $packagetab{$short}=$plain; 
                   12859: 	}
1.11      www      12860:     }
1.448     albertel 12861:     close($config);
1.329     matthew  12862: }
                   12863: 
1.1172.2.27  raeburn  12864: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12865: 
1.1172.2.27  raeburn  12866: &load_loncaparevs();
                   12867: 
                   12868: # ------------------------------------------------------- Read serverhostID table
                   12869: 
                   12870: &load_serverhomeIDs();
1.1074    raeburn  12871: 
1.1172.2.27  raeburn  12872: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12873: {
                   12874:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12875:     if (-e $file) {
                   12876:         my $parser = HTML::LCParser->new($file);
                   12877:         while (my $token = $parser->get_token()) {
                   12878:             if ($token->[0] eq 'S') {
                   12879:                 my $item = $token->[1];
                   12880:                 my $name = $token->[2]{'name'};
                   12881:                 my $value = $token->[2]{'value'};
                   12882:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12883:                     my $release = $parser->get_text();
                   12884:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12885:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12886:                 }
                   12887:             }
                   12888:         }
                   12889:     }
1.1073    raeburn  12890: }
                   12891: 
1.1138    raeburn  12892: # ---------------------------------------------------------- Read managers table
                   12893: {
                   12894:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12895:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12896:             while (my $configline=<$config>) {
                   12897:                 chomp($configline);
                   12898:                 next if ($configline =~ /^\#/);
                   12899:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12900:                     $managerstab{$configline} = 1;
                   12901:                 }
                   12902:             }
                   12903:             close($config);
                   12904:         }
                   12905:     }
                   12906: }
                   12907: 
1.329     matthew  12908: # ------------- set up temporary directory
                   12909: {
1.1117    foxr     12910:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12911: 
1.11      www      12912: }
                   12913: 
1.794     albertel 12914: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12915: 				'compress_threshold'=> 20_000,
                   12916:  			        });
1.185     www      12917: 
1.281     www      12918: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12919: $dumpcount=0;
1.958     www      12920: $locknum=0;
1.22      www      12921: 
1.163     harris41 12922: &logtouch();
1.672     albertel 12923: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12924: $readit=1;
1.564     albertel 12925:     {
                   12926: 	use integer;
                   12927: 	my $test=(2**32)+1;
1.568     albertel 12928: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12929: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12930:     }
1.195     www      12931: }
1.1       albertel 12932: }
1.179     www      12933: 
1.1       albertel 12934: 1;
1.191     harris41 12935: __END__
                   12936: 
1.243     albertel 12937: =pod
                   12938: 
1.191     harris41 12939: =head1 NAME
                   12940: 
1.243     albertel 12941: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12942: 
                   12943: =head1 SYNOPSIS
                   12944: 
1.243     albertel 12945: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12946: 
                   12947:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12948: 
1.243     albertel 12949: Common parameters:
                   12950: 
                   12951: =over 4
                   12952: 
                   12953: =item *
                   12954: 
                   12955: $uname : an internal username (if $cname expecting a course Id specifically)
                   12956: 
                   12957: =item *
                   12958: 
                   12959: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12960: 
                   12961: =item *
                   12962: 
                   12963: $symb : a resource instance identifier
                   12964: 
                   12965: =item *
                   12966: 
                   12967: $namespace : the name of a .db file that contains the data needed or
                   12968: being set.
                   12969: 
                   12970: =back
                   12971: 
1.394     bowersj2 12972: =head1 OVERVIEW
1.191     harris41 12973: 
1.394     bowersj2 12974: lonnet provides subroutines which interact with the
                   12975: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12976: about classes, users, and resources.
1.243     albertel 12977: 
                   12978: For many of these objects you can also use this to store data about
                   12979: them or modify them in various ways.
1.191     harris41 12980: 
1.394     bowersj2 12981: =head2 Symbs
1.191     harris41 12982: 
1.394     bowersj2 12983: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12984: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12985: map, the resource number of the resource in the map, and the URL of
                   12986: the resource itself. The latter is somewhat redundant, but might help
                   12987: if maps change.
                   12988: 
                   12989: An example is
                   12990: 
                   12991:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12992: 
                   12993: The respective map entry is
                   12994: 
                   12995:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12996:   title="Problem 2">
                   12997:  </resource>
                   12998: 
                   12999: Symbs are used by the random number generator, as well as to store and
                   13000: restore data specific to a certain instance of for example a problem.
                   13001: 
                   13002: =head2 Storing And Retrieving Data
                   13003: 
                   13004: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13005: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13006: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13007: is is the non-critical message twin of cstore. These functions are for
                   13008: handlers to store a perl hash to a user's permanent data space in an
                   13009: easy manner, and to retrieve it again on another call. It is expected
                   13010: that a handler would use this once at the beginning to retrieve data,
                   13011: and then again once at the end to send only the new data back.
                   13012: 
                   13013: The data is stored in the user's data directory on the user's
                   13014: homeserver under the ID of the course.
                   13015: 
                   13016: The hash that is returned by restore will have all of the previous
                   13017: value for all of the elements of the hash.
                   13018: 
                   13019: Example:
                   13020: 
                   13021:  #creating a hash
                   13022:  my %hash;
                   13023:  $hash{'foo'}='bar';
                   13024: 
                   13025:  #storing it
                   13026:  &Apache::lonnet::cstore(\%hash);
                   13027: 
                   13028:  #changing a value
                   13029:  $hash{'foo'}='notbar';
                   13030: 
                   13031:  #adding a new value
                   13032:  $hash{'bar'}='foo';
                   13033:  &Apache::lonnet::cstore(\%hash);
                   13034: 
                   13035:  #retrieving the hash
                   13036:  my %history=&Apache::lonnet::restore();
                   13037: 
                   13038:  #print the hash
                   13039:  foreach my $key (sort(keys(%history))) {
                   13040:    print("\%history{$key} = $history{$key}");
                   13041:  }
                   13042: 
                   13043: Will print out:
1.191     harris41 13044: 
1.394     bowersj2 13045:  %history{1:foo} = bar
                   13046:  %history{1:keys} = foo:timestamp
                   13047:  %history{1:timestamp} = 990455579
                   13048:  %history{2:bar} = foo
                   13049:  %history{2:foo} = notbar
                   13050:  %history{2:keys} = foo:bar:timestamp
                   13051:  %history{2:timestamp} = 990455580
                   13052:  %history{bar} = foo
                   13053:  %history{foo} = notbar
                   13054:  %history{timestamp} = 990455580
                   13055:  %history{version} = 2
                   13056: 
                   13057: Note that the special hash entries C<keys>, C<version> and
                   13058: C<timestamp> were added to the hash. C<version> will be equal to the
                   13059: total number of versions of the data that have been stored. The
                   13060: C<timestamp> attribute will be the UNIX time the hash was
                   13061: stored. C<keys> is available in every historical section to list which
                   13062: keys were added or changed at a specific historical revision of a
                   13063: hash.
                   13064: 
                   13065: B<Warning>: do not store the hash that restore returns directly. This
                   13066: will cause a mess since it will restore the historical keys as if the
                   13067: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13068: 
1.394     bowersj2 13069: Calling convention:
1.191     harris41 13070: 
1.1172.2.27  raeburn  13071:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13072:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13073: 
1.394     bowersj2 13074: For more detailed information, see lonnet specific documentation.
1.191     harris41 13075: 
1.394     bowersj2 13076: =head1 RETURN MESSAGES
1.191     harris41 13077: 
1.394     bowersj2 13078: =over 4
1.191     harris41 13079: 
1.394     bowersj2 13080: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13081: 
1.394     bowersj2 13082: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13083: when the connection is brought back up
1.191     harris41 13084: 
1.394     bowersj2 13085: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13086: for later delivery
1.191     harris41 13087: 
1.967     bisitz   13088: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13089: 
1.394     bowersj2 13090: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13091: that was requested
1.191     harris41 13092: 
1.243     albertel 13093: =back
1.191     harris41 13094: 
1.243     albertel 13095: =head1 PUBLIC SUBROUTINES
1.191     harris41 13096: 
1.243     albertel 13097: =head2 Session Environment Functions
1.191     harris41 13098: 
1.243     albertel 13099: =over 4
1.191     harris41 13100: 
1.394     bowersj2 13101: =item * 
                   13102: X<appenv()>
1.949     raeburn  13103: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13104: the user envirnoment file, and will be restored for each access this
1.620     albertel 13105: user makes during this session, also modifies the %env for the current
1.949     raeburn  13106: process. Optional rolesarrayref - if defined contains a reference to an array
                   13107: of roles which are exempt from the restriction on modifying user.role entries 
                   13108: in the user's environment.db and in %env.    
1.191     harris41 13109: 
                   13110: =item *
1.394     bowersj2 13111: X<delenv()>
1.987     raeburn  13112: B<delenv($delthis,$regexp)>: removes all items from the session
                   13113: environment file that begin with $delthis. If the 
                   13114: optional second arg - $regexp - is true, $delthis is treated as a 
                   13115: regular expression, otherwise \Q$delthis\E is used. 
                   13116: The values are also deleted from the current processes %env.
1.191     harris41 13117: 
1.795     albertel 13118: =item * get_env_multiple($name) 
                   13119: 
                   13120: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13121: values may be defined and end up as an array ref.
                   13122: 
                   13123: returns an array of values
                   13124: 
1.243     albertel 13125: =back
                   13126: 
                   13127: =head2 User Information
1.191     harris41 13128: 
1.243     albertel 13129: =over 4
1.191     harris41 13130: 
                   13131: =item *
1.394     bowersj2 13132: X<queryauthenticate()>
                   13133: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13134: authentication scheme
                   13135: 
                   13136: =item *
1.394     bowersj2 13137: X<authenticate()>
1.1073    raeburn  13138: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13139: authenticate user from domain's lib servers (first use the current
                   13140: one). C<$upass> should be the users password.
1.1073    raeburn  13141: $checkdefauth is optional (value is 1 if a check should be made to
                   13142:    authenticate user using default authentication method, and allow
                   13143:    account creation if username does not have account in the domain).
                   13144: $clientcancheckhost is optional (value is 1 if checking whether the
                   13145:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13146: 
                   13147: =item *
1.394     bowersj2 13148: X<homeserver()>
                   13149: B<homeserver($uname,$udom)>: find the server which has
                   13150: the user's directory and files (there must be only one), this caches
                   13151: the answer, and also caches if there is a borken connection.
1.191     harris41 13152: 
                   13153: =item *
1.394     bowersj2 13154: X<idget()>
                   13155: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13156: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13157: username, and only 1 username per ID in a specific domain) (returns
                   13158: hash: id=>name,id=>name)
1.191     harris41 13159: 
                   13160: =item *
1.394     bowersj2 13161: X<idrget()>
                   13162: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13163: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13164: 
                   13165: =item *
1.394     bowersj2 13166: X<idput()>
                   13167: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13168: 
                   13169: =item *
1.394     bowersj2 13170: X<rolesinit()>
1.1169    droeschl 13171: B<rolesinit($udom,$username)>: get user privileges.
                   13172: returns user role, first access and timer interval hashes
1.243     albertel 13173: 
                   13174: =item *
1.1171    droeschl 13175: X<privileged()>
                   13176: B<privileged($username,$domain)>: returns a true if user has a
                   13177: privileged and active role (i.e. su or dc), false otherwise.
                   13178: 
                   13179: =item *
1.551     albertel 13180: X<getsection()>
                   13181: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13182: course $cname, return section name/number or '' for "not in course"
                   13183: and '-1' for "no section"
                   13184: 
                   13185: =item *
1.394     bowersj2 13186: X<userenvironment()>
                   13187: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13188: passed in @what from the requested user's environment, returns a hash
                   13189: 
1.858     raeburn  13190: =item * 
                   13191: X<userlog_query()>
1.859     albertel 13192: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13193: activity.log file. %filters defines filters applied when parsing the
                   13194: log file. These can be start or end timestamps, or the type of action
                   13195: - log to look for Login or Logout events, check for Checkin or
                   13196: Checkout, role for role selection. The response is in the form
                   13197: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13198: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13199: 
1.243     albertel 13200: =back
                   13201: 
                   13202: =head2 User Roles
                   13203: 
                   13204: =over 4
                   13205: 
                   13206: =item *
                   13207: 
1.1172.2.65  raeburn  13208: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13209: returns codes for allowed actions.
                   13210: 
                   13211: The first argument is required, all others are optional.
                   13212: 
                   13213: $priv is the privilege being checked.
                   13214: $uri contains additional information about what is being checked for access (e.g.,
                   13215: URL, course ID etc.).
                   13216: $symb is the unique resource instance identifier in a course; if needed,
                   13217: but not provided, it will be retrieved via a call to &symbread().
                   13218: $role is the role for which a priv is being checked (only used if priv is evb).
                   13219: $clientip is the user's IP address (only used when checking for access to portfolio
                   13220: files).
                   13221: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13222: prevents recursive calls to &allowed.
                   13223: 
1.243     albertel 13224:  F: full access
                   13225:  U,I,K: authentication modes (cxx only)
                   13226:  '': forbidden
                   13227:  1: user needs to choose course
                   13228:  2: browse allowed
1.766     albertel 13229:  A: passphrase authentication needed
1.1172.2.65  raeburn  13230:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13231: 
                   13232: =item *
                   13233: 
1.1172.2.13  raeburn  13234: constructaccess($url,$setpriv) : check for access to construction space URL
                   13235: 
                   13236: See if the owner domain and name in the URL match those in the
                   13237: expected environment.  If so, return three element list
                   13238: ($ownername,$ownerdomain,$ownerhome).
                   13239: 
                   13240: Otherwise return the null string.
                   13241: 
                   13242: If second argument 'setpriv' is true, it assigns the privileges,
                   13243: and returns the same three element list, unless the owner has
                   13244: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13245: in which case the null string is returned.
                   13246: 
                   13247: =item *
                   13248: 
1.1172.2.84  raeburn  13249: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13250: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13251: for system, domain, and course level. $uname and $udom are optional (current
                   13252: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13253: 
                   13254: =item *
                   13255: 
1.988     raeburn  13256: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13257: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13258: $type is Course (default) or Community.
1.988     raeburn  13259: If $forcedefault evaluates to true, text returned will be default 
                   13260: text for $type. Otherwise, if this is a course, the text returned 
                   13261: will be a custom name for the role (if defined in the course's 
                   13262: environment).  If no custom name is defined the default is returned.
                   13263:    
1.832     raeburn  13264: =item *
                   13265: 
1.1172.2.23  raeburn  13266: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13267: All arguments are optional. Returns a hash of a roles, either for
                   13268: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13269: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13270: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13271: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13272: For each key, value is set to colon-separated start and end times for
                   13273: the role.  If no username and domain are specified, will default to
1.934     raeburn  13274: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13275: of role statuses (active, future or previous), roles 
                   13276: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13277: to restrict the list of roles reported. If no array ref is 
                   13278: provided for types, will default to return only active roles.
1.834     albertel 13279: 
1.1172.2.13  raeburn  13280: =item *
                   13281: 
                   13282: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13283: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13284: 
                   13285: Additional optional arguments are: $type (if role checking is to be restricted
                   13286: to certain user status types -- previous (expired roles), active (currently
                   13287: available roles) or future (roles available in the future), and
                   13288: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13289: have active Domain Coordinator role in course's domain or in additional
                   13290: domains (specified in 'Domains to check for privileged users' in course
                   13291: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13292: 
                   13293: =item *
                   13294: 
                   13295: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13296: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13297: $possdomains and $possroles are optional array refs -- to domains to check and
                   13298: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13299: users' roles.db to check for a dc or su role in any domain. This can be
                   13300: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13301: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13302: this then allows &privileged_by_domain() to be used, which caches the identity
                   13303: of privileged users, eliminating the need for repeated calls to &dump().
                   13304: 
                   13305: =item *
                   13306: 
                   13307: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13308: where the outer hash keys are domains specified in the $possdomains array ref,
                   13309: next inner hash keys are privileged roles specified in the $roles array ref,
                   13310: and the innermost hash contains key = value pairs for username:domain = end:start
                   13311: for active or future "privileged" users with that role in that domain. To avoid
                   13312: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13313: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13314: 
1.243     albertel 13315: =back
                   13316: 
                   13317: =head2 User Modification
                   13318: 
                   13319: =over 4
                   13320: 
                   13321: =item *
                   13322: 
1.957     raeburn  13323: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13324: user for the level given by URL.  Optional start and end dates (leave empty
                   13325: string or zero for "no date")
1.191     harris41 13326: 
                   13327: =item *
                   13328: 
1.243     albertel 13329: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13330: change a users, password, possible return values are: ok,
                   13331: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13332: refused
1.191     harris41 13333: 
                   13334: =item *
                   13335: 
1.243     albertel 13336: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13337: 
                   13338: =item *
                   13339: 
1.1058    raeburn  13340: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13341:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13342: 
                   13343: will update user information (firstname,middlename,lastname,generation,
                   13344: permanentemail), and if forceid is true, student/employee ID also.
                   13345: A user's institutional affiliation(s) can also be updated.
                   13346: User information fields will not be overwritten with empty entries 
                   13347: unless the field is included in the $candelete array reference.
                   13348: This array is included when a single user is modified via "Manage Users",
                   13349: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13350: 
                   13351: =item *
                   13352: 
1.286     matthew  13353: modifystudent
                   13354: 
1.957     raeburn  13355: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13356: The course id is resolved based on the current user's environment.  
                   13357: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13358: associated with a course.
                   13359: 
1.297     matthew  13360: This call is essentially a wrapper for lonnet::modifyuser and
                   13361: lonnet::modify_student_enrollment
1.286     matthew  13362: 
                   13363: Inputs: 
                   13364: 
                   13365: =over 4
                   13366: 
1.957     raeburn  13367: =item B<$udom> Student's loncapa domain
1.286     matthew  13368: 
1.957     raeburn  13369: =item B<$uname> Student's loncapa login name
1.286     matthew  13370: 
1.964     bisitz   13371: =item B<$uid> Student/Employee ID
1.286     matthew  13372: 
1.957     raeburn  13373: =item B<$umode> Student's authentication mode
1.286     matthew  13374: 
1.957     raeburn  13375: =item B<$upass> Student's password
1.286     matthew  13376: 
1.957     raeburn  13377: =item B<$first> Student's first name
1.286     matthew  13378: 
1.957     raeburn  13379: =item B<$middle> Student's middle name
1.286     matthew  13380: 
1.957     raeburn  13381: =item B<$last> Student's last name
1.286     matthew  13382: 
1.957     raeburn  13383: =item B<$gene> Student's generation
1.286     matthew  13384: 
1.957     raeburn  13385: =item B<$usec> Student's section in course
1.286     matthew  13386: 
                   13387: =item B<$end> Unix time of the roles expiration
                   13388: 
                   13389: =item B<$start> Unix time of the roles start date
                   13390: 
                   13391: =item B<$forceid> If defined, allow $uid to be changed
                   13392: 
                   13393: =item B<$desiredhome> server to use as home server for student
                   13394: 
1.957     raeburn  13395: =item B<$email> Student's permanent e-mail address
                   13396: 
                   13397: =item B<$type> Type of enrollment (auto or manual)
                   13398: 
1.963     raeburn  13399: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13400: 
                   13401: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13402: 
1.963     raeburn  13403: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13404: 
1.963     raeburn  13405: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13406: 
1.1172.2.19  raeburn  13407: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13408: 
                   13409: =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  13410: 
1.286     matthew  13411: =back
1.297     matthew  13412: 
                   13413: =item *
                   13414: 
                   13415: modify_student_enrollment
                   13416: 
1.1172.2.31  raeburn  13417: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13418: 'role.request.course' must be defined for this function to proceed.
                   13419: 
                   13420: Inputs:
                   13421: 
                   13422: =over 4
                   13423: 
1.1172.2.31  raeburn  13424: =item $udom, student's domain
1.297     matthew  13425: 
1.1172.2.31  raeburn  13426: =item $uname, student's name
1.297     matthew  13427: 
1.1172.2.31  raeburn  13428: =item $uid, student's user id
1.297     matthew  13429: 
1.1172.2.31  raeburn  13430: =item $first, student's first name
1.297     matthew  13431: 
                   13432: =item $middle
                   13433: 
                   13434: =item $last
                   13435: 
                   13436: =item $gene
                   13437: 
                   13438: =item $usec
                   13439: 
                   13440: =item $end
                   13441: 
                   13442: =item $start
                   13443: 
1.957     raeburn  13444: =item $type
                   13445: 
                   13446: =item $locktype
                   13447: 
                   13448: =item $cid
                   13449: 
                   13450: =item $selfenroll
                   13451: 
                   13452: =item $context
                   13453: 
1.1172.2.19  raeburn  13454: =item $credits, number of credits student will earn from this class
                   13455: 
1.1172.2.76  raeburn  13456: =item $instsec, institutional course section code for student
                   13457: 
1.297     matthew  13458: =back
                   13459: 
1.191     harris41 13460: 
                   13461: =item *
                   13462: 
1.243     albertel 13463: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13464: custom role; give a custom role to a user for the level given by URL.  Specify
                   13465: name and domain of role author, and role name
1.191     harris41 13466: 
                   13467: =item *
                   13468: 
1.243     albertel 13469: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13470: 
                   13471: =item *
                   13472: 
1.243     albertel 13473: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13474: 
                   13475: =back
                   13476: 
                   13477: =head2 Course Infomation
                   13478: 
                   13479: =over 4
1.191     harris41 13480: 
                   13481: =item *
                   13482: 
1.1118    foxr     13483: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13484: specified course id, including all environment settings for the
                   13485: course, the description of the course will be in the hash under the
                   13486: key 'description'
1.191     harris41 13487: 
1.1118    foxr     13488: $options is an optional parameter that if supplied is a hash reference that controls
                   13489: what how this function works.  It has the following key/values:
                   13490: 
                   13491: =over 4
                   13492: 
                   13493: =item freshen_cache
                   13494: 
                   13495: If defined, and the environment cache for the course is valid, it is 
                   13496: returned in the returned hash.
                   13497: 
                   13498: =item one_time
                   13499: 
                   13500: If defined, the last cache time is set to _now_
                   13501: 
                   13502: =item user
                   13503: 
                   13504: If defined, the supplied username is used instead of the current user.
                   13505: 
                   13506: 
                   13507: =back
                   13508: 
1.191     harris41 13509: =item *
                   13510: 
1.624     albertel 13511: resdata($name,$domain,$type,@which) : request for current parameter
                   13512: setting for a specific $type, where $type is either 'course' or 'user',
                   13513: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  13514: answers for 10 minutes.
1.243     albertel 13515: 
1.877     foxr     13516: =item *
                   13517: 
                   13518: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13519: data base, returning a hash that is keyed by the resource name and has
                   13520: values that are the resource value.  I believe that the timestamps and
                   13521: versions are also returned.
                   13522: 
1.1172.2.31  raeburn  13523: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13524: supplemental content area. This routine caches the number of files for
                   13525: 10 minutes.
                   13526: 
1.243     albertel 13527: =back
                   13528: 
                   13529: =head2 Course Modification
                   13530: 
                   13531: =over 4
1.191     harris41 13532: 
                   13533: =item *
                   13534: 
1.243     albertel 13535: writecoursepref($courseid,%prefs) : write preferences (environment
                   13536: database) for a course
1.191     harris41 13537: 
                   13538: =item *
                   13539: 
1.1011    raeburn  13540: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13541: 
                   13542: =item *
                   13543: 
1.1038    raeburn  13544: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13545: 
1.1167    droeschl 13546: =item *
                   13547: 
                   13548: is_course($courseid), is_course($cdom, $cnum)
                   13549: 
                   13550: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13551: two component version $cdom, $cnum. It checks if the specified course exists.
                   13552: 
                   13553: Returns:
                   13554:     undef if the course doesn't exist, otherwise
                   13555:     in scalar context the combined courseid.
                   13556:     in list context the two components of the course identifier, domain and 
                   13557:     courseid.    
                   13558: 
1.243     albertel 13559: =back
                   13560: 
                   13561: =head2 Resource Subroutines
                   13562: 
                   13563: =over 4
1.191     harris41 13564: 
                   13565: =item *
                   13566: 
1.243     albertel 13567: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13568: 
                   13569: =item *
                   13570: 
1.243     albertel 13571: repcopy($filename) : subscribes to the requested file, and attempts to
                   13572: replicate from the owning library server, Might return
1.607     raeburn  13573: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13574: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13575: resource. Expects the local filesystem pathname
                   13576: (/home/httpd/html/res/....)
                   13577: 
                   13578: =back
                   13579: 
                   13580: =head2 Resource Information
                   13581: 
                   13582: =over 4
1.191     harris41 13583: 
                   13584: =item *
                   13585: 
1.1172.2.28  raeburn  13586: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13587: and returns the value of a variety of different possible values,
                   13588: $varname should be a request string, and the other parameters can be
                   13589: used to specify who and what one is asking about. Ordinarily, $cid 
                   13590: does not need to be specified, as it is retrived from 
                   13591: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13592: within lonuserstate::loadmap() when initializing a course, before
                   13593: $env{'request.course.id'} has been set, so it needs to be provided
                   13594: in that one case.
1.243     albertel 13595: 
                   13596: Possible values for $varname are environment.lastname (or other item
                   13597: from the envirnment hash), user.name (or someother aspect about the
                   13598: user), resource.0.maxtries (or some other part and parameter of a
                   13599: resource)
1.204     albertel 13600: 
                   13601: =item *
                   13602: 
1.243     albertel 13603: directcondval($number) : get current value of a condition; reads from a state
                   13604: string
1.204     albertel 13605: 
                   13606: =item *
                   13607: 
1.243     albertel 13608: condval($condidx) : value of condition index based on state
1.204     albertel 13609: 
                   13610: =item *
                   13611: 
1.243     albertel 13612: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13613: resource's metadata, $what should be either a specific key, or either
                   13614: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13615: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13616: 
                   13617: this function automatically caches all requests
1.191     harris41 13618: 
                   13619: =item *
                   13620: 
1.243     albertel 13621: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13622: network of library servers; returns file handle of where SQL and regex results
                   13623: will be stored for query
1.191     harris41 13624: 
                   13625: =item *
                   13626: 
1.1172.2.66  raeburn  13627: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   13628: return symbolic list entry (all arguments optional).
                   13629: 
                   13630: Args: filename is the filename (including path) for the file for which a symb
                   13631: is required; donotrecurse, if true will prevent calls to allowed() being made
                   13632: to check access status if more than one resource was found in the bighash
                   13633: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   13634: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   13635: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13636: cause possible symbs to be checked to determine if they are subject to content
                   13637: blocking, if so they will not be included as possible symbs; possibles is a
                   13638: ref to a hash, which, as a side effect, will be populated with all possible
                   13639: symbs (content blocking not tested).
                   13640: 
1.243     albertel 13641: returns the data handle
1.191     harris41 13642: 
                   13643: =item *
                   13644: 
1.1172.2.17  raeburn  13645: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13646: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13647: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13648: on failure, user must be in a course, as it assumes the existence of
                   13649: the course initial hash, and uses $env('request.course.id'}.  The third
                   13650: arg is an optional reference to a scalar.  If this arg is passed in the
                   13651: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13652: encrypted; otherwise it will be null.
1.243     albertel 13653: 
1.191     harris41 13654: =item *
                   13655: 
1.243     albertel 13656: symbclean($symb) : removes versions numbers from a symb, returns the
                   13657: cleaned symb
1.191     harris41 13658: 
                   13659: =item *
                   13660: 
1.243     albertel 13661: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13662: course map, user must be in a course for it to work.
1.191     harris41 13663: 
                   13664: =item *
                   13665: 
1.243     albertel 13666: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13667: 
                   13668: =item *
                   13669: 
1.243     albertel 13670: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13671: a random seed, all arguments are optional, if they aren't sent it uses the
                   13672: environment to derive them. Note: if symb isn't sent and it can't get one
                   13673: from &symbread it will use the current time as its return value
1.191     harris41 13674: 
                   13675: =item *
                   13676: 
1.243     albertel 13677: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13678: unfakeable, receipt
1.191     harris41 13679: 
                   13680: =item *
                   13681: 
1.620     albertel 13682: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13683: 
                   13684: =item *
                   13685: 
1.243     albertel 13686: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13687: 
                   13688: =item *
                   13689: 
1.243     albertel 13690: 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 13691: 
                   13692: =item *
                   13693: 
1.243     albertel 13694: 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 13695: 
                   13696: =item *
                   13697: 
1.243     albertel 13698: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13699: 
                   13700: =item *
                   13701: 
1.243     albertel 13702: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13703: forcing spreadsheet to reevaluate the resource scores next time.
                   13704: 
1.1172.2.13  raeburn  13705: =item *
                   13706: 
                   13707: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13708: when viewing in course context.
                   13709: 
                   13710:  input: six args -- filename (decluttered), course number, course domain,
                   13711:                     url, symb (if registered) and group (if this is a
                   13712:                     group item -- e.g., bulletin board, group page etc.).
                   13713: 
                   13714:  output: array of five scalars --
                   13715:          $cfile -- url for file editing if editable on current server
                   13716:          $home -- homeserver of resource (i.e., for author if published,
                   13717:                                           or course if uploaded.).
                   13718:          $switchserver --  1 if server switch will be needed.
                   13719:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13720:          $forceview -- 1 if icon/link should be to go to view mode
                   13721: 
                   13722: =item *
                   13723: 
                   13724: is_course_upload($file,$cnum,$cdom)
                   13725: 
                   13726: Used in course context to determine if current file was uploaded to
                   13727: the course (i.e., would be found in /userfiles/docs on the course's
                   13728: homeserver.
                   13729: 
                   13730:   input: 3 args -- filename (decluttered), course number and course domain.
                   13731:   output: boolean -- 1 if file was uploaded.
                   13732: 
1.243     albertel 13733: =back
                   13734: 
                   13735: =head2 Storing/Retreiving Data
                   13736: 
                   13737: =over 4
1.191     harris41 13738: 
                   13739: =item *
                   13740: 
1.1172.2.64  raeburn  13741: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   13742: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13743: the remaining args aren't required and if they aren't passed or are '' they will
                   13744: be derived from the env (with the exception of $laststore, which is an
                   13745: optional arg used when a user's submission is stored in grading).
                   13746: $laststore is $version=$timestamp, where $version is the most recent version
                   13747: number retrieved for the corresponding $symb in the $namespace db file, and
                   13748: $timestamp is the timestamp for that transaction (UNIX time).
                   13749: $laststore is currently only passed when cstore() is called by
                   13750: structuretags::finalize_storage().
1.191     harris41 13751: 
                   13752: =item *
                   13753: 
1.1172.2.64  raeburn  13754: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   13755: but uses critical subroutine
1.191     harris41 13756: 
                   13757: =item *
                   13758: 
1.243     albertel 13759: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13760: all args are optional
1.191     harris41 13761: 
                   13762: =item *
                   13763: 
1.717     albertel 13764: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13765: dumps the complete (or key matching regexp) namespace into a hash
                   13766: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13767: normally &store()ed into
                   13768: 
                   13769: $range should be either an integer '100' (give me the first 100
                   13770:                                            matching records)
                   13771:               or be  two integers sperated by a - with no spaces
                   13772:                  '30-50' (give me the 30th through the 50th matching
                   13773:                           records)
                   13774: 
                   13775: 
                   13776: =item *
                   13777: 
1.1172.2.59  raeburn  13778: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 13779: replaces a &store() version of data with a replacement set of data
                   13780: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  13781: reference. If $tolog is true, the transaction is logged in the courselog
                   13782: with an action=PUTSTORE.
1.717     albertel 13783: 
                   13784: =item *
                   13785: 
1.243     albertel 13786: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13787: works very similar to store/cstore, but all data is stored in a
                   13788: temporary location and can be reset using tmpreset, $storehash should
                   13789: be a hash reference, returns nothing on success
1.191     harris41 13790: 
                   13791: =item *
                   13792: 
1.243     albertel 13793: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13794: similar to restore, but all data is stored in a temporary location and
                   13795: can be reset using tmpreset. Returns a hash of values on success,
                   13796: error string otherwise.
1.191     harris41 13797: 
                   13798: =item *
                   13799: 
1.243     albertel 13800: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13801: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13802: 
                   13803: =item *
                   13804: 
1.243     albertel 13805: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13806: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13807: 
                   13808: =item *
                   13809: 
1.243     albertel 13810: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13811: namesp ($udom and $uname are optional)
1.191     harris41 13812: 
                   13813: =item *
                   13814: 
1.702     albertel 13815: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13816: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13817: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13818: 
1.702     albertel 13819: $range should be either an integer '100' (give me the first 100
                   13820:                                            matching records)
                   13821:               or be  two integers sperated by a - with no spaces
                   13822:                  '30-50' (give me the 30th through the 50th matching
                   13823:                           records)
1.449     matthew  13824: =item *
                   13825: 
                   13826: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13827: $store can be a scalar, an array reference, or if the amount to be 
                   13828: incremented is > 1, a hash reference.
                   13829: 
                   13830: ($udom and $uname are optional)
1.191     harris41 13831: 
                   13832: =item *
                   13833: 
1.243     albertel 13834: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13835: ($udom and $uname are optional)
1.191     harris41 13836: 
                   13837: =item *
                   13838: 
1.243     albertel 13839: cput($namespace,$storehash,$udom,$uname) : critical put
                   13840: ($udom and $uname are optional)
1.191     harris41 13841: 
                   13842: =item *
                   13843: 
1.748     albertel 13844: newput($namespace,$storehash,$udom,$uname) :
                   13845: 
                   13846: Attempts to store the items in the $storehash, but only if they don't
                   13847: currently exist, if this succeeds you can be certain that you have 
                   13848: successfully created a new key value pair in the $namespace db.
                   13849: 
                   13850: 
                   13851: Args:
                   13852:  $namespace: name of database to store values to
                   13853:  $storehash: hashref to store to the db
                   13854:  $udom: (optional) domain of user containing the db
                   13855:  $uname: (optional) name of user caontaining the db
                   13856: 
                   13857: Returns:
                   13858:  'ok' -> succeeded in storing all keys of $storehash
                   13859:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13860:                         least <key> already existed in the db (other
                   13861:                         requested keys may also already exist)
1.967     bisitz   13862:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13863:  'con_lost' -> unable to contact request server
                   13864:  'refused' -> action was not allowed by remote machine
                   13865: 
                   13866: 
                   13867: =item *
                   13868: 
1.243     albertel 13869: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13870: reference filled in from namesp (encrypts the return communication)
                   13871: ($udom and $uname are optional)
1.191     harris41 13872: 
                   13873: =item *
                   13874: 
1.243     albertel 13875: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13876: critical subroutine
                   13877: 
1.806     raeburn  13878: =item *
                   13879: 
1.860     raeburn  13880: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13881: array reference filled in from namespace found in domain level on either
                   13882: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13883: 
                   13884: =item *
                   13885: 
1.860     raeburn  13886: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13887: domain level either on specified domain server ($uhome) or primary domain 
                   13888: server ($udom and $uhome are optional)
1.806     raeburn  13889: 
1.943     raeburn  13890: =item * 
                   13891: 
1.1172.2.35  raeburn  13892: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   13893: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13894: the target domain.
                   13895: 
                   13896: May also include additional key => value pairs for the following groups:
                   13897: 
                   13898: =over
                   13899: 
                   13900: =item
                   13901: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13902: 
                   13903: =over
                   13904: 
                   13905: =item defaultquota, authorquota
                   13906: 
                   13907: =back
                   13908: 
                   13909: =item
                   13910: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13911: portfolio for users).
                   13912: 
                   13913: =over
                   13914: 
                   13915: =item
                   13916: aboutme, blog, webdav, portfolio
                   13917: 
                   13918: =back
                   13919: 
                   13920: =item
                   13921: requestcourses: ability to request courses, and how requests are processed.
                   13922: 
                   13923: =over
                   13924: 
                   13925: =item
1.1172.2.37  raeburn  13926: official, unofficial, community, textbook
1.1172.2.35  raeburn  13927: 
                   13928: =back
                   13929: 
                   13930: =item
                   13931: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13932: 
                   13933: =over
                   13934: 
                   13935: =item
1.1172.2.44  raeburn  13936: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  13937: 
                   13938: =back
                   13939: 
                   13940: =item
                   13941: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13942: for course's uploaded content.
                   13943: 
                   13944: =over
                   13945: 
                   13946: =item
1.1172.2.68  raeburn  13947: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   13948: communityquota, textbookquota
1.1172.2.35  raeburn  13949: 
                   13950: =back
                   13951: 
                   13952: =item
                   13953: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13954: on your servers.
                   13955: 
                   13956: =over
                   13957: 
                   13958: =item
                   13959: remotesessions, hostedsessions
                   13960: 
                   13961: =back
                   13962: 
                   13963: =back
                   13964: 
                   13965: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13966: utility to create a configuration.db file on a domain's primary library server
                   13967: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13968: -- corresponding values are authentication type (internal, krb4, krb5,
                   13969: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   13970: will be available. Values are retrieved from cache (if current), unless the
                   13971: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13972: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13973: 
                   13974: Typical usage:
1.943     raeburn  13975: 
1.1172.2.35  raeburn  13976: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13977: 
1.243     albertel 13978: =back
                   13979: 
                   13980: =head2 Network Status Functions
                   13981: 
                   13982: =over 4
1.191     harris41 13983: 
                   13984: =item *
                   13985: 
1.1137    raeburn  13986: dirlist() : return directory list based on URI (first arg).
                   13987: 
                   13988: Inputs: 1 required, 5 optional.
                   13989: 
                   13990: =over
                   13991: 
                   13992: =item 
                   13993: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13994: 
                   13995: =item
                   13996: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13997: 
                   13998: =item
                   13999: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14000: 
                   14001: =item
                   14002: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14003: 
                   14004: =item
                   14005: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14006: 
                   14007: =item 
                   14008: $alternateRoot - path to prepend in place of path from $uri.
                   14009: 
                   14010: =back
                   14011: 
                   14012: Returns: Array of up to two items.
                   14013: 
                   14014: =over
                   14015: 
                   14016: a reference to an array of files/subdirectories
                   14017: 
                   14018: =over
                   14019: 
                   14020: Each element in the array of files/subdirectories is a & separated list of
                   14021: item name and the result of running stat on the item.  If dirlist was requested
                   14022: for a file instead of a directory, the item name will be ''. For a directory 
                   14023: listing, if the item is a metadata file, the element will end &N&M 
                   14024: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14025: default copyright set (1).  
                   14026: 
                   14027: =back
                   14028: 
                   14029: a scalar containing error condition (if encountered).
                   14030: 
                   14031: =over
                   14032: 
                   14033: =item 
                   14034: no_host (no homeserver identified for $username:$domain).
                   14035: 
                   14036: =item 
                   14037: no_such_host (server contacted for listing not identified as valid host).
                   14038: 
                   14039: =item 
                   14040: con_lost (connection to remote server failed).
                   14041: 
                   14042: =item 
                   14043: refused (invalid $username:$domain received on lond side).
                   14044: 
                   14045: =item 
                   14046: no_such_dir (directory at specified path on lond side does not exist). 
                   14047: 
                   14048: =item 
                   14049: empty (directory at specified path on lond side is empty).
                   14050: 
                   14051: =over
                   14052: 
                   14053: This is currently not encountered because the &ls3, &ls2, 
                   14054: &ls (_handler) routines on the lond side do not filter out
                   14055: . and .. from a directory listing. 
                   14056: 
                   14057: =back
                   14058: 
                   14059: =back
                   14060: 
                   14061: =back
1.191     harris41 14062: 
                   14063: =item *
                   14064: 
1.243     albertel 14065: spareserver() : find server with least workload from spare.tab
                   14066: 
1.986     foxr     14067: 
                   14068: =item *
                   14069: 
                   14070: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14071: if there is no corresponding loncapa host.
                   14072: 
1.243     albertel 14073: =back
                   14074: 
1.986     foxr     14075: 
1.243     albertel 14076: =head2 Apache Request
                   14077: 
                   14078: =over 4
1.191     harris41 14079: 
                   14080: =item *
                   14081: 
1.243     albertel 14082: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14083: localhost, posts hash
                   14084: 
                   14085: =back
                   14086: 
                   14087: =head2 Data to String to Data
                   14088: 
                   14089: =over 4
1.191     harris41 14090: 
                   14091: =item *
                   14092: 
1.243     albertel 14093: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14094: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14095: 
                   14096: =item *
                   14097: 
1.243     albertel 14098: hashref2str($hashref) : convert a hashref into a string complete with
                   14099: escaping and '=' and '&' separators, supports elements that are
                   14100: arrayrefs and hashrefs
1.191     harris41 14101: 
                   14102: =item *
                   14103: 
1.243     albertel 14104: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14105: with escaping and '&' separators, supports elements that are arrayrefs
                   14106: and hashrefs
1.191     harris41 14107: 
                   14108: =item *
                   14109: 
1.243     albertel 14110: str2hash($string) : convert string to hash using unescaping and
                   14111: splitting on '=' and '&', supports elements that are arrayrefs and
                   14112: hashrefs
1.191     harris41 14113: 
                   14114: =item *
                   14115: 
1.243     albertel 14116: str2array($string) : convert string to hash using unescaping and
                   14117: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14118: 
                   14119: =back
                   14120: 
                   14121: =head2 Logging Routines
                   14122: 
                   14123: 
                   14124: These routines allow one to make log messages in the lonnet.log and
                   14125: lonnet.perm logfiles.
1.191     harris41 14126: 
1.1119    foxr     14127: =over 4
                   14128: 
1.191     harris41 14129: =item *
                   14130: 
1.243     albertel 14131: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14132: 
                   14133: =item *
                   14134: 
1.243     albertel 14135: logthis() : append message to the normal lonnet.log file, it gets
                   14136: preiodically rolled over and deleted.
1.191     harris41 14137: 
                   14138: =item *
                   14139: 
1.243     albertel 14140: logperm() : append a permanent message to lonnet.perm.log, this log
                   14141: file never gets deleted by any automated portion of the system, only
                   14142: messages of critical importance should go in here.
                   14143: 
1.1119    foxr     14144: 
1.243     albertel 14145: =back
                   14146: 
                   14147: =head2 General File Helper Routines
                   14148: 
                   14149: =over 4
1.191     harris41 14150: 
                   14151: =item *
                   14152: 
1.481     raeburn  14153: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14154: (a) files in /uploaded
                   14155:   (i) If a local copy of the file exists - 
                   14156:       compares modification date of local copy with last-modified date for 
                   14157:       definitive version stored on home server for course. If local copy is 
                   14158:       stale, requests a new version from the home server and stores it. 
                   14159:       If the original has been removed from the home server, then local copy 
                   14160:       is unlinked.
                   14161:   (ii) If local copy does not exist -
                   14162:       requests the file from the home server and stores it. 
                   14163:   
                   14164:   If $caller is 'uploadrep':  
                   14165:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14166:     for request for files originally uploaded via DOCS. 
                   14167:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14168:   
                   14169:   Otherwise:
                   14170:      This indicates a call from the content generation phase of the request.
                   14171:      -  returns the entire contents of the file or -1.
                   14172:      
                   14173: (b) files in /res
                   14174:    - returns the entire contents of a file or -1; 
                   14175:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14176: 
1.712     albertel 14177: 
                   14178: =item *
                   14179: 
                   14180: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14181:                   reference
                   14182: 
                   14183: returns either a stat() list of data about the file or an empty list
                   14184: if the file doesn't exist or couldn't find out about it (connection
                   14185: problems or user unknown)
                   14186: 
1.191     harris41 14187: =item *
                   14188: 
1.243     albertel 14189: filelocation($dir,$file) : returns file system location of a file
                   14190: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14191: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14192: and a file of ../bob will become /a/bob)
1.191     harris41 14193: 
                   14194: =item *
                   14195: 
                   14196: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14197: filelocation except for hrefs
                   14198: 
                   14199: =item *
                   14200: 
1.1172.2.49  raeburn  14201: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14202: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14203: 
1.243     albertel 14204: =back
                   14205: 
1.608     albertel 14206: =head2 Usererfile file routines (/uploaded*)
                   14207: 
                   14208: =over 4
                   14209: 
                   14210: =item *
                   14211: 
                   14212: userfileupload(): main rotine for putting a file in a user or course's
                   14213:                   filespace, arguments are,
                   14214: 
1.620     albertel 14215:  formname - required - this is the name of the element in $env where the
1.608     albertel 14216:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14217:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14218:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14219:  context - if coursedoc, store the file in the course of the active role
                   14220:              of the current user; 
                   14221:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14222:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14223:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14224:          if undefined, it will be placed in "unknown"
                   14225: 
                   14226:  (This routine calls clean_filename() to remove any dangerous
                   14227:  characters from the filename, and then calls finuserfileupload() to
                   14228:  complete the transaction)
                   14229: 
                   14230:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14231:  and /adm/notfound.html if unsuccessful
                   14232: 
                   14233: =item *
                   14234: 
                   14235: clean_filename(): routine for cleaing a filename up for storage in
                   14236:                  userfile space, argument is:
                   14237: 
                   14238:  filename - proposed filename
                   14239: 
                   14240: returns: the new clean filename
                   14241: 
                   14242: =item *
                   14243: 
1.1090    raeburn  14244: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14245: userspace, probably shouldn't be called directly
                   14246: 
                   14247:   docuname: username or courseid of destination for the file
                   14248:   docudom: domain of user/course of destination for the file
                   14249:   formname: same as for userfileupload()
1.1090    raeburn  14250:   fname: filename (including subdirectories) for the file
                   14251:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14252:   allfiles: reference to hash used to store objects found by parser
                   14253:   codebase: reference to hash used for codebases of java objects found by parser
                   14254:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14255:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14256:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14257:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14258:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14259:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14260:   mimetype: reference to scalar to accommodate mime type determined
                   14261:             from File::MMagic if $parser = parse.
1.608     albertel 14262: 
                   14263:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14264:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14265:  was 'overwrite').
                   14266:  
1.608     albertel 14267: 
                   14268: =item *
                   14269: 
                   14270: renameuserfile(): renames an existing userfile to a new name
                   14271: 
                   14272:   Args:
                   14273:    docuname: username or courseid of destination for the file
                   14274:    docudom: domain of user/course of destination for the file
                   14275:    old: current file name (including any subdirs under userfiles)
                   14276:    new: desired file name (including any subdirs under userfiles)
                   14277: 
                   14278: =item *
                   14279: 
                   14280: mkdiruserfile(): creates a directory is a userfiles dir
                   14281: 
                   14282:   Args:
                   14283:    docuname: username or courseid of destination for the file
                   14284:    docudom: domain of user/course of destination for the file
                   14285:    dir: dir to create (including any subdirs under userfiles)
                   14286: 
                   14287: =item *
                   14288: 
                   14289: removeuserfile(): removes a file that exists in userfiles
                   14290: 
                   14291:   Args:
                   14292:    docuname: username or courseid of destination for the file
                   14293:    docudom: domain of user/course of destination for the file
                   14294:    fname: filname to delete (including any subdirs under userfiles)
                   14295: 
                   14296: =item *
                   14297: 
                   14298: removeuploadedurl(): convience function for removeuserfile()
                   14299: 
                   14300:   Args:
                   14301:    url:  a full /uploaded/... url to delete
                   14302: 
1.747     albertel 14303: =item * 
                   14304: 
                   14305: get_portfile_permissions():
                   14306:   Args:
                   14307:     domain: domain of user or course contain the portfolio files
                   14308:     user: name of user or num of course contain the portfolio files
                   14309:   Returns:
                   14310:     hashref of a dump of the proper file_permissions.db
                   14311:    
                   14312: 
                   14313: =item * 
                   14314: 
                   14315: get_access_controls():
                   14316: 
                   14317: Args:
                   14318:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14319:   group: (optional) the group you want the files associated with
                   14320:   file: (optional) the file you want access info on
                   14321: 
                   14322: Returns:
1.749     raeburn  14323:     a hash (keys are file names) of hashes containing
                   14324:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14325:         values are XML containing access control settings (see below) 
1.747     albertel 14326: 
                   14327: Internal notes:
                   14328: 
1.749     raeburn  14329:  access controls are stored in file_permissions.db as key=value pairs.
                   14330:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14331:         where scope -> public,guest,course,group,domains or users.
                   14332:               end -> UNIX time for end of access (0 -> no end date)
                   14333:               start -> UNIX time for start of access
                   14334: 
                   14335:     value -> XML description of access control
                   14336:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14337:             <start></start>
                   14338:             <end></end>
                   14339: 
                   14340:             <password></password>  for scope type = guest
                   14341: 
                   14342:             <domain></domain>     for scope type = course or group
                   14343:             <number></number>
                   14344:             <roles id="">
                   14345:              <role></role>
                   14346:              <access></access>
                   14347:              <section></section>
                   14348:              <group></group>
                   14349:             </roles>
                   14350: 
                   14351:             <dom></dom>         for scope type = domains
                   14352: 
                   14353:             <users>             for scope type = users
                   14354:              <user>
                   14355:               <uname></uname>
                   14356:               <udom></udom>
                   14357:              </user>
                   14358:             </users>
                   14359:            </scope> 
                   14360:               
                   14361:  Access data is also aggregated for each file in an additional key=value pair:
                   14362:  key -> path to file/file_name\0accesscontrol 
                   14363:  value -> reference to hash
                   14364:           hash contains key = value pairs
                   14365:           where key = uniqueID:scope_end_start
                   14366:                 value = UNIX time record was last updated
                   14367: 
                   14368:           Used to improve speed of look-ups of access controls for each file.  
                   14369:  
                   14370:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14371: 
1.1172.2.13  raeburn  14372: =item *
                   14373: 
1.749     raeburn  14374: modify_access_controls():
                   14375: 
                   14376: Modifies access controls for a portfolio file
                   14377: Args
                   14378: 1. file name
                   14379: 2. reference to hash of required changes,
                   14380: 3. domain
                   14381: 4. username
                   14382:   where domain,username are the domain of the portfolio owner 
                   14383:   (either a user or a course) 
                   14384: 
                   14385: Returns:
                   14386: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14387: 2. result of deletions ('ok' or 'error', with error message).
                   14388: 3. reference to hash of any new or updated access controls.
                   14389: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14390:    key = integer (inbound ID)
1.1172.2.13  raeburn  14391:    value = uniqueID
                   14392: 
                   14393: =item *
                   14394: 
                   14395: get_timebased_id():
                   14396: 
                   14397: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14398: course via the Course Editor (e.g., folders, composite pages,
                   14399: group bulletin boards).
                   14400: 
                   14401: Args: (first three required; six others optional)
                   14402: 
                   14403: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14404:    docssequence, or name of group
                   14405: 
                   14406: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14407:    e.g., num, boardids
                   14408: 
                   14409: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14410:    file will be named nohist_namespace.db
                   14411: 
                   14412: 4. cdom: domain of course; default is current course domain from %env
                   14413: 
                   14414: 5. cnum: course number; default is current course number from %env
                   14415: 
                   14416: 6. idtype: set to concat if an additional digit is to be appended to the
                   14417:    unix timestamp to form the suffix, if the plain timestamp is already
                   14418:    in use.  Default is to not do this, but simply increment the unix
                   14419:    timestamp by 1 until a unique key is obtained.
                   14420: 
                   14421: 7. who: holder of locking key; defaults to user:domain for user.
                   14422: 
                   14423: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14424:    retrying); default is 3.
                   14425: 
                   14426: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14427: 
                   14428: Returns:
                   14429: 
                   14430: 1. suffix obtained (numeric)
                   14431: 
                   14432: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14433: 
                   14434: 3. error: contains (localized) error message if an error occurred.
                   14435: 
1.747     albertel 14436: 
1.608     albertel 14437: =back
                   14438: 
1.243     albertel 14439: =head2 HTTP Helper Routines
                   14440: 
                   14441: =over 4
                   14442: 
1.191     harris41 14443: =item *
                   14444: 
                   14445: escape() : unpack non-word characters into CGI-compatible hex codes
                   14446: 
                   14447: =item *
                   14448: 
                   14449: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14450: 
1.243     albertel 14451: =back
                   14452: 
                   14453: =head1 PRIVATE SUBROUTINES
                   14454: 
                   14455: =head2 Underlying communication routines (Shouldn't call)
                   14456: 
                   14457: =over 4
                   14458: 
                   14459: =item *
                   14460: 
                   14461: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14462: 
                   14463: =item *
                   14464: 
                   14465: reply() : uses subreply to send a message to remote machine, logs all failures
                   14466: 
                   14467: =item *
                   14468: 
                   14469: critical() : passes a critical message to another server; if cannot
                   14470: get through then place message in connection buffer directory and
                   14471: returns con_delayed, if incapable of saving message, returns
                   14472: con_failed
                   14473: 
                   14474: =item *
                   14475: 
                   14476: reconlonc() : tries to reconnect lonc client processes.
                   14477: 
                   14478: =back
                   14479: 
                   14480: =head2 Resource Access Logging
                   14481: 
                   14482: =over 4
                   14483: 
                   14484: =item *
                   14485: 
                   14486: flushcourselogs() : flush (save) buffer logs and access logs
                   14487: 
                   14488: =item *
                   14489: 
                   14490: courselog($what) : save message for course in hash
                   14491: 
                   14492: =item *
                   14493: 
                   14494: courseacclog($what) : save message for course using &courselog().  Perform
                   14495: special processing for specific resource types (problems, exams, quizzes, etc).
                   14496: 
1.191     harris41 14497: =item *
                   14498: 
                   14499: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14500: as a PerlChildExitHandler
1.243     albertel 14501: 
                   14502: =back
                   14503: 
                   14504: =head2 Other
                   14505: 
                   14506: =over 4
                   14507: 
                   14508: =item *
                   14509: 
                   14510: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14511: 
                   14512: =back
                   14513: 
                   14514: =cut
1.877     foxr     14515: 

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