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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.57! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.56 2014/10/24 00:37:15 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1172.2.36  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   100: use LONCAPA::Lond;
1.1117    foxr      101: 
1.1090    raeburn   102: use File::Copy;
1.676     albertel  103: 
1.195     www       104: my $readit;
1.550     foxr      105: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  106: 
1.619     albertel  107: require Exporter;
                    108: 
                    109: our @ISA = qw (Exporter);
                    110: our @EXPORT = qw(%env);
                    111: 
1.1172.2.9  raeburn   112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       113: {
                    114:     my $logid;
1.1172.2.9  raeburn   115:     sub write_log {
                    116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    117:         if ($context eq 'course') {
                    118:             if (($cnum eq '') || ($cdom eq '')) {
                    119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    121:             }
1.957     raeburn   122:         }
1.1172.2.13  raeburn   123: 	$logid ++;
1.957     raeburn   124:         my $now = time();
                    125: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   126:         my $logentry = {
                    127:                          $id => {
                    128:                                   'exe_uname' => $env{'user.name'},
                    129:                                   'exe_udom'  => $env{'user.domain'},
                    130:                                   'exe_time'  => $now,
                    131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    132:                                   'delflag'   => $delflag,
                    133:                                   'logentry'  => $storehash,
                    134:                                   'uname'     => $uname,
                    135:                                   'udom'      => $udom,
                    136:                                 }
                    137:                        };
                    138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       139:     }
                    140: }
1.1       albertel  141: 
1.163     harris41  142: sub logtouch {
                    143:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  144:     unless (-e "$execdir/logs/lonnet.log") {	
                    145: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  146: 	close $fh;
                    147:     }
                    148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    150: }
                    151: 
1.1       albertel  152: sub logthis {
                    153:     my $message=shift;
                    154:     my $execdir=$perlvar{'lonDaemons'};
                    155:     my $now=time;
                    156:     my $local=localtime($now);
1.448     albertel  157:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    159: 	print $fh $logstring;
1.448     albertel  160: 	close($fh);
                    161:     }
1.1       albertel  162:     return 1;
                    163: }
                    164: 
                    165: sub logperm {
                    166:     my $message=shift;
                    167:     my $execdir=$perlvar{'lonDaemons'};
                    168:     my $now=time;
                    169:     my $local=localtime($now);
1.448     albertel  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    171: 	print $fh "$now:$message:$local\n";
                    172: 	close($fh);
                    173:     }
1.1       albertel  174:     return 1;
                    175: }
                    176: 
1.850     albertel  177: sub create_connection {
1.853     albertel  178:     my ($hostname,$lonid) = @_;
1.851     albertel  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  180: 				     Type    => SOCK_STREAM,
                    181: 				     Timeout => 10);
                    182:     return 0 if (!$client);
1.890     albertel  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  184:     my $result = <$client>;
                    185:     chomp($result);
                    186:     return 1 if ($result eq 'done');
                    187:     return 0;
                    188: }
                    189: 
1.983     raeburn   190: sub get_server_timezone {
                    191:     my ($cnum,$cdom) = @_;
                    192:     my $home=&homeserver($cnum,$cdom);
                    193:     if ($home ne 'no_host') {
                    194:         my $cachetime = 24*3600;
                    195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    196:         if (defined($cached)) {
                    197:             return $timezone;
                    198:         } else {
                    199:             my $timezone = &reply('servertimezone',$home);
                    200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    201:         }
                    202:     }
                    203: }
1.850     albertel  204: 
1.1106    raeburn   205: sub get_server_distarch {
                    206:     my ($lonhost,$ignore_cache) = @_;
                    207:     if (defined($lonhost)) {
                    208:         if (!defined(&hostname($lonhost))) {
                    209:             return;
                    210:         }
                    211:         my $cachetime = 12*3600;
                    212:         if (!$ignore_cache) {
                    213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    214:             if (defined($cached)) {
                    215:                 return $distarch;
                    216:             }
                    217:         }
                    218:         my $rep = &reply('serverdistarch',$lonhost);
                    219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    221:                 $rep eq '') {
                    222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    223:         }
                    224:     }
                    225:     return;
                    226: }
                    227: 
1.993     raeburn   228: sub get_server_loncaparev {
1.1073    raeburn   229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   230:     if (defined($lonhost)) {
                    231:         if (!defined(&hostname($lonhost))) {
                    232:             undef($lonhost);
                    233:         }
                    234:     }
                    235:     if (!defined($lonhost)) {
                    236:         if (defined(&domain($dom,'primary'))) {
                    237:             $lonhost=&domain($dom,'primary');
                    238:             if ($lonhost eq 'no_host') {
                    239:                 undef($lonhost);
                    240:             }
                    241:         }
                    242:     }
                    243:     if (defined($lonhost)) {
1.1073    raeburn   244:         my $cachetime = 12*3600;
                    245:         if (!$ignore_cache) {
                    246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    247:             if (defined($cached)) {
                    248:                 return $loncaparev;
                    249:             }
                    250:         }
                    251:         my ($answer,$loncaparev);
                    252:         my @ids=&current_machine_ids();
                    253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    254:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   256:                 $loncaparev = $1;
                    257:             }
                    258:         } else {
                    259:             $answer = &reply('serverloncaparev',$lonhost);
                    260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    261:                 if ($caller eq 'loncron') {
                    262:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   263:                     $ua->timeout(4);
1.1073    raeburn   264:                     my $protocol = $protocol{$lonhost};
                    265:                     $protocol = 'http' if ($protocol ne 'https');
                    266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    267:                     my $request=new HTTP::Request('GET',$url);
                    268:                     my $response=$ua->request($request);
                    269:                     unless ($response->is_error()) {
                    270:                         my $content = $response->content;
1.1081    raeburn   271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   272:                             $loncaparev = $1;
                    273:                         }
                    274:                     }
                    275:                 } else {
                    276:                     $loncaparev = $loncaparevs{$lonhost};
                    277:                 }
1.1081    raeburn   278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   279:                 $loncaparev = $1;
                    280:             }
1.993     raeburn   281:         }
1.1073    raeburn   282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   283:     }
                    284: }
                    285: 
1.1074    raeburn   286: sub get_server_homeID {
                    287:     my ($hostname,$ignore_cache,$caller) = @_;
                    288:     unless ($ignore_cache) {
                    289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    290:         if (defined($cached)) {
                    291:             return $serverhomeID;
                    292:         }
                    293:     }
                    294:     my $cachetime = 12*3600;
                    295:     my $serverhomeID;
                    296:     if ($caller eq 'loncron') { 
                    297:         my @machine_ids = &machine_ids($hostname);
                    298:         foreach my $id (@machine_ids) {
                    299:             my $response = &reply('serverhomeID',$id);
                    300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    301:                 $serverhomeID = $response;
                    302:                 last;
                    303:             }
                    304:         }
                    305:         if ($serverhomeID eq '') {
                    306:             $serverhomeID = $machine_ids[-1];
                    307:         }
                    308:     } else {
                    309:         $serverhomeID = $serverhomeIDs{$hostname};
                    310:     }
                    311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    312: }
                    313: 
1.1121    raeburn   314: sub get_remote_globals {
                    315:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   316:     my ($result,%returnhash,%whatneeded);
                    317:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   318:         foreach my $what (sort(keys(%{$whathash}))) {
                    319:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   320:             my ($response,$cached);
1.1121    raeburn   321:             unless ($ignore_cache) {
1.1125    raeburn   322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   323:             }
                    324:             if (defined($cached)) {
1.1125    raeburn   325:                 $returnhash{$what} = $response;
1.1121    raeburn   326:             } else {
1.1125    raeburn   327:                 $whatneeded{$what} = 1;
1.1121    raeburn   328:             }
                    329:         }
1.1125    raeburn   330:         if (keys(%whatneeded) == 0) {
                    331:             $result = 'ok';
                    332:         } else {
1.1121    raeburn   333:             my $requested = &freeze_escape(\%whatneeded);
                    334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    336:                 ($rep eq 'unknown_cmd')) {
                    337:                 $result = $rep;
                    338:             } else {
                    339:                 $result = 'ok';
1.1121    raeburn   340:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   341:                 foreach my $item (@pairs) {
                    342:                     my ($key,$value)=split(/=/,$item,2);
                    343:                     my $what = &unescape($key);
                    344:                     my $hashid = $lonhost.'-'.$what;
                    345:                     $returnhash{$what}=&thaw_unescape($value);
                    346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   347:                 }
                    348:             }
                    349:         }
                    350:     }
1.1125    raeburn   351:     return ($result,\%returnhash);
1.1121    raeburn   352: }
                    353: 
1.1124    raeburn   354: sub remote_devalidate_cache {
1.1172.2.35  raeburn   355:     my ($lonhost,$cachekeys) = @_;
                    356:     my $items;
                    357:     return unless (ref($cachekeys) eq 'ARRAY');
                    358:     my $cachestr = join('&',@{$cachekeys});
                    359:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   360: }
                    361: 
1.1       albertel  362: # -------------------------------------------------- Non-critical communication
                    363: sub subreply {
                    364:     my ($cmd,$server)=@_;
1.838     albertel  365:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      366:     #
                    367:     #  With loncnew process trimming, there's a timing hole between lonc server
                    368:     #  process exit and the master server picking up the listen on the AF_UNIX
                    369:     #  socket.  In that time interval, a lock file will exist:
                    370: 
                    371:     my $lockfile=$peerfile.".lock";
                    372:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    373: 	sleep(1);
                    374:     }
                    375:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      376:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      377:     #
1.550     foxr      378:     #   We'll give the connection a few tries before abandoning it.  If
                    379:     #   connection is not possible, we'll con_lost back to the client.
                    380:     #   
                    381:     my $client;
                    382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    384: 				      Type    => SOCK_STREAM,
                    385: 				      Timeout => 10);
1.869     albertel  386: 	if ($client) {
1.550     foxr      387: 	    last;		# Connected!
1.850     albertel  388: 	} else {
1.853     albertel  389: 	    &create_connection(&hostname($server),$server);
1.550     foxr      390: 	}
1.850     albertel  391:         sleep(1);		# Try again later if failed connection.
1.550     foxr      392:     }
                    393:     my $answer;
                    394:     if ($client) {
1.704     albertel  395: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      396: 	$answer=<$client>;
                    397: 	if (!$answer) { $answer="con_lost"; }
                    398: 	chomp($answer);
                    399:     } else {
                    400: 	$answer = 'con_lost';	# Failed connection.
                    401:     }
1.1       albertel  402:     return $answer;
                    403: }
                    404: 
                    405: sub reply {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  408:     my $answer=subreply($cmd,$server);
1.65      www       409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  410:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       411:                 " $cmd to $server returned $answer</font>");
                    412:     }
1.1       albertel  413:     return $answer;
                    414: }
                    415: 
                    416: # ----------------------------------------------------------- Send USR1 to lonc
                    417: 
                    418: sub reconlonc {
1.891     albertel  419:     my ($lonid) = @_;
                    420:     my $hostname = &hostname($lonid);
                    421:     if ($lonid) {
                    422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    423: 	if ($hostname && -e $peerfile) {
                    424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    426: 					     Type    => SOCK_STREAM,
                    427: 					     Timeout => 10);
                    428: 	    if ($client) {
                    429: 		print $client ("reset_retries\n");
                    430: 		my $answer=<$client>;
                    431: 		#reset just this one.
                    432: 	    }
                    433: 	}
                    434: 	return;
                    435:     }
                    436: 
1.836     www       437:     &logthis("Trying to reconnect lonc");
1.1       albertel  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  439:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  440: 	my $loncpid=<$fh>;
                    441:         chomp($loncpid);
                    442:         if (kill 0 => $loncpid) {
                    443: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    444:             kill USR1 => $loncpid;
                    445:             sleep 1;
1.836     www       446:          } else {
1.12      www       447: 	    &logthis(
1.672     albertel  448:                "<font color=\"blue\">WARNING:".
1.12      www       449:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  450:         }
                    451:     } else {
1.836     www       452: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  453:     }
                    454: }
                    455: 
                    456: # ------------------------------------------------------ Critical communication
1.12      www       457: 
1.1       albertel  458: sub critical {
                    459:     my ($cmd,$server)=@_;
1.838     albertel  460:     unless (&hostname($server)) {
1.672     albertel  461:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       462:                " Critical message to unknown server ($server)</font>");
                    463:         return 'no_such_host';
                    464:     }
1.1       albertel  465:     my $answer=reply($cmd,$server);
                    466:     if ($answer eq 'con_lost') {
                    467: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  468: 	my $answer=reply($cmd,$server);
1.1       albertel  469:         if ($answer eq 'con_lost') {
                    470:             my $now=time;
                    471:             my $middlename=$cmd;
1.5       www       472:             $middlename=substr($middlename,0,16);
1.1       albertel  473:             $middlename=~s/\W//g;
                    474:             my $dfilename=
1.305     www       475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    476:             $dumpcount++;
1.1       albertel  477:             {
1.448     albertel  478: 		my $dfh;
                    479: 		if (open($dfh,">$dfilename")) {
                    480: 		    print $dfh "$cmd\n"; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
                    484:             sleep 2;
                    485:             my $wcmd='';
                    486:             {
1.448     albertel  487: 		my $dfh;
                    488: 		if (open($dfh,"<$dfilename")) {
                    489: 		    $wcmd=<$dfh>; 
                    490: 		    close($dfh);
                    491: 		}
1.1       albertel  492:             }
                    493:             chomp($wcmd);
1.7       www       494:             if ($wcmd eq $cmd) {
1.672     albertel  495: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       496:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  497:                 &logperm("D:$server:$cmd");
                    498: 	        return 'con_delayed';
                    499:             } else {
1.672     albertel  500:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       501:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  502:                 &logperm("F:$server:$cmd");
                    503:                 return 'con_failed';
                    504:             }
                    505:         }
                    506:     }
                    507:     return $answer;
1.405     albertel  508: }
                    509: 
1.755     albertel  510: # ------------------------------------------- check if return value is an error
                    511: 
                    512: sub error {
                    513:     my ($result) = @_;
1.756     albertel  514:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  515: 	if ($2 == 2) { return undef; }
                    516: 	return $1;
                    517:     }
                    518:     return undef;
                    519: }
                    520: 
1.783     albertel  521: sub convert_and_load_session_env {
                    522:     my ($lonidsdir,$handle)=@_;
                    523:     my @profile;
                    524:     {
1.917     albertel  525: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    526: 	if (!$opened) {
1.915     albertel  527: 	    return 0;
                    528: 	}
1.783     albertel  529: 	flock($idf,LOCK_SH);
                    530: 	@profile=<$idf>;
                    531: 	close($idf);
                    532:     }
                    533:     my %temp_env;
                    534:     foreach my $line (@profile) {
1.786     albertel  535: 	if ($line !~ m/=/) {
                    536: 	    return 0;
                    537: 	}
1.783     albertel  538: 	chomp($line);
                    539: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    540: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    541:     }
                    542:     unlink("$lonidsdir/$handle.id");
                    543:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    544: 	    0640)) {
                    545: 	%disk_env = %temp_env;
                    546: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    547: 	untie(%disk_env);
                    548:     }
1.786     albertel  549:     return 1;
1.783     albertel  550: }
                    551: 
1.374     www       552: # ------------------------------------------- Transfer profile into environment
1.780     albertel  553: my $env_loaded;
                    554: sub transfer_profile_to_env {
1.788     albertel  555:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    556:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       557: 
1.720     albertel  558:     if (!defined($lonidsdir)) {
                    559: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    560:     }
                    561:     if (!defined($handle)) {
                    562:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    563:     }
                    564: 
1.786     albertel  565:     my $convert;
                    566:     {
1.917     albertel  567:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    568: 	if (!$opened) {
1.915     albertel  569: 	    return;
                    570: 	}
1.786     albertel  571: 	flock($idf,LOCK_SH);
                    572: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    573: 		&GDBM_READER(),0640)) {
                    574: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    575: 	    untie(%disk_env);
                    576: 	} else {
                    577: 	    $convert = 1;
                    578: 	}
                    579:     }
                    580:     if ($convert) {
                    581: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    582: 	    &logthis("Failed to load session, or convert session.");
                    583: 	}
1.374     www       584:     }
1.783     albertel  585: 
1.786     albertel  586:     my %remove;
1.783     albertel  587:     while ( my $envname = each(%env) ) {
1.433     matthew   588:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    589:             if ($time < time-300) {
1.783     albertel  590:                 $remove{$key}++;
1.433     matthew   591:             }
                    592:         }
                    593:     }
1.783     albertel  594: 
1.619     albertel  595:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  596:     $env_loaded=1;
1.783     albertel  597:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   598:         &delenv($expired_key);
1.374     www       599:     }
1.1       albertel  600: }
                    601: 
1.916     albertel  602: # ---------------------------------------------------- Check for valid session 
                    603: sub check_for_valid_session {
1.1172.2.36  raeburn   604:     my ($r,$name,$userhashref) = @_;
1.916     albertel  605:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   606:     if ($name eq '') {
                    607:         $name = 'lonID';
                    608:     }
                    609:     my $lonid=$cookies{$name};
1.916     albertel  610:     return undef if (!$lonid);
                    611: 
                    612:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   613:     my $lonidsdir;
                    614:     if ($name eq 'lonDAV') {
                    615:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    616:     } else {
                    617:         $lonidsdir=$r->dir_config('lonIDsDir');
                    618:     }
1.916     albertel  619:     return undef if (!-e "$lonidsdir/$handle.id");
                    620: 
1.917     albertel  621:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    622:     return undef if (!$opened);
1.916     albertel  623: 
                    624:     flock($idf,LOCK_SH);
                    625:     my %disk_env;
                    626:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    627: 	    &GDBM_READER(),0640)) {
                    628: 	return undef;	
                    629:     }
                    630: 
                    631:     if (!defined($disk_env{'user.name'})
                    632: 	|| !defined($disk_env{'user.domain'})) {
                    633: 	return undef;
                    634:     }
1.1172.2.18  raeburn   635: 
1.1172.2.36  raeburn   636:     if (ref($userhashref) eq 'HASH') {
                    637:         $userhashref->{'name'} = $disk_env{'user.name'};
                    638:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   639:     }
                    640: 
1.916     albertel  641:     return $handle;
                    642: }
                    643: 
1.830     albertel  644: sub timed_flock {
                    645:     my ($file,$lock_type) = @_;
                    646:     my $failed=0;
                    647:     eval {
                    648: 	local $SIG{__DIE__}='DEFAULT';
                    649: 	local $SIG{ALRM}=sub {
                    650: 	    $failed=1;
                    651: 	    die("failed lock");
                    652: 	};
                    653: 	alarm(13);
                    654: 	flock($file,$lock_type);
                    655: 	alarm(0);
                    656:     };
                    657:     if ($failed) {
                    658: 	return undef;
                    659:     } else {
                    660: 	return 1;
                    661:     }
                    662: }
                    663: 
1.5       www       664: # ---------------------------------------------------------- Append Environment
                    665: 
                    666: sub appenv {
1.949     raeburn   667:     my ($newenv,$roles) = @_;
                    668:     if (ref($newenv) eq 'HASH') {
                    669:         foreach my $key (keys(%{$newenv})) {
                    670:             my $refused = 0;
                    671: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    672:                 $refused = 1;
                    673:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   674:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   675:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    676:                         $refused = 0;
                    677:                     }
                    678:                 }
                    679:             }
                    680:             if ($refused) {
                    681:                 &logthis("<font color=\"blue\">WARNING: ".
                    682:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    683:                          .'</font>');
                    684: 	        delete($newenv->{$key});
                    685:             } else {
                    686:                 $env{$key}=$newenv->{$key};
                    687:             }
                    688:         }
                    689:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    690:         if ($opened
                    691: 	    && &timed_flock($env_file,LOCK_EX)
                    692: 	    &&
                    693: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    694: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    695: 	    while (my ($key,$value) = each(%{$newenv})) {
                    696: 	        $disk_env{$key} = $value;
                    697: 	    }
                    698: 	    untie(%disk_env);
1.35      www       699:         }
1.191     harris41  700:     }
1.56      www       701:     return 'ok';
                    702: }
                    703: # ----------------------------------------------------- Delete from Environment
                    704: 
                    705: sub delenv {
1.1104    raeburn   706:     my ($delthis,$regexp,$roles) = @_;
                    707:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    708:         my $refused = 1;
                    709:         if (ref($roles) eq 'ARRAY') {
                    710:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    711:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    712:                 $refused = 0;
                    713:             }
                    714:         }
                    715:         if ($refused) {
                    716:             &logthis("<font color=\"blue\">WARNING: ".
                    717:                      "Attempt to delete from environment ".$delthis);
                    718:             return 'error';
                    719:         }
1.56      www       720:     }
1.917     albertel  721:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    722:     if ($opened
1.915     albertel  723: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  724: 	&&
                    725: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    726: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  727: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   728: 	    if ($regexp) {
                    729:                 if ($key=~/^$delthis/) {
                    730:                     delete($env{$key});
                    731:                     delete($disk_env{$key});
                    732:                 } 
                    733:             } else {
                    734:                 if ($key=~/^\Q$delthis\E/) {
                    735: 		    delete($env{$key});
                    736: 		    delete($disk_env{$key});
                    737: 	        }
                    738:             }
1.448     albertel  739: 	}
1.783     albertel  740: 	untie(%disk_env);
1.5       www       741:     }
                    742:     return 'ok';
1.369     albertel  743: }
                    744: 
1.790     albertel  745: sub get_env_multiple {
                    746:     my ($name) = @_;
                    747:     my @values;
                    748:     if (defined($env{$name})) {
                    749:         # exists is it an array
                    750:         if (ref($env{$name})) {
                    751:             @values=@{ $env{$name} };
                    752:         } else {
                    753:             $values[0]=$env{$name};
                    754:         }
                    755:     }
                    756:     return(@values);
                    757: }
                    758: 
1.958     www       759: # ------------------------------------------------------------------- Locking
                    760: 
                    761: sub set_lock {
                    762:     my ($text)=@_;
                    763:     $locknum++;
                    764:     my $id=$$.'-'.$locknum;
                    765:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    766:              'session.lock.'.$id => $text});
                    767:     return $id;
                    768: }
                    769: 
                    770: sub get_locks {
                    771:     my $num=0;
                    772:     my %texts=();
                    773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    774:        if ($lock=~/\w/) {
                    775:           $num++;
                    776:           $texts{$lock}=$env{'session.lock.'.$lock};
                    777:        }
                    778:    }
                    779:    return ($num,%texts);
                    780: }
                    781: 
                    782: sub remove_lock {
                    783:     my ($id)=@_;
                    784:     my $newlocks='';
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if (($lock=~/\w/) && ($lock ne $id)) {
                    787:           $newlocks.=','.$lock;
                    788:        }
                    789:     }
                    790:     &appenv({'session.locks' => $newlocks});
                    791:     &delenv('session.lock.'.$id);
                    792: }
                    793: 
                    794: sub remove_all_locks {
                    795:     my $activelocks=$env{'session.locks'};
                    796:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    797:        if ($lock=~/\w/) {
                    798:           &remove_lock($lock);
                    799:        }
                    800:     }
                    801: }
                    802: 
                    803: 
1.369     albertel  804: # ------------------------------------------ Find out current server userload
                    805: sub userload {
                    806:     my $numusers=0;
                    807:     {
                    808: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    809: 	my $filename;
                    810: 	my $curtime=time;
                    811: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  812: 	    next if ($filename eq '.' || $filename eq '..');
                    813: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  814: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  815: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  816: 	}
                    817: 	closedir(LONIDS);
                    818:     }
                    819:     my $userloadpercent=0;
                    820:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    821:     if ($maxuserload) {
1.371     albertel  822: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  823:     }
1.372     albertel  824:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  825:     return $userloadpercent;
1.283     www       826: }
                    827: 
1.1       albertel  828: # ------------------------------ Find server with least workload from spare.tab
1.11      www       829: 
1.1       albertel  830: sub spareserver {
1.1083    raeburn   831:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  832:     my $spare_server;
1.370     albertel  833:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  834:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    835:                                                      :  $userloadpercent;
1.1083    raeburn   836:     my ($uint_dom,$remotesessions);
                    837:     if (($udom ne '') && (&domain($udom) ne '')) {
                    838:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    839:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    840:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    841:         $remotesessions = $udomdefaults{'remotesessions'};
                    842:     }
1.1123    raeburn   843:     my $spareshash = &this_host_spares($udom);
                    844:     if (ref($spareshash) eq 'HASH') {
                    845:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    846:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    847:                 if ($uint_dom) {
                    848:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    849:                                                  $try_server));
                    850:                 }
                    851: 	        ($spare_server, $lowest_load) =
                    852: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    853:             }
1.1083    raeburn   854:         }
1.784     albertel  855: 
1.1123    raeburn   856:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    857: 
                    858:         if (!$found_server) {
                    859:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    860: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    861:                     if ($uint_dom) {
                    862:                         next unless (&spare_can_host($udom,$uint_dom,
                    863:                                                      $remotesessions,$try_server));
                    864:                     }
                    865: 	            ($spare_server, $lowest_load) =
                    866: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    867:                 }
                    868: 	    }
                    869:         }
1.784     albertel  870:     }
                    871: 
                    872:     if (!$want_server_name) {
1.968     raeburn   873:         my $protocol = 'http';
                    874:         if ($protocol{$spare_server} eq 'https') {
                    875:             $protocol = $protocol{$spare_server};
                    876:         }
1.1001    raeburn   877:         if (defined($spare_server)) {
                    878:             my $hostname = &hostname($spare_server);
1.1083    raeburn   879:             if (defined($hostname)) {
1.1001    raeburn   880: 	        $spare_server = $protocol.'://'.$hostname;
                    881:             }
                    882:         }
1.784     albertel  883:     }
                    884:     return $spare_server;
                    885: }
                    886: 
                    887: sub compare_server_load {
1.1172.2.41  raeburn   888:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    889: 
                    890:     if ($required) {
                    891:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    892:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    893:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    894:         if (($major eq '' && $minor eq '') ||
                    895:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    896:             return ($spare_server,$lowest_load);
                    897:         }
                    898:     }
1.784     albertel  899: 
                    900:     my $loadans     = &reply('load',    $try_server);
                    901:     my $userloadans = &reply('userload',$try_server);
                    902: 
                    903:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   904: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  905:     }
                    906: 
                    907:     my $load;
                    908:     if ($loadans =~ /\d/) {
                    909: 	if ($userloadans =~ /\d/) {
                    910: 	    #both are numbers, pick the bigger one
                    911: 	    $load = ($loadans > $userloadans) ? $loadans 
                    912: 		                              : $userloadans;
1.411     albertel  913: 	} else {
1.784     albertel  914: 	    $load = $loadans;
1.411     albertel  915: 	}
1.784     albertel  916:     } else {
                    917: 	$load = $userloadans;
                    918:     }
                    919: 
                    920:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    921: 	$spare_server = $try_server;
                    922: 	$lowest_load  = $load;
1.370     albertel  923:     }
1.784     albertel  924:     return ($spare_server,$lowest_load);
1.202     matthew   925: }
1.914     albertel  926: 
                    927: # --------------------------- ask offload servers if user already has a session
                    928: sub find_existing_session {
                    929:     my ($udom,$uname) = @_;
1.1123    raeburn   930:     my $spareshash = &this_host_spares($udom);
                    931:     if (ref($spareshash) eq 'HASH') {
                    932:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    933:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    934:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    935:             }
                    936:         }
                    937:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    938:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    939:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    940:             }
                    941:         }
1.914     albertel  942:     }
                    943:     return;
                    944: }
                    945: 
                    946: # -------------------------------- ask if server already has a session for user
                    947: sub has_user_session {
                    948:     my ($lonid,$udom,$uname) = @_;
                    949:     my $result = &reply(join(':','userhassession',
                    950: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    951:     return 1 if ($result eq 'ok');
                    952: 
                    953:     return 0;
                    954: }
                    955: 
1.1076    raeburn   956: # --------- determine least loaded server in a user's domain which allows login
                    957: 
                    958: sub choose_server {
1.1172.2.47  raeburn   959:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   960:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   961:     my %servers = &get_servers($udom);
1.1076    raeburn   962:     my $lowest_load = 30000;
1.1172.2.47  raeburn   963:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    964:     if ($skiploadbal) {
                    965:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    966:         unless (defined($cached)) {
                    967:             my $cachetime = 60*60*24;
                    968:             my %domconfig =
                    969:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    970:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    971:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    972:                                            $cachetime);
                    973:             }
                    974:         }
                    975:     }
1.1076    raeburn   976:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   977:         my $loginvia;
1.1172.2.47  raeburn   978:         if ($skiploadbal) {
                    979:             if (ref($balancers) eq 'HASH') {
                    980:                 next if (exists($balancers->{$lonhost}));
                    981:             }
                    982:         }
1.1115    raeburn   983:         if ($checkloginvia) {
                    984:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   985:             if ($loginvia) {
                    986:                 my ($server,$path) = split(/:/,$loginvia);
                    987:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   988:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   989:                 if ($login_host eq $server) {
                    990:                     $portal_path = $path;
1.1151    raeburn   991:                     $isredirect = 1;
1.1116    raeburn   992:                 }
                    993:             } else {
                    994:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   995:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   996:                 if ($login_host eq $lonhost) {
                    997:                     $portal_path = '';
1.1151    raeburn   998:                     $isredirect = ''; 
1.1116    raeburn   999:                 }
                   1000:             }
                   1001:         } else {
1.1076    raeburn  1002:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1003:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1004:         }
                   1005:     }
                   1006:     if ($login_host ne '') {
1.1116    raeburn  1007:         $hostname = &hostname($login_host);
1.1076    raeburn  1008:     }
1.1151    raeburn  1009:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1010: }
                   1011: 
1.202     matthew  1012: # --------------------------------------------- Try to change a user's password
                   1013: 
                   1014: sub changepass {
1.799     raeburn  1015:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1016:     $currentpass = &escape($currentpass);
                   1017:     $newpass     = &escape($newpass);
1.1030    raeburn  1018:     my $lonhost = $perlvar{'lonHostID'};
                   1019:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1020: 		       $server);
                   1021:     if (! $answer) {
                   1022: 	&logthis("No reply on password change request to $server ".
                   1023: 		 "by $uname in domain $udom.");
                   1024:     } elsif ($answer =~ "^ok") {
                   1025:         &logthis("$uname in $udom successfully changed their password ".
                   1026: 		 "on $server.");
                   1027:     } elsif ($answer =~ "^pwchange_failure") {
                   1028: 	&logthis("$uname in $udom was unable to change their password ".
                   1029: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1030: 		 "or pwchange");
                   1031:     } elsif ($answer =~ "^non_authorized") {
                   1032:         &logthis("$uname in $udom did not get their password correct when ".
                   1033: 		 "attempting to change it on $server.");
                   1034:     } elsif ($answer =~ "^auth_mode_error") {
                   1035:         &logthis("$uname in $udom attempted to change their password despite ".
                   1036: 		 "not being locally or internally authenticated on $server.");
                   1037:     } elsif ($answer =~ "^unknown_user") {
                   1038:         &logthis("$uname in $udom attempted to change their password ".
                   1039: 		 "on $server but were unable to because $server is not ".
                   1040: 		 "their home server.");
                   1041:     } elsif ($answer =~ "^refused") {
                   1042: 	&logthis("$server refused to change $uname in $udom password because ".
                   1043: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1044:     } elsif ($answer =~ "invalid_client") {
                   1045:         &logthis("$server refused to change $uname in $udom password because ".
                   1046:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1047:     }
                   1048:     return $answer;
1.1       albertel 1049: }
                   1050: 
1.169     harris41 1051: # ----------------------- Try to determine user's current authentication scheme
                   1052: 
                   1053: sub queryauthenticate {
                   1054:     my ($uname,$udom)=@_;
1.456     albertel 1055:     my $uhome=&homeserver($uname,$udom);
                   1056:     if (!$uhome) {
                   1057: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1058: 	return 'no_host';
                   1059:     }
                   1060:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1061:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1062: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1063:     }
1.456     albertel 1064:     return $answer;
1.169     harris41 1065: }
                   1066: 
1.1       albertel 1067: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1068: 
1.1       albertel 1069: sub authenticate {
1.1073    raeburn  1070:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1071:     $upass=&escape($upass);
                   1072:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1073:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1074:     my $newhome;
1.836     www      1075:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1076: # Maybe the machine was offline and only re-appeared again recently?
                   1077:         &reconlonc();
                   1078: # One more
1.952     raeburn  1079: 	$uhome=&homeserver($uname,$udom,1);
                   1080:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1081:             if (defined(&domain($udom,'primary'))) {
                   1082:                 $newhome=&domain($udom,'primary');
                   1083:             }
                   1084:             if ($newhome ne '') {
                   1085:                 $uhome = $newhome;
                   1086:             }
                   1087:         }
1.836     www      1088: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1089: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1090: 	    return 'no_host';
                   1091:         }
1.1       albertel 1092:     }
1.1073    raeburn  1093:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1094:     if ($answer eq 'authorized') {
1.952     raeburn  1095:         if ($newhome) {
                   1096:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1097:             return 'no_account_on_host'; 
                   1098:         } else {
                   1099:             &logthis("User $uname at $udom authorized by $uhome");
                   1100:             return $uhome;
                   1101:         }
1.471     albertel 1102:     }
                   1103:     if ($answer eq 'non_authorized') {
                   1104: 	&logthis("User $uname at $udom rejected by $uhome");
                   1105: 	return 'no_host'; 
1.9       www      1106:     }
1.471     albertel 1107:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1108:     return 'no_host';
                   1109: }
                   1110: 
1.1073    raeburn  1111: sub can_host_session {
1.1074    raeburn  1112:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1113:     my $canhost = 1;
1.1074    raeburn  1114:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1115:     if (ref($remotesessions) eq 'HASH') {
                   1116:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1117:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1118:                 $canhost = 0;
                   1119:             } else {
                   1120:                 $canhost = 1;
                   1121:             }
                   1122:         }
                   1123:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1124:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1125:                 $canhost = 1;
                   1126:             } else {
                   1127:                 $canhost = 0;
                   1128:             }
                   1129:         }
                   1130:         if ($canhost) {
                   1131:             if ($remotesessions->{'version'} ne '') {
                   1132:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1133:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1134:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1135:                         my $major = $1;
                   1136:                         my $minor = $2;
                   1137:                         if (($major < $reqmajor ) ||
                   1138:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1139:                             $canhost = 0;
                   1140:                         }
                   1141:                     } else {
                   1142:                         $canhost = 0;
                   1143:                     }
                   1144:                 }
                   1145:             }
                   1146:         }
                   1147:     }
                   1148:     if ($canhost) {
                   1149:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1150:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1151:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1152:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1153:                 if (($uint_dom ne '') && 
                   1154:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1155:                     $canhost = 0;
                   1156:                 } else {
                   1157:                     $canhost = 1;
                   1158:                 }
                   1159:             }
                   1160:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1161:                 if (($uint_dom ne '') && 
                   1162:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1163:                     $canhost = 1;
                   1164:                 } else {
                   1165:                     $canhost = 0;
                   1166:                 }
                   1167:             }
                   1168:         }
                   1169:     }
                   1170:     return $canhost;
                   1171: }
                   1172: 
1.1083    raeburn  1173: sub spare_can_host {
                   1174:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1175:     my $canhost=1;
                   1176:     my @intdoms;
                   1177:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1178:     if (ref($internet_names) eq 'ARRAY') {
                   1179:         @intdoms = @{$internet_names};
                   1180:     }
                   1181:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1182:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1183:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1184:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1185:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1186:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1187:                                      $remotesessions,
                   1188:                                      $defdomdefaults{'hostedsessions'});
                   1189:     }
                   1190:     return $canhost;
                   1191: }
                   1192: 
1.1123    raeburn  1193: sub this_host_spares {
                   1194:     my ($dom) = @_;
1.1126    raeburn  1195:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1196:     my @hosts = &current_machine_ids();
                   1197:     foreach my $lonhost (@hosts) {
                   1198:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1199:             $dom_in_use = $dom;
                   1200:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1201:             last;
                   1202:         }
                   1203:     }
1.1126    raeburn  1204:     if ($dom_in_use ne '') {
                   1205:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1206:     }
                   1207:     if (ref($result) ne 'HASH') {
                   1208:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1209:         $dom_in_use = &host_domain($lonhost_in_use);
                   1210:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1211:         if (ref($result) ne 'HASH') {
                   1212:             $result = \%spareid;
                   1213:         }
                   1214:     }
                   1215:     return $result;
                   1216: }
                   1217: 
                   1218: sub spares_for_offload  {
                   1219:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1220:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1221:     if (defined($cached)) {
                   1222:         return $result;
                   1223:     } else {
1.1126    raeburn  1224:         my $cachetime = 60*60*24;
                   1225:         my %domconfig =
                   1226:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1227:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1228:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1229:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1230:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1231:                 }
                   1232:             }
                   1233:         }
                   1234:     }
1.1126    raeburn  1235:     return;
1.1123    raeburn  1236: }
                   1237: 
1.1129    raeburn  1238: sub get_lonbalancer_config {
                   1239:     my ($servers) = @_;
                   1240:     my ($currbalancer,$currtargets);
                   1241:     if (ref($servers) eq 'HASH') {
                   1242:         foreach my $server (keys(%{$servers})) {
                   1243:             my %what = (
                   1244:                          spareid => 1,
                   1245:                          perlvar => 1,
                   1246:                        );
                   1247:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1248:             if ($result eq 'ok') {
                   1249:                 if (ref($returnhash) eq 'HASH') {
                   1250:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1251:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1252:                             $currbalancer = $server;
                   1253:                             $currtargets = {};
                   1254:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1255:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1256:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1257:                                 }
                   1258:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1259:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1260:                                 }
                   1261:                             }
                   1262:                             last;
                   1263:                         }
                   1264:                     }
                   1265:                 }
                   1266:             }
                   1267:         }
                   1268:     }
                   1269:     return ($currbalancer,$currtargets);
                   1270: }
                   1271: 
                   1272: sub check_loadbalancing {
                   1273:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1274:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1275:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1276:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1277:     my @hosts = &current_machine_ids();
1.1129    raeburn  1278:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1279:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1280:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1281:     my $serverhomedom = &host_domain($lonhost);
                   1282: 
                   1283:     my $cachetime = 60*60*24;
                   1284: 
                   1285:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1286:         $dom_in_use = $udom;
                   1287:         $homeintdom = 1;
                   1288:     } else {
                   1289:         $dom_in_use = $serverhomedom;
                   1290:     }
                   1291:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1292:     unless (defined($cached)) {
                   1293:         my %domconfig =
                   1294:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1295:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1296:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1297:         }
                   1298:     }
                   1299:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1300:         ($is_balancer,$currtargets,$currrules) =
                   1301:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1302:         if ($is_balancer) {
                   1303:             if (ref($currrules) eq 'HASH') {
                   1304:                 if ($homeintdom) {
                   1305:                     if ($uname ne '') {
                   1306:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1307:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1308:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1309:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1310:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1311:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1312:                             }
                   1313:                         }
                   1314:                         if ($rule_in_effect eq '') {
                   1315:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1316:                             if ($userenv{'inststatus'} ne '') {
                   1317:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1318:                                 my ($othertitle,$usertypes,$types) =
                   1319:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1320:                                 if (ref($types) eq 'ARRAY') {
                   1321:                                     foreach my $type (@{$types}) {
                   1322:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1323:                                             if (exists($currrules->{$type})) {
                   1324:                                                 $rule_in_effect = $currrules->{$type};
                   1325:                                             }
                   1326:                                         }
                   1327:                                     }
                   1328:                                 }
                   1329:                             } else {
                   1330:                                 if (exists($currrules->{'default'})) {
                   1331:                                     $rule_in_effect = $currrules->{'default'};
                   1332:                                 }
                   1333:                             }
                   1334:                         }
                   1335:                     } else {
                   1336:                         if (exists($currrules->{'default'})) {
                   1337:                             $rule_in_effect = $currrules->{'default'};
                   1338:                         }
                   1339:                     }
                   1340:                 } else {
                   1341:                     if ($currrules->{'_LC_external'} ne '') {
                   1342:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1343:                     }
                   1344:                 }
                   1345:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1346:                                                        $uname,$udom);
                   1347:             }
                   1348:         }
                   1349:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1350:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1351:         unless (defined($cached)) {
                   1352:             my %domconfig =
                   1353:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1354:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1355:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1356:             }
                   1357:         }
                   1358:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1359:             ($is_balancer,$currtargets,$currrules) =
                   1360:                 &check_balancer_result($result,@hosts);
                   1361:             if ($is_balancer) {
1.1129    raeburn  1362:                 if (ref($currrules) eq 'HASH') {
                   1363:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1364:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1365:                     }
                   1366:                 }
                   1367:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1368:                                                        $uname,$udom);
                   1369:             }
                   1370:         } else {
                   1371:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1372:                 $is_balancer = 1;
                   1373:                 $offloadto = &this_host_spares($dom_in_use);
                   1374:             }
                   1375:         }
                   1376:     } else {
                   1377:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1378:             $is_balancer = 1;
                   1379:             $offloadto = &this_host_spares($dom_in_use);
                   1380:         }
                   1381:     }
1.1172.2.5  raeburn  1382:     if ($is_balancer) {
                   1383:         my $lowest_load = 30000;
                   1384:         if (ref($offloadto) eq 'HASH') {
                   1385:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1386:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1387:                     ($otherserver,$lowest_load) =
                   1388:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1389:                 }
1.1129    raeburn  1390:             }
1.1172.2.5  raeburn  1391:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1392: 
1.1172.2.5  raeburn  1393:             if (!$found_server) {
                   1394:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1395:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1396:                         ($otherserver,$lowest_load) =
                   1397:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1398:                     }
                   1399:                 }
                   1400:             }
                   1401:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1402:             if (@{$offloadto} == 1) {
                   1403:                 $otherserver = $offloadto->[0];
                   1404:             } elsif (@{$offloadto} > 1) {
                   1405:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1406:                     ($otherserver,$lowest_load) =
                   1407:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1408:                 }
                   1409:             }
                   1410:         }
1.1172.2.5  raeburn  1411:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1412:             $is_balancer = 0;
                   1413:             if ($uname ne '' && $udom ne '') {
                   1414:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1415: 
                   1416:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1417:                              'user.loadbalcheck.time' => time});
                   1418:                 }
1.1129    raeburn  1419:             }
                   1420:         }
                   1421:     }
                   1422:     return ($is_balancer,$otherserver);
                   1423: }
                   1424: 
1.1172.2.12  raeburn  1425: sub check_balancer_result {
                   1426:     my ($result,@hosts) = @_;
                   1427:     my ($is_balancer,$currtargets,$currrules);
                   1428:     if (ref($result) eq 'HASH') {
                   1429:         if ($result->{'lonhost'} ne '') {
                   1430:             my $currbalancer = $result->{'lonhost'};
                   1431:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1432:                 $is_balancer = 1;
                   1433:                 $currtargets = $result->{'targets'};
                   1434:                 $currrules = $result->{'rules'};
                   1435:             }
                   1436:         } else {
                   1437:             foreach my $key (keys(%{$result})) {
                   1438:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1439:                     (ref($result->{$key}) eq 'HASH')) {
                   1440:                     $is_balancer = 1;
                   1441:                     $currrules = $result->{$key}{'rules'};
                   1442:                     $currtargets = $result->{$key}{'targets'};
                   1443:                     last;
                   1444:                 }
                   1445:             }
                   1446:         }
                   1447:     }
                   1448:     return ($is_balancer,$currtargets,$currrules);
                   1449: }
                   1450: 
1.1129    raeburn  1451: sub get_loadbalancer_targets {
                   1452:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1453:     my $offloadto;
1.1172.2.4  raeburn  1454:     if ($rule_in_effect eq 'none') {
                   1455:         return [$perlvar{'lonHostID'}];
                   1456:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1457:         $offloadto = $currtargets;
                   1458:     } else {
                   1459:         if ($rule_in_effect eq 'homeserver') {
                   1460:             my $homeserver = &homeserver($uname,$udom);
                   1461:             if ($homeserver ne 'no_host') {
                   1462:                 $offloadto = [$homeserver];
                   1463:             }
                   1464:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1465:             my %domconfig =
                   1466:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1467:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1468:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1469:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1470:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1471:                     }
                   1472:                 }
                   1473:             } else {
1.1172.2.7  raeburn  1474:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1475:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1476:                 if (&hostname($remotebalancer) ne '') {
                   1477:                     $offloadto = [$remotebalancer];
                   1478:                 }
                   1479:             }
                   1480:         } elsif (&hostname($rule_in_effect) ne '') {
                   1481:             $offloadto = [$rule_in_effect];
                   1482:         }
                   1483:     }
                   1484:     return $offloadto;
                   1485: }
                   1486: 
1.1127    raeburn  1487: sub internet_dom_servers {
                   1488:     my ($dom) = @_;
                   1489:     my (%uniqservers,%servers);
                   1490:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1491:     my @machinedoms = &machine_domains($primaryserver);
                   1492:     foreach my $mdom (@machinedoms) {
                   1493:         my %currservers = %servers;
                   1494:         my %server = &get_servers($mdom);
                   1495:         %servers = (%currservers,%server);
                   1496:     }
                   1497:     my %by_hostname;
                   1498:     foreach my $id (keys(%servers)) {
                   1499:         push(@{$by_hostname{$servers{$id}}},$id);
                   1500:     }
                   1501:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1502:         if (@{$by_hostname{$hostname}} > 1) {
                   1503:             my $match = 0;
                   1504:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1505:                 if (&host_domain($id) eq $dom) {
                   1506:                     $uniqservers{$id} = $hostname;
                   1507:                     $match = 1;
                   1508:                 }
                   1509:             }
                   1510:             unless ($match) {
                   1511:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1512:             }
                   1513:         } else {
                   1514:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1515:         }
                   1516:     }
                   1517:     return %uniqservers;
                   1518: }
                   1519: 
1.1       albertel 1520: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1521: 
1.599     albertel 1522: my %homecache;
1.1       albertel 1523: sub homeserver {
1.230     stredwic 1524:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1525:     my $index="$uname:$udom";
1.426     albertel 1526: 
1.599     albertel 1527:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1528: 
                   1529:     my %servers = &get_servers($udom,'library');
                   1530:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1531:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1532: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1533: 
                   1534: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1535: 	if ($answer eq 'found') {
                   1536: 	    delete($badServerCache{$tryserver}); 
                   1537: 	    return $homecache{$index}=$tryserver;
                   1538: 	} elsif ($answer eq 'no_host') {
                   1539: 	    $badServerCache{$tryserver}=1;
                   1540: 	}
1.1       albertel 1541:     }    
                   1542:     return 'no_host';
1.70      www      1543: }
                   1544: 
                   1545: # ------------------------------------- Find the usernames behind a list of IDs
                   1546: 
                   1547: sub idget {
                   1548:     my ($udom,@ids)=@_;
                   1549:     my %returnhash=();
                   1550:     
1.841     albertel 1551:     my %servers = &get_servers($udom,'library');
                   1552:     foreach my $tryserver (keys(%servers)) {
                   1553: 	my $idlist=join('&',@ids);
                   1554: 	$idlist=~tr/A-Z/a-z/; 
                   1555: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1556: 	my @answer=();
                   1557: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1558: 	    @answer=split(/\&/,$reply);
                   1559: 	}                    ;
                   1560: 	my $i;
                   1561: 	for ($i=0;$i<=$#ids;$i++) {
                   1562: 	    if ($answer[$i]) {
                   1563: 		$returnhash{$ids[$i]}=$answer[$i];
                   1564: 	    } 
                   1565: 	}
                   1566:     } 
1.70      www      1567:     return %returnhash;
                   1568: }
                   1569: 
                   1570: # ------------------------------------- Find the IDs behind a list of usernames
                   1571: 
                   1572: sub idrget {
                   1573:     my ($udom,@unames)=@_;
                   1574:     my %returnhash=();
1.800     albertel 1575:     foreach my $uname (@unames) {
                   1576:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1577:     }
1.70      www      1578:     return %returnhash;
                   1579: }
                   1580: 
                   1581: # ------------------------------- Store away a list of names and associated IDs
                   1582: 
                   1583: sub idput {
                   1584:     my ($udom,%ids)=@_;
                   1585:     my %servers=();
1.800     albertel 1586:     foreach my $uname (keys(%ids)) {
                   1587: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1588:         my $uhom=&homeserver($uname,$udom);
1.70      www      1589:         if ($uhom ne 'no_host') {
1.800     albertel 1590:             my $id=&escape($ids{$uname});
1.70      www      1591:             $id=~tr/A-Z/a-z/;
1.800     albertel 1592:             my $esc_unam=&escape($uname);
1.70      www      1593: 	    if ($servers{$uhom}) {
1.800     albertel 1594: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1595:             } else {
1.800     albertel 1596:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1597:             }
                   1598:         }
1.191     harris41 1599:     }
1.800     albertel 1600:     foreach my $server (keys(%servers)) {
                   1601:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1602:     }
1.344     www      1603: }
                   1604: 
1.1172.2.30  raeburn  1605: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1606: 
                   1607: sub iddel {
                   1608:     my ($udom,$idshashref,$uhome)=@_;
                   1609:     my %result=();
                   1610:     unless (ref($idshashref) eq 'HASH') {
                   1611:         return %result;
                   1612:     }
                   1613:     my %servers=();
                   1614:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1615:         my $uhom;
                   1616:         if ($uhome) {
                   1617:             $uhom = $uhome;
                   1618:         } else {
                   1619:             $uhom=&homeserver($uname,$udom);
                   1620:         }
                   1621:         if ($uhom ne 'no_host') {
                   1622:             if ($servers{$uhom}) {
                   1623:                 $servers{$uhom}.='&'.&escape($id);
                   1624:             } else {
                   1625:                 $servers{$uhom}=&escape($id);
                   1626:             }
                   1627:         }
                   1628:     }
                   1629:     foreach my $server (keys(%servers)) {
                   1630:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1631:     }
                   1632:     return %result;
                   1633: }
                   1634: 
1.1023    raeburn  1635: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1636: sub dump_dom {
1.1165    droeschl 1637:     my ($namespace, $udom, $regexp) = @_;
                   1638: 
                   1639:     $udom ||= $env{'user.domain'};
                   1640: 
                   1641:     return () unless $udom;
                   1642: 
                   1643:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1644: }
                   1645: 
1.1023    raeburn  1646: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1647: 
                   1648: sub get_dom {
1.860     raeburn  1649:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57! raeburn  1650:     return if ($udom eq 'public');
1.806     raeburn  1651:     my $items='';
                   1652:     foreach my $item (@$storearr) {
                   1653:         $items.=&escape($item).'&';
                   1654:     }
                   1655:     $items=~s/\&$//;
1.860     raeburn  1656:     if (!$udom) {
                   1657:         $udom=$env{'user.domain'};
1.1172.2.57! raeburn  1658:         return if ($udom eq 'public');
1.860     raeburn  1659:         if (defined(&domain($udom,'primary'))) {
                   1660:             $uhome=&domain($udom,'primary');
                   1661:         } else {
1.874     albertel 1662:             undef($uhome);
1.860     raeburn  1663:         }
                   1664:     } else {
                   1665:         if (!$uhome) {
                   1666:             if (defined(&domain($udom,'primary'))) {
                   1667:                 $uhome=&domain($udom,'primary');
                   1668:             }
                   1669:         }
                   1670:     }
                   1671:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1672:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1673:         my %returnhash;
1.875     albertel 1674:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1675:             return %returnhash;
                   1676:         }
1.806     raeburn  1677:         my @pairs=split(/\&/,$rep);
                   1678:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1679:             return @pairs;
                   1680:         }
                   1681:         my $i=0;
                   1682:         foreach my $item (@$storearr) {
                   1683:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1684:             $i++;
                   1685:         }
                   1686:         return %returnhash;
                   1687:     } else {
1.880     banghart 1688:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1689:     }
                   1690: }
                   1691: 
                   1692: # -------------------------------------------- put items in domain db files 
                   1693: 
                   1694: sub put_dom {
1.860     raeburn  1695:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1696:     if (!$udom) {
                   1697:         $udom=$env{'user.domain'};
                   1698:         if (defined(&domain($udom,'primary'))) {
                   1699:             $uhome=&domain($udom,'primary');
                   1700:         } else {
1.874     albertel 1701:             undef($uhome);
1.860     raeburn  1702:         }
                   1703:     } else {
                   1704:         if (!$uhome) {
                   1705:             if (defined(&domain($udom,'primary'))) {
                   1706:                 $uhome=&domain($udom,'primary');
                   1707:             }
                   1708:         }
                   1709:     } 
                   1710:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1711:         my $items='';
                   1712:         foreach my $item (keys(%$storehash)) {
                   1713:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1714:         }
                   1715:         $items=~s/\&$//;
                   1716:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1717:     } else {
1.860     raeburn  1718:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1719:     }
                   1720: }
                   1721: 
1.1023    raeburn  1722: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1723: sub newput_dom {
1.1023    raeburn  1724:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1725:     my $result;
                   1726:     if (!$udom) {
                   1727:         $udom=$env{'user.domain'};
                   1728:     }
1.1023    raeburn  1729:     if ($udom) {
                   1730:         my $uname = &get_domainconfiguser($udom);
                   1731:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1732:     }
                   1733:     return $result;
                   1734: }
                   1735: 
1.1023    raeburn  1736: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1737: sub del_dom {
1.1023    raeburn  1738:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1739:     if (ref($storearr) eq 'ARRAY') {
                   1740:         if (!$udom) {
                   1741:             $udom=$env{'user.domain'};
                   1742:         }
1.1023    raeburn  1743:         if ($udom) {
                   1744:             my $uname = &get_domainconfiguser($udom); 
                   1745:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1746:         }
                   1747:     }
                   1748: }
                   1749: 
1.1023    raeburn  1750: # ----------------------------------construct domainconfig user for a domain 
                   1751: sub get_domainconfiguser {
                   1752:     my ($udom) = @_;
                   1753:     return $udom.'-domainconfig';
                   1754: }
                   1755: 
1.837     raeburn  1756: sub retrieve_inst_usertypes {
                   1757:     my ($udom) = @_;
                   1758:     my (%returnhash,@order);
1.989     raeburn  1759:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1760:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1761:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1762:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1763:     } else {
                   1764:         if (defined(&domain($udom,'primary'))) {
                   1765:             my $uhome=&domain($udom,'primary');
                   1766:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1767:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1768:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1769:                 return (\%returnhash,\@order);
                   1770:             }
                   1771:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1772:             my @pairs=split(/\&/,$hashitems);
                   1773:             foreach my $item (@pairs) {
                   1774:                 my ($key,$value)=split(/=/,$item,2);
                   1775:                 $key = &unescape($key);
                   1776:                 next if ($key =~ /^error: 2 /);
                   1777:                 $returnhash{$key}=&thaw_unescape($value);
                   1778:             }
                   1779:             my @esc_order = split(/\&/,$orderitems);
                   1780:             foreach my $item (@esc_order) {
                   1781:                 push(@order,&unescape($item));
                   1782:             }
                   1783:         } else {
1.1172.2.44  raeburn  1784:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1785:         }
1.1172.2.44  raeburn  1786:         return (\%returnhash,\@order);
1.837     raeburn  1787:     }
                   1788: }
                   1789: 
1.868     raeburn  1790: sub is_domainimage {
                   1791:     my ($url) = @_;
                   1792:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1793:         if (&domain($1) ne '') {
                   1794:             return '1';
                   1795:         }
                   1796:     }
                   1797:     return;
                   1798: }
                   1799: 
1.899     raeburn  1800: sub inst_directory_query {
                   1801:     my ($srch) = @_;
                   1802:     my $udom = $srch->{'srchdomain'};
                   1803:     my %results;
                   1804:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1805:     my $outcome;
1.899     raeburn  1806:     if ($homeserver ne '') {
1.904     albertel 1807: 	my $queryid=&reply("querysend:instdirsearch:".
                   1808: 			   &escape($srch->{'srchby'}).':'.
                   1809: 			   &escape($srch->{'srchterm'}).':'.
                   1810: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1811: 	my $host=&hostname($homeserver);
                   1812: 	if ($queryid !~/^\Q$host\E\_/) {
                   1813: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1814: 	    return;
                   1815: 	}
                   1816: 	my $response = &get_query_reply($queryid);
                   1817: 	my $maxtries = 5;
                   1818: 	my $tries = 1;
                   1819: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1820: 	    $response = &get_query_reply($queryid);
                   1821: 	    $tries ++;
                   1822: 	}
                   1823: 
                   1824:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1825:             if ($response eq 'unavailable') {
                   1826:                 $outcome = $response;
                   1827:             } else {
                   1828:                 $outcome = 'ok';
                   1829:                 my @matches = split(/\n/,$response);
                   1830:                 foreach my $match (@matches) {
                   1831:                     my ($key,$value) = split(/=/,$match);
                   1832:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1833:                 }
1.899     raeburn  1834:             }
                   1835:         }
                   1836:     }
1.909     raeburn  1837:     return ($outcome,%results);
1.899     raeburn  1838: }
                   1839: 
                   1840: sub usersearch {
                   1841:     my ($srch) = @_;
                   1842:     my $dom = $srch->{'srchdomain'};
                   1843:     my %results;
                   1844:     my %libserv = &all_library();
                   1845:     my $query = 'usersearch';
                   1846:     foreach my $tryserver (keys(%libserv)) {
                   1847:         if (&host_domain($tryserver) eq $dom) {
                   1848:             my $host=&hostname($tryserver);
                   1849:             my $queryid=
1.911     raeburn  1850:                 &reply("querysend:".&escape($query).':'.
                   1851:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1852:                        &escape($srch->{'srchtype'}).':'.
                   1853:                        &escape($srch->{'srchterm'}),$tryserver);
                   1854:             if ($queryid !~/^\Q$host\E\_/) {
                   1855:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1856:                 next;
1.899     raeburn  1857:             }
                   1858:             my $reply = &get_query_reply($queryid);
                   1859:             my $maxtries = 1;
                   1860:             my $tries = 1;
                   1861:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1862:                 $reply = &get_query_reply($queryid);
                   1863:                 $tries ++;
                   1864:             }
                   1865:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1866:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1867:             } else {
1.911     raeburn  1868:                 my @matches;
                   1869:                 if ($reply =~ /\n/) {
                   1870:                     @matches = split(/\n/,$reply);
                   1871:                 } else {
                   1872:                     @matches = split(/\&/,$reply);
                   1873:                 }
1.899     raeburn  1874:                 foreach my $match (@matches) {
                   1875:                     my ($uname,$udom,%userhash);
1.911     raeburn  1876:                     foreach my $entry (split(/:/,$match)) {
                   1877:                         my ($key,$value) =
                   1878:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1879:                         $userhash{$key} = $value;
                   1880:                         if ($key eq 'username') {
                   1881:                             $uname = $value;
                   1882:                         } elsif ($key eq 'domain') {
                   1883:                             $udom = $value;
1.911     raeburn  1884:                         }
1.899     raeburn  1885:                     }
                   1886:                     $results{$uname.':'.$udom} = \%userhash;
                   1887:                 }
                   1888:             }
                   1889:         }
                   1890:     }
                   1891:     return %results;
                   1892: }
                   1893: 
1.912     raeburn  1894: sub get_instuser {
                   1895:     my ($udom,$uname,$id) = @_;
                   1896:     my $homeserver = &domain($udom,'primary');
                   1897:     my ($outcome,%results);
                   1898:     if ($homeserver ne '') {
                   1899:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1900:                            &escape($id).':'.&escape($udom),$homeserver);
                   1901:         my $host=&hostname($homeserver);
                   1902:         if ($queryid !~/^\Q$host\E\_/) {
                   1903:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1904:             return;
                   1905:         }
                   1906:         my $response = &get_query_reply($queryid);
                   1907:         my $maxtries = 5;
                   1908:         my $tries = 1;
                   1909:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1910:             $response = &get_query_reply($queryid);
                   1911:             $tries ++;
                   1912:         }
                   1913:         if (!&error($response) && $response ne 'refused') {
                   1914:             if ($response eq 'unavailable') {
                   1915:                 $outcome = $response;
                   1916:             } else {
                   1917:                 $outcome = 'ok';
                   1918:                 my @matches = split(/\n/,$response);
                   1919:                 foreach my $match (@matches) {
                   1920:                     my ($key,$value) = split(/=/,$match);
                   1921:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1922:                 }
                   1923:             }
                   1924:         }
                   1925:     }
                   1926:     my %userinfo;
                   1927:     if (ref($results{$uname}) eq 'HASH') {
                   1928:         %userinfo = %{$results{$uname}};
                   1929:     } 
                   1930:     return ($outcome,%userinfo);
                   1931: }
                   1932: 
                   1933: sub inst_rulecheck {
1.923     raeburn  1934:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1935:     my %returnhash;
                   1936:     if ($udom ne '') {
                   1937:         if (ref($rules) eq 'ARRAY') {
                   1938:             @{$rules} = map {&escape($_);} (@{$rules});
                   1939:             my $rulestr = join(':',@{$rules});
                   1940:             my $homeserver=&domain($udom,'primary');
                   1941:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1942:                 my $response;
                   1943:                 if ($item eq 'username') {                
                   1944:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1945:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1946:                                               $homeserver));
1.923     raeburn  1947:                 } elsif ($item eq 'id') {
                   1948:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1949:                                               ':'.&escape($id).':'.$rulestr,
                   1950:                                               $homeserver));
1.945     raeburn  1951:                 } elsif ($item eq 'selfcreate') {
                   1952:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1953:                                                &escape($udom).':'.&escape($uname).
                   1954:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1955:                 }
1.912     raeburn  1956:                 if ($response ne 'refused') {
                   1957:                     my @pairs=split(/\&/,$response);
                   1958:                     foreach my $item (@pairs) {
                   1959:                         my ($key,$value)=split(/=/,$item,2);
                   1960:                         $key = &unescape($key);
                   1961:                         next if ($key =~ /^error: 2 /);
                   1962:                         $returnhash{$key}=&thaw_unescape($value);
                   1963:                     }
                   1964:                 }
                   1965:             }
                   1966:         }
                   1967:     }
                   1968:     return %returnhash;
                   1969: }
                   1970: 
                   1971: sub inst_userrules {
1.923     raeburn  1972:     my ($udom,$check) = @_;
1.912     raeburn  1973:     my (%ruleshash,@ruleorder);
                   1974:     if ($udom ne '') {
                   1975:         my $homeserver=&domain($udom,'primary');
                   1976:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1977:             my $response;
                   1978:             if ($check eq 'id') {
                   1979:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1980:                                  $homeserver);
1.943     raeburn  1981:             } elsif ($check eq 'email') {
                   1982:                 $response=&reply('instemailrules:'.&escape($udom),
                   1983:                                  $homeserver);
1.923     raeburn  1984:             } else {
                   1985:                 $response=&reply('instuserrules:'.&escape($udom),
                   1986:                                  $homeserver);
                   1987:             }
1.912     raeburn  1988:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1989:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1990:                 ($response ne 'no_such_host')) {
                   1991:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1992:                 my @pairs=split(/\&/,$hashitems);
                   1993:                 foreach my $item (@pairs) {
                   1994:                     my ($key,$value)=split(/=/,$item,2);
                   1995:                     $key = &unescape($key);
                   1996:                     next if ($key =~ /^error: 2 /);
                   1997:                     $ruleshash{$key}=&thaw_unescape($value);
                   1998:                 }
                   1999:                 my @esc_order = split(/\&/,$orderitems);
                   2000:                 foreach my $item (@esc_order) {
                   2001:                     push(@ruleorder,&unescape($item));
                   2002:                 }
                   2003:             }
                   2004:         }
                   2005:     }
                   2006:     return (\%ruleshash,\@ruleorder);
                   2007: }
                   2008: 
1.976     raeburn  2009: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2010: 
                   2011: sub get_domain_defaults {
1.1172.2.35  raeburn  2012:     my ($domain,$ignore_cache) = @_;
                   2013:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2014:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2015:     unless ($ignore_cache) {
                   2016:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2017:         if (defined($cached)) {
                   2018:             if (ref($result) eq 'HASH') {
                   2019:                 return %{$result};
                   2020:             }
1.943     raeburn  2021:         }
                   2022:     }
                   2023:     my %domdefaults;
                   2024:     my %domconfig =
1.989     raeburn  2025:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2026:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2027:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2028:                                   'requestauthor','selfenrollment',
                   2029:                                   'coursecategories'],$domain);
1.1172.2.41  raeburn  2030:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2031:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2032:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2033:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2034:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2035:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2036:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2037:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2038:     } else {
                   2039:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2040:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2041:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2042:     }
1.976     raeburn  2043:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2044:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2045:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2046:         } else {
                   2047:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2048:         }
1.1172.2.6  raeburn  2049:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2050:         foreach my $item (@usertools) {
                   2051:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2052:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2053:             }
                   2054:         }
1.1172.2.29  raeburn  2055:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2056:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2057:         }
1.976     raeburn  2058:     }
1.985     raeburn  2059:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2060:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2061:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2062:         }
                   2063:     }
1.1172.2.9  raeburn  2064:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2065:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2066:     }
1.989     raeburn  2067:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2068:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2069:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2070:         }
                   2071:     }
1.1047    raeburn  2072:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.41  raeburn  2073:         foreach my $type (@coursetypes) {
                   2074:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2075:                 unless ($type eq 'community') {
                   2076:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2077:                 }
                   2078:             }
                   2079:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2080:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2081:             }
1.1172.2.30  raeburn  2082:         }
1.1047    raeburn  2083:     }
1.1073    raeburn  2084:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2085:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2086:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2087:         }
                   2088:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2089:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2090:         }
                   2091:     }
1.1172.2.41  raeburn  2092:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2093:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2094:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2095:                             'approval','limit');
                   2096:             foreach my $type (@coursetypes) {
                   2097:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2098:                     my @mgrdc = ();
                   2099:                     foreach my $item (@settings) {
                   2100:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2101:                             push(@mgrdc,$item);
                   2102:                         }
                   2103:                     }
                   2104:                     if (@mgrdc) {
                   2105:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2106:                     }
                   2107:                 }
                   2108:             }
                   2109:         }
                   2110:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2111:             foreach my $type (@coursetypes) {
                   2112:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2113:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2114:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2115:                     }
                   2116:                 }
                   2117:             }
                   2118:         }
                   2119:     }
1.1172.2.46  raeburn  2120:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2121:         $domdefaults{'catauth'} = 'std';
                   2122:         $domdefaults{'catunauth'} = 'std';
                   2123:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2124:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2125:         }
                   2126:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2127:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2128:         }
                   2129:     }
1.1172.2.23  raeburn  2130:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2131:     return %domdefaults;
                   2132: }
                   2133: 
1.344     www      2134: # --------------------------------------------------- Assign a key to a student
                   2135: 
                   2136: sub assign_access_key {
1.364     www      2137: #
                   2138: # a valid key looks like uname:udom#comments
                   2139: # comments are being appended
                   2140: #
1.498     www      2141:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2142:     $kdom=
1.620     albertel 2143:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2144:     $knum=
1.620     albertel 2145:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2146:     $cdom=
1.620     albertel 2147:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2148:     $cnum=
1.620     albertel 2149:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2150:     $udom=$env{'user.name'} unless (defined($udom));
                   2151:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2152:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2153:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2154:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2155:                                                   # assigned to this person
                   2156:                                                   # - this should not happen,
1.345     www      2157:                                                   # unless something went wrong
                   2158:                                                   # the first time around
                   2159: # ready to assign
1.364     www      2160:         $logentry=$1.'; '.$logentry;
1.496     www      2161:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2162:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2163: # key now belongs to user
1.346     www      2164: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2165:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2166:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2167:                 return 'ok';
                   2168:             } else {
                   2169:                 return 
                   2170:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2171: 	    }
                   2172:         } else {
                   2173:             return 'error: Could not assign key, try again later.';
                   2174:         }
1.364     www      2175:     } elsif (!$existing{$ckey}) {
1.345     www      2176: # the key does not exist
                   2177: 	return 'error: The key does not exist';
                   2178:     } else {
                   2179: # the key is somebody else's
                   2180: 	return 'error: The key is already in use';
                   2181:     }
1.344     www      2182: }
                   2183: 
1.364     www      2184: # ------------------------------------------ put an additional comment on a key
                   2185: 
                   2186: sub comment_access_key {
                   2187: #
                   2188: # a valid key looks like uname:udom#comments
                   2189: # comments are being appended
                   2190: #
                   2191:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2192:     $cdom=
1.620     albertel 2193:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2194:     $cnum=
1.620     albertel 2195:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2196:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2197:     if ($existing{$ckey}) {
                   2198:         $existing{$ckey}.='; '.$logentry;
                   2199: # ready to assign
1.367     www      2200:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2201:                                                  $cdom,$cnum) eq 'ok') {
                   2202: 	    return 'ok';
                   2203:         } else {
                   2204: 	    return 'error: Count not store comment.';
                   2205:         }
                   2206:     } else {
                   2207: # the key does not exist
                   2208: 	return 'error: The key does not exist';
                   2209:     }
                   2210: }
                   2211: 
1.344     www      2212: # ------------------------------------------------------ Generate a set of keys
                   2213: 
                   2214: sub generate_access_keys {
1.364     www      2215:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2216:     $cdom=
1.620     albertel 2217:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2218:     $cnum=
1.620     albertel 2219:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2220:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2221:     unless (($cdom) && ($cnum)) { return 0; }
                   2222:     if ($number>10000) { return 0; }
                   2223:     sleep(2); # make sure don't get same seed twice
                   2224:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2225:     my $total=0;
                   2226:     for (my $i=1;$i<=$number;$i++) {
                   2227:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2228:                   sprintf("%lx",int(100000*rand)).'-'.
                   2229:                   sprintf("%lx",int(100000*rand));
                   2230:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2231:        $newkey=~s/0/h/g; # and also 0 and O
                   2232:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2233:        if ($existing{$newkey}) {
                   2234:            $i--;
                   2235:        } else {
1.364     www      2236: 	  if (&put('accesskeys',
                   2237:               { $newkey => '# generated '.localtime().
1.620     albertel 2238:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2239:                            '; '.$logentry },
                   2240: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2241:               $total++;
                   2242: 	  }
                   2243:        }
                   2244:     }
1.620     albertel 2245:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2246:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2247:     return $total;
                   2248: }
                   2249: 
                   2250: # ------------------------------------------------------- Validate an accesskey
                   2251: 
                   2252: sub validate_access_key {
                   2253:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2254:     $cdom=
1.620     albertel 2255:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2256:     $cnum=
1.620     albertel 2257:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2258:     $udom=$env{'user.domain'} unless (defined($udom));
                   2259:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2260:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2261:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2262: }
                   2263: 
                   2264: # ------------------------------------- Find the section of student in a course
1.652     albertel 2265: sub devalidate_getsection_cache {
                   2266:     my ($udom,$unam,$courseid)=@_;
                   2267:     my $hashid="$udom:$unam:$courseid";
                   2268:     &devalidate_cache_new('getsection',$hashid);
                   2269: }
1.298     matthew  2270: 
1.815     albertel 2271: sub courseid_to_courseurl {
                   2272:     my ($courseid) = @_;
                   2273:     #already url style courseid
                   2274:     return $courseid if ($courseid =~ m{^/});
                   2275: 
                   2276:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2277: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2278: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2279: 	return "/$cdom/$cnum";
                   2280:     }
                   2281: 
                   2282:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2283:     if (exists($courseinfo{'num'})) {
                   2284: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2285:     }
                   2286: 
                   2287:     return undef;
                   2288: }
                   2289: 
1.298     matthew  2290: sub getsection {
                   2291:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2292:     my $cachetime=1800;
1.551     albertel 2293: 
                   2294:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2295:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2296:     if (defined($cached)) { return $result; }
                   2297: 
1.298     matthew  2298:     my %Pending; 
                   2299:     my %Expired;
                   2300:     #
                   2301:     # Each role can either have not started yet (pending), be active, 
                   2302:     #    or have expired.
                   2303:     #
                   2304:     # If there is an active role, we are done.
                   2305:     #
                   2306:     # If there is more than one role which has not started yet, 
                   2307:     #     choose the one which will start sooner
                   2308:     # If there is one role which has not started yet, return it.
                   2309:     #
                   2310:     # If there is more than one expired role, choose the one which ended last.
                   2311:     # If there is a role which has expired, return it.
                   2312:     #
1.815     albertel 2313:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2314:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2315:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2316:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2317:         my $section=$1;
                   2318:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2319:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2320:         my $now=time;
1.548     albertel 2321:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2322:             $Expired{$end}=$section;
                   2323:             next;
                   2324:         }
1.548     albertel 2325:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2326:             $Pending{$start}=$section;
                   2327:             next;
                   2328:         }
1.599     albertel 2329:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2330:     }
                   2331:     #
                   2332:     # Presumedly there will be few matching roles from the above
                   2333:     # loop and the sorting time will be negligible.
                   2334:     if (scalar(keys(%Pending))) {
                   2335:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2336:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2337:     } 
                   2338:     if (scalar(keys(%Expired))) {
                   2339:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2340:         my $time = pop(@sorted);
1.599     albertel 2341:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2342:     }
1.599     albertel 2343:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2344: }
1.70      www      2345: 
1.599     albertel 2346: sub save_cache {
                   2347:     &purge_remembered();
1.722     albertel 2348:     #&Apache::loncommon::validate_page();
1.620     albertel 2349:     undef(%env);
1.780     albertel 2350:     undef($env_loaded);
1.599     albertel 2351: }
1.452     albertel 2352: 
1.599     albertel 2353: my $to_remember=-1;
                   2354: my %remembered;
                   2355: my %accessed;
                   2356: my $kicks=0;
                   2357: my $hits=0;
1.849     albertel 2358: sub make_key {
                   2359:     my ($name,$id) = @_;
1.872     albertel 2360:     if (length($id) > 65 
                   2361: 	&& length(&escape($id)) > 200) {
                   2362: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2363:     }
1.849     albertel 2364:     return &escape($name.':'.$id);
                   2365: }
                   2366: 
1.599     albertel 2367: sub devalidate_cache_new {
                   2368:     my ($name,$id,$debug) = @_;
                   2369:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2370:     $id=&make_key($name,$id);
1.599     albertel 2371:     $memcache->delete($id);
                   2372:     delete($remembered{$id});
                   2373:     delete($accessed{$id});
                   2374: }
                   2375: 
                   2376: sub is_cached_new {
                   2377:     my ($name,$id,$debug) = @_;
1.849     albertel 2378:     $id=&make_key($name,$id);
1.599     albertel 2379:     if (exists($remembered{$id})) {
1.1133    foxr     2380: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2381: 	$accessed{$id}=[&gettimeofday()];
                   2382: 	$hits++;
                   2383: 	return ($remembered{$id},1);
                   2384:     }
                   2385:     my $value = $memcache->get($id);
                   2386:     if (!(defined($value))) {
                   2387: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2388: 	return (undef,undef);
1.416     albertel 2389:     }
1.599     albertel 2390:     if ($value eq '__undef__') {
                   2391: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2392: 	$value=undef;
                   2393:     }
                   2394:     &make_room($id,$value,$debug);
                   2395:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2396:     return ($value,1);
                   2397: }
                   2398: 
                   2399: sub do_cache_new {
                   2400:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2401:     $id=&make_key($name,$id);
1.599     albertel 2402:     my $setvalue=$value;
                   2403:     if (!defined($setvalue)) {
                   2404: 	$setvalue='__undef__';
                   2405:     }
1.623     albertel 2406:     if (!defined($time) ) {
                   2407: 	$time=600;
                   2408:     }
1.599     albertel 2409:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2410:     my $result = $memcache->set($id,$setvalue,$time);
                   2411:     if (! $result) {
1.872     albertel 2412: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2413: 	$memcache->disconnect_all();
1.872     albertel 2414:     }
1.600     albertel 2415:     # need to make a copy of $value
1.919     albertel 2416:     &make_room($id,$value,$debug);
1.599     albertel 2417:     return $value;
                   2418: }
                   2419: 
                   2420: sub make_room {
                   2421:     my ($id,$value,$debug)=@_;
1.919     albertel 2422: 
                   2423:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2424:                                     : $value;
1.599     albertel 2425:     if ($to_remember<0) { return; }
                   2426:     $accessed{$id}=[&gettimeofday()];
                   2427:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2428:     my $to_kick;
                   2429:     my $max_time=0;
                   2430:     foreach my $other (keys(%accessed)) {
                   2431: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2432: 	    $to_kick=$other;
                   2433: 	    $max_time=&tv_interval($accessed{$other});
                   2434: 	}
                   2435:     }
                   2436:     delete($remembered{$to_kick});
                   2437:     delete($accessed{$to_kick});
                   2438:     $kicks++;
                   2439:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2440:     return;
                   2441: }
                   2442: 
1.599     albertel 2443: sub purge_remembered {
1.604     albertel 2444:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2445:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2446:     undef(%remembered);
                   2447:     undef(%accessed);
1.428     albertel 2448: }
1.70      www      2449: # ------------------------------------- Read an entry from a user's environment
                   2450: 
                   2451: sub userenvironment {
                   2452:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2453:     my $items;
                   2454:     foreach my $item (@what) {
                   2455:         $items.=&escape($item).'&';
                   2456:     }
                   2457:     $items=~s/\&$//;
1.70      www      2458:     my %returnhash=();
1.1009    raeburn  2459:     my $uhome = &homeserver($unam,$udom);
                   2460:     unless ($uhome eq 'no_host') {
                   2461:         my @answer=split(/\&/, 
                   2462:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2463:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2464:             return %returnhash;
                   2465:         }
1.1009    raeburn  2466:         my $i;
                   2467:         for ($i=0;$i<=$#what;$i++) {
                   2468: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2469:         }
1.70      www      2470:     }
                   2471:     return %returnhash;
1.1       albertel 2472: }
                   2473: 
1.617     albertel 2474: # ---------------------------------------------------------- Get a studentphoto
                   2475: sub studentphoto {
                   2476:     my ($udom,$unam,$ext) = @_;
                   2477:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2478:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2479:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2480:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2481:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2482:             } else {
                   2483:                 my ($result,$perm_reqd)=
1.707     albertel 2484: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2485:                 if ($result eq 'ok') {
                   2486:                     if (!($perm_reqd eq 'yes')) {
                   2487:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2488:                     }
                   2489:                 }
                   2490:             }
                   2491:         }
                   2492:     } else {
                   2493:         my ($result,$perm_reqd) = 
1.707     albertel 2494: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2495:         if ($result eq 'ok') {
                   2496:             if (!($perm_reqd eq 'yes')) {
                   2497:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2498:             }
                   2499:         }
                   2500:     }
                   2501:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2502: }
                   2503: 
                   2504: sub retrievestudentphoto {
                   2505:     my ($udom,$unam,$ext,$type) = @_;
                   2506:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2507:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2508:     if ($ret eq 'ok') {
                   2509:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2510:         if ($type eq 'thumbnail') {
                   2511:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2512:         }
                   2513:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2514:         return $tokenurl;
                   2515:     } else {
                   2516:         if ($type eq 'thumbnail') {
                   2517:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2518:         } else { 
                   2519:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2520:         }
1.617     albertel 2521:     }
                   2522: }
                   2523: 
1.263     www      2524: # -------------------------------------------------------------------- New chat
                   2525: 
                   2526: sub chatsend {
1.724     raeburn  2527:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2528:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2529:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2530:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2531:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2532: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2533: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2534: }
                   2535: 
                   2536: # ------------------------------------------ Find current version of a resource
                   2537: 
                   2538: sub getversion {
                   2539:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2540:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2541:     return &currentversion(&filelocation('',$fname));
                   2542: }
                   2543: 
                   2544: sub currentversion {
                   2545:     my $fname=shift;
                   2546:     my $author=$fname;
                   2547:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2548:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2549:     my $home=&homeserver($uname,$udom);
1.292     www      2550:     if ($home eq 'no_host') { 
                   2551:         return -1; 
                   2552:     }
1.1112    www      2553:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2554:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2555: 	return -1;
                   2556:     }
1.1112    www      2557:     return $answer;
1.263     www      2558: }
                   2559: 
1.1111    www      2560: #
                   2561: # Return special version number of resource if set by override, empty otherwise
                   2562: #
                   2563: sub usedversion {
                   2564:     my $fname=shift;
                   2565:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2566:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2567:     if ($urlversion) { return $urlversion; }
                   2568:     return '';
                   2569: }
                   2570: 
1.1       albertel 2571: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2572: 
1.1       albertel 2573: sub subscribe {
                   2574:     my $fname=shift;
1.761     raeburn  2575:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2576:     $fname=~s/[\n\r]//g;
1.1       albertel 2577:     my $author=$fname;
                   2578:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2579:     my ($udom,$uname)=split(/\//,$author);
                   2580:     my $home=homeserver($uname,$udom);
1.335     albertel 2581:     if ($home eq 'no_host') {
                   2582:         return 'not_found';
1.1       albertel 2583:     }
                   2584:     my $answer=reply("sub:$fname",$home);
1.64      www      2585:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2586: 	$answer.=' by '.$home;
                   2587:     }
1.1       albertel 2588:     return $answer;
                   2589: }
                   2590:     
1.8       www      2591: # -------------------------------------------------------------- Replicate file
                   2592: 
                   2593: sub repcopy {
                   2594:     my $filename=shift;
1.23      www      2595:     $filename=~s/\/+/\//g;
1.1142    raeburn  2596:     my $londocroot = $perlvar{'lonDocRoot'};
                   2597:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2598:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2599:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2600: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2601: 	return &repcopy_userfile($filename);
                   2602:     }
1.532     albertel 2603:     $filename=~s/[\n\r]//g;
1.8       www      2604:     my $transname="$filename.in.transfer";
1.828     www      2605: # FIXME: this should flock
1.607     raeburn  2606:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2607:     my $remoteurl=subscribe($filename);
1.64      www      2608:     if ($remoteurl =~ /^con_lost by/) {
                   2609: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2610:            return 'unavailable';
1.8       www      2611:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2612: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2613: 	   return 'not_found';
1.64      www      2614:     } elsif ($remoteurl =~ /^rejected by/) {
                   2615: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2616:            return 'forbidden';
1.20      www      2617:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2618:            return 'ok';
1.8       www      2619:     } else {
1.290     www      2620:         my $author=$filename;
                   2621:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2622:         my ($udom,$uname)=split(/\//,$author);
                   2623:         my $home=homeserver($uname,$udom);
                   2624:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2625:            my @parts=split(/\//,$filename);
                   2626:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2627:            if ($path ne "$londocroot/res") {
1.8       www      2628:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2629: 	       return 'bad_request';
1.8       www      2630:            }
                   2631:            my $count;
                   2632:            for ($count=5;$count<$#parts;$count++) {
                   2633:                $path.="/$parts[$count]";
                   2634:                if ((-e $path)!=1) {
                   2635: 		   mkdir($path,0777);
                   2636:                }
                   2637:            }
                   2638:            my $ua=new LWP::UserAgent;
                   2639:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2640:            my $response=$ua->request($request,$transname);
                   2641:            if ($response->is_error()) {
                   2642: 	       unlink($transname);
                   2643:                my $message=$response->status_line;
1.672     albertel 2644:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2645:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2646:                return 'unavailable';
1.8       www      2647:            } else {
1.16      www      2648: 	       if ($remoteurl!~/\.meta$/) {
                   2649:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2650:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2651:                   if ($mresponse->is_error()) {
                   2652: 		      unlink($filename.'.meta');
                   2653:                       &logthis(
1.672     albertel 2654:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2655:                   }
                   2656: 	       }
1.8       www      2657:                rename($transname,$filename);
1.607     raeburn  2658:                return 'ok';
1.8       www      2659:            }
1.290     www      2660:        }
1.8       www      2661:     }
1.330     www      2662: }
                   2663: 
                   2664: # ------------------------------------------------ Get server side include body
                   2665: sub ssi_body {
1.381     albertel 2666:     my ($filelink,%form)=@_;
1.606     matthew  2667:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2668:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2669:     }
1.953     www      2670:     my $output='';
                   2671:     my $response;
1.980     raeburn  2672:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2673:        ($output,$response)=&externalssi($filelink);
1.953     www      2674:     } else {
1.1004    droeschl 2675:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2676:        $filelink .= 'inhibitmenu=yes';
1.953     www      2677:        ($output,$response)=&ssi($filelink,%form);
                   2678:     }
1.778     albertel 2679:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2680:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2681:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2682:     if (wantarray) {
                   2683:         return ($output, $response);
                   2684:     } else {
                   2685:         return $output;
                   2686:     }
1.8       www      2687: }
                   2688: 
1.15      www      2689: # --------------------------------------------------------- Server Side Include
                   2690: 
1.782     albertel 2691: sub absolute_url {
                   2692:     my ($host_name) = @_;
                   2693:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2694:     if ($host_name eq '') {
                   2695: 	$host_name = $ENV{'SERVER_NAME'};
                   2696:     }
                   2697:     return $protocol.$host_name;
                   2698: }
                   2699: 
1.942     foxr     2700: #
                   2701: #   Server side include.
                   2702: # Parameters:
                   2703: #  fn     Possibly encrypted resource name/id.
                   2704: #  form   Hash that describes how the rendering should be done
                   2705: #         and other things.
1.944     foxr     2706: # Returns:
1.950     raeburn  2707: #   Scalar context: The content of the response.
                   2708: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2709: #     
1.15      www      2710: sub ssi {
                   2711: 
1.944     foxr     2712:     my ($fn,%form)=@_;
1.15      www      2713:     my $ua=new LWP::UserAgent;
1.23      www      2714:     my $request;
1.711     albertel 2715: 
                   2716:     $form{'no_update_last_known'}=1;
1.895     albertel 2717:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2718:     if (%form) {
1.782     albertel 2719:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2720:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2721:     } else {
1.782     albertel 2722:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2723:     }
                   2724: 
1.15      www      2725:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2726:     my $response= $ua->request($request);
1.944     foxr     2727:     if (wantarray) {
1.1172.2.3  raeburn  2728: 	return ($response->content, $response);
1.944     foxr     2729:     } else {
1.1172.2.3  raeburn  2730: 	return $response->content;
1.942     foxr     2731:     }
1.324     www      2732: }
                   2733: 
                   2734: sub externalssi {
                   2735:     my ($url)=@_;
                   2736:     my $ua=new LWP::UserAgent;
                   2737:     my $request=new HTTP::Request('GET',$url);
                   2738:     my $response=$ua->request($request);
1.954     raeburn  2739:     if (wantarray) {
                   2740:         return ($response->content, $response);
                   2741:     } else {
                   2742:         return $response->content;
                   2743:     }
1.15      www      2744: }
1.254     www      2745: 
1.492     albertel 2746: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2747: 
                   2748: sub allowuploaded {
                   2749:     my ($srcurl,$url)=@_;
                   2750:     $url=&clutter(&declutter($url));
                   2751:     my $dir=$url;
                   2752:     $dir=~s/\/[^\/]+$//;
                   2753:     my %httpref=();
                   2754:     my $httpurl=&hreflocation('',$url);
                   2755:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2756:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2757: }
1.477     raeburn  2758: 
1.1172.2.13  raeburn  2759: #
                   2760: # Determine if the current user should be able to edit a particular resource,
                   2761: # when viewing in course context.
                   2762: # (a) When viewing resource used to determine if "Edit" item is included in
                   2763: #     Functions.
                   2764: # (b) When displaying folder contents in course editor, used to determine if
                   2765: #     "Edit" link will be displayed alongside resource.
                   2766: #
                   2767: #  input: six args -- filename (decluttered), course number, course domain,
                   2768: #                   url, symb (if registered) and group (if this is a group
                   2769: #                   item -- e.g., bulletin board, group page etc.).
                   2770: #  output: array of five scalars --
                   2771: #          $cfile -- url for file editing if editable on current server
                   2772: #          $home -- homeserver of resource (i.e., for author if published,
                   2773: #                                           or course if uploaded.).
                   2774: #          $switchserver --  1 if server switch will be needed.
                   2775: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2776: #          $forceview -- 1 if icon/link should be to go to view mode
                   2777: #
                   2778: 
                   2779: sub can_edit_resource {
                   2780:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2781:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2782: #
                   2783: # For aboutme pages user can only edit his/her own.
                   2784: #
                   2785:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2786:         my ($sdom,$sname) = ($1,$2);
                   2787:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2788:             $home = $env{'user.home'};
                   2789:             $cfile = $resurl;
                   2790:             if ($env{'form.forceedit'}) {
                   2791:                 $forceview = 1;
                   2792:             } else {
                   2793:                 $forceedit = 1;
                   2794:             }
                   2795:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2796:         } else {
                   2797:             return;
                   2798:         }
                   2799:     }
                   2800: 
                   2801:     if ($env{'request.course.id'}) {
                   2802:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2803:         if ($group ne '') {
                   2804: # if this is a group homepage or group bulletin board, check group privs
                   2805:             my $allowed = 0;
                   2806:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2807:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2808:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2809:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2810:                     $allowed = 1;
                   2811:                 }
                   2812:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2813:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2814:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2815:                     $allowed = 1;
                   2816:                 }
                   2817:             }
                   2818:             if ($allowed) {
                   2819:                 $home=&homeserver($cnum,$cdom);
                   2820:                 if ($env{'form.forceedit'}) {
                   2821:                     $forceview = 1;
                   2822:                 } else {
                   2823:                     $forceedit = 1;
                   2824:                 }
                   2825:                 $cfile = $resurl;
                   2826:             } else {
                   2827:                 return;
                   2828:             }
                   2829:         } else {
1.1172.2.15  raeburn  2830:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2831:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2832:                     return;
                   2833:                 }
                   2834:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2835: #
                   2836: # No edit allowed where CC has switched to student role.
                   2837: #
                   2838:                 return;
                   2839:             }
                   2840:         }
                   2841:     }
                   2842: 
                   2843:     if ($file ne '') {
                   2844:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2845:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2846:                 $uploaded = 1;
                   2847:                 $incourse = 1;
                   2848:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2849:                     $cfile = &hreflocation('',$file);
                   2850:                     if ($env{'form.forceedit'}) {
                   2851:                         $forceview = 1;
                   2852:                     } else {
                   2853:                         $forceedit = 1;
                   2854:                     }
                   2855:                 }
                   2856:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2857:                 $incourse = 1;
                   2858:                 if ($env{'form.forceedit'}) {
                   2859:                     $forceview = 1;
                   2860:                 } else {
                   2861:                     $forceedit = 1;
                   2862:                 }
                   2863:                 $cfile = $resurl;
                   2864:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2865:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2866:                     $incourse = 1;
                   2867:                     if ($env{'form.forceedit'}) {
                   2868:                         $forceview = 1;
                   2869:                     } else {
                   2870:                         $forceedit = 1;
                   2871:                     }
                   2872:                     $cfile = $resurl;
                   2873:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2874:                     $incourse = 1;
                   2875:                     $cfile = $resurl.'/smpedit';
                   2876:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2877:                     $incourse = 1;
                   2878:                     if ($env{'form.forceedit'}) {
                   2879:                         $forceview = 1;
                   2880:                     } else {
                   2881:                         $forceedit = 1;
                   2882:                     }
                   2883:                     $cfile = $resurl;
1.1172.2.15  raeburn  2884:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2885:                     $incourse = 1;
                   2886:                     if ($env{'form.forceedit'}) {
                   2887:                         $forceview = 1;
                   2888:                     } else {
                   2889:                         $forceedit = 1;
                   2890:                     }
                   2891:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2892:                 }
                   2893:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2894:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2895:                 if (&is_on_map($template)) {
                   2896:                     $incourse = 1;
                   2897:                     $forceview = 1;
                   2898:                     $cfile = $template;
                   2899:                 }
                   2900:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2901:                     $incourse = 1;
                   2902:                     if ($env{'form.forceedit'}) {
                   2903:                         $forceview = 1;
                   2904:                     } else {
                   2905:                         $forceedit = 1;
                   2906:                     }
                   2907:                     $cfile = $resurl;
                   2908:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2909:                 $incourse = 1;
                   2910:                 $forceview = 1;
                   2911:                 if ($symb) {
                   2912:                     my ($map,$id,$res)=&decode_symb($symb);
                   2913:                     $env{'request.symb'} = $symb;
                   2914:                     $cfile = &clutter($res);
                   2915:                 } else {
                   2916:                     $cfile = $env{'form.suppurl'};
                   2917:                     $cfile =~ s{^http://}{};
                   2918:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2919:                 }
1.1172.2.31  raeburn  2920:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2921:                 if ($env{'form.forceedit'}) {
                   2922:                     $forceview = 1;
                   2923:                 } else {
                   2924:                     $forceedit = 1;
                   2925:                 }
                   2926:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2927:             }
                   2928:         }
                   2929:         if ($uploaded || $incourse) {
                   2930:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2931:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2932:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2933:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2934:             # Check that the user has permission to edit this resource
                   2935:             my $setpriv = 1;
                   2936:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2937:             if (defined($cfudom)) {
                   2938:                 $home=&homeserver($cfuname,$cfudom);
                   2939:                 $cfile=$file;
                   2940:             }
                   2941:         }
                   2942:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2943:             (($home ne '') && ($home ne 'no_host'))) {
                   2944:             my @ids=&current_machine_ids();
                   2945:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2946:                 $switchserver=1;
                   2947:             }
                   2948:         }
                   2949:     }
                   2950:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2951: }
                   2952: 
                   2953: sub is_course_upload {
                   2954:     my ($file,$cnum,$cdom) = @_;
                   2955:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2956:     $uploadpath =~ s{^\/}{};
                   2957:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2958:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2959:         return 1;
                   2960:     }
                   2961:     return;
                   2962: }
                   2963: 
                   2964: sub in_course {
                   2965:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2966:     if ($hideprivileged) {
                   2967:         my $skipuser;
1.1172.2.23  raeburn  2968:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2969:         my @possdoms = ($cdom);
                   2970:         if ($coursehash{'checkforpriv'}) {
                   2971:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   2972:         }
                   2973:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  2974:             $skipuser = 1;
                   2975:             if ($coursehash{'nothideprivileged'}) {
                   2976:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2977:                     my $user;
                   2978:                     if ($item =~ /:/) {
                   2979:                         $user = $item;
                   2980:                     } else {
                   2981:                         $user = join(':',split(/[\@]/,$item));
                   2982:                     }
                   2983:                     if ($user eq $uname.':'.$udom) {
                   2984:                         undef($skipuser);
                   2985:                         last;
                   2986:                     }
                   2987:                 }
                   2988:             }
                   2989:             if ($skipuser) {
                   2990:                 return 0;
                   2991:             }
                   2992:         }
                   2993:     }
                   2994:     $type ||= 'any';
                   2995:     if (!defined($cdom) || !defined($cnum)) {
                   2996:         my $cid  = $env{'request.course.id'};
                   2997:         $cdom = $env{'course.'.$cid.'.domain'};
                   2998:         $cnum = $env{'course.'.$cid.'.num'};
                   2999:     }
                   3000:     my $typesref;
                   3001:     if (($type eq 'any') || ($type eq 'all')) {
                   3002:         $typesref = ['active','previous','future'];
                   3003:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3004:         $typesref = [$type];
                   3005:     }
                   3006:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3007:                               $typesref,undef,[$cdom]);
                   3008:     my ($tmp) = keys(%roles);
                   3009:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3010:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3011:     if (@course_roles > 0) {
                   3012:         return 1;
                   3013:     }
                   3014:     return 0;
                   3015: }
                   3016: 
1.478     albertel 3017: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3018: # input: action, courseID, current domain, intended
1.637     raeburn  3019: #        path to file, source of file, instruction to parse file for objects,
                   3020: #        ref to hash for embedded objects,
                   3021: #        ref to hash for codebase of java objects.
1.1095    raeburn  3022: #        reference to scalar to accommodate mime type determined
                   3023: #          from File::MMagic if $parser = parse.
1.637     raeburn  3024: #
1.485     raeburn  3025: # output: url to file (if action was uploaddoc), 
                   3026: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3027: #
1.478     albertel 3028: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3029: # course.
1.477     raeburn  3030: #
1.478     albertel 3031: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3032: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3033: #          course's home server.
1.477     raeburn  3034: #
1.478     albertel 3035: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3036: #          be copied from $source (current location) to 
                   3037: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3038: #         and will then be copied to
                   3039: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3040: #         course's home server.
1.485     raeburn  3041: #
1.481     raeburn  3042: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3043: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3044: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3045: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3046: #         in course's home server.
1.637     raeburn  3047: #
1.477     raeburn  3048: 
                   3049: sub process_coursefile {
1.1095    raeburn  3050:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3051:         $mimetype)=@_;
1.477     raeburn  3052:     my $fetchresult;
1.638     albertel 3053:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3054:     if ($action eq 'propagate') {
1.638     albertel 3055:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3056: 			     $home);
1.481     raeburn  3057:     } else {
1.477     raeburn  3058:         my $fpath = '';
                   3059:         my $fname = $file;
1.478     albertel 3060:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3061:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3062:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3063:         if ($action eq 'copy') {
                   3064:             if ($source eq '') {
                   3065:                 $fetchresult = 'no source file';
                   3066:                 return $fetchresult;
                   3067:             } else {
                   3068:                 my $destination = $filepath.'/'.$fname;
                   3069:                 rename($source,$destination);
                   3070:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3071:                                  $home);
1.481     raeburn  3072:             }
                   3073:         } elsif ($action eq 'uploaddoc') {
                   3074:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3075:             print $fh $env{'form.'.$source};
1.481     raeburn  3076:             close($fh);
1.637     raeburn  3077:             if ($parser eq 'parse') {
1.1024    raeburn  3078:                 my $mm = new File::MMagic;
1.1095    raeburn  3079:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3080:                 if ($type eq 'text/html') {
1.1024    raeburn  3081:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3082:                     unless ($parse_result eq 'ok') {
                   3083:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3084:                     }
1.637     raeburn  3085:                 }
1.1095    raeburn  3086:                 if (ref($mimetype)) {
                   3087:                     $$mimetype = $type;
                   3088:                 } 
1.637     raeburn  3089:             }
1.477     raeburn  3090:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3091:                                  $home);
1.481     raeburn  3092:             if ($fetchresult eq 'ok') {
                   3093:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3094:             } else {
                   3095:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3096:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3097:                 return '/adm/notfound.html';
                   3098:             }
1.477     raeburn  3099:         }
                   3100:     }
1.485     raeburn  3101:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3102:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3103:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3104:     }
                   3105:     return $fetchresult;
                   3106: }
                   3107: 
1.637     raeburn  3108: sub build_filepath {
                   3109:     my ($fpath) = @_;
                   3110:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3111:     unless ($fpath eq '') {
                   3112:         my @parts=split('/',$fpath);
                   3113:         foreach my $part (@parts) {
                   3114:             $filepath.= '/'.$part;
                   3115:             if ((-e $filepath)!=1) {
                   3116:                 mkdir($filepath,0777);
                   3117:             }
                   3118:         }
                   3119:     }
                   3120:     return $filepath;
                   3121: }
                   3122: 
                   3123: sub store_edited_file {
1.638     albertel 3124:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3125:     my $file = $primary_url;
                   3126:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3127:     my $fpath = '';
                   3128:     my $fname = $file;
                   3129:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3130:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3131:     my $filepath = &build_filepath($fpath);
                   3132:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3133:     print $fh $content;
                   3134:     close($fh);
1.638     albertel 3135:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3136:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3137: 			  $home);
1.637     raeburn  3138:     if ($$fetchresult eq 'ok') {
                   3139:         return '/uploaded/'.$fpath.'/'.$fname;
                   3140:     } else {
1.638     albertel 3141:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3142: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3143:         return '/adm/notfound.html';
                   3144:     }
                   3145: }
                   3146: 
1.531     albertel 3147: sub clean_filename {
1.831     albertel 3148:     my ($fname,$args)=@_;
1.315     www      3149: # Replace Windows backslashes by forward slashes
1.257     www      3150:     $fname=~s/\\/\//g;
1.831     albertel 3151:     if (!$args->{'keep_path'}) {
                   3152:         # Get rid of everything but the actual filename
                   3153: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3154:     }
1.315     www      3155: # Replace spaces by underscores
                   3156:     $fname=~s/\s+/\_/g;
                   3157: # Replace all other weird characters by nothing
1.831     albertel 3158:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3159: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3160: # numbers
                   3161:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3162:     return $fname;
                   3163: }
1.1051    raeburn  3164: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3165: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3166: # image with the same aspect ratio as the original, but with dimensions which do 
                   3167: # not exceed $resizewidth and $resizeheight.
                   3168:  
1.984     neumanie 3169: sub resizeImage {
1.1051    raeburn  3170:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3171:     my $ima = Image::Magick->new;
                   3172:     my $resized;
                   3173:     if (-e $img_path) {
                   3174:         $ima->Read($img_path);
                   3175:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3176:             my $width = $ima->Get('width');
                   3177:             my $height = $ima->Get('height');
                   3178:             if ($width > $resizewidth) {
                   3179: 	        my $factor = $width/$resizewidth;
                   3180:                 my $newheight = $height/$factor;
                   3181:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3182:                 $resized = 1;
                   3183:             }
                   3184:         }
                   3185:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3186:             my $width = $ima->Get('width');
                   3187:             my $height = $ima->Get('height');
                   3188:             if ($height > $resizeheight) {
                   3189:                 my $factor = $height/$resizeheight;
                   3190:                 my $newwidth = $width/$factor;
                   3191:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3192:                 $resized = 1;
                   3193:             }
                   3194:         }
                   3195:         if ($resized) {
                   3196:             $ima->Write($img_path);
                   3197:         }
                   3198:     }
                   3199:     return;
1.977     amueller 3200: }
                   3201: 
1.608     albertel 3202: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3203: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3204: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3205: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3206: #                                    canceloverwrite, or ''. 
                   3207: #                   if 'coursedoc': upload to the current course
                   3208: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3209: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3210: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3211: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3212: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3213: #        $allfiles - reference to hash for embedded objects
                   3214: #        $codebase - reference to hash for codebase of java objects
                   3215: #        $desuname - username for permanent storage of uploaded file
                   3216: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3217: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3218: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3219: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3220: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3221: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3222: #                    from File::MMagic.
1.858     raeburn  3223: # 
1.686     albertel 3224: # output: url of file in userspace, or error: <message> 
                   3225: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3226: 
1.531     albertel 3227: sub userfileupload {
1.1090    raeburn  3228:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3229:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3230:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3231:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3232:     $fname=&clean_filename($fname);
1.1090    raeburn  3233:     # See if there is anything left
1.257     www      3234:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3235:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3236:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3237:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3238:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3239:         my $now = time;
1.1090    raeburn  3240:         my $filepath;
1.1095    raeburn  3241:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3242:              $filepath = 'tmp/helprequests/'.$now;
                   3243:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3244:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3245:                          '_'.$env{'user.domain'}.'/pending';
                   3246:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3247:             my ($docuname,$docudom);
                   3248:             if ($destudom) {
                   3249:                 $docudom = $destudom;
                   3250:             } else {
                   3251:                 $docudom = $env{'user.domain'};
                   3252:             }
                   3253:             if ($destuname) {
                   3254:                 $docuname = $destuname;
                   3255:             } else {
                   3256:                 $docuname = $env{'user.name'};
                   3257:             }
                   3258:             if (exists($env{'form.group'})) {
                   3259:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3260:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3261:             }
                   3262:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3263:             if ($context eq 'canceloverwrite') {
                   3264:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3265:                 if (-e  $tempfile) {
                   3266:                     my @info = stat($tempfile);
                   3267:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3268:                         unlink($tempfile);
                   3269:                     }
                   3270:                 }
                   3271:                 return;
1.523     raeburn  3272:             }
                   3273:         }
1.1090    raeburn  3274:         # Create the directory if not present
1.741     raeburn  3275:         my @parts=split(/\//,$filepath);
                   3276:         my $fullpath = $perlvar{'lonDaemons'};
                   3277:         for (my $i=0;$i<@parts;$i++) {
                   3278:             $fullpath .= '/'.$parts[$i];
                   3279:             if ((-e $fullpath)!=1) {
                   3280:                 mkdir($fullpath,0777);
                   3281:             }
                   3282:         }
                   3283:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3284:         print $fh $env{'form.'.$formname};
                   3285:         close($fh);
1.1090    raeburn  3286:         if ($context eq 'existingfile') {
                   3287:             my @info = stat($fullpath.'/'.$fname);
                   3288:             return ($fullpath.'/'.$fname,$info[9]);
                   3289:         } else {
                   3290:             return $fullpath.'/'.$fname;
                   3291:         }
1.523     raeburn  3292:     }
1.995     raeburn  3293:     if ($subdir eq 'scantron') {
                   3294:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3295:     } else {
1.995     raeburn  3296:         $fname="$subdir/$fname";
                   3297:     }
1.1090    raeburn  3298:     if ($context eq 'coursedoc') {
1.638     albertel 3299: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3300: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3301:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3302:             return &finishuserfileupload($docuname,$docudom,
                   3303: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3304: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3305:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3306:         } else {
1.1172.2.21  raeburn  3307:             if ($env{'form.folder'}) {
                   3308:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3309:             }
1.638     albertel 3310:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3311: 				       $fname,$formname,$parser,
1.1095    raeburn  3312: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3313:         }
1.719     banghart 3314:     } elsif (defined($destuname)) {
                   3315:         my $docuname=$destuname;
                   3316:         my $docudom=$destudom;
1.860     raeburn  3317: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3318: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3319:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3320:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3321:     } else {
1.638     albertel 3322:         my $docuname=$env{'user.name'};
                   3323:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3324:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3325:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3326:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3327:         }
1.860     raeburn  3328: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3329: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3330:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3331:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3332:     }
1.271     www      3333: }
                   3334: 
                   3335: sub finishuserfileupload {
1.860     raeburn  3336:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3337:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3338:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3339:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3340:   
1.860     raeburn  3341:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3342:     $file=$fname;
                   3343:     if ($fname=~m|/|) {
                   3344:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3345: 	$path.=$fnamepath.'/';
                   3346:     }
1.259     www      3347:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3348:     my $count;
                   3349:     for ($count=4;$count<=$#parts;$count++) {
                   3350:         $filepath.="/$parts[$count]";
                   3351:         if ((-e $filepath)!=1) {
                   3352: 	    mkdir($filepath,0777);
                   3353:         }
                   3354:     }
1.984     neumanie 3355: 
1.258     www      3356: # Save the file
                   3357:     {
1.701     albertel 3358: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3359: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3360: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3361: 	    return '/adm/notfound.html';
                   3362: 	}
1.1090    raeburn  3363:         if ($context eq 'overwrite') {
1.1117    foxr     3364:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3365:             my $target = $filepath.'/'.$file;
                   3366:             if (-e $source) {
                   3367:                 my @info = stat($source);
                   3368:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3369:                     unless (&File::Copy::move($source,$target)) {
                   3370:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3371:                         return "Moving from $source failed";
                   3372:                     }
                   3373:                 } else {
                   3374:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3375:                 }
                   3376:             } else {
                   3377:                 return "Temporary file: $source missing";
                   3378:             }
                   3379:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3380: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3381: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3382: 	    return '/adm/notfound.html';
                   3383: 	}
1.570     albertel 3384: 	close(FH);
1.1051    raeburn  3385:         if ($resizewidth && $resizeheight) {
                   3386:             my $mm = new File::MMagic;
                   3387:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3388:             if ($mime_type =~ m{^image/}) {
                   3389: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3390:             }  
1.977     amueller 3391: 	}
1.258     www      3392:     }
1.1152    raeburn  3393:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3394:         if (ref($mimetype)) {
                   3395:             if ($$mimetype eq '') {
                   3396:                 my $mm = new File::MMagic;
                   3397:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3398:                 $$mimetype = $type;
                   3399:             }
                   3400:         }
                   3401:     }
1.637     raeburn  3402:     if ($parser eq 'parse') {
1.1152    raeburn  3403:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3404:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3405:                                                        $allfiles,$codebase);
                   3406:             unless ($parse_result eq 'ok') {
                   3407:                 &logthis('Failed to parse '.$filepath.$file.
                   3408: 	   	         ' for embedded media: '.$parse_result); 
                   3409:             }
1.637     raeburn  3410:         }
                   3411:     }
1.860     raeburn  3412:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3413:         my $input = $filepath.'/'.$file;
                   3414:         my $output = $filepath.'/'.'tn-'.$file;
                   3415:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3416:         system("convert -sample $thumbsize $input $output");
                   3417:         if (-e $filepath.'/'.'tn-'.$file) {
                   3418:             $fetchthumb  = 1; 
                   3419:         }
                   3420:     }
1.858     raeburn  3421:  
1.259     www      3422: # Notify homeserver to grep it
                   3423: #
1.984     neumanie 3424:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3425:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3426:     if ($fetchresult eq 'ok') {
1.860     raeburn  3427:         if ($fetchthumb) {
                   3428:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3429:             if ($thumbresult ne 'ok') {
                   3430:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3431:                          $docuhome.': '.$thumbresult);
                   3432:             }
                   3433:         }
1.259     www      3434: #
1.258     www      3435: # Return the URL to it
1.494     albertel 3436:         return '/uploaded/'.$path.$file;
1.263     www      3437:     } else {
1.494     albertel 3438:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3439: 		 ': '.$fetchresult);
1.263     www      3440:         return '/adm/notfound.html';
1.858     raeburn  3441:     }
1.493     albertel 3442: }
                   3443: 
1.637     raeburn  3444: sub extract_embedded_items {
1.961     raeburn  3445:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3446:     my @state = ();
1.1164    raeburn  3447:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3448:     my %javafiles = (
                   3449:                       codebase => '',
                   3450:                       code => '',
                   3451:                       archive => ''
                   3452:                     );
                   3453:     my %mediafiles = (
                   3454:                       src => '',
                   3455:                       movie => '',
                   3456:                      );
1.648     raeburn  3457:     my $p;
                   3458:     if ($content) {
                   3459:         $p = HTML::LCParser->new($content);
                   3460:     } else {
1.961     raeburn  3461:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3462:     }
1.641     albertel 3463:     while (my $t=$p->get_token()) {
1.640     albertel 3464: 	if ($t->[0] eq 'S') {
                   3465: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3466: 	    push(@state, $tagname);
1.648     raeburn  3467:             if (lc($tagname) eq 'allow') {
                   3468:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3469:             }
1.640     albertel 3470: 	    if (lc($tagname) eq 'img') {
                   3471: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3472: 	    }
1.886     albertel 3473: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3474:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3475: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3476:                 }
1.886     albertel 3477: 	    }
1.645     raeburn  3478:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3479:                 my $src;
1.645     raeburn  3480:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3481:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3482:                 } else {
1.1164    raeburn  3483:                     if ($attr->{'src'} ne '') {
                   3484:                         $src = $attr->{'src'};
                   3485:                         &add_filetype($allfiles,$src,'src');
                   3486:                     }
                   3487:                 }
                   3488:                 my $text = $p->get_trimmed_text();
                   3489:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3490:                     my @swfargs = split(/,/,$1);
                   3491:                     foreach my $item (@swfargs) {
                   3492:                         $item =~ s/["']//g;
                   3493:                         $item =~ s/^\s+//;
                   3494:                         $item =~ s/\s+$//;
                   3495:                     }
                   3496:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3497:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3498:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3499:                         } else {
                   3500:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3501:                         }
                   3502:                     }
1.645     raeburn  3503:                 }
                   3504:             }
                   3505:             if (lc($tagname) eq 'link') {
                   3506:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3507:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3508:                 }
                   3509:             }
1.640     albertel 3510: 	    if (lc($tagname) eq 'object' ||
                   3511: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3512: 		foreach my $item (keys(%javafiles)) {
                   3513: 		    $javafiles{$item} = '';
                   3514: 		}
1.1164    raeburn  3515:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3516:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3517:                 }
1.640     albertel 3518: 	    }
                   3519: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3520: 		my $name = lc($attr->{'name'});
                   3521: 		foreach my $item (keys(%javafiles)) {
                   3522: 		    if ($name eq $item) {
                   3523: 			$javafiles{$item} = $attr->{'value'};
                   3524: 			last;
                   3525: 		    }
                   3526: 		}
1.1164    raeburn  3527:                 my $pathfrom;
1.640     albertel 3528: 		foreach my $item (keys(%mediafiles)) {
                   3529: 		    if ($name eq $item) {
1.1164    raeburn  3530:                         $pathfrom = $attr->{'value'};
                   3531:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3532: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3533: 			last;
                   3534: 		    }
                   3535: 		}
1.1164    raeburn  3536:                 if ($name eq 'flashvars') {
                   3537:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3538:                 }
                   3539:                 if ($pathfrom ne '') {
                   3540:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3541:                                          $pathfrom);
                   3542:                 }
1.640     albertel 3543: 	    }
                   3544: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3545: 		foreach my $item (keys(%javafiles)) {
                   3546: 		    if ($attr->{$item}) {
                   3547: 			$javafiles{$item} = $attr->{$item};
                   3548: 			last;
                   3549: 		    }
                   3550: 		}
                   3551: 		foreach my $item (keys(%mediafiles)) {
                   3552: 		    if ($attr->{$item}) {
                   3553: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3554: 			last;
                   3555: 		    }
                   3556: 		}
1.1164    raeburn  3557:                 if (lc($tagname) eq 'embed') {
                   3558:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3559:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3560:                                              $attr->{'src'});
                   3561:                     }
                   3562:                 }
1.640     albertel 3563: 	    }
1.1172.2.35  raeburn  3564:             if (lc($tagname) eq 'iframe') {
                   3565:                 my $src = $attr->{'src'} ;
                   3566:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3567:                     &add_filetype($allfiles,$src,'src');
                   3568:                 } elsif ($src =~ m{^/}) {
                   3569:                     if ($env{'request.course.id'}) {
                   3570:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3571:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3572:                         my $url = &hreflocation('',$fullpath);
                   3573:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3574:                             my $relpath = $1;
                   3575:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3576:                                 &add_filetype($allfiles,$1,'src');
                   3577:                             }
                   3578:                         }
                   3579:                     }
                   3580:                 }
                   3581:             }
1.1164    raeburn  3582:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3583:                 pop(@state);
1.1164    raeburn  3584:             }
1.640     albertel 3585: 	} elsif ($t->[0] eq 'E') {
                   3586: 	    my ($tagname) = ($t->[1]);
                   3587: 	    if ($javafiles{'codebase'} ne '') {
                   3588: 		$javafiles{'codebase'} .= '/';
                   3589: 	    }  
                   3590: 	    if (lc($tagname) eq 'applet' ||
                   3591: 		lc($tagname) eq 'object' ||
                   3592: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3593: 		) {
                   3594: 		foreach my $item (keys(%javafiles)) {
                   3595: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3596: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3597: 			&add_filetype($allfiles,$file,$item);
                   3598: 		    }
                   3599: 		}
                   3600: 	    } 
                   3601: 	    pop @state;
                   3602: 	}
                   3603:     }
1.1164    raeburn  3604:     foreach my $id (sort(keys(%flashvars))) {
                   3605:         if ($shockwave{$id} ne '') {
                   3606:             my @pairs = split(/\&/,$flashvars{$id});
                   3607:             foreach my $pair (@pairs) {
                   3608:                 my ($key,$value) = split(/\=/,$pair);
                   3609:                 if ($key eq 'thumb') {
                   3610:                     &add_filetype($allfiles,$value,$key);
                   3611:                 } elsif ($key eq 'content') {
                   3612:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3613:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3614:                     if ($ext ne '') {
                   3615:                         &add_filetype($allfiles,$path.$value,$ext);
                   3616:                     }
                   3617:                 }
                   3618:             }
                   3619:         }
                   3620:     }
1.637     raeburn  3621:     return 'ok';
                   3622: }
                   3623: 
1.639     albertel 3624: sub add_filetype {
                   3625:     my ($allfiles,$file,$type)=@_;
                   3626:     if (exists($allfiles->{$file})) {
                   3627: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3628: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3629: 	}
                   3630:     } else {
                   3631: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3632:     }
                   3633: }
                   3634: 
1.1164    raeburn  3635: sub embedded_dependency {
                   3636:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3637:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3638:         if (($identifier ne '') &&
                   3639:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3640:             ($pathfrom ne '')) {
                   3641:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3642:             foreach my $dep (@{$related->{$identifier}}) {
                   3643:                 &add_filetype($allfiles,$path.$dep,'object');
                   3644:             }
                   3645:         }
                   3646:     }
                   3647:     return;
                   3648: }
                   3649: 
1.493     albertel 3650: sub removeuploadedurl {
1.984     neumanie 3651:     my ($url)=@_;	
                   3652:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3653:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3654: }
                   3655: 
                   3656: sub removeuserfile {
                   3657:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3658:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3659:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3660:     if ($result eq 'ok') {	
1.798     raeburn  3661:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3662:             my $metafile = $fname.'.meta';
                   3663:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3664: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3665:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3666:             my $sqlresult = 
1.823     albertel 3667:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3668:                                         'portfolio_metadata',$group,
                   3669:                                         'delete');
1.798     raeburn  3670:         }
                   3671:     }
                   3672:     return $result;
1.257     www      3673: }
1.15      www      3674: 
1.530     albertel 3675: sub mkdiruserfile {
                   3676:     my ($docuname,$docudom,$dir)=@_;
                   3677:     my $home=&homeserver($docuname,$docudom);
                   3678:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3679: }
                   3680: 
1.531     albertel 3681: sub renameuserfile {
                   3682:     my ($docuname,$docudom,$old,$new)=@_;
                   3683:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3684:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3685:                         &escape("$old").':'.&escape("$new"),$home);
                   3686:     if ($result eq 'ok') {
                   3687:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3688:             my $oldmeta = $old.'.meta';
                   3689:             my $newmeta = $new.'.meta';
                   3690:             my $metaresult = 
                   3691:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3692: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3693:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3694:             my $sqlresult = 
1.823     albertel 3695:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3696:                                         'portfolio_metadata',$group,
                   3697:                                         'delete');
1.798     raeburn  3698:         }
                   3699:     }
                   3700:     return $result;
1.531     albertel 3701: }
                   3702: 
1.14      www      3703: # ------------------------------------------------------------------------- Log
                   3704: 
                   3705: sub log {
                   3706:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3707:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3708: }
                   3709: 
                   3710: # ------------------------------------------------------------------ Course Log
1.352     www      3711: #
                   3712: # This routine flushes several buffers of non-mission-critical nature
                   3713: #
1.157     www      3714: 
                   3715: sub flushcourselogs {
1.352     www      3716:     &logthis('Flushing log buffers');
                   3717: #
                   3718: # course logs
                   3719: # This is a log of all transactions in a course, which can be used
                   3720: # for data mining purposes
                   3721: #
                   3722: # It also collects the courseid database, which lists last transaction
                   3723: # times and course titles for all courseids
                   3724: #
                   3725:     my %courseidbuffer=();
1.921     raeburn  3726:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3727:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3728: 		          &escape($courselogs{$crsid}),
                   3729: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3730: 	    delete $courselogs{$crsid};
                   3731:         } else {
                   3732:             &logthis('Failed to flush log buffer for '.$crsid);
                   3733:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3734:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3735:                         " exceeded maximum size, deleting.</font>");
                   3736:                delete $courselogs{$crsid};
                   3737:             }
1.352     www      3738:         }
1.920     raeburn  3739:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3740:             'description' => $coursedescrbuf{$crsid},
                   3741:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3742:             'type'        => $coursetypebuf{$crsid},
                   3743:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3744:         };
1.191     harris41 3745:     }
1.352     www      3746: #
                   3747: # Write course id database (reverse lookup) to homeserver of courses 
                   3748: # Is used in pickcourse
                   3749: #
1.840     albertel 3750:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3751:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3752:                                     $courseidbuffer{$crs_home},
                   3753:                                     $crs_home,'timeonly');
1.352     www      3754:     }
                   3755: #
                   3756: # File accesses
                   3757: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3758: #
1.449     matthew  3759:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3760:         if ($entry =~ /___count$/) {
                   3761:             my ($dom,$name);
1.807     albertel 3762:             ($dom,$name,undef)=
1.811     albertel 3763: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3764:             if (! defined($dom) || $dom eq '' || 
                   3765:                 ! defined($name) || $name eq '') {
1.620     albertel 3766:                 my $cid = $env{'request.course.id'};
                   3767:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3768:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3769:             }
1.450     matthew  3770:             my $value = $accesshash{$entry};
                   3771:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3772:             my %temphash=($url => $value);
1.449     matthew  3773:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3774:             if ($result eq 'ok') {
                   3775:                 delete $accesshash{$entry};
                   3776:             }
                   3777:         } else {
1.811     albertel 3778:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3779:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3780:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3781:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3782:                 delete $accesshash{$entry};
                   3783:             }
1.185     www      3784:         }
1.191     harris41 3785:     }
1.352     www      3786: #
                   3787: # Roles
                   3788: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3789: #
1.800     albertel 3790:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3791:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3792: 	    split(/\:/,$entry);
                   3793:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3794:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3795:                 $rudom,$runame) eq 'ok') {
                   3796: 	    delete $userrolehash{$entry};
                   3797:         }
                   3798:     }
1.662     raeburn  3799: #
                   3800: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3801: #
                   3802:     my %domrolebuffer = ();
1.1000    raeburn  3803:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3804:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3805:         if ($domrolebuffer{$rudom}) {
                   3806:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3807:                       '='.&escape($domainrolehash{$entry});
                   3808:         } else {
                   3809:             $domrolebuffer{$rudom}.=&escape($entry).
                   3810:                       '='.&escape($domainrolehash{$entry});
                   3811:         }
                   3812:         delete $domainrolehash{$entry};
                   3813:     }
                   3814:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3815: 	my %servers = &get_servers($dom,'library');
                   3816: 	foreach my $tryserver (keys(%servers)) {
                   3817: 	    unless (&reply('domroleput:'.$dom.':'.
                   3818: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3819: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3820: 	    }
1.662     raeburn  3821:         }
                   3822:     }
1.186     www      3823:     $dumpcount++;
1.157     www      3824: }
                   3825: 
                   3826: sub courselog {
                   3827:     my $what=shift;
1.158     www      3828:     $what=time.':'.$what;
1.620     albertel 3829:     unless ($env{'request.course.id'}) { return ''; }
                   3830:     $coursedombuf{$env{'request.course.id'}}=
                   3831:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3832:     $coursenumbuf{$env{'request.course.id'}}=
                   3833:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3834:     $coursehombuf{$env{'request.course.id'}}=
                   3835:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3836:     $coursedescrbuf{$env{'request.course.id'}}=
                   3837:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3838:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3839:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3840:     $courseownerbuf{$env{'request.course.id'}}=
                   3841:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3842:     $coursetypebuf{$env{'request.course.id'}}=
                   3843:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3844:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3845: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3846:     } else {
1.620     albertel 3847: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3848:     }
1.620     albertel 3849:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3850: 	&flushcourselogs();
                   3851:     }
1.158     www      3852: }
                   3853: 
                   3854: sub courseacclog {
                   3855:     my $fnsymb=shift;
1.620     albertel 3856:     unless ($env{'request.course.id'}) { return ''; }
                   3857:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3858:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3859:         $what.=':POST';
1.583     matthew  3860:         # FIXME: Probably ought to escape things....
1.800     albertel 3861: 	foreach my $key (keys(%env)) {
                   3862:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3863:                 my $formitem = $1;
                   3864:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3865:                     $what.=':'.$formitem.'='.$env{$key};
                   3866:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3867:                     $what.=':'.$formitem.'='.$env{$key};
                   3868:                 }
1.158     www      3869:             }
1.191     harris41 3870:         }
1.583     matthew  3871:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3872:         # FIXME: We should not be depending on a form parameter that someone
                   3873:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3874:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3875:             $what.= ':POST';
                   3876:             # FIXME: Probably ought to escape things....
                   3877:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3878:                                  'crsdiscuss') {
1.620     albertel 3879:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3880:             }
                   3881:         }
1.158     www      3882:     }
                   3883:     &courselog($what);
1.149     www      3884: }
                   3885: 
1.185     www      3886: sub countacc {
                   3887:     my $url=&declutter(shift);
1.458     matthew  3888:     return if (! defined($url) || $url eq '');
1.620     albertel 3889:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3890: #
                   3891: # Mark that this url was used in this course
                   3892: #
1.620     albertel 3893:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3894: #
                   3895: # Increase the access count for this resource in this child process
                   3896: #
1.281     www      3897:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3898:     $accesshash{$key}++;
1.185     www      3899: }
1.349     www      3900: 
1.361     www      3901: sub linklog {
                   3902:     my ($from,$to)=@_;
                   3903:     $from=&declutter($from);
                   3904:     $to=&declutter($to);
                   3905:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3906:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3907: }
1.1160    www      3908: 
                   3909: sub statslog {
                   3910:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3911:     if ($users<2) { return; }
                   3912:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3913:             'course'       => $env{'request.course.id'},
                   3914:             'sections'     => '"all"',
                   3915:             'num_students' => $users,
                   3916:             'part'         => $part,
                   3917:             'symb'         => $symb,
                   3918:             'mean_tries'   => $av_attempts,
                   3919:             'deg_of_diff'  => $degdiff});
                   3920:     foreach my $key (keys(%dynstore)) {
                   3921:         $accesshash{$key}=$dynstore{$key};
                   3922:     }
                   3923: }
1.361     www      3924:   
1.349     www      3925: sub userrolelog {
                   3926:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3927:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3928:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3929:        $userrolehash
                   3930:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3931:                     =$tend.':'.$tstart;
1.662     raeburn  3932:     }
1.1169    droeschl 3933:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3934:        $userrolehash
                   3935:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3936:                     =$tend.':'.$tstart;
                   3937:     }
1.1169    droeschl 3938:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3939:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3940:        $domainrolehash
                   3941:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3942:                     = $tend.':'.$tstart;
                   3943:     }
1.351     www      3944: }
                   3945: 
1.957     raeburn  3946: sub courserolelog {
                   3947:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3948:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3949:         my $cdom = $1;
                   3950:         my $cnum = $2;
                   3951:         my $sec = $3;
                   3952:         my $namespace = 'rolelog';
                   3953:         my %storehash = (
                   3954:                            role    => $trole,
                   3955:                            start   => $tstart,
                   3956:                            end     => $tend,
                   3957:                            selfenroll => $selfenroll,
                   3958:                            context    => $context,
                   3959:                         );
                   3960:         if ($trole eq 'gr') {
                   3961:             $namespace = 'groupslog';
                   3962:             $storehash{'group'} = $sec;
                   3963:         } else {
                   3964:             $storehash{'section'} = $sec;
                   3965:         }
                   3966:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3967:                    $domain,$cnum,$cdom);
                   3968:         if (($trole ne 'st') || ($sec ne '')) {
                   3969:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3970:         }
                   3971:     }
                   3972:     return;
                   3973: }
                   3974: 
1.1172.2.9  raeburn  3975: sub domainrolelog {
                   3976:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3977:     if ($area =~ m{^/($match_domain)/$}) {
                   3978:         my $cdom = $1;
                   3979:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3980:         my $namespace = 'rolelog';
                   3981:         my %storehash = (
                   3982:                            role    => $trole,
                   3983:                            start   => $tstart,
                   3984:                            end     => $tend,
                   3985:                            context => $context,
                   3986:                         );
                   3987:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3988:                    $domain,$domconfiguser,$cdom);
                   3989:     }
                   3990:     return;
                   3991: 
                   3992: }
                   3993: 
                   3994: sub coauthorrolelog {
                   3995:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3996:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3997:         my $audom = $1;
                   3998:         my $auname = $2;
                   3999:         my $namespace = 'rolelog';
                   4000:         my %storehash = (
                   4001:                            role    => $trole,
                   4002:                            start   => $tstart,
                   4003:                            end     => $tend,
                   4004:                            context => $context,
                   4005:                         );
                   4006:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4007:                    $domain,$auname,$audom);
                   4008:     }
                   4009:     return;
                   4010: }
                   4011: 
1.351     www      4012: sub get_course_adv_roles {
1.948     raeburn  4013:     my ($cid,$codes) = @_;
1.620     albertel 4014:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4015:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4016:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4017:     my %nothide=();
1.800     albertel 4018:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4019:         if ($user !~ /:/) {
                   4020: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4021:         } else {
                   4022:             $nothide{$user}=1;
                   4023:         }
1.470     www      4024:     }
1.1172.2.23  raeburn  4025:     my @possdoms = ($coursehash{'domain'});
                   4026:     if ($coursehash{'checkforpriv'}) {
                   4027:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4028:     }
1.351     www      4029:     my %returnhash=();
                   4030:     my %dumphash=
                   4031:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4032:     my $now=time;
1.997     raeburn  4033:     my %privileged;
1.1000    raeburn  4034:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4035: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4036:         if (($tstart) && ($tstart<0)) { next; }
                   4037:         if (($tend) && ($tend<$now)) { next; }
                   4038:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4039:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4040: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4041:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4042:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4043: 	if ($role eq 'cr') { next; }
1.948     raeburn  4044:         if ($codes) {
                   4045:             if ($section) { $role .= ':'.$section; }
                   4046:             if ($returnhash{$role}) {
                   4047:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4048:             } else {
                   4049:                 $returnhash{$role}=$username.':'.$domain;
                   4050:             }
1.351     www      4051:         } else {
1.988     raeburn  4052:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4053:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4054:             if ($returnhash{$key}) {
                   4055: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4056:             } else {
                   4057:                 $returnhash{$key}=$username.':'.$domain;
                   4058:             }
1.351     www      4059:         }
1.948     raeburn  4060:     }
1.400     www      4061:     return %returnhash;
                   4062: }
                   4063: 
                   4064: sub get_my_roles {
1.937     raeburn  4065:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4066:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4067:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4068:     my (%dumphash,%nothide);
1.1086    raeburn  4069:     if ($context eq 'userroles') {
1.1166    raeburn  4070:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4071:     } else {
1.1172.2.23  raeburn  4072:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4073:         if ($hidepriv) {
                   4074:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4075:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4076:                 if ($user !~ /:/) {
                   4077:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4078:                 } else {
                   4079:                     $nothide{$user} = 1;
                   4080:                 }
                   4081:             }
                   4082:         }
1.858     raeburn  4083:     }
1.400     www      4084:     my %returnhash=();
                   4085:     my $now=time;
1.999     raeburn  4086:     my %privileged;
1.800     albertel 4087:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4088:         my ($role,$tend,$tstart);
                   4089:         if ($context eq 'userroles') {
1.1149    raeburn  4090:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4091: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4092:         } else {
                   4093:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4094:         }
1.400     www      4095:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4096:         my $status = 'active';
1.939     raeburn  4097:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4098:             $status = 'previous';
                   4099:         } 
                   4100:         if (($tstart) && ($now<$tstart)) {
                   4101:             $status = 'future';
                   4102:         }
                   4103:         if (ref($types) eq 'ARRAY') {
                   4104:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4105:                 next;
                   4106:             } 
                   4107:         } else {
                   4108:             if ($status ne 'active') {
                   4109:                 next;
                   4110:             }
                   4111:         }
1.867     raeburn  4112:         my ($rolecode,$username,$domain,$section,$area);
                   4113:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4114:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4115:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4116:         } else {
                   4117:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4118:         }
1.832     raeburn  4119:         if (ref($roledoms) eq 'ARRAY') {
                   4120:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4121:                 next;
                   4122:             }
                   4123:         }
                   4124:         if (ref($roles) eq 'ARRAY') {
                   4125:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4126:                 if ($role =~ /^cr\//) {
                   4127:                     if (!grep(/^cr$/,@{$roles})) {
                   4128:                         next;
                   4129:                     }
1.1104    raeburn  4130:                 } elsif ($role =~ /^gr\//) {
                   4131:                     if (!grep(/^gr$/,@{$roles})) {
                   4132:                         next;
                   4133:                     }
1.922     raeburn  4134:                 } else {
                   4135:                     next;
                   4136:                 }
1.832     raeburn  4137:             }
1.867     raeburn  4138:         }
1.937     raeburn  4139:         if ($hidepriv) {
1.1172.2.23  raeburn  4140:             my @privroles = ('dc','su');
1.999     raeburn  4141:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4142:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4143:             } else {
1.1172.2.23  raeburn  4144:                 my $possdoms = [$domain];
                   4145:                 if (ref($roledoms) eq 'ARRAY') {
                   4146:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4147:                 }
1.1172.2.23  raeburn  4148:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4149:                     if (!$nothide{$username.':'.$domain}) {
                   4150:                         next;
                   4151:                     }
                   4152:                 }
1.937     raeburn  4153:             }
                   4154:         }
1.933     raeburn  4155:         if ($withsec) {
                   4156:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4157:                 $tstart.':'.$tend;
                   4158:         } else {
                   4159:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4160:         }
1.832     raeburn  4161:     }
1.373     www      4162:     return %returnhash;
1.399     www      4163: }
                   4164: 
                   4165: # ----------------------------------------------------- Frontpage Announcements
                   4166: #
                   4167: #
                   4168: 
                   4169: sub postannounce {
                   4170:     my ($server,$text)=@_;
1.844     albertel 4171:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4172:     unless ($text=~/\w/) { $text=''; }
                   4173:     return &reply('setannounce:'.&escape($text),$server);
                   4174: }
                   4175: 
                   4176: sub getannounce {
1.448     albertel 4177: 
                   4178:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4179: 	my $announcement='';
1.800     albertel 4180: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4181: 	close($fh);
1.399     www      4182: 	if ($announcement=~/\w/) { 
                   4183: 	    return 
                   4184:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4185:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4186: 	} else {
                   4187: 	    return '';
                   4188: 	}
                   4189:     } else {
                   4190: 	return '';
                   4191:     }
1.351     www      4192: }
1.353     www      4193: 
                   4194: # ---------------------------------------------------------- Course ID routines
                   4195: # Deal with domain's nohist_courseid.db files
                   4196: #
                   4197: 
                   4198: sub courseidput {
1.921     raeburn  4199:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4200:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4201:     my $outcome;
                   4202:     if ($caller eq 'timeonly') {
                   4203:         my $cids = '';
                   4204:         foreach my $item (keys(%$storehash)) {
                   4205:             $cids.=&escape($item).'&';
                   4206:         }
                   4207:         $cids=~s/\&$//;
                   4208:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4209:                           $coursehome);       
                   4210:     } else {
                   4211:         my $items = '';
                   4212:         foreach my $item (keys(%$storehash)) {
                   4213:             $items.= &escape($item).'='.
                   4214:                      &freeze_escape($$storehash{$item}).'&';
                   4215:         }
                   4216:         $items=~s/\&$//;
                   4217:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4218:                           $coursehome);
1.918     raeburn  4219:     }
                   4220:     if ($outcome eq 'unknown_cmd') {
                   4221:         my $what;
                   4222:         foreach my $cid (keys(%$storehash)) {
                   4223:             $what .= &escape($cid).'=';
1.921     raeburn  4224:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4225:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4226:             }
                   4227:             $what =~ s/\:$/&/;
                   4228:         }
                   4229:         $what =~ s/\&$//;  
                   4230:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4231:     } else {
                   4232:         return $outcome;
                   4233:     }
1.353     www      4234: }
                   4235: 
                   4236: sub courseiddump {
1.921     raeburn  4237:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4238:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4239:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4240:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
                   4241:         $hasuniquecode)=@_;
1.918     raeburn  4242:     my $as_hash = 1;
                   4243:     my %returnhash;
                   4244:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4245:     my %libserv = &all_library();
                   4246:     foreach my $tryserver (keys(%libserv)) {
                   4247:         if ( (  $hostidflag == 1 
                   4248: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4249: 	     || (!defined($hostidflag)) ) {
                   4250: 
1.918     raeburn  4251: 	    if (($domfilter eq '') ||
                   4252: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4253:                 my $rep;
                   4254:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4255:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4256:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4257:                                 &escape($descfilter), &escape($instcodefilter),
                   4258:                                 &escape($ownerfilter), &escape($coursefilter),
                   4259:                                 &escape($typefilter), &escape($regexp_ok),
                   4260:                                 $as_hash, &escape($selfenrollonly),
                   4261:                                 &escape($catfilter), $showhidden, $caller,
                   4262:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4263:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.38  raeburn  4264:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22  raeburn  4265:                 } else {
                   4266:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4267:                              $sincefilter.':'.&escape($descfilter).':'.
                   4268:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4269:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4270:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4271:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4272:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4273:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4274:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38  raeburn  4275:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22  raeburn  4276:                              $tryserver);
                   4277:                 }
                   4278: 
1.918     raeburn  4279:                 my @pairs=split(/\&/,$rep);
                   4280:                 foreach my $item (@pairs) {
                   4281:                     my ($key,$value)=split(/\=/,$item,2);
                   4282:                     $key = &unescape($key);
                   4283:                     next if ($key =~ /^error: 2 /);
                   4284:                     my $result = &thaw_unescape($value);
                   4285:                     if (ref($result) eq 'HASH') {
                   4286:                         $returnhash{$key}=$result;
                   4287:                     } else {
1.921     raeburn  4288:                         my @responses = split(/:/,$value);
                   4289:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4290:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4291:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4292:                         }
1.1008    raeburn  4293:                     }
1.353     www      4294:                 }
                   4295:             }
                   4296:         }
                   4297:     }
                   4298:     return %returnhash;
                   4299: }
                   4300: 
1.1055    raeburn  4301: sub courselastaccess {
                   4302:     my ($cdom,$cnum,$hostidref) = @_;
                   4303:     my %returnhash;
                   4304:     if ($cdom && $cnum) {
                   4305:         my $chome = &homeserver($cnum,$cdom);
                   4306:         if ($chome ne 'no_host') {
                   4307:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4308:             &extract_lastaccess(\%returnhash,$rep);
                   4309:         }
                   4310:     } else {
                   4311:         if (!$cdom) { $cdom=''; }
                   4312:         my %libserv = &all_library();
                   4313:         foreach my $tryserver (keys(%libserv)) {
                   4314:             if (ref($hostidref) eq 'ARRAY') {
                   4315:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4316:             } 
                   4317:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4318:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4319:                 &extract_lastaccess(\%returnhash,$rep);
                   4320:             }
                   4321:         }
                   4322:     }
                   4323:     return %returnhash;
                   4324: }
                   4325: 
                   4326: sub extract_lastaccess {
                   4327:     my ($returnhash,$rep) = @_;
                   4328:     if (ref($returnhash) eq 'HASH') {
                   4329:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4330:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4331:                  $rep eq '') {
                   4332:             my @pairs=split(/\&/,$rep);
                   4333:             foreach my $item (@pairs) {
                   4334:                 my ($key,$value)=split(/\=/,$item,2);
                   4335:                 $key = &unescape($key);
                   4336:                 next if ($key =~ /^error: 2 /);
                   4337:                 $returnhash->{$key} = &thaw_unescape($value);
                   4338:             }
                   4339:         }
                   4340:     }
                   4341:     return;
                   4342: }
                   4343: 
1.658     raeburn  4344: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4345: 
                   4346: sub dcmailput {
1.685     raeburn  4347:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4348:     my $status = &Apache::lonnet::critical(
1.740     www      4349:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4350:        &escape($message),$server);
1.662     raeburn  4351:     return $status;
                   4352: }
                   4353: 
1.658     raeburn  4354: sub dcmaildump {
                   4355:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4356:     my %returnhash=();
1.846     albertel 4357: 
                   4358:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4359:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4360:                                                          &escape($enddate).':';
                   4361: 	my @esc_senders=map { &escape($_)} @$senders;
                   4362: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4363: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4364:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4365:             if (($key) && ($value)) {
                   4366:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4367:             }
                   4368:         }
                   4369:     }
                   4370:     return %returnhash;
                   4371: }
1.662     raeburn  4372: # ---------------------------------------------------------- Domain roles
                   4373: 
                   4374: sub get_domain_roles {
                   4375:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4376:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4377:         $startdate = '.';
                   4378:     }
1.1018    raeburn  4379:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4380:         $enddate = '.';
                   4381:     }
1.922     raeburn  4382:     my $rolelist;
                   4383:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4384:         $rolelist = join('&',@{$roles});
1.922     raeburn  4385:     }
1.662     raeburn  4386:     my %personnel = ();
1.841     albertel 4387: 
                   4388:     my %servers = &get_servers($dom,'library');
                   4389:     foreach my $tryserver (keys(%servers)) {
                   4390: 	%{$personnel{$tryserver}}=();
                   4391: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4392: 					    &escape($startdate).':'.
                   4393: 					    &escape($enddate).':'.
                   4394: 					    &escape($rolelist), $tryserver))) {
                   4395: 	    my ($key,$value) = split(/\=/,$line,2);
                   4396: 	    if (($key) && ($value)) {
                   4397: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4398: 	    }
                   4399: 	}
1.662     raeburn  4400:     }
                   4401:     return %personnel;
                   4402: }
1.658     raeburn  4403: 
1.1057    www      4404: # ----------------------------------------------------------- Interval timing 
1.149     www      4405: 
1.1153    www      4406: {
                   4407: # Caches needed for speedup of navmaps
                   4408: # We don't want to cache this for very long at all (5 seconds at most)
                   4409: # 
                   4410: # The user for whom we cache
                   4411: my $cachedkey='';
                   4412: # The cached times for this user
                   4413: my %cachedtimes=();
                   4414: # When this was last done
                   4415: my $cachedtime=();
                   4416: 
                   4417: sub load_all_first_access {
1.1154    raeburn  4418:     my ($uname,$udom)=@_;
1.1156    www      4419:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4420:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4421:         return;
                   4422:     }
                   4423:     $cachedtime=time;
                   4424:     $cachedkey=$uname.':'.$udom;
                   4425:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4426: }
                   4427: 
1.504     albertel 4428: sub get_first_access {
1.1162    raeburn  4429:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4430:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4431:     if ($argsymb) { $symb=$argsymb; }
                   4432:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4433:     if ($argmap) { $map = $argmap; }
1.926     albertel 4434:     if ($type eq 'course') {
                   4435: 	$res='course';
                   4436:     } elsif ($type eq 'map') {
1.588     albertel 4437: 	$res=&symbread($map);
                   4438:     } else {
                   4439: 	$res=$symb;
                   4440:     }
1.1153    www      4441:     &load_all_first_access($uname,$udom);
                   4442:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4443: }
                   4444: 
                   4445: sub set_first_access {
1.1162    raeburn  4446:     my ($type,$interval)=@_;
1.790     albertel 4447:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4448:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4449:     if ($type eq 'course') {
                   4450: 	$res='course';
                   4451:     } elsif ($type eq 'map') {
1.588     albertel 4452: 	$res=&symbread($map);
                   4453:     } else {
                   4454: 	$res=$symb;
                   4455:     }
1.1153    www      4456:     $cachedkey='';
1.1162    raeburn  4457:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4458:     if (!$firstaccess) {
1.1162    raeburn  4459:         my $start = time;
                   4460: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4461:                           $udom,$uname);
                   4462:         if ($putres eq 'ok') {
                   4463:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4464:                  $udom,$uname); 
                   4465:             &appenv(
                   4466:                      {
                   4467:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4468:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4469:                      }
                   4470:                   );
                   4471:         }
                   4472:         return $putres;
1.505     albertel 4473:     }
                   4474:     return 'already_set';
1.504     albertel 4475: }
1.1153    www      4476: }
1.1172.2.32  raeburn  4477: 
                   4478: sub checkout {
                   4479:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4480:     my $now=time;
                   4481:     my $lonhost=$perlvar{'lonHostID'};
                   4482:     my $infostr=&escape(
                   4483:                  'CHECKOUTTOKEN&'.
                   4484:                  $tuname.'&'.
                   4485:                  $tudom.'&'.
                   4486:                  $tcrsid.'&'.
                   4487:                  $symb.'&'.
                   4488:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4489:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4490:     if ($token=~/^error\:/) {
                   4491:         &logthis("<font color=\"blue\">WARNING: ".
                   4492:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4493:                  "</font>");
                   4494:         return '';
                   4495:     }
                   4496: 
                   4497:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4498:     $token=~tr/a-z/A-Z/;
                   4499: 
                   4500:     my %infohash=('resource.0.outtoken' => $token,
                   4501:                   'resource.0.checkouttime' => $now,
                   4502:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4503: 
                   4504:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4505:        return '';
                   4506:     } else {
                   4507:         &logthis("<font color=\"blue\">WARNING: ".
                   4508:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4509:                  "</font>");
                   4510:     }
                   4511: 
                   4512:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4513:                          &escape('Checkout '.$infostr.' - '.
                   4514:                                                  $token)) ne 'ok') {
                   4515:         return '';
                   4516:     } else {
                   4517:         &logthis("<font color=\"blue\">WARNING: ".
                   4518:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4519:                  "</font>");
                   4520:     }
                   4521:     return $token;
                   4522: }
                   4523: 
                   4524: # ------------------------------------------------------------ Check in an item
                   4525: 
                   4526: sub checkin {
                   4527:     my $token=shift;
                   4528:     my $now=time;
                   4529:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4530:     $lonhost=~tr/A-Z/a-z/;
                   4531:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4532:     $dtoken=~s/\W/\_/g;
                   4533:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4534:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4535: 
                   4536:     unless (($tuname) && ($tudom)) {
                   4537:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4538:         return '';
                   4539:     }
                   4540: 
                   4541:     unless (&allowed('mgr',$tcrsid)) {
                   4542:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4543:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4544:         return '';
                   4545:     }
                   4546: 
                   4547:     my %infohash=('resource.0.intoken' => $token,
                   4548:                   'resource.0.checkintime' => $now,
                   4549:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4550: 
                   4551:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4552:        return '';
                   4553:     }
                   4554: 
                   4555:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4556:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4557:         return '';
                   4558:     }
                   4559: 
                   4560:     return ($symb,$tuname,$tudom,$tcrsid);
                   4561: }
                   4562: 
1.110     www      4563: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4564: 
                   4565: sub expirespread {
                   4566:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4567:     my $cid=$env{'request.course.id'}; 
1.110     www      4568:     if ($cid) {
                   4569:        my $now=time;
                   4570:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4571:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4572:                             $env{'course.'.$cid.'.num'}.
1.110     www      4573: 	        	    ':nohist_expirationdates:'.
                   4574:                             &escape($key).'='.$now,
1.620     albertel 4575:                             $env{'course.'.$cid.'.home'})
1.110     www      4576:     }
                   4577:     return 'ok';
1.14      www      4578: }
                   4579: 
1.109     www      4580: # ----------------------------------------------------- Devalidate Spreadsheets
                   4581: 
                   4582: sub devalidate {
1.325     www      4583:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4584:     my $cid=$env{'request.course.id'}; 
1.109     www      4585:     if ($cid) {
1.391     matthew  4586:         # delete the stored spreadsheets for
                   4587:         # - the student level sheet of this user in course's homespace
                   4588:         # - the assessment level sheet for this resource 
                   4589:         #   for this user in user's homespace
1.553     albertel 4590: 	# - current conditional state info
1.325     www      4591: 	my $key=$uname.':'.$udom.':';
1.109     www      4592:         my $status=
1.299     matthew  4593: 	    &del('nohist_calculatedsheets',
1.391     matthew  4594: 		 [$key.'studentcalc:'],
1.620     albertel 4595: 		 $env{'course.'.$cid.'.domain'},
                   4596: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4597: 		.' '.
                   4598: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4599: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4600:         unless ($status eq 'ok ok') {
                   4601:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4602:                     $uname.' at '.$udom.' for '.
1.109     www      4603: 		    $symb.': '.$status);
1.133     albertel 4604:         }
1.553     albertel 4605: 	&delenv('user.state.'.$cid);
1.109     www      4606:     }
                   4607: }
                   4608: 
1.265     albertel 4609: sub get_scalar {
                   4610:     my ($string,$end) = @_;
                   4611:     my $value;
                   4612:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4613: 	$value = $1;
                   4614:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4615: 	$value = $1;
                   4616:     }
                   4617:     return &unescape($value);
                   4618: }
                   4619: 
                   4620: sub array2str {
                   4621:   my (@array) = @_;
                   4622:   my $result=&arrayref2str(\@array);
                   4623:   $result=~s/^__ARRAY_REF__//;
                   4624:   $result=~s/__END_ARRAY_REF__$//;
                   4625:   return $result;
                   4626: }
                   4627: 
1.204     albertel 4628: sub arrayref2str {
                   4629:   my ($arrayref) = @_;
1.265     albertel 4630:   my $result='__ARRAY_REF__';
1.204     albertel 4631:   foreach my $elem (@$arrayref) {
1.265     albertel 4632:     if(ref($elem) eq 'ARRAY') {
                   4633:       $result.=&arrayref2str($elem).'&';
                   4634:     } elsif(ref($elem) eq 'HASH') {
                   4635:       $result.=&hashref2str($elem).'&';
                   4636:     } elsif(ref($elem)) {
                   4637:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4638:     } else {
                   4639:       $result.=&escape($elem).'&';
                   4640:     }
                   4641:   }
                   4642:   $result=~s/\&$//;
1.265     albertel 4643:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4644:   return $result;
                   4645: }
                   4646: 
1.168     albertel 4647: sub hash2str {
1.204     albertel 4648:   my (%hash) = @_;
                   4649:   my $result=&hashref2str(\%hash);
1.265     albertel 4650:   $result=~s/^__HASH_REF__//;
                   4651:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4652:   return $result;
                   4653: }
                   4654: 
                   4655: sub hashref2str {
                   4656:   my ($hashref)=@_;
1.265     albertel 4657:   my $result='__HASH_REF__';
1.800     albertel 4658:   foreach my $key (sort(keys(%$hashref))) {
                   4659:     if (ref($key) eq 'ARRAY') {
                   4660:       $result.=&arrayref2str($key).'=';
                   4661:     } elsif (ref($key) eq 'HASH') {
                   4662:       $result.=&hashref2str($key).'=';
                   4663:     } elsif (ref($key)) {
1.265     albertel 4664:       $result.='=';
1.800     albertel 4665:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4666:     } else {
1.1132    raeburn  4667: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4668:     }
                   4669: 
1.800     albertel 4670:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4671:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4672:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4673:       $result.=&hashref2str($hashref->{$key}).'&';
                   4674:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4675:        $result.='&';
1.800     albertel 4676:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4677:     } else {
1.800     albertel 4678:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4679:     }
                   4680:   }
1.168     albertel 4681:   $result=~s/\&$//;
1.265     albertel 4682:   $result .= '__END_HASH_REF__';
1.168     albertel 4683:   return $result;
                   4684: }
                   4685: 
                   4686: sub str2hash {
1.265     albertel 4687:     my ($string)=@_;
                   4688:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4689:     return %$hash;
                   4690: }
                   4691: 
                   4692: sub str2hashref {
1.168     albertel 4693:   my ($string) = @_;
1.265     albertel 4694: 
                   4695:   my %hash;
                   4696: 
                   4697:   if($string !~ /^__HASH_REF__/) {
                   4698:       if (! ($string eq '' || !defined($string))) {
                   4699: 	  $hash{'error'}='Not hash reference';
                   4700:       }
                   4701:       return (\%hash, $string);
                   4702:   }
                   4703: 
                   4704:   $string =~ s/^__HASH_REF__//;
                   4705: 
                   4706:   while($string !~ /^__END_HASH_REF__/) {
                   4707:       #key
                   4708:       my $key='';
                   4709:       if($string =~ /^__HASH_REF__/) {
                   4710:           ($key, $string)=&str2hashref($string);
                   4711:           if(defined($key->{'error'})) {
                   4712:               $hash{'error'}='Bad data';
                   4713:               return (\%hash, $string);
                   4714:           }
                   4715:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4716:           ($key, $string)=&str2arrayref($string);
                   4717:           if($key->[0] eq 'Array reference error') {
                   4718:               $hash{'error'}='Bad data';
                   4719:               return (\%hash, $string);
                   4720:           }
                   4721:       } else {
                   4722:           $string =~ s/^(.*?)=//;
1.267     albertel 4723: 	  $key=&unescape($1);
1.265     albertel 4724:       }
                   4725:       $string =~ s/^=//;
                   4726: 
                   4727:       #value
                   4728:       my $value='';
                   4729:       if($string =~ /^__HASH_REF__/) {
                   4730:           ($value, $string)=&str2hashref($string);
                   4731:           if(defined($value->{'error'})) {
                   4732:               $hash{'error'}='Bad data';
                   4733:               return (\%hash, $string);
                   4734:           }
                   4735:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4736:           ($value, $string)=&str2arrayref($string);
                   4737:           if($value->[0] eq 'Array reference error') {
                   4738:               $hash{'error'}='Bad data';
                   4739:               return (\%hash, $string);
                   4740:           }
                   4741:       } else {
                   4742: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4743:       }
                   4744:       $string =~ s/^&//;
                   4745: 
                   4746:       $hash{$key}=$value;
1.204     albertel 4747:   }
1.265     albertel 4748: 
                   4749:   $string =~ s/^__END_HASH_REF__//;
                   4750: 
                   4751:   return (\%hash, $string);
1.204     albertel 4752: }
                   4753: 
                   4754: sub str2array {
1.265     albertel 4755:     my ($string)=@_;
                   4756:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4757:     return @$array;
                   4758: }
                   4759: 
                   4760: sub str2arrayref {
1.204     albertel 4761:   my ($string) = @_;
1.265     albertel 4762:   my @array;
                   4763: 
                   4764:   if($string !~ /^__ARRAY_REF__/) {
                   4765:       if (! ($string eq '' || !defined($string))) {
                   4766: 	  $array[0]='Array reference error';
                   4767:       }
                   4768:       return (\@array, $string);
                   4769:   }
                   4770: 
                   4771:   $string =~ s/^__ARRAY_REF__//;
                   4772: 
                   4773:   while($string !~ /^__END_ARRAY_REF__/) {
                   4774:       my $value='';
                   4775:       if($string =~ /^__HASH_REF__/) {
                   4776:           ($value, $string)=&str2hashref($string);
                   4777:           if(defined($value->{'error'})) {
                   4778:               $array[0] ='Array reference error';
                   4779:               return (\@array, $string);
                   4780:           }
                   4781:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4782:           ($value, $string)=&str2arrayref($string);
                   4783:           if($value->[0] eq 'Array reference error') {
                   4784:               $array[0] ='Array reference error';
                   4785:               return (\@array, $string);
                   4786:           }
                   4787:       } else {
                   4788: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4789:       }
                   4790:       $string =~ s/^&//;
                   4791: 
                   4792:       push(@array, $value);
1.191     harris41 4793:   }
1.265     albertel 4794: 
                   4795:   $string =~ s/^__END_ARRAY_REF__//;
                   4796: 
                   4797:   return (\@array, $string);
1.168     albertel 4798: }
                   4799: 
1.167     albertel 4800: # -------------------------------------------------------------------Temp Store
                   4801: 
1.168     albertel 4802: sub tmpreset {
                   4803:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4804:   if (!$symb) {
                   4805:     $symb=&symbread();
1.620     albertel 4806:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4807:   }
                   4808:   $symb=escape($symb);
                   4809: 
1.620     albertel 4810:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4811:   $namespace=~s/\//\_/g;
                   4812:   $namespace=~s/\W//g;
                   4813: 
1.620     albertel 4814:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4815:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4816:   if ($domain eq 'public' && $stuname eq 'public') {
                   4817:       $stuname=$ENV{'REMOTE_ADDR'};
                   4818:   }
1.1117    foxr     4819:   my $path=LONCAPA::tempdir();
1.168     albertel 4820:   my %hash;
                   4821:   if (tie(%hash,'GDBM_File',
                   4822: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4823: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4824:     foreach my $key (keys(%hash)) {
1.180     albertel 4825:       if ($key=~ /:$symb/) {
1.168     albertel 4826: 	delete($hash{$key});
                   4827:       }
                   4828:     }
                   4829:   }
                   4830: }
                   4831: 
1.167     albertel 4832: sub tmpstore {
1.168     albertel 4833:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4834: 
                   4835:   if (!$symb) {
                   4836:     $symb=&symbread();
1.620     albertel 4837:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4838:   }
                   4839:   $symb=escape($symb);
                   4840: 
                   4841:   if (!$namespace) {
                   4842:     # I don't think we would ever want to store this for a course.
                   4843:     # it seems this will only be used if we don't have a course.
1.620     albertel 4844:     #$namespace=$env{'request.course.id'};
1.168     albertel 4845:     #if (!$namespace) {
1.620     albertel 4846:       $namespace=$env{'request.state'};
1.168     albertel 4847:     #}
                   4848:   }
                   4849:   $namespace=~s/\//\_/g;
                   4850:   $namespace=~s/\W//g;
1.620     albertel 4851:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4852:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4853:   if ($domain eq 'public' && $stuname eq 'public') {
                   4854:       $stuname=$ENV{'REMOTE_ADDR'};
                   4855:   }
1.168     albertel 4856:   my $now=time;
                   4857:   my %hash;
1.1117    foxr     4858:   my $path=LONCAPA::tempdir();
1.168     albertel 4859:   if (tie(%hash,'GDBM_File',
                   4860: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4861: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4862:     $hash{"version:$symb"}++;
                   4863:     my $version=$hash{"version:$symb"};
                   4864:     my $allkeys=''; 
                   4865:     foreach my $key (keys(%$storehash)) {
                   4866:       $allkeys.=$key.':';
1.591     albertel 4867:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4868:     }
                   4869:     $hash{"$version:$symb:timestamp"}=$now;
                   4870:     $allkeys.='timestamp';
                   4871:     $hash{"$version:keys:$symb"}=$allkeys;
                   4872:     if (untie(%hash)) {
                   4873:       return 'ok';
                   4874:     } else {
                   4875:       return "error:$!";
                   4876:     }
                   4877:   } else {
                   4878:     return "error:$!";
                   4879:   }
                   4880: }
1.167     albertel 4881: 
1.168     albertel 4882: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4883: 
1.168     albertel 4884: sub tmprestore {
                   4885:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4886: 
1.168     albertel 4887:   if (!$symb) {
                   4888:     $symb=&symbread();
1.620     albertel 4889:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4890:   }
                   4891:   $symb=escape($symb);
                   4892: 
1.620     albertel 4893:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4894: 
1.620     albertel 4895:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4896:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4897:   if ($domain eq 'public' && $stuname eq 'public') {
                   4898:       $stuname=$ENV{'REMOTE_ADDR'};
                   4899:   }
1.168     albertel 4900:   my %returnhash;
                   4901:   $namespace=~s/\//\_/g;
                   4902:   $namespace=~s/\W//g;
                   4903:   my %hash;
1.1117    foxr     4904:   my $path=LONCAPA::tempdir();
1.168     albertel 4905:   if (tie(%hash,'GDBM_File',
                   4906: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4907: 	  &GDBM_READER(),0640)) {
1.168     albertel 4908:     my $version=$hash{"version:$symb"};
                   4909:     $returnhash{'version'}=$version;
                   4910:     my $scope;
                   4911:     for ($scope=1;$scope<=$version;$scope++) {
                   4912:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4913:       my @keys=split(/:/,$vkeys);
                   4914:       my $key;
                   4915:       $returnhash{"$scope:keys"}=$vkeys;
                   4916:       foreach $key (@keys) {
1.591     albertel 4917: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4918: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4919:       }
                   4920:     }
1.168     albertel 4921:     if (!(untie(%hash))) {
                   4922:       return "error:$!";
                   4923:     }
                   4924:   } else {
                   4925:     return "error:$!";
                   4926:   }
                   4927:   return %returnhash;
1.167     albertel 4928: }
                   4929: 
1.9       www      4930: # ----------------------------------------------------------------------- Store
                   4931: 
                   4932: sub store {
1.124     www      4933:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4934:     my $home='';
                   4935: 
1.168     albertel 4936:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4937: 
1.213     www      4938:     $symb=&symbclean($symb);
1.122     albertel 4939:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4940: 
1.620     albertel 4941:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4942:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4943: 
                   4944:     &devalidate($symb,$stuname,$domain);
1.109     www      4945: 
                   4946:     $symb=escape($symb);
1.187     www      4947:     if (!$namespace) { 
1.620     albertel 4948:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4949:           return ''; 
                   4950:        } 
                   4951:     }
1.620     albertel 4952:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4953: 
                   4954:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4955:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4956: 
1.12      www      4957:     my $namevalue='';
1.800     albertel 4958:     foreach my $key (keys(%$storehash)) {
                   4959:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4960:     }
1.12      www      4961:     $namevalue=~s/\&$//;
1.187     www      4962:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4963:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4964: }
                   4965: 
1.47      www      4966: # -------------------------------------------------------------- Critical Store
                   4967: 
                   4968: sub cstore {
1.124     www      4969:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4970:     my $home='';
                   4971: 
1.168     albertel 4972:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4973: 
1.213     www      4974:     $symb=&symbclean($symb);
1.122     albertel 4975:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4976: 
1.620     albertel 4977:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4978:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4979: 
                   4980:     &devalidate($symb,$stuname,$domain);
1.109     www      4981: 
                   4982:     $symb=escape($symb);
1.187     www      4983:     if (!$namespace) { 
1.620     albertel 4984:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4985:           return ''; 
                   4986:        } 
                   4987:     }
1.620     albertel 4988:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4989: 
                   4990:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4991:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4992: 
1.47      www      4993:     my $namevalue='';
1.800     albertel 4994:     foreach my $key (keys(%$storehash)) {
                   4995:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4996:     }
1.47      www      4997:     $namevalue=~s/\&$//;
1.187     www      4998:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4999:     return critical
                   5000:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      5001: }
                   5002: 
1.9       www      5003: # --------------------------------------------------------------------- Restore
                   5004: 
                   5005: sub restore {
1.124     www      5006:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5007:     my $home='';
                   5008: 
1.168     albertel 5009:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5010: 
1.122     albertel 5011:     if (!$symb) {
1.1172.2.26  raeburn  5012:         return if ($namespace eq 'courserequests');
                   5013:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5014:     } else {
1.1172.2.26  raeburn  5015:         unless ($namespace eq 'courserequests') {
                   5016:             $symb=&escape(&symbclean($symb));
                   5017:         }
1.122     albertel 5018:     }
1.188     www      5019:     if (!$namespace) { 
1.620     albertel 5020:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5021:           return ''; 
                   5022:        } 
                   5023:     }
1.620     albertel 5024:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5025:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5026:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5027:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5028: 
1.12      www      5029:     my %returnhash=();
1.800     albertel 5030:     foreach my $line (split(/\&/,$answer)) {
                   5031: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5032:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5033:     }
1.75      www      5034:     my $version;
                   5035:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5036:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5037:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5038:        }
1.75      www      5039:     }
1.13      www      5040:     return %returnhash;
1.34      www      5041: }
                   5042: 
                   5043: # ---------------------------------------------------------- Course Description
1.1118    foxr     5044: #
                   5045: #  
1.34      www      5046: 
                   5047: sub coursedescription {
1.731     albertel 5048:     my ($courseid,$args)=@_;
1.34      www      5049:     $courseid=~s/^\///;
1.49      www      5050:     $courseid=~s/\_/\//g;
1.34      www      5051:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5052:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5053:     my $normalid=$cdomain.'_'.$cnum;
                   5054:     # need to always cache even if we get errors otherwise we keep 
                   5055:     # trying and trying and trying to get the course description.
                   5056:     my %envhash=();
                   5057:     my %returnhash=();
1.731     albertel 5058:     
                   5059:     my $expiretime=600;
                   5060:     if ($env{'request.course.id'} eq $normalid) {
                   5061: 	$expiretime=120;
                   5062:     }
                   5063: 
                   5064:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5065:     if (!$args->{'freshen_cache'}
                   5066: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5067: 	foreach my $key (keys(%env)) {
                   5068: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5069: 	    my ($setting) = $1;
                   5070: 	    $returnhash{$setting} = $env{$key};
                   5071: 	}
                   5072: 	return %returnhash;
                   5073:     }
                   5074: 
1.1118    foxr     5075:     # get the data again
                   5076: 
1.731     albertel 5077:     if (!$args->{'one_time'}) {
                   5078: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5079:     }
1.811     albertel 5080: 
1.34      www      5081:     if ($chome ne 'no_host') {
1.302     albertel 5082:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5083:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5084: 	   my $username = $env{'user.name'}; # Defult username
                   5085: 	   if(defined $args->{'user'}) {
                   5086: 	       $username = $args->{'user'};
                   5087: 	   }
1.129     albertel 5088:            $returnhash{'home'}= $chome;
                   5089: 	   $returnhash{'domain'} = $cdomain;
                   5090: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5091:            if (!defined($returnhash{'type'})) {
                   5092:                $returnhash{'type'} = 'Course';
                   5093:            }
1.130     albertel 5094:            while (my ($name,$value) = each %returnhash) {
1.53      www      5095:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5096:            }
1.270     www      5097:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5098:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5099: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5100:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5101:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5102:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5103:        }
                   5104:     }
1.731     albertel 5105:     if (!$args->{'one_time'}) {
1.949     raeburn  5106: 	&appenv(\%envhash);
1.731     albertel 5107:     }
1.302     albertel 5108:     return %returnhash;
1.461     www      5109: }
                   5110: 
1.1080    raeburn  5111: sub update_released_required {
                   5112:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5113:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5114:         $cid = $env{'request.course.id'};
                   5115:         $cdom = $env{'course.'.$cid.'.domain'};
                   5116:         $cnum = $env{'course.'.$cid.'.num'};
                   5117:         $chome = $env{'course.'.$cid.'.home'};
                   5118:     }
                   5119:     if ($needsrelease) {
                   5120:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5121:         my $needsupdate;
                   5122:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5123:             $needsupdate = 1;
                   5124:         } else {
                   5125:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5126:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5127:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5128:                 $needsupdate = 1;
                   5129:             }
                   5130:         }
                   5131:         if ($needsupdate) {
                   5132:             my %needshash = (
                   5133:                              'internal.releaserequired' => $needsrelease,
                   5134:                             );
                   5135:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5136:             if ($putresult eq 'ok') {
                   5137:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5138:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5139:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5140:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5141:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5142:                 }
                   5143:             }
                   5144:         }
                   5145:     }
                   5146:     return;
                   5147: }
                   5148: 
1.461     www      5149: # -------------------------------------------------See if a user is privileged
                   5150: 
                   5151: sub privileged {
1.1172.2.23  raeburn  5152:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5153:     my $now = time;
1.1172.2.23  raeburn  5154:     my $roles;
                   5155:     if (ref($possroles) eq 'ARRAY') {
                   5156:         $roles = $possroles;
                   5157:     } else {
                   5158:         $roles = ['dc','su'];
                   5159:     }
                   5160:     if (ref($possdomains) eq 'ARRAY') {
                   5161:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5162:         foreach my $dom (@{$possdomains}) {
                   5163:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5164:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5165:                 foreach my $role (@{$roles}) {
                   5166:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5167:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5168:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5169:                             return 1 unless (($end && $end < $now) ||
                   5170:                                              ($start && $start > $now));
                   5171:                         }
                   5172:                     }
                   5173:                 }
                   5174:             }
                   5175:         }
                   5176:     } else {
                   5177:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5178:         my $now = time;
1.1170    droeschl 5179: 
1.1172.2.23  raeburn  5180:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 5181:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5182:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5183:                 return 1 unless ($tend && $tend < $now)
                   5184:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5185:             }
1.1172.2.23  raeburn  5186:         }
                   5187:     }
1.461     www      5188:     return 0;
1.9       www      5189: }
1.1       albertel 5190: 
1.1172.2.23  raeburn  5191: sub privileged_by_domain {
                   5192:     my ($domains,$roles) = @_;
                   5193:     my %privileged = ();
                   5194:     my $cachetime = 60*60*24;
                   5195:     my $now = time;
                   5196:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5197:         return %privileged;
                   5198:     }
                   5199:     foreach my $dom (@{$domains}) {
                   5200:         next if (ref($privileged{$dom}) eq 'HASH');
                   5201:         my $needroles;
                   5202:         foreach my $role (@{$roles}) {
                   5203:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5204:             if (defined($cached)) {
                   5205:                 if (ref($result) eq 'HASH') {
                   5206:                     $privileged{$dom}{$role} = $result;
                   5207:                 }
                   5208:             } else {
                   5209:                 $needroles = 1;
                   5210:             }
                   5211:         }
                   5212:         if ($needroles) {
                   5213:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5214:             $privileged{$dom} = {};
                   5215:             foreach my $server (keys(%dompersonnel)) {
                   5216:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5217:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5218:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5219:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5220:                         next if ($end && $end < $now);
                   5221:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5222:                             $dompersonnel{$server}{$item};
                   5223:                     }
                   5224:                 }
                   5225:             }
                   5226:             if (ref($privileged{$dom}) eq 'HASH') {
                   5227:                 foreach my $role (@{$roles}) {
                   5228:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5229:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5230:                     } else {
                   5231:                         my %hash = ();
                   5232:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5233:                     }
                   5234:                 }
                   5235:             }
                   5236:         }
                   5237:     }
                   5238:     return %privileged;
                   5239: }
                   5240: 
1.103     harris41 5241: # -------------------------------------------------------- Get user privileges
1.11      www      5242: 
                   5243: sub rolesinit {
1.1169    droeschl 5244:     my ($domain, $username) = @_;
                   5245:     my %userroles = ('user.login.time' => time);
                   5246:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5247: 
                   5248:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5249:     # also, blocking can be triggered by an activating timer
                   5250:     # it's saved in the user's %env.
                   5251:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5252:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5253:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5254:         %timerintchk, %timerintenv);
                   5255: 
1.1162    raeburn  5256:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5257:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5258:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5259:     }
1.1169    droeschl 5260: 
1.1162    raeburn  5261:     foreach my $key (keys(%timerinterval)) {
                   5262:         my ($cid,$rest) = split(/\0/,$key);
                   5263:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5264:     }
1.1169    droeschl 5265: 
1.11      www      5266:     my %allroles=();
1.1162    raeburn  5267:     my %allgroups=();
1.11      www      5268: 
1.1169    droeschl 5269:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5270:         my $role = $rolesdump{$area};
                   5271:         $area =~ s/\_\w\w$//;
                   5272: 
                   5273:         my ($trole, $tend, $tstart, $group_privs);
                   5274: 
                   5275:         if ($role =~ /^cr/) {
                   5276:         # Custom role, defined by a user 
                   5277:         # e.g., user.role.cr/msu/smith/mynewrole
                   5278:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5279:                 $trole = $1;
                   5280:                 ($tend, $tstart) = split('_', $2);
                   5281:             } else {
                   5282:                 $trole = $role;
                   5283:             }
                   5284:         } elsif ($role =~ m|^gr/|) {
                   5285:         # Role of member in a group, defined within a course/community
                   5286:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5287:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5288:             next if $tstart eq '-1';
                   5289:             ($trole, $group_privs) = split(/\//, $trole);
                   5290:             $group_privs = &unescape($group_privs);
                   5291:         } else {
                   5292:         # Just a normal role, defined in roles.tab
                   5293:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5294:         }
                   5295: 
                   5296:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5297:                  $username);
                   5298:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5299: 
                   5300:         # role expired or not available yet?
                   5301:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5302:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5303: 
                   5304:         next if $area eq '' or $trole eq '';
                   5305: 
                   5306:         my $spec = "$trole.$area";
                   5307:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5308: 
                   5309:         if ($trole =~ /^cr\//) {
                   5310:         # Custom role, defined by a user
                   5311:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5312:         } elsif ($trole eq 'gr') {
                   5313:         # Role of a member in a group, defined within a course/community
                   5314:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5315:             next;
                   5316:         } else {
                   5317:         # Normal role, defined in roles.tab
                   5318:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5319:         }
                   5320: 
                   5321:         my $cid = $tdomain.'_'.$trest;
                   5322:         unless ($firstaccchk{$cid}) {
                   5323:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5324:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5325:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5326:                         $coursetimerstarts{$cid}{$item}; 
                   5327:                 }
                   5328:             }
                   5329:             $firstaccchk{$cid} = 1;
                   5330:         }
                   5331:         unless ($timerintchk{$cid}) {
                   5332:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5333:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5334:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5335:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5336:                 }
1.12      www      5337:             }
1.1169    droeschl 5338:             $timerintchk{$cid} = 1;
1.191     harris41 5339:         }
1.11      www      5340:     }
1.1169    droeschl 5341: 
                   5342:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5343:         \%allroles, \%allgroups);
                   5344:     $env{'user.adv'} = $userroles{'user.adv'};
                   5345: 
1.1162    raeburn  5346:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5347: }
                   5348: 
1.567     raeburn  5349: sub set_arearole {
1.1172.2.19  raeburn  5350:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5351:     unless ($nolog) {
1.567     raeburn  5352: # log the associated role with the area
1.1172.2.19  raeburn  5353:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5354:     }
1.743     albertel 5355:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5356: }
                   5357: 
                   5358: sub custom_roleprivs {
                   5359:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5360:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5361:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5362:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5363:         my ($rdummy,$roledef)=
                   5364:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5365:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5366:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5367:             if (defined($syspriv)) {
1.1043    raeburn  5368:                 if ($trest =~ /^$match_community$/) {
                   5369:                     $syspriv =~ s/bre\&S//; 
                   5370:                 }
1.567     raeburn  5371:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5372:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5373:             }
                   5374:             if ($tdomain ne '') {
                   5375:                 if (defined($dompriv)) {
                   5376:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5377:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5378:                 }
                   5379:                 if (($trest ne '') && (defined($coursepriv))) {
                   5380:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5381:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5382:                 }
                   5383:             }
                   5384:         }
                   5385:     }
                   5386: }
                   5387: 
1.678     raeburn  5388: sub group_roleprivs {
                   5389:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5390:     my $access = 1;
                   5391:     my $now = time;
                   5392:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5393:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5394:     if ($access) {
1.811     albertel 5395:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5396:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5397:     }
                   5398: }
1.567     raeburn  5399: 
                   5400: sub standard_roleprivs {
                   5401:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5402:     if (defined($pr{$trole.':s'})) {
                   5403:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5404:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5405:     }
                   5406:     if ($tdomain ne '') {
                   5407:         if (defined($pr{$trole.':d'})) {
                   5408:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5409:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5410:         }
                   5411:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5412:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5413:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5414:         }
                   5415:     }
                   5416: }
                   5417: 
                   5418: sub set_userprivs {
1.1064    raeburn  5419:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5420:     my $author=0;
                   5421:     my $adv=0;
1.678     raeburn  5422:     my %grouproles = ();
                   5423:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5424:         my @groupkeys; 
1.1000    raeburn  5425:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5426:             push(@groupkeys,$role);
                   5427:         }
                   5428:         if (ref($groups_roles) eq 'HASH') {
                   5429:             foreach my $key (keys(%{$groups_roles})) {
                   5430:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5431:                     push(@groupkeys,$key);
                   5432:                 }
                   5433:             }
                   5434:         }
                   5435:         if (@groupkeys > 0) {
                   5436:             foreach my $role (@groupkeys) {
                   5437:                 my ($trole,$area,$sec,$extendedarea);
                   5438:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5439:                     $trole = $1;
                   5440:                     $area = $2;
                   5441:                     $sec = $3;
                   5442:                     $extendedarea = $area.$sec;
                   5443:                     if (exists($$allgroups{$area})) {
                   5444:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5445:                             my $spec = $trole.'.'.$extendedarea;
                   5446:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5447:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5448:                         }
1.678     raeburn  5449:                     }
                   5450:                 }
                   5451:             }
                   5452:         }
                   5453:     }
1.800     albertel 5454:     foreach my $group (keys(%grouproles)) {
                   5455:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5456:     }
1.800     albertel 5457:     foreach my $role (keys(%{$allroles})) {
                   5458:         my %thesepriv;
1.941     raeburn  5459:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5460:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5461:             if ($item ne '') {
                   5462:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5463:                 if ($restrictions eq '') {
                   5464:                     $thesepriv{$privilege}='F';
                   5465:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5466:                     $thesepriv{$privilege}.=$restrictions;
                   5467:                 }
                   5468:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5469:             }
                   5470:         }
                   5471:         my $thesestr='';
1.1104    raeburn  5472:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5473: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5474: 	}
                   5475:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5476:     }
                   5477:     return ($author,$adv);
                   5478: }
                   5479: 
1.994     raeburn  5480: sub role_status {
1.1104    raeburn  5481:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5482:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5483:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5484:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5485:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5486:             $$where = '/'.$two;
1.994     raeburn  5487:             $$trolecode=$$role.'.'.$$where;
                   5488:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5489:             $$tstatus='is';
1.1104    raeburn  5490:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5491:                 $$tstatus='future';
1.1034    raeburn  5492:                 if ($$tstart<$now) {
                   5493:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5494:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5495:                             my (%allroles,%allgroups,$group_privs,
                   5496:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5497:                             my %userroles = (
                   5498:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5499:                             );
1.1064    raeburn  5500:                             @rolecodes = ('cm'); 
1.1002    raeburn  5501:                             my $spec=$$role.'.'.$$where;
                   5502:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5503:                             if ($$role =~ /^cr\//) {
                   5504:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5505:                                 push(@rolecodes,'cr');
1.1002    raeburn  5506:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5507:                                 push(@rolecodes,$$role);
1.1002    raeburn  5508:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5509:                                                     $env{'user.name'});
1.1064    raeburn  5510:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5511:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5512:                                 $group_privs = &unescape($group_privs);
                   5513:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5514:                                 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  5515:                                 &get_groups_roles($tdomain,$trest,
                   5516:                                                   \%course_roles,\@rolecodes,
                   5517:                                                   \%groups_roles);
1.1002    raeburn  5518:                             } else {
1.1064    raeburn  5519:                                 push(@rolecodes,$$role);
1.1002    raeburn  5520:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5521:                             }
1.1064    raeburn  5522:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5523:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5524:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5525:                         }
                   5526:                     }
1.1034    raeburn  5527:                     $$tstatus = 'is';
1.1002    raeburn  5528:                 }
1.994     raeburn  5529:             }
                   5530:             if ($$tend) {
1.1104    raeburn  5531:                 if ($$tend<$update) {
1.994     raeburn  5532:                     $$tstatus='expired';
                   5533:                 } elsif ($$tend<$now) {
                   5534:                     $$tstatus='will_not';
                   5535:                 }
                   5536:             }
                   5537:         }
                   5538:     }
                   5539: }
                   5540: 
1.1104    raeburn  5541: sub get_groups_roles {
                   5542:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5543:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5544:                   (ref($rolecodes) eq 'ARRAY') && 
                   5545:                   (ref($groups_roles) eq 'HASH')); 
                   5546:     if (keys(%{$cdom_courseroles}) > 0) {
                   5547:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5548:         if ($cdom ne '' && $cnum ne '') {
                   5549:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5550:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5551:                     my $crsrole = $1;
                   5552:                     my $crssec = $2;
                   5553:                     if ($crsrole =~ /^cr/) {
                   5554:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5555:                             push(@{$rolecodes},'cr');
                   5556:                         }
                   5557:                     } else {
                   5558:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5559:                             push(@{$rolecodes},$crsrole);
                   5560:                         }
                   5561:                     }
                   5562:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5563:                     if ($crssec ne '') {
                   5564:                         $rolekey .= "/$crssec";
                   5565:                     }
                   5566:                     $rolekey .= './';
                   5567:                     $groups_roles->{$rolekey} = $rolecodes;
                   5568:                 }
                   5569:             }
                   5570:         }
                   5571:     }
                   5572:     return;
                   5573: }
                   5574: 
                   5575: sub delete_env_groupprivs {
                   5576:     my ($where,$courseroles,$possroles) = @_;
                   5577:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5578:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5579:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5580:         %{$courseroles->{$udom}} =
                   5581:             &get_my_roles('','','userroles',['active'],
                   5582:                           $possroles,[$udom],1);
                   5583:     }
                   5584:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5585:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5586:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5587:             my $area = '/'.$cdom.'/'.$cnum;
                   5588:             my $privkey = "user.priv.$crsrole.$area";
                   5589:             if ($crssec ne '') {
                   5590:                 $privkey .= '/'.$crssec;
                   5591:             }
                   5592:             $privkey .= ".$area/$group";
                   5593:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5594:         }
                   5595:     }
                   5596:     return;
                   5597: }
                   5598: 
1.994     raeburn  5599: sub check_adhoc_privs {
1.1104    raeburn  5600:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5601:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5602:     my $setprivs;
1.994     raeburn  5603:     if ($env{$cckey}) {
                   5604:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5605:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5606:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5607:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5608:             $setprivs = 1;
1.994     raeburn  5609:         }
                   5610:     } else {
1.1088    raeburn  5611:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5612:         $setprivs = 1;
1.994     raeburn  5613:     }
1.1172.2.9  raeburn  5614:     return $setprivs;
1.994     raeburn  5615: }
                   5616: 
                   5617: sub set_adhoc_privileges {
                   5618: # role can be cc or ca
1.1088    raeburn  5619:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5620:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5621:     my $spec = $role.'.'.$area;
                   5622:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5623:                                   $env{'user.name'},1);
1.994     raeburn  5624:     my %ccrole = ();
                   5625:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5626:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5627:     &appenv(\%userroles,[$role,'cm']);
                   5628:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5629:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5630:         &appenv( {'request.role'        => $spec,
                   5631:                   'request.role.domain' => $dcdom,
                   5632:                   'request.course.sec'  => ''
                   5633:                  }
                   5634:                );
                   5635:         my $tadv=0;
                   5636:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5637:         &appenv({'request.role.adv'    => $tadv});
                   5638:     }
1.994     raeburn  5639: }
                   5640: 
1.12      www      5641: # --------------------------------------------------------------- get interface
                   5642: 
                   5643: sub get {
1.131     albertel 5644:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5645:    my $items='';
1.800     albertel 5646:    foreach my $item (@$storearr) {
                   5647:        $items.=&escape($item).'&';
1.191     harris41 5648:    }
1.12      www      5649:    $items=~s/\&$//;
1.620     albertel 5650:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5651:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5652:    my $uhome=&homeserver($uname,$udomain);
                   5653: 
1.133     albertel 5654:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5655:    my @pairs=split(/\&/,$rep);
1.273     albertel 5656:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5657:      return @pairs;
                   5658:    }
1.15      www      5659:    my %returnhash=();
1.42      www      5660:    my $i=0;
1.800     albertel 5661:    foreach my $item (@$storearr) {
                   5662:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5663:       $i++;
1.191     harris41 5664:    }
1.15      www      5665:    return %returnhash;
1.27      www      5666: }
                   5667: 
                   5668: # --------------------------------------------------------------- del interface
                   5669: 
                   5670: sub del {
1.133     albertel 5671:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5672:    my $items='';
1.800     albertel 5673:    foreach my $item (@$storearr) {
                   5674:        $items.=&escape($item).'&';
1.191     harris41 5675:    }
1.984     neumanie 5676: 
1.27      www      5677:    $items=~s/\&$//;
1.620     albertel 5678:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5679:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5680:    my $uhome=&homeserver($uname,$udomain);
                   5681:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5682: }
                   5683: 
                   5684: # -------------------------------------------------------------- dump interface
                   5685: 
1.1172.2.22  raeburn  5686: sub unserialize {
                   5687:     my ($rep, $escapedkeys) = @_;
                   5688: 
                   5689:     return {} if $rep =~ /^error/;
                   5690: 
                   5691:     my %returnhash=();
                   5692:     foreach my $item (split(/\&/,$rep)) {
                   5693:         my ($key, $value) = split(/=/, $item, 2);
                   5694:         $key = unescape($key) unless $escapedkeys;
                   5695:         next if $key =~ /^error: 2 /;
                   5696:         $returnhash{$key} = &thaw_unescape($value);
                   5697:     }
                   5698:     return \%returnhash;
                   5699: }
                   5700: 
                   5701: # see Lond::dump_with_regexp
                   5702: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5703: sub dump {
1.1172.2.22  raeburn  5704:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5705:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5706:     if (!$uname) { $uname=$env{'user.name'}; }
                   5707:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5708: 
1.1172.2.55  raeburn  5709:     if ($regexp) {
                   5710:         $regexp=&escape($regexp);
                   5711:     } else {
                   5712:         $regexp='.';
                   5713:     }
1.1172.2.22  raeburn  5714:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5715:         # user is hosted on this machine
1.1172.2.55  raeburn  5716:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5717:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5718:         return %{&unserialize($reply, $escapedkeys)};
                   5719:     }
1.1166    raeburn  5720:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5721:     my @pairs=split(/\&/,$rep);
                   5722:     my %returnhash=();
1.1098    foxr     5723:     if (!($rep =~ /^error/ )) {
                   5724: 	foreach my $item (@pairs) {
                   5725: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5726:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5727: 	    next if ($key =~ /^error: 2 /);
                   5728: 	    $returnhash{$key}=&thaw_unescape($value);
                   5729: 	}
1.755     albertel 5730:     }
                   5731:     return %returnhash;
1.407     www      5732: }
                   5733: 
1.1098    foxr     5734: 
1.717     albertel 5735: # --------------------------------------------------------- dumpstore interface
                   5736: 
                   5737: sub dumpstore {
                   5738:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5739:    # same as dump but keys must be escaped. They may contain colon separated
                   5740:    # lists of values that may themself contain colons (e.g. symbs).
                   5741:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5742: }
                   5743: 
1.407     www      5744: # -------------------------------------------------------------- keys interface
                   5745: 
                   5746: sub getkeys {
                   5747:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5748:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5749:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5750:    my $uhome=&homeserver($uname,$udomain);
                   5751:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5752:    my @keyarray=();
1.800     albertel 5753:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5754:       next if ($key =~ /^error: 2 /);
1.800     albertel 5755:       push(@keyarray,&unescape($key));
1.407     www      5756:    }
                   5757:    return @keyarray;
1.318     matthew  5758: }
                   5759: 
1.319     matthew  5760: # --------------------------------------------------------------- currentdump
                   5761: sub currentdump {
1.328     matthew  5762:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5763:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5764:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5765:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5766:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  5767:    my $rep;
                   5768: 
                   5769:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5770:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   5771:                    $courseid)));
                   5772:    } else {
                   5773:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5774:    }
                   5775: 
1.318     matthew  5776:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5777:    #
1.318     matthew  5778:    my %returnhash=();
1.319     matthew  5779:    #
                   5780:    if ($rep eq "unknown_cmd") { 
                   5781:        # an old lond will not know currentdump
                   5782:        # Do a dump and make it look like a currentdump
1.822     albertel 5783:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5784:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5785:        my %hash = @tmp;
                   5786:        @tmp=();
1.424     matthew  5787:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5788:    } else {
                   5789:        my @pairs=split(/\&/,$rep);
1.800     albertel 5790:        foreach my $pair (@pairs) {
                   5791:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5792:            my ($symb,$param) = split(/:/,$key);
                   5793:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5794:                                                         &thaw_unescape($value);
1.319     matthew  5795:        }
1.191     harris41 5796:    }
1.12      www      5797:    return %returnhash;
1.424     matthew  5798: }
                   5799: 
                   5800: sub convert_dump_to_currentdump{
                   5801:     my %hash = %{shift()};
                   5802:     my %returnhash;
                   5803:     # Code ripped from lond, essentially.  The only difference
                   5804:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5805:     # we might run in to problems with parameter names =~ /^v\./
                   5806:     while (my ($key,$value) = each(%hash)) {
                   5807:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5808: 	$symb  = &unescape($symb);
                   5809: 	$param = &unescape($param);
1.424     matthew  5810:         next if ($v eq 'version' || $symb eq 'keys');
                   5811:         next if (exists($returnhash{$symb}) &&
                   5812:                  exists($returnhash{$symb}->{$param}) &&
                   5813:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5814:         $returnhash{$symb}->{$param}=$value;
                   5815:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5816:     }
                   5817:     #
                   5818:     # Remove all of the keys in the hashes which keep track of
                   5819:     # the version of the parameter.
                   5820:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5821:         # use a foreach because we are going to delete from the hash.
                   5822:         foreach my $key (keys(%$param_hash)) {
                   5823:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5824:         }
                   5825:     }
                   5826:     return \%returnhash;
1.12      www      5827: }
                   5828: 
1.627     albertel 5829: # ------------------------------------------------------ critical inc interface
                   5830: 
                   5831: sub cinc {
                   5832:     return &inc(@_,'critical');
                   5833: }
                   5834: 
1.449     matthew  5835: # --------------------------------------------------------------- inc interface
                   5836: 
                   5837: sub inc {
1.627     albertel 5838:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5839:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5840:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5841:     my $uhome=&homeserver($uname,$udomain);
                   5842:     my $items='';
                   5843:     if (! ref($store)) {
                   5844:         # got a single value, so use that instead
                   5845:         $items = &escape($store).'=&';
                   5846:     } elsif (ref($store) eq 'SCALAR') {
                   5847:         $items = &escape($$store).'=&';        
                   5848:     } elsif (ref($store) eq 'ARRAY') {
                   5849:         $items = join('=&',map {&escape($_);} @{$store});
                   5850:     } elsif (ref($store) eq 'HASH') {
                   5851:         while (my($key,$value) = each(%{$store})) {
                   5852:             $items.= &escape($key).'='.&escape($value).'&';
                   5853:         }
                   5854:     }
                   5855:     $items=~s/\&$//;
1.627     albertel 5856:     if ($critical) {
                   5857: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5858:     } else {
                   5859: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5860:     }
1.449     matthew  5861: }
                   5862: 
1.12      www      5863: # --------------------------------------------------------------- put interface
                   5864: 
                   5865: sub put {
1.134     albertel 5866:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5867:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5868:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5869:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5870:    my $items='';
1.800     albertel 5871:    foreach my $item (keys(%$storehash)) {
                   5872:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5873:    }
1.12      www      5874:    $items=~s/\&$//;
1.134     albertel 5875:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5876: }
                   5877: 
1.631     albertel 5878: # ------------------------------------------------------------ newput interface
                   5879: 
                   5880: sub newput {
                   5881:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5882:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5883:    if (!$uname) { $uname=$env{'user.name'}; }
                   5884:    my $uhome=&homeserver($uname,$udomain);
                   5885:    my $items='';
                   5886:    foreach my $key (keys(%$storehash)) {
                   5887:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5888:    }
                   5889:    $items=~s/\&$//;
                   5890:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5891: }
                   5892: 
                   5893: # ---------------------------------------------------------  putstore interface
                   5894: 
1.524     raeburn  5895: sub putstore {
1.715     albertel 5896:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5897:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5898:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5899:    my $uhome=&homeserver($uname,$udomain);
                   5900:    my $items='';
1.715     albertel 5901:    foreach my $key (keys(%$storehash)) {
                   5902:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5903:    }
1.715     albertel 5904:    $items=~s/\&$//;
1.716     albertel 5905:    my $esc_symb=&escape($symb);
                   5906:    my $esc_v=&escape($version);
1.715     albertel 5907:    my $reply =
1.716     albertel 5908:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5909: 	      $uhome);
                   5910:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5911:        # gfall back to way things use to be done
1.715     albertel 5912:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5913: 			    $uname);
1.524     raeburn  5914:    }
1.715     albertel 5915:    return $reply;
                   5916: }
                   5917: 
                   5918: sub old_putstore {
1.716     albertel 5919:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5920:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5921:     if (!$uname) { $uname=$env{'user.name'}; }
                   5922:     my $uhome=&homeserver($uname,$udomain);
                   5923:     my %newstorehash;
1.800     albertel 5924:     foreach my $item (keys(%$storehash)) {
                   5925: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5926: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5927:     }
                   5928:     my $items='';
                   5929:     my %allitems = ();
1.800     albertel 5930:     foreach my $item (keys(%newstorehash)) {
                   5931: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5932: 	    my $key = $1.':keys:'.$2;
                   5933: 	    $allitems{$key} .= $3.':';
                   5934: 	}
1.800     albertel 5935: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5936:     }
1.800     albertel 5937:     foreach my $item (keys(%allitems)) {
                   5938: 	$allitems{$item} =~ s/\:$//;
                   5939: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5940:     }
                   5941:     $items=~s/\&$//;
                   5942:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5943: }
                   5944: 
1.47      www      5945: # ------------------------------------------------------ critical put interface
                   5946: 
                   5947: sub cput {
1.134     albertel 5948:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5949:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5950:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5951:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5952:    my $items='';
1.800     albertel 5953:    foreach my $item (keys(%$storehash)) {
                   5954:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5955:    }
1.47      www      5956:    $items=~s/\&$//;
1.134     albertel 5957:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5958: }
                   5959: 
                   5960: # -------------------------------------------------------------- eget interface
                   5961: 
                   5962: sub eget {
1.133     albertel 5963:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5964:    my $items='';
1.800     albertel 5965:    foreach my $item (@$storearr) {
                   5966:        $items.=&escape($item).'&';
1.191     harris41 5967:    }
1.12      www      5968:    $items=~s/\&$//;
1.620     albertel 5969:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5970:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5971:    my $uhome=&homeserver($uname,$udomain);
                   5972:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5973:    my @pairs=split(/\&/,$rep);
                   5974:    my %returnhash=();
1.42      www      5975:    my $i=0;
1.800     albertel 5976:    foreach my $item (@$storearr) {
                   5977:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5978:       $i++;
1.191     harris41 5979:    }
1.12      www      5980:    return %returnhash;
                   5981: }
                   5982: 
1.667     albertel 5983: # ------------------------------------------------------------ tmpput interface
                   5984: sub tmpput {
1.802     raeburn  5985:     my ($storehash,$server,$context)=@_;
1.667     albertel 5986:     my $items='';
1.800     albertel 5987:     foreach my $item (keys(%$storehash)) {
                   5988: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5989:     }
                   5990:     $items=~s/\&$//;
1.802     raeburn  5991:     if (defined($context)) {
                   5992:         $items .= ':'.&escape($context);
                   5993:     }
1.667     albertel 5994:     return &reply("tmpput:$items",$server);
                   5995: }
                   5996: 
                   5997: # ------------------------------------------------------------ tmpget interface
                   5998: sub tmpget {
1.688     albertel 5999:     my ($token,$server)=@_;
                   6000:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6001:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6002:     my %returnhash;
                   6003:     foreach my $item (split(/\&/,$rep)) {
                   6004: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6005:         next if ($key =~ /^error: 2 /);
1.667     albertel 6006: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6007:     }
                   6008:     return %returnhash;
                   6009: }
                   6010: 
1.1113    raeburn  6011: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6012: sub tmpdel {
                   6013:     my ($token,$server)=@_;
                   6014:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6015:     return &reply("tmpdel:$token",$server);
                   6016: }
                   6017: 
1.1172.2.13  raeburn  6018: # ------------------------------------------------------------ get_timebased_id
                   6019: 
                   6020: sub get_timebased_id {
                   6021:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6022:         $maxtries) = @_;
                   6023:     my ($newid,$error,$dellock);
                   6024:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6025:         return ('','ok','invalid call to get suffix');
                   6026:     }
                   6027: 
                   6028: # set defaults for any optional args for which values were not supplied
                   6029:     if ($who eq '') {
                   6030:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6031:     }
                   6032:     if (!$locktries) {
                   6033:         $locktries = 3;
                   6034:     }
                   6035:     if (!$maxtries) {
                   6036:         $maxtries = 10;
                   6037:     }
                   6038: 
                   6039:     if (($cdom eq '') || ($cnum eq '')) {
                   6040:         if ($env{'request.course.id'}) {
                   6041:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6042:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6043:         }
                   6044:         if (($cdom eq '') || ($cnum eq '')) {
                   6045:             return ('','ok','call to get suffix not in course context');
                   6046:         }
                   6047:     }
                   6048: 
                   6049: # construct locking item
                   6050:     my $lockhash = {
                   6051:                       $prefix."\0".'locked_'.$keyid => $who,
                   6052:                    };
                   6053:     my $tries = 0;
                   6054: 
                   6055: # attempt to get lock on nohist_$namespace file
                   6056:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6057:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6058:         $tries ++;
                   6059:         sleep 1;
                   6060:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6061:     }
                   6062: 
                   6063: # attempt to get unique identifier, based on current timestamp
                   6064:     if ($gotlock eq 'ok') {
                   6065:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6066:         my $id = time;
                   6067:         $newid = $id;
1.1172.2.56  raeburn  6068:         if ($idtype eq 'addcode') {
                   6069:             $newid .= &sixnum_code();
                   6070:         }
1.1172.2.13  raeburn  6071:         my $idtries = 0;
                   6072:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6073:             if ($idtype eq 'concat') {
                   6074:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6075:             } elsif ($idtype eq 'addcode') {
                   6076:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6077:             } else {
                   6078:                 $newid ++;
                   6079:             }
                   6080:             $idtries ++;
                   6081:         }
                   6082:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6083:             my %new_item =  (
                   6084:                               $prefix."\0".$newid => $who,
                   6085:                             );
                   6086:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6087:                                                  $cdom,$cnum);
                   6088:             if ($putresult ne 'ok') {
                   6089:                 undef($newid);
                   6090:                 $error = 'error saving new item: '.$putresult;
                   6091:             }
                   6092:         } else {
1.1172.2.56  raeburn  6093:              undef($newid);
1.1172.2.13  raeburn  6094:              $error = ('error: no unique suffix available for the new item ');
                   6095:         }
                   6096: #  remove lock
                   6097:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6098:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6099:     } else {
                   6100:         $error = "error: could not obtain lockfile\n";
                   6101:         $dellock = 'ok';
                   6102:     }
                   6103:     return ($newid,$dellock,$error);
                   6104: }
                   6105: 
1.1172.2.56  raeburn  6106: sub sixnum_code {
                   6107:     my $code;
                   6108:     for (0..6) {
                   6109:         $code .= int( rand(9) );
                   6110:     }
                   6111:     return $code;
                   6112: }
                   6113: 
1.765     albertel 6114: # -------------------------------------------------- portfolio access checking
                   6115: 
                   6116: sub portfolio_access {
1.766     albertel 6117:     my ($requrl) = @_;
1.765     albertel 6118:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   6119:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  6120:     if ($result) {
                   6121:         my %setters;
                   6122:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6123:             my ($startblock,$endblock) =
                   6124:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6125:             if ($startblock && $endblock) {
                   6126:                 return 'B';
                   6127:             }
                   6128:         } else {
                   6129:             my ($startblock,$endblock) =
                   6130:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6131:             if ($startblock && $endblock) {
                   6132:                 return 'B';
                   6133:             }
                   6134:         }
                   6135:     }
1.765     albertel 6136:     if ($result eq 'ok') {
1.766     albertel 6137:        return 'F';
1.765     albertel 6138:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6139:        return 'A';
1.765     albertel 6140:     }
1.766     albertel 6141:     return '';
1.765     albertel 6142: }
                   6143: 
                   6144: sub get_portfolio_access {
1.767     albertel 6145:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   6146: 
                   6147:     if (!ref($access_hash)) {
                   6148: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6149: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6150: 						   $file_name);
                   6151: 	$access_hash = $access_controls{$file_name};
                   6152:     }
                   6153: 
1.765     albertel 6154:     my ($public,$guest,@domains,@users,@courses,@groups);
                   6155:     my $now = time;
                   6156:     if (ref($access_hash) eq 'HASH') {
                   6157:         foreach my $key (keys(%{$access_hash})) {
                   6158:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6159:             if ($start > $now) {
                   6160:                 next;
                   6161:             }
                   6162:             if ($end && $end<$now) {
                   6163:                 next;
                   6164:             }
                   6165:             if ($scope eq 'public') {
                   6166:                 $public = $key;
                   6167:                 last;
                   6168:             } elsif ($scope eq 'guest') {
                   6169:                 $guest = $key;
                   6170:             } elsif ($scope eq 'domains') {
                   6171:                 push(@domains,$key);
                   6172:             } elsif ($scope eq 'users') {
                   6173:                 push(@users,$key);
                   6174:             } elsif ($scope eq 'course') {
                   6175:                 push(@courses,$key);
                   6176:             } elsif ($scope eq 'group') {
                   6177:                 push(@groups,$key);
                   6178:             }
                   6179:         }
                   6180:         if ($public) {
                   6181:             return 'ok';
                   6182:         }
                   6183:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6184:             if ($guest) {
                   6185:                 return $guest;
                   6186:             }
                   6187:         } else {
                   6188:             if (@domains > 0) {
                   6189:                 foreach my $domkey (@domains) {
                   6190:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6191:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6192:                             return 'ok';
                   6193:                         }
                   6194:                     }
                   6195:                 }
                   6196:             }
                   6197:             if (@users > 0) {
                   6198:                 foreach my $userkey (@users) {
1.865     raeburn  6199:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6200:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6201:                             if (ref($item) eq 'HASH') {
                   6202:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6203:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6204:                                     return 'ok';
                   6205:                                 }
                   6206:                             }
                   6207:                         }
                   6208:                     } 
1.765     albertel 6209:                 }
                   6210:             }
                   6211:             my %roleshash;
                   6212:             my @courses_and_groups = @courses;
                   6213:             push(@courses_and_groups,@groups); 
                   6214:             if (@courses_and_groups > 0) {
                   6215:                 my (%allgroups,%allroles); 
                   6216:                 my ($start,$end,$role,$sec,$group);
                   6217:                 foreach my $envkey (%env) {
1.1060    raeburn  6218:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6219:                         my $cid = $2.'_'.$3; 
                   6220:                         if ($1 eq 'gr') {
                   6221:                             $group = $4;
                   6222:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6223:                         } else {
                   6224:                             if ($4 eq '') {
                   6225:                                 $sec = 'none';
                   6226:                             } else {
                   6227:                                 $sec = $4;
                   6228:                             }
                   6229:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6230:                         }
1.811     albertel 6231:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6232:                         my $cid = $2.'_'.$3;
                   6233:                         if ($4 eq '') {
                   6234:                             $sec = 'none';
                   6235:                         } else {
                   6236:                             $sec = $4;
                   6237:                         }
                   6238:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6239:                     }
                   6240:                 }
                   6241:                 if (keys(%allroles) == 0) {
                   6242:                     return;
                   6243:                 }
                   6244:                 foreach my $key (@courses_and_groups) {
                   6245:                     my %content = %{$$access_hash{$key}};
                   6246:                     my $cnum = $content{'number'};
                   6247:                     my $cdom = $content{'domain'};
                   6248:                     my $cid = $cdom.'_'.$cnum;
                   6249:                     if (!exists($allroles{$cid})) {
                   6250:                         next;
                   6251:                     }    
                   6252:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6253:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6254:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6255:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6256:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6257:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6258:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6259:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6260:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6261:                                         if (grep/^all$/,@sections) {
                   6262:                                             return 'ok';
                   6263:                                         } else {
                   6264:                                             if (grep/^$sec$/,@sections) {
                   6265:                                                 return 'ok';
                   6266:                                             }
                   6267:                                         }
                   6268:                                     }
                   6269:                                 }
                   6270:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6271:                                     if (grep/^none$/,@groups) {
                   6272:                                         return 'ok';
                   6273:                                     }
                   6274:                                 } else {
                   6275:                                     if (grep/^all$/,@groups) {
                   6276:                                         return 'ok';
                   6277:                                     } 
                   6278:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6279:                                         if (grep/^$group$/,@groups) {
                   6280:                                             return 'ok';
                   6281:                                         }
                   6282:                                     }
                   6283:                                 } 
                   6284:                             }
                   6285:                         }
                   6286:                     }
                   6287:                 }
                   6288:             }
                   6289:             if ($guest) {
                   6290:                 return $guest;
                   6291:             }
                   6292:         }
                   6293:     }
                   6294:     return;
                   6295: }
                   6296: 
                   6297: sub course_group_datechecker {
                   6298:     my ($dates,$now,$status) = @_;
                   6299:     my ($start,$end) = split(/\./,$dates);
                   6300:     if (!$start && !$end) {
                   6301:         return 'ok';
                   6302:     }
                   6303:     if (grep/^active$/,@{$status}) {
                   6304:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6305:             return 'ok';
                   6306:         }
                   6307:     }
                   6308:     if (grep/^previous$/,@{$status}) {
                   6309:         if ($end > $now ) {
                   6310:             return 'ok';
                   6311:         }
                   6312:     }
                   6313:     if (grep/^future$/,@{$status}) {
                   6314:         if ($start > $now) {
                   6315:             return 'ok';
                   6316:         }
                   6317:     }
                   6318:     return; 
                   6319: }
                   6320: 
                   6321: sub parse_portfolio_url {
                   6322:     my ($url) = @_;
                   6323: 
                   6324:     my ($type,$udom,$unum,$group,$file_name);
                   6325:     
1.823     albertel 6326:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6327: 	$type = 1;
                   6328:         $udom = $1;
                   6329:         $unum = $2;
                   6330:         $file_name = $3;
1.823     albertel 6331:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6332: 	$type = 2;
                   6333:         $udom = $1;
                   6334:         $unum = $2;
                   6335:         $group = $3;
                   6336:         $file_name = $3.'/'.$4;
                   6337:     }
                   6338:     if (wantarray) {
                   6339: 	return ($type,$udom,$unum,$file_name,$group);
                   6340:     }
                   6341:     return $type;
                   6342: }
                   6343: 
                   6344: sub is_portfolio_url {
                   6345:     my ($url) = @_;
                   6346:     return scalar(&parse_portfolio_url($url));
                   6347: }
                   6348: 
1.798     raeburn  6349: sub is_portfolio_file {
                   6350:     my ($file) = @_;
1.820     raeburn  6351:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6352:         return 1;
                   6353:     }
                   6354:     return;
                   6355: }
                   6356: 
1.976     raeburn  6357: sub usertools_access {
1.1084    raeburn  6358:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6359:     my ($access,%tools);
                   6360:     if ($context eq '') {
                   6361:         $context = 'tools';
                   6362:     }
                   6363:     if ($context eq 'requestcourses') {
                   6364:         %tools = (
                   6365:                       official   => 1,
                   6366:                       unofficial => 1,
1.1006    raeburn  6367:                       community  => 1,
1.1172.2.37  raeburn  6368:                       textbook   => 1,
1.985     raeburn  6369:                  );
1.1172.2.9  raeburn  6370:     } elsif ($context eq 'requestauthor') {
                   6371:         %tools = (
                   6372:                       requestauthor => 1,
                   6373:                  );
1.985     raeburn  6374:     } else {
                   6375:         %tools = (
                   6376:                       aboutme   => 1,
                   6377:                       blog      => 1,
1.1172.2.6  raeburn  6378:                       webdav    => 1,
1.985     raeburn  6379:                       portfolio => 1,
                   6380:                  );
                   6381:     }
1.976     raeburn  6382:     return if (!defined($tools{$tool}));
                   6383: 
1.1172.2.35  raeburn  6384:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6385:         $udom = $env{'user.domain'};
                   6386:         $uname = $env{'user.name'};
                   6387:     }
                   6388: 
1.978     raeburn  6389:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6390:         if ($action ne 'reload') {
1.985     raeburn  6391:             if ($context eq 'requestcourses') {
                   6392:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6393:             } elsif ($context eq 'requestauthor') {
                   6394:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6395:             } else {
                   6396:                 return $env{'environment.availabletools.'.$tool};
                   6397:             }
                   6398:         }
1.976     raeburn  6399:     }
                   6400: 
1.1172.2.9  raeburn  6401:     my ($toolstatus,$inststatus,$envkey);
                   6402:     if ($context eq 'requestauthor') {
                   6403:         $envkey = $context;
                   6404:     } else {
                   6405:         $envkey = $context.'.'.$tool;
                   6406:     }
1.976     raeburn  6407: 
1.985     raeburn  6408:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6409:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6410:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6411:         $inststatus = $env{'environment.inststatus'};
                   6412:     } else {
1.1084    raeburn  6413:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6414:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6415:             $inststatus = $userenvref->{'inststatus'};
                   6416:         } else {
1.1172.2.9  raeburn  6417:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6418:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6419:             $inststatus = $userenv{'inststatus'};
                   6420:         }
1.976     raeburn  6421:     }
                   6422: 
                   6423:     if ($toolstatus ne '') {
                   6424:         if ($toolstatus) {
                   6425:             $access = 1;
                   6426:         } else {
                   6427:             $access = 0;
                   6428:         }
                   6429:         return $access;
                   6430:     }
                   6431: 
1.1084    raeburn  6432:     my ($is_adv,%domdef);
                   6433:     if (ref($is_advref) eq 'HASH') {
                   6434:         $is_adv = $is_advref->{'is_adv'};
                   6435:     } else {
                   6436:         $is_adv = &is_advanced_user($udom,$uname);
                   6437:     }
                   6438:     if (ref($domdefref) eq 'HASH') {
                   6439:         %domdef = %{$domdefref};
                   6440:     } else {
                   6441:         %domdef = &get_domain_defaults($udom);
                   6442:     }
1.976     raeburn  6443:     if (ref($domdef{$tool}) eq 'HASH') {
                   6444:         if ($is_adv) {
                   6445:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6446:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6447:                     $access = 1;
                   6448:                 } else {
                   6449:                     $access = 0;
                   6450:                 }
                   6451:                 return $access;
                   6452:             }
                   6453:         }
                   6454:         if ($inststatus ne '') {
                   6455:             my ($hasaccess,$hasnoaccess);
                   6456:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6457:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6458:                     if ($domdef{$tool}{$affiliation}) {
                   6459:                         $hasaccess = 1;
                   6460:                     } else {
                   6461:                         $hasnoaccess = 1;
                   6462:                     }
                   6463:                 }
                   6464:             }
                   6465:             if ($hasaccess || $hasnoaccess) {
                   6466:                 if ($hasaccess) {
                   6467:                     $access = 1;
                   6468:                 } elsif ($hasnoaccess) {
                   6469:                     $access = 0; 
                   6470:                 }
                   6471:                 return $access;
                   6472:             }
                   6473:         } else {
                   6474:             if ($domdef{$tool}{'default'} ne '') {
                   6475:                 if ($domdef{$tool}{'default'}) {
                   6476:                     $access = 1;
                   6477:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6478:                     $access = 0;
                   6479:                 }
                   6480:                 return $access;
                   6481:             }
                   6482:         }
                   6483:     } else {
1.1172.2.6  raeburn  6484:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6485:             $access = 1;
                   6486:         } else {
                   6487:             $access = 0;
                   6488:         }
1.976     raeburn  6489:         return $access;
                   6490:     }
                   6491: }
                   6492: 
1.1050    raeburn  6493: sub is_course_owner {
                   6494:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6495:     if (($udom eq '') || ($uname eq '')) {
                   6496:         $udom = $env{'user.domain'};
                   6497:         $uname = $env{'user.name'};
                   6498:     }
                   6499:     unless (($udom eq '') || ($uname eq '')) {
                   6500:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6501:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6502:                 return 1;
                   6503:             } else {
                   6504:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6505:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6506:                     return 1;
                   6507:                 }
                   6508:             }
                   6509:         }
                   6510:     }
                   6511:     return;
                   6512: }
                   6513: 
1.976     raeburn  6514: sub is_advanced_user {
                   6515:     my ($udom,$uname) = @_;
1.1085    raeburn  6516:     if ($udom ne '' && $uname ne '') {
                   6517:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6518:             if (wantarray) {
                   6519:                 return ($env{'user.adv'},$env{'user.author'});
                   6520:             } else {
                   6521:                 return $env{'user.adv'};
                   6522:             }
1.1085    raeburn  6523:         }
                   6524:     }
1.976     raeburn  6525:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6526:     my %allroles;
1.1128    raeburn  6527:     my ($is_adv,$is_author);
1.976     raeburn  6528:     foreach my $role (keys(%roleshash)) {
                   6529:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6530:         my $area = '/'.$tdomain.'/'.$trest;
                   6531:         if ($sec ne '') {
                   6532:             $area .= '/'.$sec;
                   6533:         }
                   6534:         if (($area ne '') && ($trole ne '')) {
                   6535:             my $spec=$trole.'.'.$area;
                   6536:             if ($trole =~ /^cr\//) {
                   6537:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6538:             } elsif ($trole ne 'gr') {
                   6539:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6540:             }
1.1128    raeburn  6541:             if ($trole eq 'au') {
                   6542:                 $is_author = 1;
                   6543:             }
1.976     raeburn  6544:         }
                   6545:     }
                   6546:     foreach my $role (keys(%allroles)) {
                   6547:         last if ($is_adv);
                   6548:         foreach my $item (split(/:/,$allroles{$role})) {
                   6549:             if ($item ne '') {
                   6550:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6551:                 if ($privilege eq 'adv') {
                   6552:                     $is_adv = 1;
                   6553:                     last;
                   6554:                 }
                   6555:             }
                   6556:         }
                   6557:     }
1.1128    raeburn  6558:     if (wantarray) {
                   6559:         return ($is_adv,$is_author);
                   6560:     }
1.976     raeburn  6561:     return $is_adv;
                   6562: }
1.798     raeburn  6563: 
1.1035    raeburn  6564: sub check_can_request {
1.1036    raeburn  6565:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6566:     my $canreq = 0;
                   6567:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6568:     my @options = ('approval','validate','autolimit');
                   6569:     my $optregex = join('|',@options);
                   6570:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6571:         foreach my $type (@{$types}) {
                   6572:             if (&usertools_access($env{'user.name'},
                   6573:                                   $env{'user.domain'},
                   6574:                                   $type,undef,'requestcourses')) {
                   6575:                 $canreq ++;
1.1036    raeburn  6576:                 if (ref($request_domains) eq 'HASH') {
                   6577:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6578:                 }
1.1035    raeburn  6579:                 if ($dom eq $env{'user.domain'}) {
                   6580:                     $can_request->{$type} = 1;
                   6581:                 }
                   6582:             }
                   6583:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6584:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6585:                 if (@curr > 0) {
1.1036    raeburn  6586:                     foreach my $item (@curr) {
                   6587:                         if (ref($request_domains) eq 'HASH') {
                   6588:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6589:                             if ($otherdom ne '') {
                   6590:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6591:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6592:                                         push(@{$request_domains->{$type}},$otherdom);
                   6593:                                     }
                   6594:                                 } else {
                   6595:                                     push(@{$request_domains->{$type}},$otherdom);
                   6596:                                 }
                   6597:                             }
                   6598:                         }
                   6599:                     }
                   6600:                     unless($dom eq $env{'user.domain'}) {
                   6601:                         $canreq ++;
1.1035    raeburn  6602:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6603:                             $can_request->{$type} = 1;
                   6604:                         }
                   6605:                     }
                   6606:                 }
                   6607:             }
                   6608:         }
                   6609:     }
                   6610:     return $canreq;
                   6611: }
                   6612: 
1.341     www      6613: # ---------------------------------------------- Custom access rule evaluation
                   6614: 
                   6615: sub customaccess {
                   6616:     my ($priv,$uri)=@_;
1.807     albertel 6617:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6618:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6619:     $udom = &LONCAPA::clean_domain($udom);
                   6620:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6621:     my $access=0;
1.800     albertel 6622:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6623: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6624: 	if ($type eq 'user') {
                   6625: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6626: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6627: 		if ($tdom) {
                   6628: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6629: 		}
1.896     albertel 6630: 		if ($tuname) {
                   6631: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6632: 		}
                   6633: 		$access=($effect eq 'allow');
                   6634: 		last;
                   6635: 	    }
                   6636: 	} else {
                   6637: 	    if ($role) {
                   6638: 		if ($role ne $urole) { next; }
                   6639: 	    }
                   6640: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6641: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6642: 		if ($tdom) {
                   6643: 		    if ($tdom ne $udom) { next; }
                   6644: 		}
                   6645: 		if ($tcrs) {
                   6646: 		    if ($tcrs ne $ucrs) { next; }
                   6647: 		}
                   6648: 		if ($tsec) {
                   6649: 		    if ($tsec ne $usec) { next; }
                   6650: 		}
                   6651: 		$access=($effect eq 'allow');
                   6652: 		last;
                   6653: 	    }
                   6654: 	    if ($realm eq '' && $role eq '') {
                   6655: 		$access=($effect eq 'allow');
                   6656: 	    }
1.402     bowersj2 6657: 	}
1.341     www      6658:     }
                   6659:     return $access;
                   6660: }
                   6661: 
1.103     harris41 6662: # ------------------------------------------------- Check for a user privilege
1.12      www      6663: 
                   6664: sub allowed {
1.810     raeburn  6665:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6666:     my $ver_orguri=$uri;
1.439     www      6667:     $uri=&deversion($uri);
1.152     www      6668:     my $orguri=$uri;
1.52      www      6669:     $uri=&declutter($uri);
1.809     raeburn  6670: 
1.810     raeburn  6671:     if ($priv eq 'evb') {
                   6672: # Evade communication block restrictions for specified role in a course
                   6673:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6674:             return $1;
                   6675:         } else {
                   6676:             return;
                   6677:         }
                   6678:     }
                   6679: 
1.620     albertel 6680:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6681: # Free bre access to adm and meta resources
1.775     albertel 6682:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6683: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6684: 	&& ($priv eq 'bre')) {
1.14      www      6685: 	return 'F';
1.159     www      6686:     }
                   6687: 
1.545     banghart 6688: # Free bre access to user's own portfolio contents
1.714     raeburn  6689:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6690:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6691: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6692:         my %setters;
                   6693:         my ($startblock,$endblock) = 
                   6694:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6695:         if ($startblock && $endblock) {
                   6696:             return 'B';
                   6697:         } else {
                   6698:             return 'F';
                   6699:         }
1.545     banghart 6700:     }
                   6701: 
1.762     raeburn  6702: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6703:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6704:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6705:         if (exists($env{'request.course.id'})) {
                   6706:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6707:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6708:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6709:                 my $courseprivid=$env{'request.course.id'};
                   6710:                 $courseprivid=~s/\_/\//;
                   6711:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6712:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6713:                     return $1; 
1.762     raeburn  6714:                 } else {
                   6715:                     if ($env{'request.course.sec'}) {
                   6716:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6717:                     }
                   6718:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6719:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6720:                         return $2;
                   6721:                     }
1.714     raeburn  6722:                 }
                   6723:             }
                   6724:         }
                   6725:     }
                   6726: 
1.159     www      6727: # Free bre to public access
                   6728: 
                   6729:     if ($priv eq 'bre') {
1.238     www      6730:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6731: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6732:            return 'F'; 
                   6733:         }
1.238     www      6734:         if ($copyright eq 'priv') {
                   6735:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6736: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6737: 		return '';
                   6738:             }
                   6739:         }
                   6740:         if ($copyright eq 'domain') {
                   6741:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6742: 	    unless (($env{'user.domain'} eq $1) ||
                   6743:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6744: 		return '';
                   6745:             }
1.262     matthew  6746:         }
1.620     albertel 6747:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6748:             # Library role, so allow browsing of resources in this domain.
                   6749:             return 'F';
1.238     www      6750:         }
1.341     www      6751:         if ($copyright eq 'custom') {
                   6752: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6753:         }
1.14      www      6754:     }
1.264     matthew  6755:     # Domain coordinator is trying to create a course
1.620     albertel 6756:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6757:         # uri is the requested domain in this case.
                   6758:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6759:         # a role of dc for the domain in question.
1.620     albertel 6760:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6761:     }
1.29      www      6762: 
1.52      www      6763:     my $thisallowed='';
                   6764:     my $statecond=0;
                   6765:     my $courseprivid='';
                   6766: 
1.1039    raeburn  6767:     my $ownaccess;
1.1043    raeburn  6768:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6769:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6770:         if ($uri eq '') {
                   6771:             $ownaccess = 1;
                   6772:         } else {
                   6773:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6774:                 my $udom = $env{'user.domain'};
                   6775:                 my $uname = $env{'user.name'};
                   6776:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6777:                     $ownaccess = 1;
1.1040    raeburn  6778:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6779:                     unless ($uri =~ m{\.\./}) {
                   6780:                         $ownaccess = 1;
                   6781:                     }
                   6782:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6783:                     my $now = time;
                   6784:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6785:                         my $adom = $1;
                   6786:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6787:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6788:                                 my ($start,$end) = split('.',$env{$key});
                   6789:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6790:                                     $ownaccess = 1;
                   6791:                                     last;
                   6792:                                 }
                   6793:                             }
                   6794:                         }
                   6795:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6796:                         my $adom = $1;
                   6797:                         my $aname = $2;
1.1042    raeburn  6798:                         foreach my $role ('ca','aa') { 
                   6799:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6800:                                 my ($start,$end) =
                   6801:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6802:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6803:                                     $ownaccess = 1;
                   6804:                                     last;
                   6805:                                 }
1.1039    raeburn  6806:                             }
                   6807:                         }
                   6808:                     }
                   6809:                 }
                   6810:             }
                   6811:         }
                   6812:     }
                   6813: 
1.52      www      6814: # Course
                   6815: 
1.620     albertel 6816:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6817:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6818:             $thisallowed.=$1;
                   6819:         }
1.52      www      6820:     }
1.29      www      6821: 
1.52      www      6822: # Domain
                   6823: 
1.620     albertel 6824:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6825:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6826:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6827:             $thisallowed.=$1;
                   6828:         }
1.12      www      6829:     }
1.52      www      6830: 
1.1141    raeburn  6831: # User who is not author or co-author might still be able to edit
                   6832: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6833:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6834:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6835:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6836:             $thisallowed.=$1;
                   6837:         }
                   6838:     }
                   6839: 
1.52      www      6840: # Course: uri itself is a course
1.66      www      6841:     my $courseuri=$uri;
                   6842:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6843:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6844: 
1.620     albertel 6845:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6846:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6847:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6848:             $thisallowed.=$1;
                   6849:         }
1.12      www      6850:     }
1.29      www      6851: 
1.665     albertel 6852: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6853: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6854:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6855: 	$thisallowed='';
1.671     raeburn  6856:         my ($match)=&is_on_map($uri);
                   6857:         if ($match) {
                   6858:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6859:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6860:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6861:                 if (@blockers > 0) {
                   6862:                     $thisallowed = 'B';
                   6863:                 } else {
                   6864:                     $thisallowed.=$1;
                   6865:                 }
1.671     raeburn  6866:             }
                   6867:         } else {
1.705     albertel 6868:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6869:             if ($refuri) {
                   6870:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6871:                     $thisallowed='F';
1.671     raeburn  6872:                 } else {
                   6873:                     $refuri=&declutter($refuri);
                   6874:                     my ($match) = &is_on_map($refuri);
                   6875:                     if ($match) {
1.1162    raeburn  6876:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6877:                         if (@blockers > 0) {
                   6878:                             $thisallowed = 'B';
                   6879:                         } else {
                   6880:                             $thisallowed='F';
                   6881:                         }
1.671     raeburn  6882:                     }
1.669     raeburn  6883:                 }
1.671     raeburn  6884:             }
                   6885:         }
1.314     www      6886:     }
1.492     albertel 6887: 
1.766     albertel 6888:     if ($priv eq 'bre'
                   6889: 	&& $thisallowed ne 'F' 
                   6890: 	&& $thisallowed ne '2'
                   6891: 	&& &is_portfolio_url($uri)) {
                   6892: 	$thisallowed = &portfolio_access($uri);
                   6893:     }
                   6894:     
1.52      www      6895: # Full access at system, domain or course-wide level? Exit.
1.29      www      6896:     if ($thisallowed=~/F/) {
                   6897: 	return 'F';
                   6898:     }
                   6899: 
1.52      www      6900: # If this is generating or modifying users, exit with special codes
1.29      www      6901: 
1.643     www      6902:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6903: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6904: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6905: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6906: 	    unless ($auname) { return $thisallowed; }
                   6907: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6908: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6909: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6910: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6911: 	}
1.52      www      6912: 	return $thisallowed;
                   6913:     }
                   6914: #
1.103     harris41 6915: # Gathered so far: system, domain and course wide privileges
1.52      www      6916: #
                   6917: # Course: See if uri or referer is an individual resource that is part of 
                   6918: # the course
                   6919: 
1.620     albertel 6920:     if ($env{'request.course.id'}) {
1.232     www      6921: 
1.620     albertel 6922:        $courseprivid=$env{'request.course.id'};
                   6923:        if ($env{'request.course.sec'}) {
                   6924:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6925:        }
                   6926:        $courseprivid=~s/\_/\//;
                   6927:        my $checkreferer=1;
1.232     www      6928:        my ($match,$cond)=&is_on_map($uri);
                   6929:        if ($match) {
                   6930:            $statecond=$cond;
1.620     albertel 6931:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6932:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6933:                my $value = $1;
                   6934:                if ($priv eq 'bre') {
                   6935:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6936:                    if (@blockers > 0) {
                   6937:                        $thisallowed = 'B';
                   6938:                    } else {
                   6939:                        $thisallowed.=$value;
                   6940:                    }
                   6941:                } else {
                   6942:                    $thisallowed.=$value;
                   6943:                }
1.52      www      6944:                $checkreferer=0;
                   6945:            }
1.29      www      6946:        }
1.83      www      6947:        
1.148     www      6948:        if ($checkreferer) {
1.620     albertel 6949: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6950:             unless ($refuri) {
1.800     albertel 6951:                 foreach my $key (keys(%env)) {
                   6952: 		    if ($key=~/^httpref\..*\*/) {
                   6953: 			my $pattern=$key;
1.156     www      6954:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6955:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6956:                         $pattern=~s/\//\\\//g;
1.152     www      6957:                         if ($orguri=~/$pattern/) {
1.800     albertel 6958: 			    $refuri=$env{$key};
1.148     www      6959:                         }
                   6960:                     }
1.191     harris41 6961:                 }
1.148     www      6962:             }
1.232     www      6963: 
1.148     www      6964:          if ($refuri) { 
1.152     www      6965: 	  $refuri=&declutter($refuri);
1.232     www      6966:           my ($match,$cond)=&is_on_map($refuri);
                   6967:             if ($match) {
                   6968:               my $refstatecond=$cond;
1.620     albertel 6969:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6970:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6971:                   my $value = $1;
                   6972:                   if ($priv eq 'bre') {
                   6973:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6974:                       if (@blockers > 0) {
                   6975:                           $thisallowed = 'B';
                   6976:                       } else {
                   6977:                           $thisallowed.=$value;
                   6978:                       }
                   6979:                   } else {
                   6980:                       $thisallowed.=$value;
                   6981:                   }
1.53      www      6982:                   $uri=$refuri;
                   6983:                   $statecond=$refstatecond;
1.52      www      6984:               }
                   6985:           }
1.148     www      6986:         }
1.29      www      6987:        }
1.52      www      6988:    }
1.29      www      6989: 
1.52      www      6990: #
1.103     harris41 6991: # Gathered now: all privileges that could apply, and condition number
1.52      www      6992: # 
                   6993: #
                   6994: # Full or no access?
                   6995: #
1.29      www      6996: 
1.52      www      6997:     if ($thisallowed=~/F/) {
                   6998: 	return 'F';
                   6999:     }
1.29      www      7000: 
1.52      www      7001:     unless ($thisallowed) {
                   7002:         return '';
                   7003:     }
1.29      www      7004: 
1.52      www      7005: # Restrictions exist, deal with them
                   7006: #
                   7007: #   C:according to course preferences
                   7008: #   R:according to resource settings
                   7009: #   L:unless locked
                   7010: #   X:according to user session state
                   7011: #
                   7012: 
                   7013: # Possibly locked functionality, check all courses
1.54      www      7014: # Locks might take effect only after 10 minutes cache expiration for other
                   7015: # courses, and 2 minutes for current course
1.52      www      7016: 
                   7017:     my $envkey;
                   7018:     if ($thisallowed=~/L/) {
1.1000    raeburn  7019:         foreach $envkey (keys(%env)) {
1.54      www      7020:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7021:                my $courseid=$2;
                   7022:                my $roleid=$1.'.'.$2;
1.92      www      7023:                $courseid=~s/^\///;
1.54      www      7024:                my $expiretime=600;
1.620     albertel 7025:                if ($env{'request.role'} eq $roleid) {
1.54      www      7026: 		  $expiretime=120;
                   7027:                }
                   7028: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7029:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7030:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7031: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7032:                }
1.620     albertel 7033:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7034:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7035: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7036:                        &log($env{'user.domain'},$env{'user.name'},
                   7037:                             $env{'user.home'},
1.57      www      7038:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7039:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7040:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7041: 		       return '';
                   7042:                    }
                   7043:                }
1.620     albertel 7044:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7045:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7046: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7047:                        &log($env{'user.domain'},$env{'user.name'},
                   7048:                             $env{'user.home'},
1.57      www      7049:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7050:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7051:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7052: 		       return '';
                   7053:                    }
                   7054:                }
                   7055: 	   }
1.29      www      7056:        }
1.52      www      7057:     }
                   7058:    
                   7059: #
                   7060: # Rest of the restrictions depend on selected course
                   7061: #
                   7062: 
1.620     albertel 7063:     unless ($env{'request.course.id'}) {
1.766     albertel 7064: 	if ($thisallowed eq 'A') {
                   7065: 	    return 'A';
1.814     raeburn  7066:         } elsif ($thisallowed eq 'B') {
                   7067:             return 'B';
1.766     albertel 7068: 	} else {
                   7069: 	    return '1';
                   7070: 	}
1.52      www      7071:     }
1.29      www      7072: 
1.52      www      7073: #
                   7074: # Now user is definitely in a course
                   7075: #
1.53      www      7076: 
                   7077: 
                   7078: # Course preferences
                   7079: 
                   7080:    if ($thisallowed=~/C/) {
1.620     albertel 7081:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7082:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7083:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7084: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7085: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7086: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7087: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7088: 			$env{'request.course.id'});
                   7089: 	   }
1.237     www      7090:            return '';
                   7091:        }
                   7092: 
1.620     albertel 7093:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7094: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7095: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7096: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7097: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7098: 			$env{'request.course.id'});
                   7099: 	   }
1.54      www      7100:            return '';
                   7101:        }
1.53      www      7102:    }
                   7103: 
                   7104: # Resource preferences
                   7105: 
                   7106:    if ($thisallowed=~/R/) {
1.620     albertel 7107:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7108:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7109: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7110: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7111: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7112: 	   }
                   7113: 	   return '';
1.54      www      7114:        }
1.53      www      7115:    }
1.30      www      7116: 
1.246     www      7117: # Restricted by state or randomout?
1.30      www      7118: 
1.52      www      7119:    if ($thisallowed=~/X/) {
1.620     albertel 7120:       if ($env{'acc.randomout'}) {
1.579     albertel 7121: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7122:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7123:             return ''; 
                   7124:          }
1.247     www      7125:       }
                   7126:       if (&condval($statecond)) {
1.52      www      7127: 	 return '2';
                   7128:       } else {
                   7129:          return '';
                   7130:       }
                   7131:    }
1.30      www      7132: 
1.766     albertel 7133:     if ($thisallowed eq 'A') {
                   7134: 	return 'A';
1.814     raeburn  7135:     } elsif ($thisallowed eq 'B') {
                   7136:         return 'B';
1.766     albertel 7137:     }
1.52      www      7138:    return 'F';
1.232     www      7139: }
1.1162    raeburn  7140: 
1.1172.2.13  raeburn  7141: # ------------------------------------------- Check construction space access
                   7142: 
                   7143: sub constructaccess {
                   7144:     my ($url,$setpriv)=@_;
                   7145: 
                   7146: # We do not allow editing of previous versions of files
                   7147:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7148: 
                   7149: # Get username and domain from URL
                   7150:     my ($ownername,$ownerdomain,$ownerhome);
                   7151: 
                   7152:     ($ownerdomain,$ownername) =
                   7153:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7154: 
                   7155: # The URL does not really point to any authorspace, forget it
                   7156:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7157: 
                   7158: # Now we need to see if the user has access to the authorspace of
                   7159: # $ownername at $ownerdomain
                   7160: 
                   7161:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7162: # Real author for this?
                   7163:        $ownerhome = $env{'user.home'};
                   7164:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7165:           return ($ownername,$ownerdomain,$ownerhome);
                   7166:        }
                   7167:     } else {
                   7168: # Co-author for this?
                   7169:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7170:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7171:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7172:             return ($ownername,$ownerdomain,$ownerhome);
                   7173:         }
                   7174:     }
                   7175: 
                   7176: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7177: # we might as well leave
                   7178:    unless ($setpriv) { return ''; }
                   7179: 
                   7180: # Backdoor access?
                   7181:     my $allowed=&allowed('eco',$ownerdomain);
                   7182: # Nope
                   7183:     unless ($allowed) { return ''; }
                   7184: # Looks like we may have access, but could be locked by the owner of the construction space
                   7185:     if ($allowed eq 'U') {
                   7186:         my %blocked=&get('environment',['domcoord.author'],
                   7187:                          $ownerdomain,$ownername);
                   7188: # Is blocked by owner
                   7189:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7190:     }
                   7191:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7192: # Grant temporary access
                   7193:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7194:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7195:         if (!$update) { $update = $then; }
                   7196:         my $refresh=$env{'user.refresh.time'};
                   7197:         if (!$refresh) { $refresh = $update; }
                   7198:         my $now = time;
                   7199:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7200:                            $now,'ca','constructaccess');
                   7201:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7202:         return($ownername,$ownerdomain,$ownerhome);
                   7203:     }
                   7204: # No business here
                   7205:     return '';
                   7206: }
                   7207: 
1.1162    raeburn  7208: sub get_comm_blocks {
                   7209:     my ($cdom,$cnum) = @_;
                   7210:     if ($cdom eq '' || $cnum eq '') {
                   7211:         return unless ($env{'request.course.id'});
                   7212:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7213:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7214:     }
                   7215:     my %commblocks;
                   7216:     my $hashid=$cdom.'_'.$cnum;
                   7217:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7218:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7219:         %commblocks = %{$blocksref};
                   7220:     } else {
                   7221:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7222:         my $cachetime = 600;
                   7223:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7224:     }
                   7225:     return %commblocks;
                   7226: }
                   7227: 
                   7228: sub has_comm_blocking {
                   7229:     my ($priv,$symb,$uri,$blocks) = @_;
                   7230:     return unless ($env{'request.course.id'});
                   7231:     return unless ($priv eq 'bre');
                   7232:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7233:     my %commblocks;
                   7234:     if (ref($blocks) eq 'HASH') {
                   7235:         %commblocks = %{$blocks};
                   7236:     } else {
                   7237:         %commblocks = &get_comm_blocks();
                   7238:     }
                   7239:     return unless (keys(%commblocks) > 0);
                   7240:     if (!$symb) { $symb=&symbread($uri,1); }
                   7241:     my ($map,$resid,undef)=&decode_symb($symb);
                   7242:     my %tocheck = (
                   7243:                     maps      => $map,
                   7244:                     resources => $symb,
                   7245:                   );
                   7246:     my @blockers;
                   7247:     my $now = time;
1.1163    raeburn  7248:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7249:     foreach my $block (keys(%commblocks)) {
                   7250:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7251:             my ($start,$end) = ($1,$2);
                   7252:             if ($start <= $now && $end >= $now) {
                   7253:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7254:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7255:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7256:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7257:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7258:                                     push(@blockers,$block);
                   7259:                                 }
                   7260:                             }
                   7261:                         }
                   7262:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7263:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7264:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7265:                                     push(@blockers,$block);
                   7266:                                 }
                   7267:                             }
                   7268:                         }
                   7269:                     }
                   7270:                 }
                   7271:             }
                   7272:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7273:             my $item = $1;
1.1163    raeburn  7274:             my @to_test;
1.1162    raeburn  7275:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7276:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7277:                     my $check_interval;
                   7278:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7279:                         my @interval;
                   7280:                         my $type = 'map';
                   7281:                         if ($item eq 'course') {
                   7282:                             $type = 'course';
                   7283:                             @interval=&EXT("resource.0.interval");
                   7284:                         } else {
                   7285:                             if ($item =~ /___\d+___/) {
                   7286:                                 $type = 'resource';
                   7287:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7288:                                 if (ref($navmap)) {                        
                   7289:                                     my $res = $navmap->getBySymb($item); 
                   7290:                                     push(@to_test,$res);
                   7291:                                 }
1.1162    raeburn  7292:                             } else {
                   7293:                                 my $mapsymb = &symbread($item,1);
                   7294:                                 if ($mapsymb) {
                   7295:                                     if (ref($navmap)) {
                   7296:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7297:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7298:                                         foreach my $res (@to_test) {
1.1162    raeburn  7299:                                             my $symb = $res->symb();
                   7300:                                             next if ($symb eq $mapsymb);
                   7301:                                             if ($symb ne '') {
                   7302:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7303:                                                 last;
                   7304:                                             }
                   7305:                                         }
                   7306:                                     }
                   7307:                                 }
                   7308:                             }
                   7309:                         }
                   7310:                         if ($interval[0] =~ /\d+/) {
                   7311:                             my $first_access;
                   7312:                             if ($type eq 'resource') {
                   7313:                                 $first_access=&get_first_access($interval[1],$item);
                   7314:                             } elsif ($type eq 'map') {
                   7315:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7316:                             } else {
                   7317:                                 $first_access=&get_first_access($interval[1]);
                   7318:                             }
                   7319:                             if ($first_access) {
                   7320:                                 my $timesup = $first_access+$interval[0];
                   7321:                                 if ($timesup > $now) {
1.1163    raeburn  7322:                                     foreach my $res (@to_test) {
                   7323:                                         if ($res->is_problem()) {
                   7324:                                             if ($res->completable()) {
                   7325:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7326:                                                     push(@blockers,$block);
                   7327:                                                 }
                   7328:                                                 last;
                   7329:                                             }
                   7330:                                         }
1.1162    raeburn  7331:                                     }
                   7332:                                 }
                   7333:                             }
                   7334:                         }
                   7335:                     }
                   7336:                 }
                   7337:             }
                   7338:         }
                   7339:     }
                   7340:     return @blockers;
                   7341: }
                   7342: 
                   7343: sub check_docs_block {
                   7344:     my ($docsblock,$tocheck) =@_;
                   7345:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7346:         return;
                   7347:     }
                   7348:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7349:         if ($tocheck->{'maps'}) {
                   7350:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7351:                 return 1;
                   7352:             }
                   7353:         }
                   7354:     }
                   7355:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7356:         if ($tocheck->{'resources'}) {
                   7357:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7358:                 return 1;
                   7359:             }
                   7360:         }
                   7361:     }
                   7362:     return;
                   7363: }
                   7364: 
1.1133    foxr     7365: #
                   7366: #   Removes the versino from a URI and
                   7367: #   splits it in to its filename and path to the filename.
                   7368: #   Seems like File::Basename could have done this more clearly.
                   7369: #   Parameters:
                   7370: #      $uri   - input URI
                   7371: #   Returns:
                   7372: #     Two element list consisting of 
                   7373: #     $pathname  - the URI up to and excluding the trailing /
                   7374: #     $filename  - The part of the URI following the last /
                   7375: #  NOTE:
                   7376: #    Another realization of this is simply:
                   7377: #    use File::Basename;
                   7378: #    ...
                   7379: #    $uri = shift;
                   7380: #    $filename = basename($uri);
                   7381: #    $path     = dirname($uri);
                   7382: #    return ($filename, $path);
                   7383: #
                   7384: #     The implementation below is probably faster however.
                   7385: #
1.710     albertel 7386: sub split_uri_for_cond {
                   7387:     my $uri=&deversion(&declutter(shift));
                   7388:     my @uriparts=split(/\//,$uri);
                   7389:     my $filename=pop(@uriparts);
                   7390:     my $pathname=join('/',@uriparts);
                   7391:     return ($pathname,$filename);
                   7392: }
1.232     www      7393: # --------------------------------------------------- Is a resource on the map?
                   7394: 
                   7395: sub is_on_map {
1.710     albertel 7396:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7397:     #Trying to find the conditional for the file
1.620     albertel 7398:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7399: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7400:     if ($match) {
1.289     bowersj2 7401: 	return (1,$1);
                   7402:     } else {
1.434     www      7403: 	return (0,0);
1.289     bowersj2 7404:     }
1.12      www      7405: }
                   7406: 
1.427     www      7407: # --------------------------------------------------------- Get symb from alias
                   7408: 
                   7409: sub get_symb_from_alias {
                   7410:     my $symb=shift;
                   7411:     my ($map,$resid,$url)=&decode_symb($symb);
                   7412: # Already is a symb
                   7413:     if ($url) { return $symb; }
                   7414: # Must be an alias
                   7415:     my $aliassymb='';
                   7416:     my %bighash;
1.620     albertel 7417:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7418:                             &GDBM_READER(),0640)) {
                   7419:         my $rid=$bighash{'mapalias_'.$symb};
                   7420: 	if ($rid) {
                   7421: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7422: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7423: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7424: 	}
                   7425:         untie %bighash;
                   7426:     }
                   7427:     return $aliassymb;
                   7428: }
                   7429: 
1.12      www      7430: # ----------------------------------------------------------------- Define Role
                   7431: 
                   7432: sub definerole {
                   7433:   if (allowed('mcr','/')) {
                   7434:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7435:     foreach my $role (split(':',$sysrole)) {
                   7436: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7437:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7438:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7439: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7440:                return "refused:s:$crole&$cqual"; 
                   7441:             }
                   7442:         }
1.191     harris41 7443:     }
1.800     albertel 7444:     foreach my $role (split(':',$domrole)) {
                   7445: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7446:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7447:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7448: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7449:                return "refused:d:$crole&$cqual"; 
                   7450:             }
                   7451:         }
1.191     harris41 7452:     }
1.800     albertel 7453:     foreach my $role (split(':',$courole)) {
                   7454: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7455:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7456:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7457: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7458:                return "refused:c:$crole&$cqual"; 
                   7459:             }
                   7460:         }
1.191     harris41 7461:     }
1.620     albertel 7462:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7463:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7464: 	        "rolesdef_$rolename=".
                   7465:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7466:     return reply($command,$env{'user.home'});
1.12      www      7467:   } else {
                   7468:     return 'refused';
                   7469:   }
1.105     harris41 7470: }
                   7471: 
                   7472: # ---------------- Make a metadata query against the network of library servers
                   7473: 
                   7474: sub metadata_query {
1.1172.2.33  raeburn  7475:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7476:     my %rhash;
1.845     albertel 7477:     my %libserv = &all_library();
1.244     matthew  7478:     my @server_list = (defined($server_array) ? @$server_array
                   7479:                                               : keys(%libserv) );
                   7480:     for my $server (@server_list) {
1.1172.2.33  raeburn  7481:         my $domains = '';
                   7482:         if (ref($domains_hash) eq 'HASH') {
                   7483:             $domains = $domains_hash->{$server};    
                   7484:         }
1.118     harris41 7485: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  7486: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7487: 	    $rhash{$server}=$reply;
                   7488: 	}
                   7489: 	else {
                   7490: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  7491: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7492: 			     $server);
                   7493: 	    $rhash{$server}=$reply;
                   7494: 	}
1.112     harris41 7495:     }
1.118     harris41 7496:     return \%rhash;
1.240     www      7497: }
                   7498: 
                   7499: # ----------------------------------------- Send log queries and wait for reply
                   7500: 
                   7501: sub log_query {
                   7502:     my ($uname,$udom,$query,%filters)=@_;
                   7503:     my $uhome=&homeserver($uname,$udom);
                   7504:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7505:     my $uhost=&hostname($uhome);
1.800     albertel 7506:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7507:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7508:                        $uhome);
1.479     albertel 7509:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7510:     return get_query_reply($queryid);
                   7511: }
                   7512: 
1.818     raeburn  7513: # -------------------------- Update MySQL table for portfolio file
                   7514: 
                   7515: sub update_portfolio_table {
1.821     raeburn  7516:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7517:     if ($group ne '') {
                   7518:         $file_name =~s /^\Q$group\E//;
                   7519:     }
1.818     raeburn  7520:     my $homeserver = &homeserver($uname,$udom);
                   7521:     my $queryid=
1.821     raeburn  7522:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7523:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7524:     my $reply = &get_query_reply($queryid);
                   7525:     return $reply;
                   7526: }
                   7527: 
1.899     raeburn  7528: # -------------------------- Update MySQL allusers table
                   7529: 
                   7530: sub update_allusers_table {
                   7531:     my ($uname,$udom,$names) = @_;
                   7532:     my $homeserver = &homeserver($uname,$udom);
                   7533:     my $queryid=
                   7534:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7535:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7536:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7537:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7538:                'generation='.&escape($names->{'generation'}).'%%'.
                   7539:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7540:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7541:     return;
1.899     raeburn  7542: }
                   7543: 
1.508     raeburn  7544: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7545: 
                   7546: sub fetch_enrollment_query {
1.511     raeburn  7547:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7548:     my $homeserver;
1.547     raeburn  7549:     my $maxtries = 1;
1.508     raeburn  7550:     if ($context eq 'automated') {
                   7551:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7552:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7553:     } else {
                   7554:         $homeserver = &homeserver($cnum,$dom);
                   7555:     }
1.838     albertel 7556:     my $host=&hostname($homeserver);
1.506     raeburn  7557:     my $cmd = '';
1.1000    raeburn  7558:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7559:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7560:     }
                   7561:     $cmd =~ s/%%$//;
                   7562:     $cmd = &escape($cmd);
                   7563:     my $query = 'fetchenrollment';
1.620     albertel 7564:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7565:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7566:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7567:         return 'error: '.$queryid;
                   7568:     }
1.506     raeburn  7569:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7570:     my $tries = 1;
                   7571:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7572:         $reply = &get_query_reply($queryid);
                   7573:         $tries ++;
                   7574:     }
1.526     raeburn  7575:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7576:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7577:     } else {
1.901     albertel 7578:         my @responses = split(/:/,$reply);
1.515     raeburn  7579:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7580:             foreach my $line (@responses) {
                   7581:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7582:                 $$replyref{$key} = $value;
                   7583:             }
                   7584:         } else {
1.1117    foxr     7585:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7586:             foreach my $line (@responses) {
                   7587:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7588:                 $$replyref{$key} = $value;
                   7589:                 if ($value > 0) {
1.800     albertel 7590:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7591:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7592:                         my $destname = $pathname.'/'.$filename;
                   7593:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7594:                         if ($xml_classlist =~ /^error/) {
                   7595:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7596:                         } else {
1.506     raeburn  7597:                             if ( open(FILE,">$destname") ) {
                   7598:                                 print FILE &unescape($xml_classlist);
                   7599:                                 close(FILE);
1.526     raeburn  7600:                             } else {
                   7601:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7602:                             }
                   7603:                         }
                   7604:                     }
                   7605:                 }
                   7606:             }
                   7607:         }
                   7608:         return 'ok';
                   7609:     }
                   7610:     return 'error';
                   7611: }
                   7612: 
1.242     www      7613: sub get_query_reply {
                   7614:     my $queryid=shift;
1.1117    foxr     7615:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7616:     my $reply='';
                   7617:     for (1..100) {
                   7618: 	sleep 2;
                   7619:         if (-e $replyfile.'.end') {
1.448     albertel 7620: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7621: 		$reply = join('',<$fh>);
                   7622: 		close($fh);
1.240     www      7623: 	   } else { return 'error: reply_file_error'; }
1.242     www      7624:            return &unescape($reply);
                   7625: 	}
1.240     www      7626:     }
1.242     www      7627:     return 'timeout:'.$queryid;
1.240     www      7628: }
                   7629: 
                   7630: sub courselog_query {
1.241     www      7631: #
                   7632: # possible filters:
                   7633: # url: url or symb
                   7634: # username
                   7635: # domain
                   7636: # action: view, submit, grade
                   7637: # start: timestamp
                   7638: # end: timestamp
                   7639: #
1.240     www      7640:     my (%filters)=@_;
1.620     albertel 7641:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7642:     if ($filters{'url'}) {
                   7643: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7644:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7645:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7646:     }
1.620     albertel 7647:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7648:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7649:     return &log_query($cname,$cdom,'courselog',%filters);
                   7650: }
                   7651: 
                   7652: sub userlog_query {
1.858     raeburn  7653: #
                   7654: # possible filters:
                   7655: # action: log check role
                   7656: # start: timestamp
                   7657: # end: timestamp
                   7658: #
1.240     www      7659:     my ($uname,$udom,%filters)=@_;
                   7660:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7661: }
                   7662: 
1.506     raeburn  7663: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7664: 
                   7665: sub auto_run {
1.508     raeburn  7666:     my ($cnum,$cdom) = @_;
1.876     raeburn  7667:     my $response = 0;
                   7668:     my $settings;
                   7669:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7670:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7671:         $settings = $domconfig{'autoenroll'};
                   7672:         if ($settings->{'run'} eq '1') {
                   7673:             $response = 1;
                   7674:         }
                   7675:     } else {
1.934     raeburn  7676:         my $homeserver;
                   7677:         if (&is_course($cdom,$cnum)) {
                   7678:             $homeserver = &homeserver($cnum,$cdom);
                   7679:         } else {
                   7680:             $homeserver = &domain($cdom,'primary');
                   7681:         }
                   7682:         if ($homeserver ne 'no_host') {
                   7683:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7684:         }
1.876     raeburn  7685:     }
1.506     raeburn  7686:     return $response;
                   7687: }
1.776     albertel 7688: 
1.506     raeburn  7689: sub auto_get_sections {
1.508     raeburn  7690:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7691:     my $homeserver;
                   7692:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7693:         $homeserver = &homeserver($cnum,$cdom);
                   7694:     }
                   7695:     if (!defined($homeserver)) { 
                   7696:         if ($cdom =~ /^$match_domain$/) {
                   7697:             $homeserver = &domain($cdom,'primary');
                   7698:         }
                   7699:     }
                   7700:     my @secs;
                   7701:     if (defined($homeserver)) {
                   7702:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7703:         unless ($response eq 'refused') {
                   7704:             @secs = split(/:/,$response);
                   7705:         }
1.506     raeburn  7706:     }
                   7707:     return @secs;
                   7708: }
1.776     albertel 7709: 
1.506     raeburn  7710: sub auto_new_course {
1.1099    raeburn  7711:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7712:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7713:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7714:     return $response;
                   7715: }
1.776     albertel 7716: 
1.506     raeburn  7717: sub auto_validate_courseID {
1.508     raeburn  7718:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7719:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7720:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7721:     return $response;
                   7722: }
1.776     albertel 7723: 
1.1007    raeburn  7724: sub auto_validate_instcode {
1.1020    raeburn  7725:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7726:     my ($homeserver,$response);
                   7727:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7728:         $homeserver = &homeserver($cnum,$cdom);
                   7729:     }
                   7730:     if (!defined($homeserver)) {
                   7731:         if ($cdom =~ /^$match_domain$/) {
                   7732:             $homeserver = &domain($cdom,'primary');
                   7733:         }
                   7734:     }
1.1065    raeburn  7735:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7736:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7737:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7738:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7739: }
                   7740: 
1.506     raeburn  7741: sub auto_create_password {
1.873     raeburn  7742:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7743:     my ($homeserver,$response);
1.506     raeburn  7744:     my $create_passwd = 0;
                   7745:     my $authchk = '';
1.873     raeburn  7746:     if ($udom =~ /^$match_domain$/) {
                   7747:         $homeserver = &domain($udom,'primary');
                   7748:     }
                   7749:     if ($homeserver eq '') {
                   7750:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7751:             $homeserver = &homeserver($cnum,$cdom);
                   7752:         }
                   7753:     }
                   7754:     if ($homeserver eq '') {
                   7755:         $authchk = 'nodomain';
1.506     raeburn  7756:     } else {
1.873     raeburn  7757:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7758:         if ($response eq 'refused') {
                   7759:             $authchk = 'refused';
                   7760:         } else {
1.901     albertel 7761:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7762:         }
1.506     raeburn  7763:     }
                   7764:     return ($authparam,$create_passwd,$authchk);
                   7765: }
                   7766: 
1.706     raeburn  7767: sub auto_photo_permission {
                   7768:     my ($cnum,$cdom,$students) = @_;
                   7769:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7770:     my ($outcome,$perm_reqd,$conditions) = 
                   7771: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7772:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7773: 	return (undef,undef);
                   7774:     }
1.706     raeburn  7775:     return ($outcome,$perm_reqd,$conditions);
                   7776: }
                   7777: 
                   7778: sub auto_checkphotos {
                   7779:     my ($uname,$udom,$pid) = @_;
                   7780:     my $homeserver = &homeserver($uname,$udom);
                   7781:     my ($result,$resulttype);
                   7782:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7783: 				   &escape($uname).':'.&escape($pid),
                   7784: 				   $homeserver));
1.709     albertel 7785:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7786: 	return (undef,undef);
                   7787:     }
1.706     raeburn  7788:     if ($outcome) {
                   7789:         ($result,$resulttype) = split(/:/,$outcome);
                   7790:     } 
                   7791:     return ($result,$resulttype);
                   7792: }
                   7793: 
                   7794: sub auto_photochoice {
                   7795:     my ($cnum,$cdom) = @_;
                   7796:     my $homeserver = &homeserver($cnum,$cdom);
                   7797:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7798: 						       &escape($cdom),
                   7799: 						       $homeserver)));
1.709     albertel 7800:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7801: 	return (undef,undef);
                   7802:     }
1.706     raeburn  7803:     return ($update,$comment);
                   7804: }
                   7805: 
                   7806: sub auto_photoupdate {
                   7807:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7808:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7809:     my $host=&hostname($homeserver);
1.706     raeburn  7810:     my $cmd = '';
                   7811:     my $maxtries = 1;
1.800     albertel 7812:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7813:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7814:     }
                   7815:     $cmd =~ s/%%$//;
                   7816:     $cmd = &escape($cmd);
                   7817:     my $query = 'institutionalphotos';
                   7818:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7819:     unless ($queryid=~/^\Q$host\E\_/) {
                   7820:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7821:         return 'error: '.$queryid;
                   7822:     }
                   7823:     my $reply = &get_query_reply($queryid);
                   7824:     my $tries = 1;
                   7825:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7826:         $reply = &get_query_reply($queryid);
                   7827:         $tries ++;
                   7828:     }
                   7829:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7830:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7831:     } else {
                   7832:         my @responses = split(/:/,$reply);
                   7833:         my $outcome = shift(@responses); 
                   7834:         foreach my $item (@responses) {
                   7835:             my ($key,$value) = split(/=/,$item);
                   7836:             $$photo{$key} = $value;
                   7837:         }
                   7838:         return $outcome;
                   7839:     }
                   7840:     return 'error';
                   7841: }
                   7842: 
1.521     raeburn  7843: sub auto_instcode_format {
1.793     albertel 7844:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7845: 	$cat_order) = @_;
1.521     raeburn  7846:     my $courses = '';
1.772     raeburn  7847:     my @homeservers;
1.521     raeburn  7848:     if ($caller eq 'global') {
1.841     albertel 7849: 	my %servers = &get_servers($codedom,'library');
                   7850: 	foreach my $tryserver (keys(%servers)) {
                   7851: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7852: 		push(@homeservers,$tryserver);
                   7853: 	    }
1.584     raeburn  7854:         }
1.1022    raeburn  7855:     } elsif ($caller eq 'requests') {
                   7856:         if ($codedom =~ /^$match_domain$/) {
                   7857:             my $chome = &domain($codedom,'primary');
                   7858:             unless ($chome eq 'no_host') {
                   7859:                 push(@homeservers,$chome);
                   7860:             }
                   7861:         }
1.521     raeburn  7862:     } else {
1.772     raeburn  7863:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7864:     }
1.793     albertel 7865:     foreach my $code (keys(%{$instcodes})) {
                   7866:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7867:     }
                   7868:     chop($courses);
1.772     raeburn  7869:     my $ok_response = 0;
                   7870:     my $response;
                   7871:     while (@homeservers > 0 && $ok_response == 0) {
                   7872:         my $server = shift(@homeservers); 
                   7873:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7874:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7875:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7876: 		split(/:/,$response);
1.772     raeburn  7877:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7878:             push(@{$codetitles},&str2array($codetitles_str));
                   7879:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7880:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7881:             $ok_response = 1;
                   7882:         }
                   7883:     }
                   7884:     if ($ok_response) {
1.521     raeburn  7885:         return 'ok';
1.772     raeburn  7886:     } else {
                   7887:         return $response;
1.521     raeburn  7888:     }
                   7889: }
                   7890: 
1.792     raeburn  7891: sub auto_instcode_defaults {
                   7892:     my ($domain,$returnhash,$code_order) = @_;
                   7893:     my @homeservers;
1.841     albertel 7894: 
                   7895:     my %servers = &get_servers($domain,'library');
                   7896:     foreach my $tryserver (keys(%servers)) {
                   7897: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7898: 	    push(@homeservers,$tryserver);
                   7899: 	}
1.792     raeburn  7900:     }
1.841     albertel 7901: 
1.792     raeburn  7902:     my $response;
1.841     albertel 7903:     foreach my $server (@homeservers) {
1.792     raeburn  7904:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7905:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7906: 	
                   7907: 	foreach my $pair (split(/\&/,$response)) {
                   7908: 	    my ($name,$value)=split(/\=/,$pair);
                   7909: 	    if ($name eq 'code_order') {
                   7910: 		@{$code_order} = split(/\&/,&unescape($value));
                   7911: 	    } else {
                   7912: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7913: 	    }
                   7914: 	}
                   7915: 	return 'ok';
1.792     raeburn  7916:     }
1.841     albertel 7917: 
                   7918:     return $response;
1.1003    raeburn  7919: }
                   7920: 
                   7921: sub auto_possible_instcodes {
1.1007    raeburn  7922:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7923:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7924:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7925:         return;
                   7926:     }
1.1003    raeburn  7927:     my (@homeservers,$uhome);
                   7928:     if (defined(&domain($domain,'primary'))) {
                   7929:         $uhome=&domain($domain,'primary');
                   7930:         push(@homeservers,&domain($domain,'primary'));
                   7931:     } else {
                   7932:         my %servers = &get_servers($domain,'library');
                   7933:         foreach my $tryserver (keys(%servers)) {
                   7934:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7935:                 push(@homeservers,$tryserver);
                   7936:             }
                   7937:         }
                   7938:     }
                   7939:     my $response;
                   7940:     foreach my $server (@homeservers) {
                   7941:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7942:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7943:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7944:             split(':',$response);
                   7945:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7946:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7947:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7948:             my ($name,$value)=split('=',$item);
                   7949:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7950:         }
                   7951:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7952:             my ($name,$value)=split('=',$item);
                   7953:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7954:         }
                   7955:         return 'ok';
                   7956:     }
                   7957:     return $response;
                   7958: }
1.792     raeburn  7959: 
1.1010    raeburn  7960: sub auto_courserequest_checks {
                   7961:     my ($dom) = @_;
1.1020    raeburn  7962:     my ($homeserver,%validations);
                   7963:     if ($dom =~ /^$match_domain$/) {
                   7964:         $homeserver = &domain($dom,'primary');
                   7965:     }
                   7966:     unless ($homeserver eq 'no_host') {
                   7967:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7968:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7969:             my @items = split(/&/,$response);
                   7970:             foreach my $item (@items) {
                   7971:                 my ($key,$value) = split('=',$item);
                   7972:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7973:             }
                   7974:         }
                   7975:     }
1.1010    raeburn  7976:     return %validations; 
                   7977: }
                   7978: 
1.1020    raeburn  7979: sub auto_courserequest_validation {
1.1172.2.43  raeburn  7980:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  7981:     my ($homeserver,$response);
                   7982:     if ($dom =~ /^$match_domain$/) {
                   7983:         $homeserver = &domain($dom,'primary');
                   7984:     }
1.1172.2.43  raeburn  7985:     unless ($homeserver eq 'no_host') {
                   7986:         my $customdata;
                   7987:         if (ref($custominfo) eq 'HASH') {
                   7988:             $customdata = &freeze_escape($custominfo);
                   7989:         }
1.1020    raeburn  7990:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7991:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  7992:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   7993:                                     $customdata,$homeserver));
1.1020    raeburn  7994:     }
                   7995:     return $response;
                   7996: }
                   7997: 
1.777     albertel 7998: sub auto_validate_class_sec {
1.918     raeburn  7999:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8000:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8001:     my $ownerlist;
                   8002:     if (ref($owners) eq 'ARRAY') {
                   8003:         $ownerlist = join(',',@{$owners});
                   8004:     } else {
                   8005:         $ownerlist = $owners;
                   8006:     }
1.773     raeburn  8007:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8008:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8009:     return $response;
                   8010: }
                   8011: 
1.1172.2.38  raeburn  8012: sub auto_crsreq_update {
                   8013:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8014:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8015:     my ($homeserver,%crsreqresponse);
                   8016:     if ($cdom =~ /^$match_domain$/) {
                   8017:         $homeserver = &domain($cdom,'primary');
                   8018:     }
                   8019:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8020:         my $info;
                   8021:         if (ref($inbound) eq 'HASH') {
                   8022:             $info = &freeze_escape($inbound);
                   8023:         }
                   8024:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8025:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8026:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8027:                             &escape($title).':'.&escape($code).':'.
                   8028:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8029:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8030:             my @items = split(/&/,$response);
                   8031:             foreach my $item (@items) {
                   8032:                 my ($key,$value) = split('=',$item);
                   8033:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8034:             }
                   8035:         }
                   8036:     }
                   8037:     return \%crsreqresponse;
                   8038: }
                   8039: 
1.679     raeburn  8040: # ------------------------------------------------------- Course Group routines
                   8041: 
                   8042: sub get_coursegroups {
1.809     raeburn  8043:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8044:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8045: }
                   8046: 
1.679     raeburn  8047: sub modify_coursegroup {
                   8048:     my ($cdom,$cnum,$groupsettings) = @_;
                   8049:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8050: }
                   8051: 
1.809     raeburn  8052: sub toggle_coursegroup_status {
                   8053:     my ($cdom,$cnum,$group,$action) = @_;
                   8054:     my ($from_namespace,$to_namespace);
                   8055:     if ($action eq 'delete') {
                   8056:         $from_namespace = 'coursegroups';
                   8057:         $to_namespace = 'deleted_groups';
                   8058:     } else {
                   8059:         $from_namespace = 'deleted_groups';
                   8060:         $to_namespace = 'coursegroups';
                   8061:     }
                   8062:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8063:     if (my $tmp = &error(%curr_group)) {
                   8064:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8065:         return ('read error',$tmp);
                   8066:     } else {
                   8067:         my %savedsettings = %curr_group; 
1.809     raeburn  8068:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8069:         my $deloutcome;
                   8070:         if ($result eq 'ok') {
1.809     raeburn  8071:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8072:         } else {
                   8073:             return ('write error',$result);
                   8074:         }
                   8075:         if ($deloutcome eq 'ok') {
                   8076:             return 'ok';
                   8077:         } else {
                   8078:             return ('delete error',$deloutcome);
                   8079:         }
                   8080:     }
                   8081: }
                   8082: 
1.679     raeburn  8083: sub modify_group_roles {
1.957     raeburn  8084:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8085:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8086:     my $role = 'gr/'.&escape($userprivs);
                   8087:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8088:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8089:     if ($result eq 'ok') {
                   8090:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8091:     }
1.679     raeburn  8092:     return $result;
                   8093: }
                   8094: 
                   8095: sub modify_coursegroup_membership {
                   8096:     my ($cdom,$cnum,$membership) = @_;
                   8097:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8098:     return $result;
                   8099: }
                   8100: 
1.682     raeburn  8101: sub get_active_groups {
                   8102:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8103:     my $now = time;
                   8104:     my %groups = ();
                   8105:     foreach my $key (keys(%env)) {
1.811     albertel 8106:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8107:             my ($start,$end) = split(/\./,$env{$key});
                   8108:             if (($end!=0) && ($end<$now)) { next; }
                   8109:             if (($start!=0) && ($start>$now)) { next; }
                   8110:             if ($1 eq $cdom && $2 eq $cnum) {
                   8111:                 $groups{$3} = $env{$key} ;
                   8112:             }
                   8113:         }
                   8114:     }
                   8115:     return %groups;
                   8116: }
                   8117: 
1.683     raeburn  8118: sub get_group_membership {
                   8119:     my ($cdom,$cnum,$group) = @_;
                   8120:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8121: }
                   8122: 
                   8123: sub get_users_groups {
                   8124:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8125:     my @usersgroups;
1.683     raeburn  8126:     my $cachetime=1800;
                   8127: 
                   8128:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8129:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8130:     if (defined($cached)) {
1.734     albertel 8131:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8132:     } else {  
                   8133:         $grouplist = '';
1.816     raeburn  8134:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8135:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8136:         my $access_end = $env{'course.'.$courseid.
                   8137:                               '.default_enrollment_end_date'};
                   8138:         my $now = time;
                   8139:         foreach my $key (keys(%roleshash)) {
                   8140:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8141:                 my $group = $1;
                   8142:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8143:                     my $start = $2;
                   8144:                     my $end = $1;
                   8145:                     if ($start == -1) { next; } # deleted from group
                   8146:                     if (($start!=0) && ($start>$now)) { next; }
                   8147:                     if (($end!=0) && ($end<$now)) {
                   8148:                         if ($access_end && $access_end < $now) {
                   8149:                             if ($access_end - $end < 86400) {
                   8150:                                 push(@usersgroups,$group);
1.733     raeburn  8151:                             }
                   8152:                         }
1.817     raeburn  8153:                         next;
1.733     raeburn  8154:                     }
1.817     raeburn  8155:                     push(@usersgroups,$group);
1.683     raeburn  8156:                 }
                   8157:             }
                   8158:         }
1.817     raeburn  8159:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8160:         $grouplist = join(':',@usersgroups);
                   8161:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8162:     }
1.733     raeburn  8163:     return @usersgroups;
1.683     raeburn  8164: }
                   8165: 
                   8166: sub devalidate_getgroups_cache {
                   8167:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8168:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8169: 
1.683     raeburn  8170:     my $hashid="$udom:$uname:$courseid";
                   8171:     &devalidate_cache_new('getgroups',$hashid);
                   8172: }
                   8173: 
1.12      www      8174: # ------------------------------------------------------------------ Plain Text
                   8175: 
                   8176: sub plaintext {
1.988     raeburn  8177:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8178:     if ($short =~ m{^cr/}) {
1.758     albertel 8179: 	return (split('/',$short))[-1];
                   8180:     }
1.742     raeburn  8181:     if (!defined($cid)) {
                   8182:         $cid = $env{'request.course.id'};
                   8183:     }
                   8184:     my %rolenames = (
1.1008    raeburn  8185:                       Course    => 'std',
                   8186:                       Community => 'alt1',
1.742     raeburn  8187:                     );
1.1037    raeburn  8188:     if ($cid ne '') {
                   8189:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8190:             unless ($forcedefault) {
                   8191:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8192:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8193:                 return &Apache::lonlocal::mt($roletext);
                   8194:             }
                   8195:         }
                   8196:     }
                   8197:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8198:         (defined($rolenames{$type})) && 
                   8199:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8200:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8201:     } elsif ($cid ne '') {
                   8202:         my $crstype = $env{'course.'.$cid.'.type'};
                   8203:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8204:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8205:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8206:         }
1.742     raeburn  8207:     }
1.1037    raeburn  8208:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8209: }
                   8210: 
                   8211: # ----------------------------------------------------------------- Assign Role
                   8212: 
                   8213: sub assignrole {
1.957     raeburn  8214:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8215:         $context)=@_;
1.21      www      8216:     my $mrole;
                   8217:     if ($role =~ /^cr\//) {
1.393     www      8218:         my $cwosec=$url;
1.811     albertel 8219:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8220: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8221:            my $refused = 1;
                   8222:            if ($context eq 'requestcourses') {
                   8223:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8224:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8225:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8226:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8227:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8228:                            if ($crsenv{'internal.courseowner'} eq
                   8229:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8230:                                $refused = '';
                   8231:                            }
                   8232:                        }
                   8233:                    }
                   8234:                }
                   8235:            }
                   8236:            if ($refused) {
                   8237:                &logthis('Refused custom assignrole: '.
                   8238:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8239:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8240:                return 'refused';
                   8241:            }
1.104     www      8242:         }
1.21      www      8243:         $mrole='cr';
1.678     raeburn  8244:     } elsif ($role =~ /^gr\//) {
                   8245:         my $cwogrp=$url;
1.811     albertel 8246:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8247:         unless (&allowed('mdg',$cwogrp)) {
                   8248:             &logthis('Refused group assignrole: '.
                   8249:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8250:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8251:             return 'refused';
                   8252:         }
                   8253:         $mrole='gr';
1.21      www      8254:     } else {
1.82      www      8255:         my $cwosec=$url;
1.811     albertel 8256:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8257:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8258:             my $refused;
                   8259:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8260:                 if (!(&allowed('c'.$role,$url))) {
                   8261:                     $refused = 1;
                   8262:                 }
                   8263:             } else {
                   8264:                 $refused = 1;
                   8265:             }
1.947     raeburn  8266:             if ($refused) {
1.1045    raeburn  8267:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8268:                 if (!$selfenroll && $context eq 'course') {
                   8269:                     my %crsenv;
                   8270:                     if ($role eq 'cc' || $role eq 'co') {
                   8271:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8272:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8273:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8274:                                 if ($crsenv{'internal.courseowner'} eq 
                   8275:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8276:                                     $refused = '';
                   8277:                                 }
                   8278:                             }
                   8279:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8280:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8281:                                 if ($crsenv{'internal.courseowner'} eq 
                   8282:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8283:                                     $refused = '';
                   8284:                                 }
                   8285:                             }
                   8286:                         }
                   8287:                     }
                   8288:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8289:                     $refused = '';
1.1017    raeburn  8290:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8291:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8292:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8293:                         my $wrongcc;
                   8294:                         if ($cnum =~ /^$match_community$/) {
                   8295:                             $wrongcc = 1 if ($role eq 'cc');
                   8296:                         } else {
                   8297:                             $wrongcc = 1 if ($role eq 'co');
                   8298:                         }
                   8299:                         unless ($wrongcc) {
                   8300:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8301:                             if ($crsenv{'internal.courseowner'} eq 
                   8302:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8303:                                 $refused = '';
                   8304:                             }
1.1017    raeburn  8305:                         }
                   8306:                     }
1.1172.2.9  raeburn  8307:                 } elsif ($context eq 'requestauthor') {
                   8308:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8309:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8310:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8311:                             $refused = '';
                   8312:                         } else {
                   8313:                             my %domdefaults = &get_domain_defaults($udom);
                   8314:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8315:                                 my $checkbystatus;
                   8316:                                 if ($env{'user.adv'}) {
                   8317:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8318:                                     if ($disposition eq 'automatic') {
                   8319:                                         $refused = '';
                   8320:                                     } elsif ($disposition eq '') {
                   8321:                                         $checkbystatus = 1;
                   8322:                                     }
                   8323:                                 } else {
                   8324:                                     $checkbystatus = 1;
                   8325:                                 }
                   8326:                                 if ($checkbystatus) {
                   8327:                                     if ($env{'environment.inststatus'}) {
                   8328:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8329:                                         foreach my $type (@inststatuses) {
                   8330:                                             if (($type ne '') &&
                   8331:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8332:                                                 $refused = '';
                   8333:                                             }
                   8334:                                         }
                   8335:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8336:                                         $refused = '';
                   8337:                                     }
                   8338:                                 }
                   8339:                             }
                   8340:                         }
                   8341:                     }
1.1017    raeburn  8342:                 }
                   8343:                 if ($refused) {
1.947     raeburn  8344:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8345:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8346: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8347:                     return 'refused';
                   8348:                 }
1.932     raeburn  8349:             }
1.1131    raeburn  8350:         } elsif ($role eq 'au') {
                   8351:             if ($url ne '/'.$udom.'/') {
                   8352:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8353:                          ' to assign author role for '.$uname.':'.$udom.
                   8354:                          ' in domain: '.$url.' refused (wrong domain).');
                   8355:                 return 'refused';
                   8356:             }
1.104     www      8357:         }
1.21      www      8358:         $mrole=$role;
                   8359:     }
1.620     albertel 8360:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8361:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8362:     if ($end) { $command.='_'.$end; }
1.21      www      8363:     if ($start) {
                   8364: 	if ($end) { 
1.81      www      8365:            $command.='_'.$start; 
1.21      www      8366:         } else {
1.81      www      8367:            $command.='_0_'.$start;
1.21      www      8368:         }
                   8369:     }
1.739     raeburn  8370:     my $origstart = $start;
                   8371:     my $origend = $end;
1.957     raeburn  8372:     my $delflag;
1.357     www      8373: # actually delete
                   8374:     if ($deleteflag) {
1.373     www      8375: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8376: # modify command to delete the role
1.620     albertel 8377:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8378:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8379: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8380: # set start and finish to negative values for userrolelog
                   8381:            $start=-1;
                   8382:            $end=-1;
1.957     raeburn  8383:            $delflag = 1;
1.357     www      8384:         }
                   8385:     }
                   8386: # send command
1.349     www      8387:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8388: # log new user role if status is ok
1.349     www      8389:     if ($answer eq 'ok') {
1.663     raeburn  8390: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8391:         if (($role eq 'cc') || ($role eq 'in') ||
                   8392:             ($role eq 'ep') || ($role eq 'ad') ||
                   8393:             ($role eq 'ta') || ($role eq 'st') ||
                   8394:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8395:             ($role eq 'co')) {
1.1172.2.13  raeburn  8396: # for course roles, perform group memberships changes triggered by role change.
                   8397:             unless ($role =~ /^gr/) {
                   8398:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8399:                                                  $origstart,$selfenroll,$context);
                   8400:             }
1.1172.2.9  raeburn  8401:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8402:                            $selfenroll,$context);
                   8403:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8404:                  ($role eq 'au') || ($role eq 'dc')) {
                   8405:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8406:                            $context);
                   8407:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8408:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8409:                              $context);
                   8410:         }
1.1053    raeburn  8411:         if ($role eq 'cc') {
                   8412:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8413:         }
1.349     www      8414:     }
                   8415:     return $answer;
1.169     harris41 8416: }
                   8417: 
1.1053    raeburn  8418: sub autoupdate_coowners {
                   8419:     my ($url,$end,$start,$uname,$udom) = @_;
                   8420:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8421:     if (($cdom ne '') && ($cnum ne '')) {
                   8422:         my $now = time;
                   8423:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8424:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8425:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8426:             my $instcode = $coursehash{'internal.coursecode'};
                   8427:             if ($instcode ne '') {
1.1056    raeburn  8428:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8429:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8430:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8431:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8432:                         if ($result eq 'valid') {
                   8433:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8434:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8435:                                     push(@newcoowners,$coowner);
                   8436:                                 }
                   8437:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8438:                                     push(@newcoowners,$uname.':'.$udom);
                   8439:                                 }
                   8440:                                 @newcoowners = sort(@newcoowners);
                   8441:                             } else {
                   8442:                                 push(@newcoowners,$uname.':'.$udom);
                   8443:                             }
                   8444:                         } else {
                   8445:                             if ($coursehash{'internal.co-owners'}) {
                   8446:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8447:                                     unless ($coowner eq $uname.':'.$udom) {
                   8448:                                         push(@newcoowners,$coowner);
                   8449:                                     }
                   8450:                                 }
                   8451:                                 unless (@newcoowners > 0) {
                   8452:                                     $delcoowners = 1;
                   8453:                                     $coowners = '';
                   8454:                                 }
                   8455:                             }
                   8456:                         }
                   8457:                         if (@newcoowners || $delcoowners) {
                   8458:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8459:                                             $delcoowners,@newcoowners);
                   8460:                         }
                   8461:                     }
                   8462:                 }
                   8463:             }
                   8464:         }
                   8465:     }
                   8466: }
                   8467: 
                   8468: sub store_coowners {
                   8469:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8470:     my $cid = $cdom.'_'.$cnum;
                   8471:     my ($coowners,$delresult,$putresult);
                   8472:     if (@newcoowners) {
                   8473:         $coowners = join(',',@newcoowners);
                   8474:         my %coownershash = (
                   8475:                             'internal.co-owners' => $coowners,
                   8476:                            );
                   8477:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8478:         if ($putresult eq 'ok') {
                   8479:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8480:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8481:             }
                   8482:         }
                   8483:     }
                   8484:     if ($delcoowners) {
                   8485:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8486:         if ($delresult eq 'ok') {
                   8487:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8488:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8489:             }
                   8490:         }
                   8491:     }
                   8492:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8493:         my %crsinfo =
                   8494:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8495:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8496:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8497:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8498:         }
                   8499:     }
                   8500: }
                   8501: 
1.169     harris41 8502: # -------------------------------------------------- Modify user authentication
1.197     www      8503: # Overrides without validation
                   8504: 
1.169     harris41 8505: sub modifyuserauth {
                   8506:     my ($udom,$uname,$umode,$upass)=@_;
                   8507:     my $uhome=&homeserver($uname,$udom);
1.197     www      8508:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8509:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8510:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8511:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8512:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8513: 		     &escape($upass),$uhome);
1.620     albertel 8514:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8515:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8516:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8517:     &log($udom,,$uname,$uhome,
1.620     albertel 8518:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8519:                                      $env{'user.name'}.', '.$umode.
1.197     www      8520:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8521:     unless ($reply eq 'ok') {
1.197     www      8522:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8523: 	return 'error: '.$reply;
                   8524:     }   
1.170     harris41 8525:     return 'ok';
1.80      www      8526: }
                   8527: 
1.81      www      8528: # --------------------------------------------------------------- Modify a user
1.80      www      8529: 
1.81      www      8530: sub modifyuser {
1.206     matthew  8531:     my ($udom,    $uname, $uid,
                   8532:         $umode,   $upass, $first,
                   8533:         $middle,  $last,  $gene,
1.1058    raeburn  8534:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8535:     $udom= &LONCAPA::clean_domain($udom);
                   8536:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8537:     my $showcandelete = 'none';
                   8538:     if (ref($candelete) eq 'ARRAY') {
                   8539:         if (@{$candelete} > 0) {
                   8540:             $showcandelete = join(', ',@{$candelete});
                   8541:         }
                   8542:     }
1.81      www      8543:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8544:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8545: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8546:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8547:                                      ' desiredhome not specified'). 
1.620     albertel 8548:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8549:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8550:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8551:     my $newuser;
                   8552:     if ($uhome eq 'no_host') {
                   8553:         $newuser = 1;
                   8554:     }
1.80      www      8555: # ----------------------------------------------------------------- Create User
1.406     albertel 8556:     if (($uhome eq 'no_host') && 
                   8557: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8558:         my $unhome='';
1.844     albertel 8559:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8560:             $unhome = $desiredhome;
1.620     albertel 8561: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8562: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8563:         } else { # load balancing routine for determining $unhome
1.81      www      8564:             my $loadm=10000000;
1.841     albertel 8565: 	    my %servers = &get_servers($udom,'library');
                   8566: 	    foreach my $tryserver (keys(%servers)) {
                   8567: 		my $answer=reply('load',$tryserver);
                   8568: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8569: 		    $loadm=$answer;
                   8570: 		    $unhome=$tryserver;
                   8571: 		}
1.80      www      8572: 	    }
                   8573:         }
                   8574:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8575: 	    return 'error: unable to find a home server for '.$uname.
                   8576:                    ' in domain '.$udom;
1.80      www      8577:         }
                   8578:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8579:                          &escape($upass),$unhome);
                   8580: 	unless ($reply eq 'ok') {
                   8581:             return 'error: '.$reply;
                   8582:         }   
1.230     stredwic 8583:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8584:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8585: 	    return 'error: unable verify users home machine.';
1.80      www      8586:         }
1.209     matthew  8587:     }   # End of creation of new user
1.80      www      8588: # ---------------------------------------------------------------------- Add ID
                   8589:     if ($uid) {
                   8590:        $uid=~tr/A-Z/a-z/;
                   8591:        my %uidhash=&idrget($udom,$uname);
1.196     www      8592:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8593:          && (!$forceid)) {
1.80      www      8594: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8595: 	      return 'error: user id "'.$uid.'" does not match '.
                   8596:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8597:           }
                   8598:        } else {
                   8599: 	  &idput($udom,($uname => $uid));
                   8600:        }
                   8601:     }
                   8602: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8603:     my @tmp=&get('environment',
1.899     raeburn  8604: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8605:                     'permanentemail','inststatus'],
1.134     albertel 8606: 		   $udom,$uname);
1.1075    raeburn  8607:     my (%names,%oldnames);
1.313     matthew  8608:     if ($tmp[0] =~ m/^error:.*/) { 
                   8609:         %names=(); 
                   8610:     } else {
                   8611:         %names = @tmp;
1.1075    raeburn  8612:         %oldnames = %names;
1.313     matthew  8613:     }
1.388     www      8614: #
1.1058    raeburn  8615: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8616: # of users did not contain them), do not overwrite existing values
                   8617: # unless field is in $candelete array ref.  
                   8618: #
                   8619: 
                   8620:     my @fields = ('firstname','middlename','lastname','generation',
                   8621:                   'permanentemail','id');
                   8622:     my %newvalues;
                   8623:     if (ref($candelete) eq 'ARRAY') {
                   8624:         foreach my $field (@fields) {
                   8625:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8626:                 if ($field eq 'firstname') {
                   8627:                     $names{$field} = $first;
                   8628:                 } elsif ($field eq 'middlename') {
                   8629:                     $names{$field} = $middle;
                   8630:                 } elsif ($field eq 'lastname') {
                   8631:                     $names{$field} = $last;
                   8632:                 } elsif ($field eq 'generation') { 
                   8633:                     $names{$field} = $gene;
                   8634:                 } elsif ($field eq 'permanentemail') {
                   8635:                     $names{$field} = $email;
                   8636:                 } elsif ($field eq 'id') {
                   8637:                     $names{$field}  = $uid;
                   8638:                 }
                   8639:             }
                   8640:         }
                   8641:     }
1.388     www      8642:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8643:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8644:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8645:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8646:     if ($email) {
                   8647:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8648:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8649:     }
1.899     raeburn  8650:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8651:     if (defined($inststatus)) {
                   8652:         $names{'inststatus'} = '';
                   8653:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8654:         if (ref($usertypes) eq 'HASH') {
                   8655:             my @okstatuses; 
                   8656:             foreach my $item (split(/:/,$inststatus)) {
                   8657:                 if (defined($usertypes->{$item})) {
                   8658:                     push(@okstatuses,$item);  
                   8659:                 }
                   8660:             }
                   8661:             if (@okstatuses) {
                   8662:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8663:             }
                   8664:         }
                   8665:     }
1.1075    raeburn  8666:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8667:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8668:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8669:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8670:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8671:     } else {
                   8672:         $logmsg .= ' during self creation';
                   8673:     }
1.1075    raeburn  8674:     my $changed;
                   8675:     if ($newuser) {
                   8676:         $changed = 1;
                   8677:     } else {
                   8678:         foreach my $field (@fields) {
                   8679:             if ($names{$field} ne $oldnames{$field}) {
                   8680:                 $changed = 1;
                   8681:                 last;
                   8682:             }
                   8683:         }
                   8684:     }
                   8685:     unless ($changed) {
                   8686:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8687:         &logthis($logmsg);
                   8688:         return 'ok';
                   8689:     }
                   8690:     my $reply = &put('environment', \%names, $udom,$uname);
                   8691:     if ($reply ne 'ok') { 
                   8692:         return 'error: '.$reply;
                   8693:     }
1.1087    raeburn  8694:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8695:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8696:     }
1.1075    raeburn  8697:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8698:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8699:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8700:     &logthis($logmsg);
1.134     albertel 8701:     return 'ok';
1.80      www      8702: }
                   8703: 
1.81      www      8704: # -------------------------------------------------------------- Modify student
1.80      www      8705: 
1.81      www      8706: sub modifystudent {
                   8707:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8708:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8709:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8710:     if (!$cid) {
1.620     albertel 8711: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8712: 	    return 'not_in_class';
                   8713: 	}
1.80      www      8714:     }
                   8715: # --------------------------------------------------------------- Make the user
1.81      www      8716:     my $reply=&modifyuser
1.209     matthew  8717: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8718:          $desiredhome,$email,$inststatus);
1.80      www      8719:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8720:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  8721:     # student's environment
1.297     matthew  8722:     $uid = undef if (!$forceid);
1.455     albertel 8723:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8724: 					$gene,$usec,$end,$start,$type,$locktype,
                   8725:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8726:     return $reply;
                   8727: }
                   8728: 
                   8729: sub modify_student_enrollment {
1.1172.2.23  raeburn  8730:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8731:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8732:     my ($cdom,$cnum,$chome);
                   8733:     if (!$cid) {
1.620     albertel 8734: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8735: 	    return 'not_in_class';
                   8736: 	}
1.620     albertel 8737: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8738: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8739:     } else {
                   8740: 	($cdom,$cnum)=split(/_/,$cid);
                   8741:     }
1.620     albertel 8742:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8743:     if (!$chome) {
1.457     raeburn  8744: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8745:     }
1.455     albertel 8746:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8747:     # Make sure the user exists
1.81      www      8748:     my $uhome=&homeserver($uname,$udom);
                   8749:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8750: 	return 'error: no such user';
                   8751:     }
1.297     matthew  8752:     # Get student data if we were not given enough information
                   8753:     if (!defined($first)  || $first  eq '' || 
                   8754:         !defined($last)   || $last   eq '' || 
                   8755:         !defined($uid)    || $uid    eq '' || 
                   8756:         !defined($middle) || $middle eq '' || 
                   8757:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8758:         # They did not supply us with enough data to enroll the student, so
                   8759:         # we need to pick up more information.
1.297     matthew  8760:         my %tmp = &get('environment',
1.294     matthew  8761:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8762:                        ,$udom,$uname);
                   8763: 
1.800     albertel 8764:         #foreach my $key (keys(%tmp)) {
                   8765:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8766:         #}
1.294     matthew  8767:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8768:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8769:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8770:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8771:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8772:     }
1.556     albertel 8773:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8774:     my $user = "$uname:$udom";
                   8775:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8776:     my $reply=cput('classlist',
1.1148    raeburn  8777: 		   {$user => 
1.1172.2.19  raeburn  8778: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8779: 		   $cdom,$cnum);
1.1148    raeburn  8780:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8781:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8782:     } else { 
1.81      www      8783: 	return 'error: '.$reply;
                   8784:     }
1.297     matthew  8785:     # Add student role to user
1.83      www      8786:     my $uurl='/'.$cid;
1.81      www      8787:     $uurl=~s/\_/\//g;
                   8788:     if ($usec) {
                   8789: 	$uurl.='/'.$usec;
                   8790:     }
1.1148    raeburn  8791:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8792:                              $selfenroll,$context);
                   8793:     if ($result ne 'ok') {
                   8794:         if ($old_entry{$user} ne '') {
                   8795:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8796:         } else {
                   8797:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8798:         }
                   8799:     }
                   8800:     return $result; 
1.21      www      8801: }
                   8802: 
1.556     albertel 8803: sub format_name {
                   8804:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8805:     my $name;
                   8806:     if ($first ne 'lastname') {
                   8807: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8808:     } else {
                   8809: 	if ($lastname=~/\S/) {
                   8810: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8811: 	    $name=~s/\s+,/,/;
                   8812: 	} else {
                   8813: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8814: 	}
                   8815:     }
                   8816:     $name=~s/^\s+//;
                   8817:     $name=~s/\s+$//;
                   8818:     $name=~s/\s+/ /g;
                   8819:     return $name;
                   8820: }
                   8821: 
1.84      www      8822: # ------------------------------------------------- Write to course preferences
                   8823: 
                   8824: sub writecoursepref {
                   8825:     my ($courseid,%prefs)=@_;
                   8826:     $courseid=~s/^\///;
                   8827:     $courseid=~s/\_/\//g;
                   8828:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8829:     my $chome=homeserver($cnum,$cdomain);
                   8830:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8831: 	return 'error: no such course';
                   8832:     }
                   8833:     my $cstring='';
1.800     albertel 8834:     foreach my $pref (keys(%prefs)) {
                   8835: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8836:     }
1.84      www      8837:     $cstring=~s/\&$//;
                   8838:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8839: }
                   8840: 
                   8841: # ---------------------------------------------------------- Make/modify course
                   8842: 
                   8843: sub createcourse {
1.741     raeburn  8844:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8845:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8846:     $url=&declutter($url);
                   8847:     my $cid='';
1.1028    raeburn  8848:     if ($context eq 'requestcourses') {
                   8849:         my $can_create = 0;
                   8850:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8851:         if ($udom eq $ownerdom) {
                   8852:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8853:                                   $context)) {
                   8854:                 $can_create = 1;
                   8855:             }
                   8856:         } else {
                   8857:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8858:                                            $category);
                   8859:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8860:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8861:                 if (@curr > 0) {
                   8862:                     my @options = qw(approval validate autolimit);
                   8863:                     my $optregex = join('|',@options);
                   8864:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8865:                         $can_create = 1;
                   8866:                     }
                   8867:                 }
                   8868:             }
                   8869:         }
                   8870:         if ($can_create) {
                   8871:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8872:                 unless (&allowed('ccc',$udom)) {
                   8873:                     return 'refused'; 
                   8874:                 }
1.1017    raeburn  8875:             }
                   8876:         } else {
                   8877:             return 'refused';
                   8878:         }
1.1028    raeburn  8879:     } elsif (!&allowed('ccc',$udom)) {
                   8880:         return 'refused';
1.84      www      8881:     }
1.1011    raeburn  8882: # --------------------------------------------------------------- Get Unique ID
                   8883:     my $uname;
                   8884:     if ($cnum =~ /^$match_courseid$/) {
                   8885:         my $chome=&homeserver($cnum,$udom,'true');
                   8886:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8887:             $uname = $cnum;
                   8888:         } else {
1.1038    raeburn  8889:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8890:         }
                   8891:     } else {
1.1038    raeburn  8892:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8893:     }
                   8894:     return $uname if ($uname =~ /^error/);
                   8895: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8896:     if (!defined($course_server)) {
                   8897:         if (defined(&domain($udom,'primary'))) {
                   8898:             $course_server = &domain($udom,'primary');
                   8899:         } else {
                   8900:             $course_server = $env{'user.home'}; 
                   8901:         }
                   8902:     }
                   8903:     my %host_servers =
                   8904:         &Apache::lonnet::get_servers($udom,'library');
                   8905:     unless ($host_servers{$course_server}) {
                   8906:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8907:     }
1.84      www      8908: # ------------------------------------------------------------- Make the course
                   8909:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8910:                       $course_server);
1.84      www      8911:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8912:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8913:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8914: 	return 'error: no such course';
                   8915:     }
1.271     www      8916: # ----------------------------------------------------------------- Course made
1.516     raeburn  8917: # log existence
1.1029    raeburn  8918:     my $now = time;
1.918     raeburn  8919:     my $newcourse = {
                   8920:                     $udom.'_'.$uname => {
1.921     raeburn  8921:                                      description => $description,
                   8922:                                      inst_code   => $inst_code,
                   8923:                                      owner       => $course_owner,
                   8924:                                      type        => $crstype,
1.1029    raeburn  8925:                                      creator     => $env{'user.name'}.':'.
                   8926:                                                     $env{'user.domain'},
                   8927:                                      created     => $now,
                   8928:                                      context     => $context,
1.918     raeburn  8929:                                                 },
                   8930:                     };
1.921     raeburn  8931:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8932: # set toplevel url
1.271     www      8933:     my $topurl=$url;
                   8934:     unless ($nonstandard) {
                   8935: # ------------------------------------------ For standard courses, make top url
                   8936:         my $mapurl=&clutter($url);
1.278     www      8937:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8938:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8939: <map>
                   8940: <resource id="1" type="start"></resource>
                   8941: <resource id="2" src="$mapurl"></resource>
                   8942: <resource id="3" type="finish"></resource>
                   8943: <link index="1" from="1" to="2"></link>
                   8944: <link index="2" from="2" to="3"></link>
                   8945: </map>
                   8946: ENDINITMAP
                   8947:         $topurl=&declutter(
1.638     albertel 8948:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8949:                           );
                   8950:     }
                   8951: # ----------------------------------------------------------- Write preferences
1.84      www      8952:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8953:                      ('description'              => $description,
                   8954:                       'url'                      => $topurl,
                   8955:                       'internal.creator'         => $env{'user.name'}.':'.
                   8956:                                                     $env{'user.domain'},
                   8957:                       'internal.created'         => $now,
                   8958:                       'internal.creationcontext' => $context)
                   8959:                     );
1.84      www      8960:     return '/'.$udom.'/'.$uname;
                   8961: }
                   8962: 
1.1011    raeburn  8963: # ------------------------------------------------------------------- Create ID
                   8964: sub generate_coursenum {
1.1038    raeburn  8965:     my ($udom,$crstype) = @_;
1.1011    raeburn  8966:     my $domdesc = &domain($udom);
                   8967:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8968:     my $first;
                   8969:     if ($crstype eq 'Community') {
                   8970:         $first = '0';
                   8971:     } else {
                   8972:         $first = int(1+rand(9)); 
                   8973:     } 
                   8974:     my $uname=$first.
1.1011    raeburn  8975:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8976:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8977:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8978: # ----------------------------------------------- Make sure that does not exist
                   8979:     my $uhome=&homeserver($uname,$udom,'true');
                   8980:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8981:         if ($crstype eq 'Community') {
                   8982:             $first = '0';
                   8983:         } else {
                   8984:             $first = int(1+rand(9));
                   8985:         }
                   8986:         $uname=$first.
1.1011    raeburn  8987:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8988:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8989:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8990:         $uhome=&homeserver($uname,$udom,'true');
                   8991:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8992:             return 'error: unable to generate unique course-ID';
                   8993:         }
                   8994:     }
                   8995:     return $uname;
                   8996: }
                   8997: 
1.813     albertel 8998: sub is_course {
1.1167    droeschl 8999:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9000:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9001: 
                   9002:     return unless $cdom and $cnum;
                   9003: 
                   9004:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9005:         '.');
                   9006: 
1.1172.2.23  raeburn  9007:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9008:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9009: }
                   9010: 
1.1015    raeburn  9011: sub store_userdata {
                   9012:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9013:     my $result;
1.1016    raeburn  9014:     if ($datakey ne '') {
1.1013    raeburn  9015:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9016:             if ($udom eq '' || $uname eq '') {
                   9017:                 $udom = $env{'user.domain'};
                   9018:                 $uname = $env{'user.name'};
                   9019:             }
                   9020:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9021:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9022:                 $result = 'error: no_host';
                   9023:             } else {
                   9024:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9025:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9026: 
                   9027:                 my $namevalue='';
                   9028:                 foreach my $key (keys(%{$storehash})) {
                   9029:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9030:                 }
                   9031:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9032:                 unless ($namespace eq 'courserequests') {
                   9033:                     $datakey = &escape($datakey);
                   9034:                 }
1.1105    raeburn  9035:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9036:                                   $namevalue,$uhome);
1.1013    raeburn  9037:             }
                   9038:         } else {
                   9039:             $result = 'error: data to store was not a hash reference'; 
                   9040:         }
                   9041:     } else {
                   9042:         $result= 'error: invalid requestkey'; 
                   9043:     }
                   9044:     return $result;
                   9045: }
                   9046: 
1.21      www      9047: # ---------------------------------------------------------- Assign Custom Role
                   9048: 
                   9049: sub assigncustomrole {
1.957     raeburn  9050:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9051:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9052:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9053: }
                   9054: 
                   9055: # ----------------------------------------------------------------- Revoke Role
                   9056: 
                   9057: sub revokerole {
1.957     raeburn  9058:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9059:     my $now=time;
1.965     raeburn  9060:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9061: }
                   9062: 
                   9063: # ---------------------------------------------------------- Revoke Custom Role
                   9064: 
                   9065: sub revokecustomrole {
1.957     raeburn  9066:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9067:     my $now=time;
1.357     www      9068:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9069:            $deleteflag,$selfenroll,$context);
1.17      www      9070: }
                   9071: 
1.533     banghart 9072: # ------------------------------------------------------------ Disk usage
1.535     albertel 9073: sub diskusage {
1.955     raeburn  9074:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9075:     $directorypath =~ s/\/$//;
                   9076:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9077:                        .&escape($getpropath).':'.&escape($uname).':'
                   9078:                        .&escape($udom),homeserver($uname,$udom));
                   9079:     if ($listing eq 'unknown_cmd') {
                   9080:         if ($getpropath) {
                   9081:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9082:         }
                   9083:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9084:     }
1.514     albertel 9085:     return $listing;
1.512     banghart 9086: }
                   9087: 
1.566     banghart 9088: sub is_locked {
1.1096    raeburn  9089:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9090:     my @check;
                   9091:     my $is_locked;
1.1093    raeburn  9092:     push (@check,$file_name);
1.613     albertel 9093:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9094: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9095:     my ($tmp)=keys(%locked);
                   9096:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9097:     
1.566     banghart 9098:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9099:         $is_locked = 'false';
                   9100:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9101:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9102:                $is_locked = 'true';
1.1096    raeburn  9103:                if (ref($which) eq 'ARRAY') {
                   9104:                    push(@{$which},$entry);
                   9105:                } else {
                   9106:                    last;
                   9107:                }
1.745     raeburn  9108:            }
                   9109:        }
1.566     banghart 9110:     } else {
                   9111:         $is_locked = 'false';
                   9112:     }
1.1093    raeburn  9113:     return $is_locked;
1.566     banghart 9114: }
                   9115: 
1.759     albertel 9116: sub declutter_portfile {
                   9117:     my ($file) = @_;
1.833     albertel 9118:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9119:     return $file;
                   9120: }
                   9121: 
1.559     banghart 9122: # ------------------------------------------------------------- Mark as Read Only
                   9123: 
                   9124: sub mark_as_readonly {
                   9125:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9126:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9127:     my ($tmp)=keys(%current_permissions);
                   9128:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9129:     foreach my $file (@{$files}) {
1.759     albertel 9130: 	$file = &declutter_portfile($file);
1.561     banghart 9131:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9132:     }
1.613     albertel 9133:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9134:     return;
                   9135: }
                   9136: 
1.572     banghart 9137: # ------------------------------------------------------------Save Selected Files
                   9138: 
                   9139: sub save_selected_files {
                   9140:     my ($user, $path, @files) = @_;
                   9141:     my $filename = $user."savedfiles";
1.573     banghart 9142:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9143:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9144:     foreach my $file (@files) {
1.620     albertel 9145:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9146:     }
                   9147:     foreach my $file (@other_files) {
1.574     banghart 9148:         print (OUT $file."\n");
1.572     banghart 9149:     }
1.574     banghart 9150:     close (OUT);
1.572     banghart 9151:     return 'ok';
                   9152: }
                   9153: 
1.574     banghart 9154: sub clear_selected_files {
                   9155:     my ($user) = @_;
                   9156:     my $filename = $user."savedfiles";
1.1117    foxr     9157:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9158:     print (OUT undef);
                   9159:     close (OUT);
                   9160:     return ("ok");    
                   9161: }
                   9162: 
1.572     banghart 9163: sub files_in_path {
                   9164:     my ($user, $path) = @_;
                   9165:     my $filename = $user."savedfiles";
                   9166:     my %return_files;
1.1117    foxr     9167:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9168:     while (my $line_in = <IN>) {
1.574     banghart 9169:         chomp ($line_in);
                   9170:         my @paths_and_file = split (m!/!, $line_in);
                   9171:         my $file_part = pop (@paths_and_file);
                   9172:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9173:         $path_part.='/';
                   9174:         my $path_and_file = $path_part.$file_part;
                   9175:         if ($path_part eq $path) {
                   9176:             $return_files{$file_part}= 'selected';
                   9177:         }
                   9178:     }
1.574     banghart 9179:     close (IN);
                   9180:     return (\%return_files);
1.572     banghart 9181: }
                   9182: 
                   9183: # called in portfolio select mode, to show files selected NOT in current directory
                   9184: sub files_not_in_path {
                   9185:     my ($user, $path) = @_;
                   9186:     my $filename = $user."savedfiles";
                   9187:     my @return_files;
                   9188:     my $path_part;
1.1117    foxr     9189:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9190:     while (my $line = <IN>) {
1.572     banghart 9191:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9192:         my @paths_and_file = split(m|/|, $line);
                   9193:         my $file_part = pop(@paths_and_file);
                   9194:         chomp($file_part);
                   9195:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9196:         $path_part .= '/';
                   9197:         my $path_and_file = $path_part.$file_part;
                   9198:         if ($path_part ne $path) {
1.800     albertel 9199:             push(@return_files, ($path_and_file));
1.572     banghart 9200:         }
                   9201:     }
1.800     albertel 9202:     close(OUT);
1.574     banghart 9203:     return (@return_files);
1.572     banghart 9204: }
                   9205: 
1.745     raeburn  9206: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9207: 
1.745     raeburn  9208: sub get_portfile_permissions {
                   9209:     my ($domain,$user) = @_;
1.613     albertel 9210:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9211:     my ($tmp)=keys(%current_permissions);
                   9212:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9213:     return \%current_permissions;
                   9214: }
                   9215: 
                   9216: #---------------------------------------------Get portfolio file access controls
                   9217: 
1.749     raeburn  9218: sub get_access_controls {
1.745     raeburn  9219:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9220:     my %access;
                   9221:     my $real_file = $file;
                   9222:     $file =~ s/\.meta$//;
1.745     raeburn  9223:     if (defined($file)) {
1.749     raeburn  9224:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9225:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9226:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9227:             }
                   9228:         }
1.745     raeburn  9229:     } else {
1.749     raeburn  9230:         foreach my $key (keys(%{$current_permissions})) {
                   9231:             if ($key =~ /\0accesscontrol$/) {
                   9232:                 if (defined($group)) {
                   9233:                     if ($key !~ m-^\Q$group\E/-) {
                   9234:                         next;
                   9235:                     }
                   9236:                 }
                   9237:                 my ($fullpath) = split(/\0/,$key);
                   9238:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9239:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9240:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9241:                     }
                   9242:                 }
                   9243:             }
                   9244:         }
                   9245:     }
                   9246:     return %access;
                   9247: }
                   9248: 
                   9249: sub modify_access_controls {
                   9250:     my ($file_name,$changes,$domain,$user)=@_;
                   9251:     my ($outcome,$deloutcome);
                   9252:     my %store_permissions;
                   9253:     my %new_values;
                   9254:     my %new_control;
                   9255:     my %translation;
                   9256:     my @deletions = ();
                   9257:     my $now = time;
                   9258:     if (exists($$changes{'activate'})) {
                   9259:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9260:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9261:             my $numnew = scalar(@newitems);
                   9262:             for (my $i=0; $i<$numnew; $i++) {
                   9263:                 my $newkey = $newitems[$i];
                   9264:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9265:                 if ($newkey =~ /^\d+:/) { 
                   9266:                     $newkey =~ s/^(\d+)/$newid/;
                   9267:                     $translation{$1} = $newid;
                   9268:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9269:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9270:                     $translation{$1} = $newid;
                   9271:                 }
1.749     raeburn  9272:                 $new_values{$file_name."\0".$newkey} = 
                   9273:                                           $$changes{'activate'}{$newitems[$i]};
                   9274:                 $new_control{$newkey} = $now;
                   9275:             }
                   9276:         }
                   9277:     }
                   9278:     my %todelete;
                   9279:     my %changed_items;
                   9280:     foreach my $action ('delete','update') {
                   9281:         if (exists($$changes{$action})) {
                   9282:             if (ref($$changes{$action}) eq 'HASH') {
                   9283:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9284:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9285:                     if ($action eq 'delete') { 
                   9286:                         $todelete{$itemnum} = 1;
                   9287:                     } else {
                   9288:                         $changed_items{$itemnum} = $key;
                   9289:                     }
                   9290:                 }
1.745     raeburn  9291:             }
                   9292:         }
1.749     raeburn  9293:     }
                   9294:     # get lock on access controls for file.
                   9295:     my $lockhash = {
                   9296:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9297:                                                        ':'.$env{'user.domain'},
                   9298:                    }; 
                   9299:     my $tries = 0;
                   9300:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9301:    
                   9302:     while (($gotlock ne 'ok') && $tries <3) {
                   9303:         $tries ++;
                   9304:         sleep 1;
                   9305:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9306:     }
                   9307:     if ($gotlock eq 'ok') {
                   9308:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9309:         my ($tmp)=keys(%curr_permissions);
                   9310:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9311:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9312:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9313:             if (ref($curr_controls) eq 'HASH') {
                   9314:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9315:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9316:                     if (defined($todelete{$itemnum})) {
                   9317:                         push(@deletions,$file_name."\0".$control_item);
                   9318:                     } else {
                   9319:                         if (defined($changed_items{$itemnum})) {
                   9320:                             $new_control{$changed_items{$itemnum}} = $now;
                   9321:                             push(@deletions,$file_name."\0".$control_item);
                   9322:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9323:                         } else {
                   9324:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9325:                         }
                   9326:                     }
1.745     raeburn  9327:                 }
                   9328:             }
                   9329:         }
1.970     raeburn  9330:         my ($group);
                   9331:         if (&is_course($domain,$user)) {
                   9332:             ($group,my $file) = split(/\//,$file_name,2);
                   9333:         }
1.749     raeburn  9334:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9335:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9336:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9337:         #  remove lock
                   9338:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9339:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9340:         my $sqlresult =
1.970     raeburn  9341:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9342:                                     $group);
1.749     raeburn  9343:     } else {
                   9344:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9345:     }
1.749     raeburn  9346:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9347: }
                   9348: 
1.827     raeburn  9349: sub make_public_indefinitely {
                   9350:     my ($requrl) = @_;
                   9351:     my $now = time;
                   9352:     my $action = 'activate';
                   9353:     my $aclnum = 0;
                   9354:     if (&is_portfolio_url($requrl)) {
                   9355:         my (undef,$udom,$unum,$file_name,$group) =
                   9356:             &parse_portfolio_url($requrl);
                   9357:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9358:         my %access_controls = &get_access_controls($current_perms,
                   9359:                                                    $group,$file_name);
                   9360:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9361:             my ($num,$scope,$end,$start) = 
                   9362:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9363:             if ($scope eq 'public') {
                   9364:                 if ($start <= $now && $end == 0) {
                   9365:                     $action = 'none';
                   9366:                 } else {
                   9367:                     $action = 'update';
                   9368:                     $aclnum = $num;
                   9369:                 }
                   9370:                 last;
                   9371:             }
                   9372:         }
                   9373:         if ($action eq 'none') {
                   9374:              return 'ok';
                   9375:         } else {
                   9376:             my %changes;
                   9377:             my $newend = 0;
                   9378:             my $newstart = $now;
                   9379:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9380:             $changes{$action}{$newkey} = {
                   9381:                 type => 'public',
                   9382:                 time => {
                   9383:                     start => $newstart,
                   9384:                     end   => $newend,
                   9385:                 },
                   9386:             };
                   9387:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9388:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9389:             return $outcome;
                   9390:         }
                   9391:     } else {
                   9392:         return 'invalid';
                   9393:     }
                   9394: }
                   9395: 
1.745     raeburn  9396: #------------------------------------------------------Get Marked as Read Only
                   9397: 
                   9398: sub get_marked_as_readonly {
                   9399:     my ($domain,$user,$what,$group) = @_;
                   9400:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9401:     my @readonly_files;
1.629     banghart 9402:     my $cmp1=$what;
                   9403:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9404:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9405:         if (defined($group)) {
                   9406:             if ($file_name !~ m-^\Q$group\E/-) {
                   9407:                 next;
                   9408:             }
                   9409:         }
1.561     banghart 9410:         if (ref($value) eq "ARRAY"){
                   9411:             foreach my $stored_what (@{$value}) {
1.629     banghart 9412:                 my $cmp2=$stored_what;
1.759     albertel 9413:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9414:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9415:                 }
1.629     banghart 9416:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9417:                     push(@readonly_files, $file_name);
1.745     raeburn  9418:                     last;
1.563     banghart 9419:                 } elsif (!defined($what)) {
                   9420:                     push(@readonly_files, $file_name);
1.745     raeburn  9421:                     last;
1.561     banghart 9422:                 }
                   9423:             }
1.745     raeburn  9424:         }
1.561     banghart 9425:     }
                   9426:     return @readonly_files;
                   9427: }
1.577     banghart 9428: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9429: 
1.577     banghart 9430: sub get_marked_as_readonly_hash {
1.745     raeburn  9431:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9432:     my %readonly_files;
1.745     raeburn  9433:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9434:         if (defined($group)) {
                   9435:             if ($file_name !~ m-^\Q$group\E/-) {
                   9436:                 next;
                   9437:             }
                   9438:         }
1.577     banghart 9439:         if (ref($value) eq "ARRAY"){
                   9440:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9441:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9442:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9443:                         if ($lock_descriptor eq 'graded') {
                   9444:                             $readonly_files{$file_name} = 'graded';
                   9445:                         } elsif ($lock_descriptor eq 'handback') {
                   9446:                             $readonly_files{$file_name} = 'handback';
                   9447:                         } else {
                   9448:                             if (!exists($readonly_files{$file_name})) {
                   9449:                                 $readonly_files{$file_name} = 'locked';
                   9450:                             }
                   9451:                         }
1.745     raeburn  9452:                     }
1.750     banghart 9453:                 } 
1.577     banghart 9454:             }
                   9455:         } 
                   9456:     }
                   9457:     return %readonly_files;
                   9458: }
1.559     banghart 9459: # ------------------------------------------------------------ Unmark as Read Only
                   9460: 
                   9461: sub unmark_as_readonly {
1.629     banghart 9462:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9463:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9464:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9465:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9466:     my $symb_crs = $what;
                   9467:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9468:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9469:     my ($tmp)=keys(%current_permissions);
                   9470:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9471:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9472:     foreach my $file (@readonly_files) {
1.759     albertel 9473: 	my $clean_file = &declutter_portfile($file);
                   9474: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9475: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9476:         my @new_locks;
                   9477:         my @del_keys;
                   9478:         if (ref($current_locks) eq "ARRAY"){
                   9479:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9480:                 my $compare=$locker;
1.749     raeburn  9481:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9482:                     $compare=join('',@{$locker});
1.746     raeburn  9483:                     if ($compare ne $symb_crs) {
                   9484:                         push(@new_locks, $locker);
                   9485:                     }
1.563     banghart 9486:                 }
                   9487:             }
1.650     albertel 9488:             if (scalar(@new_locks) > 0) {
1.563     banghart 9489:                 $current_permissions{$file} = \@new_locks;
                   9490:             } else {
                   9491:                 push(@del_keys, $file);
1.613     albertel 9492:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9493:                 delete($current_permissions{$file});
1.563     banghart 9494:             }
                   9495:         }
1.561     banghart 9496:     }
1.613     albertel 9497:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9498:     return;
                   9499: }
1.512     banghart 9500: 
1.17      www      9501: # ------------------------------------------------------------ Directory lister
                   9502: 
                   9503: sub dirlist {
1.955     raeburn  9504:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9505:     $uri=~s/^\///;
                   9506:     $uri=~s/\/$//;
1.253     stredwic 9507:     my ($udom, $uname);
1.955     raeburn  9508:     if ($getuserdir) {
1.253     stredwic 9509:         $udom = $userdomain;
                   9510:         $uname = $username;
1.955     raeburn  9511:     } else {
                   9512:         (undef,$udom,$uname)=split(/\//,$uri);
                   9513:         if(defined($userdomain)) {
                   9514:             $udom = $userdomain;
                   9515:         }
                   9516:         if(defined($username)) {
                   9517:             $uname = $username;
                   9518:         }
1.253     stredwic 9519:     }
1.955     raeburn  9520:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9521: 
1.955     raeburn  9522:     $dirRoot = $perlvar{'lonDocRoot'};
                   9523:     if (defined($getpropath)) {
                   9524:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9525:         $dirRoot =~ s/\/$//;
1.955     raeburn  9526:     } elsif (defined($getuserdir)) {
                   9527:         my $subdir=$uname.'__';
                   9528:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9529:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9530:                    ."/$udom/$subdir/$uname";
                   9531:     } elsif (defined($alternateRoot)) {
                   9532:         $dirRoot = $alternateRoot;
1.751     banghart 9533:     }
1.253     stredwic 9534: 
                   9535:     if($udom) {
                   9536:         if($uname) {
1.1135    raeburn  9537:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9538:             if ($uhome eq 'no_host') {
                   9539:                 return ([],'no_host');
                   9540:             }
1.955     raeburn  9541:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9542:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9543:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9544:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9545:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9546:             } else {
                   9547:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9548:             }
1.605     matthew  9549:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9550:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9551:                 @listing_results = split(/:/,$listing);
                   9552:             } else {
                   9553:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9554:             }
1.1135    raeburn  9555:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9556:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9557:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9558:                 return ([],$listing);
                   9559:             } else {
                   9560:                 return (\@listing_results);
1.1135    raeburn  9561:             }
1.955     raeburn  9562:         } elsif(!$alternateRoot) {
1.1136    raeburn  9563:             my (%allusers,%listerror);
1.841     albertel 9564: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9565:  	    foreach my $tryserver (keys(%servers)) {
                   9566:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9567:                                   &escape($udom),$tryserver);
                   9568:                 if ($listing eq 'unknown_cmd') {
                   9569: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9570: 				      $udom, $tryserver);
                   9571:                 } else {
                   9572:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9573:                 }
1.841     albertel 9574: 		if ($listing eq 'unknown_cmd') {
                   9575: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9576: 				      $udom, $tryserver);
                   9577: 		    @listing_results = split(/:/,$listing);
                   9578: 		} else {
                   9579: 		    @listing_results =
                   9580: 			map { &unescape($_); } split(/:/,$listing);
                   9581: 		}
1.1136    raeburn  9582:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9583:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9584:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9585:                     $listerror{$tryserver} = $listing;
                   9586:                 } else {
1.841     albertel 9587: 		    foreach my $line (@listing_results) {
                   9588: 			my ($entry) = split(/&/,$line,2);
                   9589: 			$allusers{$entry} = 1;
                   9590: 		    }
                   9591: 		}
1.253     stredwic 9592:             }
1.1136    raeburn  9593:             my @alluserslist=();
1.800     albertel 9594:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9595:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9596:             }
1.1136    raeburn  9597:             return (\@alluserslist);
1.253     stredwic 9598:         } else {
1.1136    raeburn  9599:             return ([],'missing username');
1.253     stredwic 9600:         }
1.955     raeburn  9601:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9602:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9603:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9604:         return (\@all_domains);
1.955     raeburn  9605:     } else {
1.1136    raeburn  9606:         return ([],'missing domain');
1.275     stredwic 9607:     }
                   9608: }
                   9609: 
                   9610: # --------------------------------------------- GetFileTimestamp
                   9611: # This function utilizes dirlist and returns the date stamp for
                   9612: # when it was last modified.  It will also return an error of -1
                   9613: # if an error occurs
                   9614: 
                   9615: sub GetFileTimestamp {
1.955     raeburn  9616:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9617:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9618:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9619:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9620:                                     undef,$getuserdir);
                   9621:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9622:         return -1;
                   9623:     }
                   9624:     if (ref($fileref) eq 'ARRAY') {
                   9625:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9626:         # @stats contains first the filename, then the stat output
                   9627:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9628:     } else {
                   9629:         return -1;
1.253     stredwic 9630:     }
1.26      www      9631: }
                   9632: 
1.712     albertel 9633: sub stat_file {
                   9634:     my ($uri) = @_;
1.787     albertel 9635:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9636: 
1.955     raeburn  9637:     my ($udom,$uname,$file);
1.712     albertel 9638:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9639: 	($udom,$uname,$file) =
1.811     albertel 9640: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9641: 	$file = 'userfiles/'.$file;
                   9642:     }
                   9643:     if ($uri =~ m-^/res/-) {
                   9644: 	($udom,$uname) = 
1.807     albertel 9645: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9646: 	$file = $uri;
                   9647:     }
                   9648: 
                   9649:     if (!$udom || !$uname || !$file) {
                   9650: 	# unable to handle the uri
                   9651: 	return ();
                   9652:     }
1.956     raeburn  9653:     my $getpropath;
                   9654:     if ($file =~ /^userfiles\//) {
                   9655:         $getpropath = 1;
                   9656:     }
1.1136    raeburn  9657:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9658:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9659:         return ();
                   9660:     } else {
                   9661:         if (ref($listref) eq 'ARRAY') {
                   9662:             my @stats = split('&',$listref->[0]);
                   9663: 	    shift(@stats); #filename is first
                   9664: 	    return @stats;
                   9665:         }
1.712     albertel 9666:     }
                   9667:     return ();
                   9668: }
                   9669: 
1.26      www      9670: # -------------------------------------------------------- Value of a Condition
                   9671: 
1.713     albertel 9672: # gets the value of a specific preevaluated condition
                   9673: #    stored in the string  $env{user.state.<cid>}
                   9674: # or looks up a condition reference in the bighash and if if hasn't
                   9675: # already been evaluated recurses into docondval to get the value of
                   9676: # the condition, then memoizing it to 
                   9677: #   $env{user.state.<cid>.<condition>}
1.40      www      9678: sub directcondval {
                   9679:     my $number=shift;
1.620     albertel 9680:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9681: 	&Apache::lonuserstate::evalstate();
                   9682:     }
1.713     albertel 9683:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9684: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9685:     } elsif ($number =~ /^_/) {
                   9686: 	my $sub_condition;
                   9687: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9688: 		&GDBM_READER(),0640)) {
                   9689: 	    $sub_condition=$bighash{'conditions'.$number};
                   9690: 	    untie(%bighash);
                   9691: 	}
                   9692: 	my $value = &docondval($sub_condition);
1.949     raeburn  9693: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9694: 	return $value;
                   9695:     }
1.620     albertel 9696:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9697:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9698:     } else {
                   9699:        return 2;
                   9700:     }
                   9701: }
                   9702: 
1.713     albertel 9703: # get the collection of conditions for this resource
1.26      www      9704: sub condval {
                   9705:     my $condidx=shift;
1.54      www      9706:     my $allpathcond='';
1.713     albertel 9707:     foreach my $cond (split(/\|/,$condidx)) {
                   9708: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9709: 	    $allpathcond.=
                   9710: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9711: 	}
1.191     harris41 9712:     }
1.54      www      9713:     $allpathcond=~s/\|$//;
1.713     albertel 9714:     return &docondval($allpathcond);
                   9715: }
                   9716: 
                   9717: #evaluates an expression of conditions
                   9718: sub docondval {
                   9719:     my ($allpathcond) = @_;
                   9720:     my $result=0;
                   9721:     if ($env{'request.course.id'}
                   9722: 	&& defined($allpathcond)) {
                   9723: 	my $operand='|';
                   9724: 	my @stack;
                   9725: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9726: 	    if ($chunk eq '(') {
                   9727: 		push @stack,($operand,$result);
                   9728: 	    } elsif ($chunk eq ')') {
                   9729: 		my $before=pop @stack;
                   9730: 		if (pop @stack eq '&') {
                   9731: 		    $result=$result>$before?$before:$result;
                   9732: 		} else {
                   9733: 		    $result=$result>$before?$result:$before;
                   9734: 		}
                   9735: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9736: 		$operand=$chunk;
                   9737: 	    } else {
                   9738: 		my $new=directcondval($chunk);
                   9739: 		if ($operand eq '&') {
                   9740: 		    $result=$result>$new?$new:$result;
                   9741: 		} else {
                   9742: 		    $result=$result>$new?$result:$new;
                   9743: 		}
                   9744: 	    }
                   9745: 	}
1.26      www      9746:     }
                   9747:     return $result;
1.421     albertel 9748: }
                   9749: 
                   9750: # ---------------------------------------------------- Devalidate courseresdata
                   9751: 
                   9752: sub devalidatecourseresdata {
                   9753:     my ($coursenum,$coursedomain)=@_;
                   9754:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9755:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9756: }
                   9757: 
1.763     www      9758: 
1.200     www      9759: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9760: #
                   9761: #  Parameters:
                   9762: #      $coursenum    - Number of the course.
                   9763: #      $coursedomain - Domain at which the course was created.
                   9764: #  Returns:
                   9765: #     A hash of the course parameters along (I think) with timestamps
                   9766: #     and version info.
1.877     foxr     9767: 
1.624     albertel 9768: sub get_courseresdata {
                   9769:     my ($coursenum,$coursedomain)=@_;
1.200     www      9770:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9771:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9772:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9773:     my %dumpreply;
1.417     albertel 9774:     unless (defined($cached)) {
1.624     albertel 9775: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9776: 	$result=\%dumpreply;
1.251     albertel 9777: 	my ($tmp) = keys(%dumpreply);
                   9778: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9779: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9780: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9781: 	    return $tmp;
1.416     albertel 9782: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9783: 	    $result=undef;
1.599     albertel 9784: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9785: 	}
                   9786:     }
1.624     albertel 9787:     return $result;
                   9788: }
                   9789: 
1.633     albertel 9790: sub devalidateuserresdata {
                   9791:     my ($uname,$udom)=@_;
                   9792:     my $hashid="$udom:$uname";
                   9793:     &devalidate_cache_new('userres',$hashid);
                   9794: }
                   9795: 
1.624     albertel 9796: sub get_userresdata {
                   9797:     my ($uname,$udom)=@_;
                   9798:     #most student don\'t have any data set, check if there is some data
                   9799:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9800: 
                   9801:     my $hashid="$udom:$uname";
                   9802:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9803:     if (!defined($cached)) {
                   9804: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9805: 	$result=\%resourcedata;
                   9806: 	&do_cache_new('userres',$hashid,$result,600);
                   9807:     }
                   9808:     my ($tmp)=keys(%$result);
                   9809:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9810: 	return $result;
                   9811:     }
                   9812:     #error 2 occurs when the .db doesn't exist
                   9813:     if ($tmp!~/error: 2 /) {
1.672     albertel 9814: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9815: 		 " Trying to get resource data for ".
                   9816: 		 $uname." at ".$udom.": ".
                   9817: 		 $tmp."</font>");
                   9818:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9819: 	#&EXT_cache_set($udom,$uname);
                   9820: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9821: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9822:     }
                   9823:     return $tmp;
                   9824: }
1.879     foxr     9825: #----------------------------------------------- resdata - return resource data
                   9826: #  Purpose:
                   9827: #    Return resource data for either users or for a course.
                   9828: #  Parameters:
                   9829: #     $name      - Course/user name.
                   9830: #     $domain    - Name of the domain the user/course is registered on.
                   9831: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9832: #     @which     - Array of names of resources desired.
                   9833: #  Returns:
                   9834: #     The value of the first reasource in @which that is found in the
                   9835: #     resource hash.
                   9836: #  Exceptional Conditions:
                   9837: #     If the $type passed in is not valid (not the string 'course' or 
                   9838: #     'user', an undefined  reference is returned.
                   9839: #     If none of the resources are found, an undef is returned
1.624     albertel 9840: sub resdata {
                   9841:     my ($name,$domain,$type,@which)=@_;
                   9842:     my $result;
                   9843:     if ($type eq 'course') {
                   9844: 	$result=&get_courseresdata($name,$domain);
                   9845:     } elsif ($type eq 'user') {
                   9846: 	$result=&get_userresdata($name,$domain);
                   9847:     }
                   9848:     if (!ref($result)) { return $result; }    
1.251     albertel 9849:     foreach my $item (@which) {
1.927     albertel 9850: 	if (defined($result->{$item->[0]})) {
                   9851: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9852: 	}
1.250     albertel 9853:     }
1.291     albertel 9854:     return undef;
1.200     www      9855: }
                   9856: 
1.1172.2.31  raeburn  9857: sub get_numsuppfiles {
                   9858:     my ($cnum,$cdom,$ignorecache)=@_;
                   9859:     my $hashid=$cnum.':'.$cdom;
                   9860:     my ($suppcount,$cached);
                   9861:     unless ($ignorecache) {
                   9862:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9863:     }
                   9864:     unless (defined($cached)) {
                   9865:         my $chome=&homeserver($cnum,$cdom);
                   9866:         unless ($chome eq 'no_host') {
                   9867:             ($suppcount,my $errors) = (0,0);
                   9868:             my $suppmap = 'supplemental.sequence';
                   9869:             ($suppcount,$errors) =
                   9870:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9871:         }
                   9872:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9873:     }
                   9874:     return $suppcount;
                   9875: }
                   9876: 
1.379     matthew  9877: #
                   9878: # EXT resource caching routines
                   9879: #
                   9880: 
                   9881: sub clear_EXT_cache_status {
1.383     albertel 9882:     &delenv('cache.EXT.');
1.379     matthew  9883: }
                   9884: 
                   9885: sub EXT_cache_status {
                   9886:     my ($target_domain,$target_user) = @_;
1.383     albertel 9887:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9888:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9889:         # We know already the user has no data
                   9890:         return 1;
                   9891:     } else {
                   9892:         return 0;
                   9893:     }
                   9894: }
                   9895: 
                   9896: sub EXT_cache_set {
                   9897:     my ($target_domain,$target_user) = @_;
1.383     albertel 9898:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9899:     #&appenv({$cachename => time});
1.379     matthew  9900: }
                   9901: 
1.28      www      9902: # --------------------------------------------------------- Value of a Variable
1.58      www      9903: sub EXT {
1.715     albertel 9904: 
1.1172.2.28  raeburn  9905:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9906:     unless ($varname) { return ''; }
1.218     albertel 9907:     #get real user name/domain, courseid and symb
                   9908:     my $courseid;
1.359     albertel 9909:     my $publicuser;
1.427     www      9910:     if ($symbparm) {
                   9911: 	$symbparm=&get_symb_from_alias($symbparm);
                   9912:     }
1.218     albertel 9913:     if (!($uname && $udom)) {
1.790     albertel 9914:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9915:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9916:     } else {
1.620     albertel 9917: 	$courseid=$env{'request.course.id'};
1.218     albertel 9918:     }
1.48      www      9919:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9920:     my $rest;
1.320     albertel 9921:     if (defined($therest[0])) {
1.48      www      9922:        $rest=join('.',@therest);
                   9923:     } else {
                   9924:        $rest='';
                   9925:     }
1.320     albertel 9926: 
1.57      www      9927:     my $qualifierrest=$qualifier;
                   9928:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9929:     my $spacequalifierrest=$space;
                   9930:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9931:     if ($realm eq 'user') {
1.48      www      9932: # --------------------------------------------------------------- user.resource
                   9933: 	if ($space eq 'resource') {
1.651     albertel 9934: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9935: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9936: 		 &&
1.744     albertel 9937: 		 ($symbparm eq &symbread()) ) {	
                   9938: 		# if we are in the middle of processing the resource the
                   9939: 		# get the value we are planning on committing
                   9940:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9941:                     return $Apache::lonhomework::results{$qualifierrest};
                   9942:                 } else {
                   9943:                     return $Apache::lonhomework::history{$qualifierrest};
                   9944:                 }
1.335     albertel 9945: 	    } else {
1.359     albertel 9946: 		my %restored;
1.620     albertel 9947: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9948: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9949: 		} else {
                   9950: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9951: 		}
1.335     albertel 9952: 		return $restored{$qualifierrest};
                   9953: 	    }
1.48      www      9954: # ----------------------------------------------------------------- user.access
                   9955:         } elsif ($space eq 'access') {
1.218     albertel 9956: 	    # FIXME - not supporting calls for a specific user
1.48      www      9957:             return &allowed($qualifier,$rest);
                   9958: # ------------------------------------------ user.preferences, user.environment
                   9959:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9960: 	    if (($uname eq $env{'user.name'}) &&
                   9961: 		($udom eq $env{'user.domain'})) {
                   9962: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9963: 	    } else {
1.359     albertel 9964: 		my %returnhash;
                   9965: 		if (!$publicuser) {
                   9966: 		    %returnhash=&userenvironment($udom,$uname,
                   9967: 						 $qualifierrest);
                   9968: 		}
1.218     albertel 9969: 		return $returnhash{$qualifierrest};
                   9970: 	    }
1.48      www      9971: # ----------------------------------------------------------------- user.course
                   9972:         } elsif ($space eq 'course') {
1.218     albertel 9973: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9974:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9975: # ------------------------------------------------------------------- user.role
                   9976:         } elsif ($space eq 'role') {
1.218     albertel 9977: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9978:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9979:             if ($qualifier eq 'value') {
                   9980: 		return $role;
                   9981:             } elsif ($qualifier eq 'extent') {
                   9982:                 return $where;
                   9983:             }
                   9984: # ----------------------------------------------------------------- user.domain
                   9985:         } elsif ($space eq 'domain') {
1.218     albertel 9986:             return $udom;
1.48      www      9987: # ------------------------------------------------------------------- user.name
                   9988:         } elsif ($space eq 'name') {
1.218     albertel 9989:             return $uname;
1.48      www      9990: # ---------------------------------------------------- Any other user namespace
1.29      www      9991:         } else {
1.359     albertel 9992: 	    my %reply;
                   9993: 	    if (!$publicuser) {
                   9994: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9995: 	    }
                   9996: 	    return $reply{$qualifierrest};
1.48      www      9997:         }
1.236     www      9998:     } elsif ($realm eq 'query') {
                   9999: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10000:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10001: 						[$spacequalifierrest]);
1.620     albertel 10002: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10003:    } elsif ($realm eq 'request') {
1.48      www      10004: # ------------------------------------------------------------- request.browser
                   10005:         if ($space eq 'browser') {
1.1145    bisitz   10006:             return $env{'browser.'.$qualifier};
1.57      www      10007: # ------------------------------------------------------------ request.filename
                   10008:         } else {
1.620     albertel 10009:             return $env{'request.'.$spacequalifierrest};
1.29      www      10010:         }
1.28      www      10011:     } elsif ($realm eq 'course') {
1.48      www      10012: # ---------------------------------------------------------- course.description
1.620     albertel 10013:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10014:     } elsif ($realm eq 'resource') {
1.165     www      10015: 
1.620     albertel 10016: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10017: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10018: 	}
1.693     albertel 10019: 
1.1172.2.30  raeburn  10020:         if ($qualifier eq '') {
                   10021: 	    if ($space eq 'title') {
                   10022: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10023: 	        return &gettitle($symbparm);
                   10024: 	    }
1.693     albertel 10025: 	
1.1172.2.30  raeburn  10026: 	    if ($space eq 'map') {
                   10027: 	        my ($map) = &decode_symb($symbparm);
                   10028: 	        return &symbread($map);
                   10029: 	    }
                   10030:             if ($space eq 'maptitle') {
                   10031:                 my ($map) = &decode_symb($symbparm);
                   10032:                 return &gettitle($map);
                   10033:             }
                   10034: 	    if ($space eq 'filename') {
                   10035: 	        if ($symbparm) {
                   10036: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10037: 	        }
                   10038: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10039: 	    }
1.1172.2.30  raeburn  10040: 
                   10041:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10042:                 if ($space eq 'visibleparts') {
                   10043:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10044:                     my $item;
                   10045:                     if (ref($navmap)) {
                   10046:                         my $res = $navmap->getBySymb($symbparm);
                   10047:                         my $parts = $res->parts();
                   10048:                         if (ref($parts) eq 'ARRAY') {
                   10049:                             $item = join(',',@{$parts});
                   10050:                         }
                   10051:                         undef($navmap);
                   10052:                     }
                   10053:                     return $item;
                   10054:                 }
                   10055:             }
                   10056:         }
1.693     albertel 10057: 
                   10058: 	my ($section, $group, @groups);
1.593     albertel 10059: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10060:         if (($courseid eq '') && ($cid)) {
                   10061:             $courseid = $cid;
                   10062:         }
                   10063: 	if (($symbparm && $courseid) && 
                   10064: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10065: 
1.218     albertel 10066: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10067: 
1.60      www      10068: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10069: 	    my $symbp=$symbparm;
1.735     albertel 10070: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10071: 
                   10072: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10073: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10074: 
1.620     albertel 10075: 	    if (($env{'user.name'} eq $uname) &&
                   10076: 		($env{'user.domain'} eq $udom)) {
                   10077: 		$section=$env{'request.course.sec'};
1.733     raeburn  10078:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10079:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10080: 	    } else {
1.539     albertel 10081: 		if (! defined($usection)) {
1.551     albertel 10082: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10083: 		} else {
                   10084: 		    $section = $usection;
                   10085: 		}
1.733     raeburn  10086:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10087: 	    }
                   10088: 
                   10089: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10090: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10091: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10092: 
1.593     albertel 10093: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10094: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10095: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10096: 
1.60      www      10097: # ----------------------------------------------------------- first, check user
1.624     albertel 10098: 
                   10099: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10100: 				       ([$courselevelr,'resource'],
                   10101: 					[$courselevelm,'map'     ],
                   10102: 					[$courselevel, 'course'  ]));
1.931     albertel 10103: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10104: 
1.594     albertel 10105: # ------------------------------------------------ second, check some of course
1.684     raeburn  10106:             my $coursereply;
1.691     raeburn  10107:             if (@groups > 0) {
                   10108:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10109:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10110:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10111:             }
1.96      www      10112: 
1.684     raeburn  10113: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10114: 				  $env{'course.'.$courseid.'.domain'},
                   10115: 				  'course',
                   10116: 				  ([$seclevelr,   'resource'],
                   10117: 				   [$seclevelm,   'map'     ],
                   10118: 				   [$seclevel,    'course'  ],
                   10119: 				   [$courselevelr,'resource']));
                   10120: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10121: 
1.60      www      10122: # ------------------------------------------------------ third, check map parms
1.218     albertel 10123: 	    my %parmhash=();
                   10124: 	    my $thisparm='';
                   10125: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10126: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10127: 		    &GDBM_READER(),0640)) {
1.218     albertel 10128: 		$thisparm=$parmhash{$symbparm};
                   10129: 		untie(%parmhash);
                   10130: 	    }
1.927     albertel 10131: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10132: 	}
1.594     albertel 10133: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10134: 
1.218     albertel 10135: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10136: 	my $filename;
                   10137: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10138: 	if ($symbparm) {
1.409     www      10139: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10140: 	} else {
1.620     albertel 10141: 	    $filename=$env{'request.filename'};
1.282     albertel 10142: 	}
                   10143: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10144: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10145: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10146: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10147: 
1.927     albertel 10148: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10149: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10150: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10151: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10152: 				     $env{'course.'.$courseid.'.domain'},
                   10153: 				     'course',
1.927     albertel 10154: 				     ([$courselevelm,'map'   ],
                   10155: 				      [$courselevel, 'course']));
                   10156: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10157: 	}
1.145     www      10158: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10159: 	unless ($space eq '0') {
1.336     albertel 10160: 	    my @parts=split(/_/,$space);
                   10161: 	    my $id=pop(@parts);
                   10162: 	    my $part=join('_',@parts);
                   10163: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10164: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10165: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10166: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10167: 	}
1.395     albertel 10168: 	if ($recurse) { return undef; }
                   10169: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10170: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10171: # ---------------------------------------------------- Any other user namespace
                   10172:     } elsif ($realm eq 'environment') {
                   10173: # ----------------------------------------------------------------- environment
1.620     albertel 10174: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10175: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10176: 	} else {
1.770     albertel 10177: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10178: 		return '';
                   10179: 	    }
1.219     albertel 10180: 	    my %returnhash=&userenvironment($udom,$uname,
                   10181: 					    $spacequalifierrest);
                   10182: 	    return $returnhash{$spacequalifierrest};
                   10183: 	}
1.28      www      10184:     } elsif ($realm eq 'system') {
1.48      www      10185: # ----------------------------------------------------------------- system.time
                   10186: 	if ($space eq 'time') {
                   10187: 	    return time;
                   10188:         }
1.696     albertel 10189:     } elsif ($realm eq 'server') {
                   10190: # ----------------------------------------------------------------- system.time
                   10191: 	if ($space eq 'name') {
                   10192: 	    return $ENV{'SERVER_NAME'};
                   10193:         }
1.28      www      10194:     }
1.48      www      10195:     return '';
1.61      www      10196: }
                   10197: 
1.927     albertel 10198: sub get_reply {
                   10199:     my ($reply_value) = @_;
1.940     raeburn  10200:     if (ref($reply_value) eq 'ARRAY') {
                   10201:         if (wantarray) {
                   10202: 	    return @$reply_value;
                   10203:         }
                   10204:         return $reply_value->[0];
                   10205:     } else {
                   10206:         return $reply_value;
1.927     albertel 10207:     }
                   10208: }
                   10209: 
1.691     raeburn  10210: sub check_group_parms {
                   10211:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10212:     my @groupitems = ();
                   10213:     my $resultitem;
1.927     albertel 10214:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10215:     foreach my $group (@{$groups}) {
                   10216:         foreach my $level (@levels) {
1.927     albertel 10217:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10218:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10219:         }
                   10220:     }
                   10221:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10222:                             $env{'course.'.$courseid.'.domain'},
                   10223:                                      'course',@groupitems);
                   10224:     return $coursereply;
                   10225: }
                   10226: 
                   10227: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10228:     my ($courseid,@groups) = @_;
                   10229:     @groups = sort(@groups);
1.691     raeburn  10230:     return @groups;
                   10231: }
                   10232: 
1.395     albertel 10233: sub packages_tab_default {
                   10234:     my ($uri,$varname)=@_;
                   10235:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10236: 
                   10237:     my (@extension,@specifics,$do_default);
                   10238:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10239: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10240: 	if ($pack_type eq 'default') {
                   10241: 	    $do_default=1;
                   10242: 	} elsif ($pack_type eq 'extension') {
                   10243: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10244: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10245: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10246: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10247: 	}
                   10248:     }
                   10249:     # first look for a package that matches the requested part id
                   10250:     foreach my $package (@specifics) {
                   10251: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10252: 	next if ($pack_part ne $part);
                   10253: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10254: 	    return $packagetab{"$pack_type&$name&default"};
                   10255: 	}
                   10256:     }
                   10257:     # look for any possible matching non extension_ package
                   10258:     foreach my $package (@specifics) {
                   10259: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10260: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10261: 	    return $packagetab{"$pack_type&$name&default"};
                   10262: 	}
1.585     albertel 10263: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10264: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10265: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10266: 	}
                   10267:     }
1.738     albertel 10268:     # look for any posible extension_ match
                   10269:     foreach my $package (@extension) {
                   10270: 	my ($package,$pack_type)=@{$package};
                   10271: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10272: 	    return $packagetab{"$pack_type&$name&default"};
                   10273: 	}
                   10274: 	if (defined($packagetab{$package."&$name&default"})) {
                   10275: 	    return $packagetab{$package."&$name&default"};
                   10276: 	}
                   10277:     }
                   10278:     # look for a global default setting
                   10279:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10280: 	return $packagetab{"default&$name&default"};
                   10281:     }
1.395     albertel 10282:     return undef;
                   10283: }
                   10284: 
1.334     albertel 10285: sub add_prefix_and_part {
                   10286:     my ($prefix,$part)=@_;
                   10287:     my $keyroot;
                   10288:     if (defined($prefix) && $prefix !~ /^__/) {
                   10289: 	# prefix that has a part already
                   10290: 	$keyroot=$prefix;
                   10291:     } elsif (defined($prefix)) {
                   10292: 	# prefix that is missing a part
                   10293: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10294:     } else {
                   10295: 	# no prefix at all
                   10296: 	if (defined($part)) { $keyroot='_'.$part; }
                   10297:     }
                   10298:     return $keyroot;
                   10299: }
                   10300: 
1.71      www      10301: # ---------------------------------------------------------------- Get metadata
                   10302: 
1.599     albertel 10303: my %metaentry;
1.1070    www      10304: my %importedpartids;
1.71      www      10305: sub metadata {
1.176     www      10306:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10307:     $uri=&declutter($uri);
1.288     albertel 10308:     # if it is a non metadata possible uri return quickly
1.529     albertel 10309:     if (($uri eq '') || 
                   10310: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10311: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10312:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10313: 	return undef;
                   10314:     }
1.1172.2.49  raeburn  10315:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10316: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10317: 	return undef;
1.288     albertel 10318:     }
1.73      www      10319:     my $filename=$uri;
                   10320:     $uri=~s/\.meta$//;
1.172     www      10321: #
                   10322: # Is the metadata already cached?
1.177     www      10323: # Look at timestamp of caching
1.172     www      10324: # Everything is cached by the main uri, libraries are never directly cached
                   10325: #
1.428     albertel 10326:     if (!defined($liburi)) {
1.599     albertel 10327: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10328: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10329:     }
                   10330:     {
1.1069    www      10331: # Imported parts would go here
1.1070    www      10332:         my %importedids=();
                   10333:         my @origfileimportpartids=();
1.1069    www      10334:         my $importedparts=0;
1.172     www      10335: #
                   10336: # Is this a recursive call for a library?
                   10337: #
1.599     albertel 10338: #	if (! exists($metacache{$uri})) {
                   10339: #	    $metacache{$uri}={};
                   10340: #	}
1.924     albertel 10341: 	my $cachetime = 60*60;
1.171     www      10342:         if ($liburi) {
                   10343: 	    $liburi=&declutter($liburi);
                   10344:             $filename=$liburi;
1.401     bowersj2 10345:         } else {
1.599     albertel 10346: 	    &devalidate_cache_new('meta',$uri);
                   10347: 	    undef(%metaentry);
1.401     bowersj2 10348: 	}
1.140     www      10349:         my %metathesekeys=();
1.73      www      10350:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10351: 	my $metastring;
1.1140    www      10352: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10353: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10354: 	    $metastring = 
1.929     albertel 10355: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10356: 					  ('grade_target' => 'meta'));
                   10357: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10358: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10359:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10360: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10361: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10362: 	    $metastring=&getfile($file);
1.489     albertel 10363: 	}
1.208     albertel 10364:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10365:         my $token;
1.140     www      10366:         undef %metathesekeys;
1.71      www      10367:         while ($token=$parser->get_token) {
1.339     albertel 10368: 	    if ($token->[0] eq 'S') {
                   10369: 		if (defined($token->[2]->{'package'})) {
1.172     www      10370: #
                   10371: # This is a package - get package info
                   10372: #
1.339     albertel 10373: 		    my $package=$token->[2]->{'package'};
                   10374: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10375: 		    if (defined($token->[2]->{'id'})) { 
                   10376: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10377: 		    }
1.599     albertel 10378: 		    if ($metaentry{':packages'}) {
                   10379: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10380: 		    } else {
1.599     albertel 10381: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10382: 		    }
1.736     albertel 10383: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10384: 			my $part=$keyroot;
                   10385: 			$part=~s/^\_//;
1.736     albertel 10386: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10387: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10388: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10389: 			    # ignore package.tab specified default values
                   10390:                             # here &package_tab_default() will fetch those
                   10391: 			    if ($subp eq 'default') { next; }
1.736     albertel 10392: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10393: 			    my $unikey;
                   10394: 			    if ($pack =~ /_0$/) {
                   10395: 				$unikey='parameter_0_'.$name;
                   10396: 				$part=0;
                   10397: 			    } else {
                   10398: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10399: 			    }
1.339     albertel 10400: 			    if ($subp eq 'display') {
                   10401: 				$value.=' [Part: '.$part.']';
                   10402: 			    }
1.599     albertel 10403: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10404: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10405: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10406: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10407: 			    }
1.599     albertel 10408: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10409: 				$metaentry{':'.$unikey}=
                   10410: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10411: 			    }
1.339     albertel 10412: 			}
                   10413: 		    }
                   10414: 		} else {
1.172     www      10415: #
                   10416: # This is not a package - some other kind of start tag
1.339     albertel 10417: #
                   10418: 		    my $entry=$token->[1];
1.1068    www      10419: 		    my $unikey='';
1.175     www      10420: 
1.339     albertel 10421: 		    if ($entry eq 'import') {
1.175     www      10422: #
                   10423: # Importing a library here
1.339     albertel 10424: #
1.1067    www      10425:                         my $location=$parser->get_text('/import');
                   10426:                         my $dir=$filename;
                   10427:                         $dir=~s|[^/]*$||;
                   10428:                         $location=&filelocation($dir,$location);
1.1069    www      10429:                        
1.1068    www      10430:                         my $importmode=$token->[2]->{'importmode'};
                   10431:                         if ($importmode eq 'problem') {
1.1069    www      10432: # Import as problem/response
1.1068    www      10433:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10434:                         } elsif ($importmode eq 'part') {
                   10435: # Import as part(s)
1.1069    www      10436:                            $importedparts=1;
                   10437: # We need to get the original file and the imported file to get the part order correct
                   10438: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10439: # Load and inspect original file
1.1070    www      10440:                            if ($#origfileimportpartids<0) {
                   10441:                               undef(%importedpartids);
                   10442:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10443:                               my $origfile=&getfile($origfilelocation);
                   10444:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10445:                            }
                   10446: 
1.1069    www      10447: # Load and inspect imported file
                   10448:                            my $impfile=&getfile($location);
                   10449:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10450:                            if ($#impfilepartids>=0) {
                   10451: # This problem had parts
1.1070    www      10452:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10453:                            } else {
                   10454: # Importing by turning a single problem into a problem part
                   10455: # It gets the import-tags ID as part-ID
                   10456:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10457:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10458:                            }
1.1068    www      10459:                         } else {
                   10460: # Normal import
                   10461:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10462:                            if (defined($token->[2]->{'id'})) {
                   10463:                               $unikey.='_'.$token->[2]->{'id'};
                   10464:                            }
1.1067    www      10465:                         }
                   10466: 
1.339     albertel 10467: 			if ($depthcount<20) {
1.736     albertel 10468: 			    my $metadata = 
                   10469: 				&metadata($uri,'keys', $location,$unikey,
                   10470: 					  $depthcount+1);
                   10471: 			    foreach my $meta (split(',',$metadata)) {
                   10472: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10473: 				$metathesekeys{$meta}=1;
1.339     albertel 10474: 			    }
1.1068    www      10475: 			
                   10476:                         }
1.1067    www      10477: 		    } else {
                   10478: #
                   10479: # Not importing, some other kind of non-package, non-library start tag
                   10480: # 
                   10481:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10482:                         if (defined($token->[2]->{'id'})) {
                   10483:                             $unikey.='_'.$token->[2]->{'id'};
                   10484:                         }
1.339     albertel 10485: 			if (defined($token->[2]->{'name'})) { 
                   10486: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10487: 			}
                   10488: 			$metathesekeys{$unikey}=1;
1.736     albertel 10489: 			foreach my $param (@{$token->[3]}) {
                   10490: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10491: 				$token->[2]->{$param};
1.339     albertel 10492: 			}
                   10493: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10494: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10495: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10496: 		 # only ws inside the tag, and not in default, so use default
                   10497: 		 # as value
1.599     albertel 10498: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10499: 			} elsif ( $internaltext =~ /\S/ ) {
                   10500: 		  # something interesting inside the tag
                   10501: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10502: 			} else {
1.908     albertel 10503: 		  # no interesting values, don't set a default
1.339     albertel 10504: 			}
1.172     www      10505: # end of not-a-package not-a-library import
1.339     albertel 10506: 		    }
1.172     www      10507: # end of not-a-package start tag
1.339     albertel 10508: 		}
1.172     www      10509: # the next is the end of "start tag"
1.339     albertel 10510: 	    }
                   10511: 	}
1.483     albertel 10512: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10513: 	$extension = lc($extension);
                   10514: 	if ($extension eq 'htm') { $extension='html'; }
                   10515: 
1.737     albertel 10516: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10517: 	    #no specific packages #how's our extension
                   10518: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10519: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10520: 					 \%metathesekeys);
                   10521: 	}
1.883     albertel 10522: 
                   10523: 	if (!exists($metaentry{':packages'})
                   10524: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10525: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10526: 		#no specific packages well let's get default then
                   10527: 		if ($key!~/^default&/) { next; }
1.488     albertel 10528: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10529: 					     \%metathesekeys);
                   10530: 	    }
                   10531: 	}
1.338     www      10532: # are there custom rights to evaluate
1.599     albertel 10533: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10534: 
1.338     www      10535:     #
                   10536:     # Importing a rights file here
1.339     albertel 10537:     #
                   10538: 	    unless ($depthcount) {
1.599     albertel 10539: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10540: 		my $dir=$filename;
                   10541: 		$dir=~s|[^/]*$||;
                   10542: 		$location=&filelocation($dir,$location);
1.736     albertel 10543: 		my $rights_metadata =
                   10544: 		    &metadata($uri,'keys',$location,'_rights',
                   10545: 			      $depthcount+1);
                   10546: 		foreach my $rights (split(',',$rights_metadata)) {
                   10547: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10548: 		    $metathesekeys{$rights}=1;
1.339     albertel 10549: 		}
                   10550: 	    }
                   10551: 	}
1.737     albertel 10552: 	# uniqifiy package listing
                   10553: 	my %seen;
                   10554: 	my @uniq_packages =
                   10555: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10556: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10557: 
1.1070    www      10558:         if ($importedparts) {
                   10559: # We had imported parts and need to rebuild partorder
                   10560:            $metaentry{':partorder'}='';
                   10561:            $metathesekeys{'partorder'}=1;
                   10562:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10563:                if ($origfileimportpartids[$index] eq 'part') {
                   10564: # original part, part of the problem
                   10565:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10566:                } else {
                   10567: # we have imported parts at this position
                   10568:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10569:                }
                   10570:            }
                   10571:            $metaentry{':partorder'}=~s/^\,//;
                   10572:         }
                   10573: 
1.737     albertel 10574: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10575: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10576: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10577: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10578: # this is the end of "was not already recently cached
1.71      www      10579:     }
1.599     albertel 10580:     return $metaentry{':'.$what};
1.261     albertel 10581: }
                   10582: 
1.488     albertel 10583: sub metadata_create_package_def {
1.483     albertel 10584:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10585:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10586:     if ($subp eq 'default') { next; }
                   10587:     
1.599     albertel 10588:     if (defined($metaentry{':packages'})) {
                   10589: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10590:     } else {
1.599     albertel 10591: 	$metaentry{':packages'}=$package;
1.483     albertel 10592:     }
                   10593:     my $value=$packagetab{$key};
                   10594:     my $unikey;
                   10595:     $unikey='parameter_0_'.$name;
1.599     albertel 10596:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10597:     $$metathesekeys{$unikey}=1;
1.599     albertel 10598:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10599: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10600:     }
1.599     albertel 10601:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10602: 	$metaentry{':'.$unikey}=
                   10603: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10604:     }
                   10605: }
                   10606: 
1.261     albertel 10607: sub metadata_generate_part0 {
                   10608:     my ($metadata,$metacache,$uri) = @_;
                   10609:     my %allnames;
1.737     albertel 10610:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10611: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10612: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10613: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10614: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10615: 	    $allnames{$name}=$part;
                   10616: 	  }
                   10617: 	}
                   10618:     }
                   10619:     foreach my $name (keys(%allnames)) {
                   10620:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10621:       my $key=":parameter_0_$name";
1.261     albertel 10622:       $$metacache{"$key.part"}='0';
                   10623:       $$metacache{"$key.name"}=$name;
1.428     albertel 10624:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10625: 					   $allnames{$name}.'_'.$name.
                   10626: 					   '.type'};
1.428     albertel 10627:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10628: 			     '.display'};
1.644     www      10629:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10630:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10631:       $$metacache{"$key.display"}=$olddis;
                   10632:     }
1.71      www      10633: }
                   10634: 
1.764     albertel 10635: # ------------------------------------------------------ Devalidate title cache
                   10636: 
                   10637: sub devalidate_title_cache {
                   10638:     my ($url)=@_;
                   10639:     if (!$env{'request.course.id'}) { return; }
                   10640:     my $symb=&symbread($url);
                   10641:     if (!$symb) { return; }
                   10642:     my $key=$env{'request.course.id'}."\0".$symb;
                   10643:     &devalidate_cache_new('title',$key);
                   10644: }
                   10645: 
1.1014    droeschl 10646: # ------------------------------------------------- Get the title of a course
                   10647: 
                   10648: sub current_course_title {
                   10649:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10650: }
1.301     www      10651: # ------------------------------------------------- Get the title of a resource
                   10652: 
                   10653: sub gettitle {
                   10654:     my $urlsymb=shift;
                   10655:     my $symb=&symbread($urlsymb);
1.534     albertel 10656:     if ($symb) {
1.620     albertel 10657: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10658: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10659: 	if (defined($cached)) { 
                   10660: 	    return $result;
                   10661: 	}
1.534     albertel 10662: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10663: 	my $title='';
1.907     albertel 10664: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10665: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10666: 	} else {
                   10667: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10668: 		    &GDBM_READER(),0640)) {
                   10669: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10670: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10671: 		untie(%bighash);
                   10672: 	    }
1.534     albertel 10673: 	}
                   10674: 	$title=~s/\&colon\;/\:/gs;
                   10675: 	if ($title) {
1.1159    www      10676: # Remember both $symb and $title for dynamic metadata
                   10677:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10678:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10679: # Cache this title and then return it
1.599     albertel 10680: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10681: 	}
                   10682: 	$urlsymb=$url;
                   10683:     }
                   10684:     my $title=&metadata($urlsymb,'title');
                   10685:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10686:     return $title;
1.301     www      10687: }
1.613     albertel 10688: 
1.614     albertel 10689: sub get_slot {
                   10690:     my ($which,$cnum,$cdom)=@_;
                   10691:     if (!$cnum || !$cdom) {
1.790     albertel 10692: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10693: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10694: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10695:     }
1.703     albertel 10696:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10697:     my %slotinfo;
                   10698:     if (exists($remembered{$key})) {
                   10699: 	$slotinfo{$which} = $remembered{$key};
                   10700:     } else {
                   10701: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10702: 	&Apache::lonhomework::showhash(%slotinfo);
                   10703: 	my ($tmp)=keys(%slotinfo);
                   10704: 	if ($tmp=~/^error:/) { return (); }
                   10705: 	$remembered{$key} = $slotinfo{$which};
                   10706:     }
1.616     albertel 10707:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10708: 	return %{$slotinfo{$which}};
                   10709:     }
                   10710:     return $slotinfo{$which};
1.614     albertel 10711: }
1.1150    raeburn  10712: 
                   10713: sub get_reservable_slots {
                   10714:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10715:     my $now = time;
                   10716:     my $reservable_info;
                   10717:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10718:     if (exists($remembered{$key})) {
                   10719:         $reservable_info = $remembered{$key};
                   10720:     } else {
                   10721:         my %resv;
                   10722:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10723:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10724:         $reservable_info = \%resv;
                   10725:         $remembered{$key} = $reservable_info;
                   10726:     }
                   10727:     return $reservable_info;
                   10728: }
                   10729: 
                   10730: sub get_course_slots {
                   10731:     my ($cnum,$cdom) = @_;
                   10732:     my $hashid=$cnum.':'.$cdom;
                   10733:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10734:     if (defined($cached)) {
                   10735:         if (ref($result) eq 'HASH') {
                   10736:             return %{$result};
                   10737:         }
                   10738:     } else {
                   10739:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10740:         my ($tmp) = keys(%slots);
                   10741:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  10742:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10743:             return %slots;
                   10744:         }
                   10745:     }
                   10746:     return;
                   10747: }
                   10748: 
                   10749: sub devalidate_slots_cache {
                   10750:     my ($cnum,$cdom)=@_;
                   10751:     my $hashid=$cnum.':'.$cdom;
                   10752:     &devalidate_cache_new('allslots',$hashid);
                   10753: }
                   10754: 
1.1172.2.8  raeburn  10755: sub get_coursechange {
                   10756:     my ($cdom,$cnum) = @_;
                   10757:     if ($cdom eq '' || $cnum eq '') {
                   10758:         return unless ($env{'request.course.id'});
                   10759:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10760:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10761:     }
                   10762:     my $hashid=$cdom.'_'.$cnum;
                   10763:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10764:     if ((defined($cached)) && ($change ne '')) {
                   10765:         return $change;
                   10766:     } else {
                   10767:         my %crshash;
                   10768:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10769:         if ($crshash{'internal.contentchange'} eq '') {
                   10770:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10771:             if ($change eq '') {
                   10772:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10773:                 $change = $crshash{'internal.created'};
                   10774:             }
                   10775:         } else {
                   10776:             $change = $crshash{'internal.contentchange'};
                   10777:         }
                   10778:         my $cachetime = 600;
                   10779:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10780:     }
                   10781:     return $change;
                   10782: }
                   10783: 
                   10784: sub devalidate_coursechange_cache {
                   10785:     my ($cnum,$cdom)=@_;
                   10786:     my $hashid=$cnum.':'.$cdom;
                   10787:     &devalidate_cache_new('crschange',$hashid);
                   10788: }
                   10789: 
1.31      www      10790: # ------------------------------------------------- Update symbolic store links
                   10791: 
                   10792: sub symblist {
                   10793:     my ($mapname,%newhash)=@_;
1.438     www      10794:     $mapname=&deversion(&declutter($mapname));
1.31      www      10795:     my %hash;
1.620     albertel 10796:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10797:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10798:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10799: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10800: 		next if ($url eq 'last_known'
                   10801: 			 && $env{'form.no_update_last_known'});
                   10802: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10803: 						    $newhash{$url}->[1],
                   10804: 						    $newhash{$url}->[0]);
1.191     harris41 10805:             }
1.31      www      10806:             if (untie(%hash)) {
                   10807: 		return 'ok';
                   10808:             }
                   10809:         }
                   10810:     }
                   10811:     return 'error';
1.212     www      10812: }
                   10813: 
                   10814: # --------------------------------------------------------------- Verify a symb
                   10815: 
                   10816: sub symbverify {
1.1172.2.11  raeburn  10817:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10818:     my $thisfn=$thisurl;
1.439     www      10819:     $thisfn=&declutter($thisfn);
1.215     www      10820: # direct jump to resource in page or to a sequence - will construct own symbs
                   10821:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10822: # check URL part
1.409     www      10823:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10824: 
1.431     www      10825:     unless ($url eq $thisfn) { return 0; }
1.213     www      10826: 
1.216     www      10827:     $symb=&symbclean($symb);
1.510     www      10828:     $thisurl=&deversion($thisurl);
1.439     www      10829:     $thisfn=&deversion($thisfn);
1.213     www      10830: 
                   10831:     my %bighash;
                   10832:     my $okay=0;
1.431     www      10833: 
1.620     albertel 10834:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10835:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10836:         my $noclutter;
1.1032    raeburn  10837:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10838:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10839:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10840:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10841:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10842:                 $noclutter = 1;
                   10843:             }
                   10844:         }
                   10845:         my $ids;
                   10846:         if ($noclutter) {
                   10847:             $ids=$bighash{'ids_'.$thisurl};
                   10848:         } else {
                   10849:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10850:         }
1.1102    raeburn  10851:         unless ($ids) {
1.1172.2.13  raeburn  10852:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10853:             $ids=$bighash{$idkey};
1.216     www      10854:         }
                   10855:         if ($ids) {
                   10856: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10857:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10858:                 $symb =~ s/\?.+$//;
                   10859:             }
1.800     albertel 10860: 	    foreach my $id (split(/\,/,$ids)) {
                   10861: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10862:                if (
                   10863:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10864:    eq $symb) {
1.1172.2.11  raeburn  10865:                    if (ref($encstate)) {
                   10866:                        $$encstate = $bighash{'encrypted_'.$id};
                   10867:                    }
1.1172.2.13  raeburn  10868:                    if (($env{'request.role.adv'}) ||
                   10869:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10870:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10871:                        $okay=1;
                   10872:                        last;
                   10873:                    }
                   10874:                }
                   10875:            }
1.216     www      10876:         }
1.213     www      10877: 	untie(%bighash);
                   10878:     }
                   10879:     return $okay;
1.31      www      10880: }
                   10881: 
1.210     www      10882: # --------------------------------------------------------------- Clean-up symb
                   10883: 
                   10884: sub symbclean {
                   10885:     my $symb=shift;
1.568     albertel 10886:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10887: # remove version from map
                   10888:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10889: 
1.210     www      10890: # remove version from URL
                   10891:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10892: 
1.507     www      10893: # remove wrapper
                   10894: 
1.510     www      10895:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10896:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10897:     return $symb;
1.409     www      10898: }
                   10899: 
                   10900: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10901: 
                   10902: sub encode_symb {
                   10903:     my ($map,$resid,$url)=@_;
                   10904:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10905: }
1.409     www      10906: 
                   10907: sub decode_symb {
1.568     albertel 10908:     my $symb=shift;
                   10909:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10910:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10911:     return (&fixversion($map),$resid,&fixversion($url));
                   10912: }
                   10913: 
                   10914: sub fixversion {
                   10915:     my $fn=shift;
1.609     banghart 10916:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10917:     my %bighash;
                   10918:     my $uri=&clutter($fn);
1.620     albertel 10919:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10920: # is this cached?
1.599     albertel 10921:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10922:     if (defined($cached)) { return $result; }
                   10923: # unfortunately not cached, or expired
1.620     albertel 10924:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10925: 	    &GDBM_READER(),0640)) {
                   10926:  	if ($bighash{'version_'.$uri}) {
                   10927:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10928:  	    unless (($version eq 'mostrecent') || 
                   10929: 		    ($version==&getversion($uri))) {
1.440     www      10930:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10931:  	    }
                   10932:  	}
                   10933:  	untie %bighash;
1.413     www      10934:     }
1.599     albertel 10935:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10936: }
                   10937: 
                   10938: sub deversion {
                   10939:     my $url=shift;
                   10940:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10941:     return $url;
1.210     www      10942: }
                   10943: 
1.31      www      10944: # ------------------------------------------------------ Return symb list entry
                   10945: 
                   10946: sub symbread {
1.249     www      10947:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.54  raeburn  10948:     my $cache_str='request.symbread.cached.'.$thisfn;
                   10949:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      10950: # no filename provided? try from environment
1.1172.2.54  raeburn  10951:     unless ($thisfn) {
1.620     albertel 10952:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10953:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10954:         }
                   10955:         $thisfn=$env{'request.filename'};
1.44      www      10956:     }
1.569     albertel 10957:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10958: # is that filename actually a symb? Verify, clean, and return
                   10959:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10960: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10961: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10962: 	}
1.242     www      10963:     }
1.44      www      10964:     $thisfn=declutter($thisfn);
1.31      www      10965:     my %hash;
1.37      www      10966:     my %bighash;
                   10967:     my $syval='';
1.620     albertel 10968:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10969:         my $targetfn = $thisfn;
1.609     banghart 10970:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10971:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10972:         }
1.687     albertel 10973: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10974: 	    $targetfn=$1;
                   10975: 	}
1.620     albertel 10976:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10977:                       &GDBM_READER(),0640)) {
1.481     raeburn  10978: 	    $syval=$hash{$targetfn};
1.37      www      10979:             untie(%hash);
                   10980:         }
                   10981: # ---------------------------------------------------------- There was an entry
                   10982:         if ($syval) {
1.601     albertel 10983: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10984: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10985: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10986: 		    #return $env{$cache_str}='';
1.601     albertel 10987: 		#}    
                   10988: 		#$syval.=$1;
                   10989: 	    #}
1.37      www      10990:         } else {
                   10991: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10992:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10993:                             &GDBM_READER(),0640)) {
1.37      www      10994: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10995:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10996:               unless ($ids) { 
                   10997:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10998:               }
                   10999:               unless ($ids) {
                   11000: # alias?
                   11001: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11002:               }
1.37      www      11003:               if ($ids) {
                   11004: # ------------------------------------------------------------------- Has ID(s)
                   11005:                  my @possibilities=split(/\,/,$ids);
1.39      www      11006:                  if ($#possibilities==0) {
                   11007: # ----------------------------------------------- There is only one possibility
1.37      www      11008: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11009: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11010: 						    $resid,$thisfn);
1.249     www      11011:                  } elsif (!$donotrecurse) {
1.39      www      11012: # ------------------------------------------ There is more than one possibility
                   11013:                      my $realpossible=0;
1.800     albertel 11014:                      foreach my $id (@possibilities) {
                   11015: 			 my $file=$bighash{'src_'.$id};
1.39      www      11016:                          if (&allowed('bre',$file)) {
1.800     albertel 11017:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      11018:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11019: 				$realpossible++;
1.626     albertel 11020:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11021: 						    $resid,$thisfn);
1.39      www      11022:                             }
                   11023: 			 }
1.191     harris41 11024:                      }
1.39      www      11025: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11026:                  } else {
                   11027:                      $syval='';
1.37      www      11028:                  }
                   11029: 	      }
                   11030:               untie(%bighash)
1.481     raeburn  11031:            }
1.31      www      11032:         }
1.62      www      11033:         if ($syval) {
1.620     albertel 11034: 	    return $env{$cache_str}=$syval;
1.62      www      11035:         }
1.31      www      11036:     }
1.949     raeburn  11037:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11038:     return $env{$cache_str}='';
1.31      www      11039: }
                   11040: 
                   11041: # ---------------------------------------------------------- Return random seed
                   11042: 
1.32      www      11043: sub numval {
                   11044:     my $txt=shift;
                   11045:     $txt=~tr/A-J/0-9/;
                   11046:     $txt=~tr/a-j/0-9/;
                   11047:     $txt=~tr/K-T/0-9/;
                   11048:     $txt=~tr/k-t/0-9/;
                   11049:     $txt=~tr/U-Z/0-5/;
                   11050:     $txt=~tr/u-z/0-5/;
                   11051:     $txt=~s/\D//g;
1.564     albertel 11052:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11053:     return int($txt);
1.368     albertel 11054: }
                   11055: 
1.484     albertel 11056: sub numval2 {
                   11057:     my $txt=shift;
                   11058:     $txt=~tr/A-J/0-9/;
                   11059:     $txt=~tr/a-j/0-9/;
                   11060:     $txt=~tr/K-T/0-9/;
                   11061:     $txt=~tr/k-t/0-9/;
                   11062:     $txt=~tr/U-Z/0-5/;
                   11063:     $txt=~tr/u-z/0-5/;
                   11064:     $txt=~s/\D//g;
                   11065:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11066:     my $total;
                   11067:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11068:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11069:     return int($total);
                   11070: }
                   11071: 
1.575     albertel 11072: sub numval3 {
                   11073:     use integer;
                   11074:     my $txt=shift;
                   11075:     $txt=~tr/A-J/0-9/;
                   11076:     $txt=~tr/a-j/0-9/;
                   11077:     $txt=~tr/K-T/0-9/;
                   11078:     $txt=~tr/k-t/0-9/;
                   11079:     $txt=~tr/U-Z/0-5/;
                   11080:     $txt=~tr/u-z/0-5/;
                   11081:     $txt=~s/\D//g;
                   11082:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11083:     my $total;
                   11084:     foreach my $val (@txts) { $total+=$val; }
                   11085:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11086:     return $total;
                   11087: }
                   11088: 
1.675     albertel 11089: sub digest {
                   11090:     my ($data)=@_;
                   11091:     my $digest=&Digest::MD5::md5($data);
                   11092:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11093:     my ($e,$f);
                   11094:     {
                   11095:         use integer;
                   11096:         $e=($a+$b);
                   11097:         $f=($c+$d);
                   11098:         if ($_64bit) {
                   11099:             $e=(($e<<32)>>32);
                   11100:             $f=(($f<<32)>>32);
                   11101:         }
                   11102:     }
                   11103:     if (wantarray) {
                   11104: 	return ($e,$f);
                   11105:     } else {
                   11106: 	my $g;
                   11107: 	{
                   11108: 	    use integer;
                   11109: 	    $g=($e+$f);
                   11110: 	    if ($_64bit) {
                   11111: 		$g=(($g<<32)>>32);
                   11112: 	    }
                   11113: 	}
                   11114: 	return $g;
                   11115:     }
                   11116: }
                   11117: 
1.368     albertel 11118: sub latest_rnd_algorithm_id {
1.675     albertel 11119:     return '64bit5';
1.366     albertel 11120: }
1.32      www      11121: 
1.503     albertel 11122: sub get_rand_alg {
                   11123:     my ($courseid)=@_;
1.790     albertel 11124:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11125:     if ($courseid) {
1.620     albertel 11126: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11127:     }
                   11128:     return &latest_rnd_algorithm_id();
                   11129: }
                   11130: 
1.562     albertel 11131: sub validCODE {
                   11132:     my ($CODE)=@_;
                   11133:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11134:     return 0;
                   11135: }
                   11136: 
1.491     albertel 11137: sub getCODE {
1.620     albertel 11138:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11139:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11140: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11141: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11142: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11143:     }
                   11144:     return undef;
                   11145: }
1.1133    foxr     11146: #
                   11147: #  Determines the random seed for a specific context:
                   11148: #
                   11149: # parameters:
                   11150: #   symb      - in course context the symb for the seed.
                   11151: #   course_id - The course id of the form domain_coursenum.
                   11152: #   domain    - Domain for the user.
                   11153: #   course    - Course for the user.
                   11154: #   cenv      - environment of the course.
                   11155: #
                   11156: # NOTE:
                   11157: #   All parameters are picked out of the environment if missing
                   11158: #   or not defined.
                   11159: #   If a symb cannot be determined the current time is used instead.
                   11160: #
                   11161: #  For a given well defined symb, courside, domain, username,
                   11162: #  and course environment, the seed is reproducible.
                   11163: #
1.31      www      11164: sub rndseed {
1.1133    foxr     11165:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11166:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11167:     if (!defined($symb)) {
1.366     albertel 11168: 	unless ($symb=$wsymb) { return time; }
                   11169:     }
1.1146    foxr     11170:     if (!defined $courseid) { 
                   11171: 	$courseid=$wcourseid; 
                   11172:     }
                   11173:     if (!defined $domain) { $domain=$wdomain; }
                   11174:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11175: 
                   11176:     my $which;
                   11177:     if (defined($cenv->{'rndseed'})) {
                   11178: 	$which = $cenv->{'rndseed'};
                   11179:     } else {
                   11180: 	$which =&get_rand_alg($courseid);
                   11181:     }
1.491     albertel 11182:     if (defined(&getCODE())) {
1.675     albertel 11183: 	if ($which eq '64bit5') {
                   11184: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11185: 	} elsif ($which eq '64bit4') {
1.575     albertel 11186: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11187: 	} else {
                   11188: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11189: 	}
1.675     albertel 11190:     } elsif ($which eq '64bit5') {
                   11191: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11192:     } elsif ($which eq '64bit4') {
                   11193: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11194:     } elsif ($which eq '64bit3') {
                   11195: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11196:     } elsif ($which eq '64bit2') {
                   11197: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11198:     } elsif ($which eq '64bit') {
                   11199: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11200:     }
                   11201:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11202: }
                   11203: 
                   11204: sub rndseed_32bit {
                   11205:     my ($symb,$courseid,$domain,$username)=@_;
                   11206:     {
                   11207: 	use integer;
                   11208: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11209: 	my $symbseed=numval($symb) << 22;
                   11210: 	my $namechck=unpack("%32C*",$username) << 17;
                   11211: 	my $nameseed=numval($username) << 12;
                   11212: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11213: 	my $courseseed=unpack("%32C*",$courseid);
                   11214: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11215: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11216: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11217: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11218: 	return $num;
                   11219:     }
                   11220: }
                   11221: 
                   11222: sub rndseed_64bit {
                   11223:     my ($symb,$courseid,$domain,$username)=@_;
                   11224:     {
                   11225: 	use integer;
                   11226: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11227: 	my $symbseed=numval($symb) << 10;
                   11228: 	my $namechck=unpack("%32S*",$username);
                   11229: 	
                   11230: 	my $nameseed=numval($username) << 21;
                   11231: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11232: 	my $courseseed=unpack("%32S*",$courseid);
                   11233: 	
                   11234: 	my $num1=$symbchck+$symbseed+$namechck;
                   11235: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11236: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11237: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11238: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11239: 	return "$num1,$num2";
1.155     albertel 11240:     }
1.366     albertel 11241: }
                   11242: 
1.443     albertel 11243: sub rndseed_64bit2 {
                   11244:     my ($symb,$courseid,$domain,$username)=@_;
                   11245:     {
                   11246: 	use integer;
                   11247: 	# strings need to be an even # of cahracters long, it it is odd the
                   11248:         # last characters gets thrown away
                   11249: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11250: 	my $symbseed=numval($symb) << 10;
                   11251: 	my $namechck=unpack("%32S*",$username.' ');
                   11252: 	
                   11253: 	my $nameseed=numval($username) << 21;
1.501     albertel 11254: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11255: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11256: 	
                   11257: 	my $num1=$symbchck+$symbseed+$namechck;
                   11258: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11259: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11260: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11261: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11262: 	return "$num1,$num2";
                   11263:     }
                   11264: }
                   11265: 
                   11266: sub rndseed_64bit3 {
                   11267:     my ($symb,$courseid,$domain,$username)=@_;
                   11268:     {
                   11269: 	use integer;
                   11270: 	# strings need to be an even # of cahracters long, it it is odd the
                   11271:         # last characters gets thrown away
                   11272: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11273: 	my $symbseed=numval2($symb) << 10;
                   11274: 	my $namechck=unpack("%32S*",$username.' ');
                   11275: 	
                   11276: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11277: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11278: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11279: 	
                   11280: 	my $num1=$symbchck+$symbseed+$namechck;
                   11281: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11282: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11283: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11284: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11285: 	
1.503     albertel 11286: 	return "$num1:$num2";
1.443     albertel 11287:     }
                   11288: }
                   11289: 
1.575     albertel 11290: sub rndseed_64bit4 {
                   11291:     my ($symb,$courseid,$domain,$username)=@_;
                   11292:     {
                   11293: 	use integer;
                   11294: 	# strings need to be an even # of cahracters long, it it is odd the
                   11295:         # last characters gets thrown away
                   11296: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11297: 	my $symbseed=numval3($symb) << 10;
                   11298: 	my $namechck=unpack("%32S*",$username.' ');
                   11299: 	
                   11300: 	my $nameseed=numval3($username) << 21;
                   11301: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11302: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11303: 	
                   11304: 	my $num1=$symbchck+$symbseed+$namechck;
                   11305: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11306: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11307: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11308: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11309: 	
1.575     albertel 11310: 	return "$num1:$num2";
                   11311:     }
                   11312: }
                   11313: 
1.675     albertel 11314: sub rndseed_64bit5 {
                   11315:     my ($symb,$courseid,$domain,$username)=@_;
                   11316:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11317:     return "$num1:$num2";
                   11318: }
                   11319: 
1.366     albertel 11320: sub rndseed_CODE_64bit {
                   11321:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11322:     {
1.366     albertel 11323: 	use integer;
1.443     albertel 11324: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11325: 	my $symbseed=numval2($symb);
1.491     albertel 11326: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11327: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11328: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11329: 	my $num1=$symbseed+$CODEchck;
                   11330: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11331: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11332: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11333: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11334: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11335: 	return "$num1:$num2";
1.366     albertel 11336:     }
                   11337: }
                   11338: 
1.575     albertel 11339: sub rndseed_CODE_64bit4 {
                   11340:     my ($symb,$courseid,$domain,$username)=@_;
                   11341:     {
                   11342: 	use integer;
                   11343: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11344: 	my $symbseed=numval3($symb);
                   11345: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11346: 	my $CODEseed=numval3(&getCODE());
                   11347: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11348: 	my $num1=$symbseed+$CODEchck;
                   11349: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11350: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11351: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11352: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11353: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11354: 	return "$num1:$num2";
                   11355:     }
                   11356: }
                   11357: 
1.675     albertel 11358: sub rndseed_CODE_64bit5 {
                   11359:     my ($symb,$courseid,$domain,$username)=@_;
                   11360:     my $code = &getCODE();
                   11361:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11362:     return "$num1:$num2";
                   11363: }
                   11364: 
1.366     albertel 11365: sub setup_random_from_rndseed {
                   11366:     my ($rndseed)=@_;
1.503     albertel 11367:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  11368: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11369:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11370:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11371:         } else {
                   11372:             &Math::Random::random_set_seed($num1,$num2);
                   11373:         }
1.366     albertel 11374:     } else {
                   11375: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11376:     }
1.36      albertel 11377: }
                   11378: 
1.474     albertel 11379: sub latest_receipt_algorithm_id {
1.835     albertel 11380:     return 'receipt3';
1.474     albertel 11381: }
                   11382: 
1.480     www      11383: sub recunique {
                   11384:     my $fucourseid=shift;
                   11385:     my $unique;
1.835     albertel 11386:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11387: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11388: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11389:     } else {
                   11390: 	$unique=$perlvar{'lonReceipt'};
                   11391:     }
                   11392:     return unpack("%32C*",$unique);
                   11393: }
                   11394: 
                   11395: sub recprefix {
                   11396:     my $fucourseid=shift;
                   11397:     my $prefix;
1.835     albertel 11398:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11399: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11400: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11401:     } else {
                   11402: 	$prefix=$perlvar{'lonHostID'};
                   11403:     }
                   11404:     return unpack("%32C*",$prefix);
                   11405: }
                   11406: 
1.76      www      11407: sub ireceipt {
1.474     albertel 11408:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11409: 
                   11410:     my $return =&recprefix($fucourseid).'-';
                   11411: 
                   11412:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11413: 	$env{'request.state'} eq 'construct') {
                   11414: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11415: 	return $return;
                   11416:     }
                   11417: 
1.76      www      11418:     my $cuname=unpack("%32C*",$funame);
                   11419:     my $cudom=unpack("%32C*",$fudom);
                   11420:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11421:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11422:     my $cunique=&recunique($fucourseid);
1.474     albertel 11423:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11424:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11425: 
1.790     albertel 11426: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11427: 			       
                   11428: 	$return.= ($cunique%$cuname+
                   11429: 		   $cunique%$cudom+
                   11430: 		   $cusymb%$cuname+
                   11431: 		   $cusymb%$cudom+
                   11432: 		   $cucourseid%$cuname+
                   11433: 		   $cucourseid%$cudom+
                   11434: 		   $cpart%$cuname+
                   11435: 		   $cpart%$cudom);
                   11436:     } else {
                   11437: 	$return.= ($cunique%$cuname+
                   11438: 		   $cunique%$cudom+
                   11439: 		   $cusymb%$cuname+
                   11440: 		   $cusymb%$cudom+
                   11441: 		   $cucourseid%$cuname+
                   11442: 		   $cucourseid%$cudom);
                   11443:     }
                   11444:     return $return;
1.76      www      11445: }
                   11446: 
                   11447: sub receipt {
1.474     albertel 11448:     my ($part)=@_;
1.790     albertel 11449:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11450:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11451: }
1.260     ng       11452: 
1.790     albertel 11453: sub whichuser {
                   11454:     my ($passedsymb)=@_;
                   11455:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11456:     if (defined($env{'form.grade_symb'})) {
                   11457: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11458: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11459: 	if (!$allowed &&
                   11460: 	    exists($env{'request.course.sec'}) &&
                   11461: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11462: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11463: 			      '/'.$env{'request.course.sec'});
                   11464: 	}
                   11465: 	if ($allowed) {
                   11466: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11467: 	    $courseid=$tmp_courseid;
                   11468: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11469: 	    ($name)=&get_env_multiple('form.grade_username');
                   11470: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11471: 	}
                   11472:     }
                   11473:     if (!$passedsymb) {
                   11474: 	$symb=&symbread();
                   11475:     } else {
                   11476: 	$symb=$passedsymb;
                   11477:     }
                   11478:     $courseid=$env{'request.course.id'};
                   11479:     $domain=$env{'user.domain'};
                   11480:     $name=$env{'user.name'};
                   11481:     if ($name eq 'public' && $domain eq 'public') {
                   11482: 	if (!defined($env{'form.username'})) {
                   11483: 	    $env{'form.username'}.=time.rand(10000000);
                   11484: 	}
                   11485: 	$name.=$env{'form.username'};
                   11486:     }
                   11487:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11488: 
                   11489: }
                   11490: 
1.36      albertel 11491: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11492: # returns either the contents of the file or 
                   11493: # -1 if the file doesn't exist
1.481     raeburn  11494: #
                   11495: # if the target is a file that was uploaded via DOCS, 
                   11496: # a check will be made to see if a current copy exists on the local server,
                   11497: # if it does this will be served, otherwise a copy will be retrieved from
                   11498: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11499: # the local server.   
1.472     albertel 11500: 
1.36      albertel 11501: sub getfile {
1.538     albertel 11502:     my ($file) = @_;
1.609     banghart 11503:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11504:     &repcopy($file);
                   11505:     return &readfile($file);
                   11506: }
                   11507: 
                   11508: sub repcopy_userfile {
                   11509:     my ($file)=@_;
1.1142    raeburn  11510:     my $londocroot = $perlvar{'lonDocRoot'};
                   11511:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11512:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11513:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11514: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11515:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11516:     if (-e "$file") {
1.828     www      11517: # we already have a local copy, check it out
1.538     albertel 11518: 	my @fileinfo = stat($file);
1.828     www      11519: 	my $rtncode;
                   11520: 	my $info;
1.538     albertel 11521: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11522: 	if ($lwpresp ne 'ok') {
1.828     www      11523: # there is no such file anymore, even though we had a local copy
1.482     albertel 11524: 	    if ($rtncode eq '404') {
1.538     albertel 11525: 		unlink($file);
1.482     albertel 11526: 	    }
                   11527: 	    return -1;
                   11528: 	}
                   11529: 	if ($info < $fileinfo[9]) {
1.828     www      11530: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11531: 	    return 'ok';
1.828     www      11532: 	} else {
                   11533: # the file is outdated, get rid of it
                   11534: 	    unlink($file);
1.482     albertel 11535: 	}
1.828     www      11536:     }
                   11537: # one way or the other, at this point, we don't have the file
                   11538: # construct the correct path for the file
                   11539:     my @parts = ($cdom,$cnum); 
                   11540:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11541: 	push @parts, split(/\//,$1);
                   11542:     }
                   11543:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11544:     foreach my $part (@parts) {
                   11545: 	$path .= '/'.$part;
                   11546: 	if (!-e $path) {
                   11547: 	    mkdir($path,0770);
1.482     albertel 11548: 	}
                   11549:     }
1.828     www      11550: # now the path exists for sure
                   11551: # get a user agent
                   11552:     my $ua=new LWP::UserAgent;
                   11553:     my $transferfile=$file.'.in.transfer';
                   11554: # FIXME: this should flock
                   11555:     if (-e $transferfile) { return 'ok'; }
                   11556:     my $request;
                   11557:     $uri=~s/^\///;
1.980     raeburn  11558:     my $homeserver = &homeserver($cnum,$cdom);
                   11559:     my $protocol = $protocol{$homeserver};
                   11560:     $protocol = 'http' if ($protocol ne 'https');
                   11561:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11562:     my $response=$ua->request($request,$transferfile);
                   11563: # did it work?
                   11564:     if ($response->is_error()) {
                   11565: 	unlink($transferfile);
                   11566: 	&logthis("Userfile repcopy failed for $uri");
                   11567: 	return -1;
                   11568:     }
                   11569: # worked, rename the transfer file
                   11570:     rename($transferfile,$file);
1.607     raeburn  11571:     return 'ok';
1.481     raeburn  11572: }
                   11573: 
1.517     albertel 11574: sub tokenwrapper {
                   11575:     my $uri=shift;
1.980     raeburn  11576:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11577:     $uri=~s|^/||;
1.620     albertel 11578:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11579:     my $token=$1;
1.552     albertel 11580:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11581:     if ($udom && $uname && $file) {
                   11582: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11583:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11584:         my $homeserver = &homeserver($uname,$udom);
                   11585:         my $protocol = $protocol{$homeserver};
                   11586:         $protocol = 'http' if ($protocol ne 'https');
                   11587:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11588:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11589:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11590:     } else {
                   11591:         return '/adm/notfound.html';
                   11592:     }
                   11593: }
                   11594: 
1.828     www      11595: # call with reqtype HEAD: get last modification time
                   11596: # call with reqtype GET: get the file contents
                   11597: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11598: #
1.481     raeburn  11599: sub getuploaded {
                   11600:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11601:     $uri=~s/^\///;
1.980     raeburn  11602:     my $homeserver = &homeserver($cnum,$cdom);
                   11603:     my $protocol = $protocol{$homeserver};
                   11604:     $protocol = 'http' if ($protocol ne 'https');
                   11605:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11606:     my $ua=new LWP::UserAgent;
                   11607:     my $request=new HTTP::Request($reqtype,$uri);
                   11608:     my $response=$ua->request($request);
                   11609:     $$rtncode = $response->code;
1.482     albertel 11610:     if (! $response->is_success()) {
                   11611: 	return 'failed';
                   11612:     }      
                   11613:     if ($reqtype eq 'HEAD') {
1.486     www      11614: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11615:     } elsif ($reqtype eq 'GET') {
                   11616: 	$$info = $response->content;
1.472     albertel 11617:     }
1.482     albertel 11618:     return 'ok';
1.36      albertel 11619: }
                   11620: 
1.481     raeburn  11621: sub readfile {
                   11622:     my $file = shift;
                   11623:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11624:     my $fh;
                   11625:     open($fh,"<$file");
                   11626:     my $a='';
1.800     albertel 11627:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11628:     return $a;
                   11629: }
                   11630: 
1.36      albertel 11631: sub filelocation {
1.590     banghart 11632:     my ($dir,$file) = @_;
                   11633:     my $location;
                   11634:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11635: 
                   11636:     if ($file =~ m-^/adm/-) {
                   11637: 	$file=~s-^/adm/wrapper/-/-;
                   11638: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11639:     }
1.882     albertel 11640: 
1.1139    www      11641:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11642:         $location = $file;
1.609     banghart 11643:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11644:         my ($udom,$uname,$filename)=
1.811     albertel 11645:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11646:         my $home=&homeserver($uname,$udom);
                   11647:         my $is_me=0;
                   11648:         my @ids=&current_machine_ids();
                   11649:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11650:         if ($is_me) {
1.1117    foxr     11651:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11652:         } else {
                   11653:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11654:   	      $udom.'/'.$uname.'/'.$filename;
                   11655:         }
1.882     albertel 11656:     } elsif ($file =~ m-^/adm/-) {
                   11657: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11658:     } else {
                   11659:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11660:         $file=~s:^/(res|priv)/:/:;
                   11661:         my $space=$1;
1.590     banghart 11662:         if ( !( $file =~ m:^/:) ) {
                   11663:             $location = $dir. '/'.$file;
                   11664:         } else {
1.1142    raeburn  11665:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11666:         }
1.59      albertel 11667:     }
1.590     banghart 11668:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11669:     while ($location=~m{/\.\./}) {
                   11670: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11671: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11672: 	} else {
                   11673: 	    $location=~ s{/\.\./}{/}g;
                   11674: 	}
                   11675:     } #remove dir/..
1.590     banghart 11676:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11677:     return $location;
1.46      www      11678: }
1.36      albertel 11679: 
1.46      www      11680: sub hreflocation {
                   11681:     my ($dir,$file)=@_;
1.980     raeburn  11682:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11683: 	$file=filelocation($dir,$file);
1.700     albertel 11684:     } elsif ($file=~m-^/adm/-) {
                   11685: 	$file=~s-^/adm/wrapper/-/-;
                   11686: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11687:     }
                   11688:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11689: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11690:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11691: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11692: 	        {/uploaded/$1/$2/}x;
1.46      www      11693:     }
1.913     albertel 11694:     if ($file=~ m{^/userfiles/}) {
                   11695: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11696:     }
1.462     albertel 11697:     return $file;
1.465     albertel 11698: }
                   11699: 
1.1139    www      11700: 
                   11701: 
                   11702: 
                   11703: 
1.465     albertel 11704: sub current_machine_domains {
1.853     albertel 11705:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11706: }
                   11707: 
                   11708: sub machine_domains {
                   11709:     my ($hostname) = @_;
1.465     albertel 11710:     my @domains;
1.838     albertel 11711:     my %hostname = &all_hostnames();
1.465     albertel 11712:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11713: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11714: 	if ($hostname eq $name) {
1.844     albertel 11715: 	    push(@domains,&host_domain($id));
1.465     albertel 11716: 	}
                   11717:     }
                   11718:     return @domains;
                   11719: }
                   11720: 
                   11721: sub current_machine_ids {
1.853     albertel 11722:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11723: }
                   11724: 
                   11725: sub machine_ids {
                   11726:     my ($hostname) = @_;
                   11727:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11728:     my @ids;
1.888     albertel 11729:     my %name_to_host = &all_names();
1.889     albertel 11730:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11731: 	return @{ $name_to_host{$hostname} };
                   11732:     }
                   11733:     return;
1.31      www      11734: }
                   11735: 
1.824     raeburn  11736: sub additional_machine_domains {
                   11737:     my @domains;
                   11738:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11739:     while( my $line = <$fh>) {
                   11740:         $line =~ s/\s//g;
                   11741:         push(@domains,$line);
                   11742:     }
                   11743:     return @domains;
                   11744: }
                   11745: 
                   11746: sub default_login_domain {
                   11747:     my $domain = $perlvar{'lonDefDomain'};
                   11748:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11749:     foreach my $posdom (&current_machine_domains(),
                   11750:                         &additional_machine_domains()) {
                   11751:         if (lc($posdom) eq lc($testdomain)) {
                   11752:             $domain=$posdom;
                   11753:             last;
                   11754:         }
                   11755:     }
                   11756:     return $domain;
                   11757: }
                   11758: 
1.31      www      11759: # ------------------------------------------------------------- Declutters URLs
                   11760: 
                   11761: sub declutter {
                   11762:     my $thisfn=shift;
1.569     albertel 11763:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  11764:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   11765:         $thisfn=~s{^/home/httpd/html}{};
                   11766:     }
1.31      www      11767:     $thisfn=~s/^\///;
1.697     albertel 11768:     $thisfn=~s|^adm/wrapper/||;
                   11769:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11770:     $thisfn=~s/^res\///;
1.1172    bisitz   11771:     $thisfn=~s/^priv\///;
1.1032    raeburn  11772:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11773:         $thisfn=~s/\?.+$//;
                   11774:     }
1.268     www      11775:     return $thisfn;
                   11776: }
                   11777: 
                   11778: # ------------------------------------------------------------- Clutter up URLs
                   11779: 
                   11780: sub clutter {
                   11781:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11782:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11783: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11784:        $thisfn='/res'.$thisfn; 
                   11785:     }
1.1031    raeburn  11786:     if ($thisfn !~m|^/adm|) {
                   11787: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11788: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11789: 	} else {
                   11790: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11791: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11792: 	    if ($embstyle eq 'ssi'
                   11793: 		|| ($embstyle eq 'hdn')
                   11794: 		|| ($embstyle eq 'rat')
                   11795: 		|| ($embstyle eq 'prv')
                   11796: 		|| ($embstyle eq 'ign')) {
                   11797: 		#do nothing with these
                   11798: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11799: 		|| ($embstyle eq 'emb')
                   11800: 		|| ($embstyle eq 'wrp')) {
                   11801: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11802: 	    } elsif ($embstyle eq 'unk'
                   11803: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11804: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11805: 	    } else {
1.718     www      11806: #		&logthis("Got a blank emb style");
1.695     albertel 11807: 	    }
1.694     albertel 11808: 	}
                   11809:     }
1.31      www      11810:     return $thisfn;
1.12      www      11811: }
                   11812: 
1.787     albertel 11813: sub clutter_with_no_wrapper {
                   11814:     my $uri = &clutter(shift);
                   11815:     if ($uri =~ m-^/adm/-) {
                   11816: 	$uri =~ s-^/adm/wrapper/-/-;
                   11817: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11818:     }
                   11819:     return $uri;
                   11820: }
                   11821: 
1.557     albertel 11822: sub freeze_escape {
                   11823:     my ($value)=@_;
                   11824:     if (ref($value)) {
                   11825: 	$value=&nfreeze($value);
                   11826: 	return '__FROZEN__'.&escape($value);
                   11827:     }
                   11828:     return &escape($value);
                   11829: }
                   11830: 
1.11      www      11831: 
1.557     albertel 11832: sub thaw_unescape {
                   11833:     my ($value)=@_;
                   11834:     if ($value =~ /^__FROZEN__/) {
                   11835: 	substr($value,0,10,undef);
                   11836: 	$value=&unescape($value);
                   11837: 	return &thaw($value);
                   11838:     }
                   11839:     return &unescape($value);
                   11840: }
                   11841: 
1.436     albertel 11842: sub correct_line_ends {
                   11843:     my ($result)=@_;
                   11844:     $$result =~s/\r\n/\n/mg;
                   11845:     $$result =~s/\r/\n/mg;
1.415     albertel 11846: }
1.1       albertel 11847: # ================================================================ Main Program
                   11848: 
1.184     www      11849: sub goodbye {
1.204     albertel 11850:    &logthis("Starting Shut down");
1.443     albertel 11851: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11852:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11853: #converted
1.599     albertel 11854: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11855:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11856: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11857: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11858: #1.1 only
1.870     albertel 11859: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11860: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11861: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11862: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11863:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11864:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11865:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11866:    &flushcourselogs();
                   11867:    &logthis("Shutting down");
                   11868: }
                   11869: 
1.852     albertel 11870: sub get_dns {
1.1172.2.17  raeburn  11871:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11872:     if (!$ignore_cache) {
                   11873: 	my ($content,$cached)=
                   11874: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11875: 	if ($cached) {
1.1172.2.17  raeburn  11876: 	    &$func($content,$hashref);
1.869     albertel 11877: 	    return;
                   11878: 	}
                   11879:     }
                   11880: 
                   11881:     my %alldns;
1.852     albertel 11882:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11883:     foreach my $dns (<$config>) {
                   11884: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11885:         my $line = $1;
                   11886:         my ($host,$protocol) = split(/:/,$line);
                   11887:         if ($protocol ne 'https') {
                   11888:             $protocol = 'http';
                   11889:         }
                   11890: 	$alldns{$host} = $protocol;
1.869     albertel 11891:     }
                   11892:     while (%alldns) {
1.1172.2.52  raeburn  11893: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 11894: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11895:         $ua->timeout(30);
1.979     raeburn  11896: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11897: 	my $response=$ua->request($request);
1.979     raeburn  11898:         delete($alldns{$dns});
1.852     albertel 11899: 	next if ($response->is_error());
                   11900: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11901:         unless ($nocache) {
1.1172.2.23  raeburn  11902: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  11903:         }
                   11904: 	&$func(\@content,$hashref);
1.869     albertel 11905: 	return;
1.852     albertel 11906:     }
                   11907:     close($config);
1.871     albertel 11908:     my $which = (split('/',$url))[3];
                   11909:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11910:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11911:     my @content = <$config>;
1.1172.2.17  raeburn  11912:     &$func(\@content,$hashref);
                   11913:     return;
                   11914: }
                   11915: 
                   11916: # ------------------------------------------------------Get DNS checksums file
                   11917: sub parse_dns_checksums_tab {
                   11918:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  11919:     my $lonhost = $perlvar{'lonHostID'};
                   11920:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  11921:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  11922:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   11923:     my $webconfdir = '/etc/httpd/conf';
                   11924:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   11925:         $webconfdir = '/etc/apache2';
                   11926:     } elsif ($distro =~ /^sles(\d+)$/) {
                   11927:         if ($1 >= 10) {
                   11928:             $webconfdir = '/etc/apache2';
                   11929:         }
                   11930:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   11931:         if ($1 >= 10.0) {
                   11932:             $webconfdir = '/etc/apache2';
                   11933:         }
                   11934:     }
1.1172.2.17  raeburn  11935:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11936:     my (%chksum,%revnum);
                   11937:     if (ref($lines) eq 'ARRAY') {
                   11938:         chomp(@{$lines});
1.1172.2.34  raeburn  11939:         my $version = shift(@{$lines});
                   11940:         if ($version eq $release) {
1.1172.2.17  raeburn  11941:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  11942:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  11943:                 if ($file =~ m{^/etc/httpd/conf}) {
                   11944:                     if ($webconfdir eq '/etc/apache2') {
                   11945:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   11946:                     }
                   11947:                 }
1.1172.2.34  raeburn  11948:                 $chksum{$file} = $shasum;
                   11949:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  11950:             }
                   11951:             if (ref($hashref) eq 'HASH') {
                   11952:                 %{$hashref} = (
                   11953:                                 sums     => \%chksum,
                   11954:                                 versions => \%revnum,
                   11955:                               );
                   11956:             }
                   11957:         }
                   11958:     }
1.869     albertel 11959:     return;
1.852     albertel 11960: }
1.1172.2.17  raeburn  11961: 
                   11962: sub fetch_dns_checksums {
                   11963:     my %checksums;
1.1172.2.34  raeburn  11964:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  11965:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  11966:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11967:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  11968:              \%checksums);
                   11969:     return \%checksums;
                   11970: }
                   11971: 
1.327     albertel 11972: # ------------------------------------------------------------ Read domain file
                   11973: {
1.852     albertel 11974:     my $loaded;
1.846     albertel 11975:     my %domain;
                   11976: 
1.852     albertel 11977:     sub parse_domain_tab {
                   11978: 	my ($lines) = @_;
                   11979: 	foreach my $line (@$lines) {
                   11980: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11981: 
1.846     albertel 11982: 	    chomp($line);
1.852     albertel 11983: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11984: 	    my %this_domain;
                   11985: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11986: 			       'lang_def', 'city', 'longi', 'lati',
                   11987: 			       'primary') {
                   11988: 		$this_domain{$field} = shift(@elements);
                   11989: 	    }
                   11990: 	    $domain{$name} = \%this_domain;
1.852     albertel 11991: 	}
                   11992:     }
1.864     albertel 11993: 
                   11994:     sub reset_domain_info {
                   11995: 	undef($loaded);
                   11996: 	undef(%domain);
                   11997:     }
                   11998: 
1.852     albertel 11999:     sub load_domain_tab {
1.869     albertel 12000: 	my ($ignore_cache) = @_;
                   12001: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 12002: 	my $fh;
                   12003: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12004: 	    my @lines = <$fh>;
                   12005: 	    &parse_domain_tab(\@lines);
1.448     albertel 12006: 	}
1.852     albertel 12007: 	close($fh);
                   12008: 	$loaded = 1;
1.327     albertel 12009:     }
1.846     albertel 12010: 
                   12011:     sub domain {
1.852     albertel 12012: 	&load_domain_tab() if (!$loaded);
                   12013: 
1.846     albertel 12014: 	my ($name,$what) = @_;
                   12015: 	return if ( !exists($domain{$name}) );
                   12016: 
                   12017: 	if (!$what) {
                   12018: 	    return $domain{$name}{'description'};
                   12019: 	}
                   12020: 	return $domain{$name}{$what};
                   12021:     }
1.974     raeburn  12022: 
                   12023:     sub domain_info {
                   12024:         &load_domain_tab() if (!$loaded);
                   12025:         return %domain;
                   12026:     }
                   12027: 
1.327     albertel 12028: }
                   12029: 
                   12030: 
1.1       albertel 12031: # ------------------------------------------------------------- Read hosts file
                   12032: {
1.838     albertel 12033:     my %hostname;
1.844     albertel 12034:     my %hostdom;
1.845     albertel 12035:     my %libserv;
1.852     albertel 12036:     my $loaded;
1.888     albertel 12037:     my %name_to_host;
1.1074    raeburn  12038:     my %internetdom;
1.1107    raeburn  12039:     my %LC_dns_serv;
1.852     albertel 12040: 
                   12041:     sub parse_hosts_tab {
                   12042: 	my ($file) = @_;
                   12043: 	foreach my $configline (@$file) {
                   12044: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12045:             chomp($configline);
                   12046: 	    if ($configline =~ /^\^/) {
                   12047:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12048:                     $LC_dns_serv{$1} = 1;
                   12049:                 }
                   12050:                 next;
                   12051:             }
1.1074    raeburn  12052: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12053: 	    $name=~s/\s//g;
                   12054: 	    if ($id && $domain && $role && $name) {
                   12055: 		$hostname{$id}=$name;
1.888     albertel 12056: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12057: 		$hostdom{$id}=$domain;
                   12058: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12059:                 if (defined($protocol)) {
                   12060:                     if ($protocol eq 'https') {
                   12061:                         $protocol{$id} = $protocol;
                   12062:                     } else {
                   12063:                         $protocol{$id} = 'http'; 
                   12064:                     }
1.968     raeburn  12065:                 } else {
1.969     raeburn  12066:                     $protocol{$id} = 'http';
1.968     raeburn  12067:                 }
1.1074    raeburn  12068:                 if (defined($intdom)) {
                   12069:                     $internetdom{$id} = $intdom;
                   12070:                 }
1.852     albertel 12071: 	    }
                   12072: 	}
                   12073:     }
1.864     albertel 12074:     
                   12075:     sub reset_hosts_info {
1.897     albertel 12076: 	&purge_remembered();
1.864     albertel 12077: 	&reset_domain_info();
                   12078: 	&reset_hosts_ip_info();
1.892     albertel 12079: 	undef(%name_to_host);
1.864     albertel 12080: 	undef(%hostname);
                   12081: 	undef(%hostdom);
                   12082: 	undef(%libserv);
                   12083: 	undef($loaded);
                   12084:     }
1.1       albertel 12085: 
1.852     albertel 12086:     sub load_hosts_tab {
1.869     albertel 12087: 	my ($ignore_cache) = @_;
                   12088: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 12089: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12090: 	my @config = <$config>;
                   12091: 	&parse_hosts_tab(\@config);
                   12092: 	close($config);
                   12093: 	$loaded=1;
1.1       albertel 12094:     }
1.852     albertel 12095: 
1.838     albertel 12096:     sub hostname {
1.852     albertel 12097: 	&load_hosts_tab() if (!$loaded);
                   12098: 
1.838     albertel 12099: 	my ($lonid) = @_;
                   12100: 	return $hostname{$lonid};
                   12101:     }
1.845     albertel 12102: 
1.838     albertel 12103:     sub all_hostnames {
1.852     albertel 12104: 	&load_hosts_tab() if (!$loaded);
                   12105: 
1.838     albertel 12106: 	return %hostname;
                   12107:     }
1.845     albertel 12108: 
1.888     albertel 12109:     sub all_names {
                   12110: 	&load_hosts_tab() if (!$loaded);
                   12111: 
                   12112: 	return %name_to_host;
                   12113:     }
                   12114: 
1.974     raeburn  12115:     sub all_host_domain {
                   12116:         &load_hosts_tab() if (!$loaded);
                   12117:         return %hostdom;
                   12118:     }
                   12119: 
1.845     albertel 12120:     sub is_library {
1.852     albertel 12121: 	&load_hosts_tab() if (!$loaded);
                   12122: 
1.845     albertel 12123: 	return exists($libserv{$_[0]});
                   12124:     }
                   12125: 
                   12126:     sub all_library {
1.852     albertel 12127: 	&load_hosts_tab() if (!$loaded);
                   12128: 
1.845     albertel 12129: 	return %libserv;
                   12130:     }
                   12131: 
1.1062    droeschl 12132:     sub unique_library {
                   12133: 	#2x reverse removes all hostnames that appear more than once
                   12134:         my %unique = reverse &all_library();
                   12135:         return reverse %unique;
                   12136:     }
                   12137: 
1.841     albertel 12138:     sub get_servers {
1.852     albertel 12139: 	&load_hosts_tab() if (!$loaded);
                   12140: 
1.841     albertel 12141: 	my ($domain,$type) = @_;
                   12142: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12143: 	                                          : %hostname;
                   12144: 	my %result;
1.842     albertel 12145: 	if (ref($domain) eq 'ARRAY') {
                   12146: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12147: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12148: 		    $result{$host} = $hostname;
                   12149: 		}
                   12150: 	    }
                   12151: 	} else {
                   12152: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12153: 		if ($hostdom{$host} eq $domain) {
                   12154: 		    $result{$host} = $hostname;
                   12155: 		}
1.841     albertel 12156: 	    }
                   12157: 	}
                   12158: 	return %result;
                   12159:     }
1.845     albertel 12160: 
1.1062    droeschl 12161:     sub get_unique_servers {
                   12162:         my %unique = reverse &get_servers(@_);
                   12163: 	return reverse %unique;
                   12164:     }
                   12165: 
1.844     albertel 12166:     sub host_domain {
1.852     albertel 12167: 	&load_hosts_tab() if (!$loaded);
                   12168: 
1.844     albertel 12169: 	my ($lonid) = @_;
                   12170: 	return $hostdom{$lonid};
                   12171:     }
                   12172: 
1.841     albertel 12173:     sub all_domains {
1.852     albertel 12174: 	&load_hosts_tab() if (!$loaded);
                   12175: 
1.841     albertel 12176: 	my %seen;
                   12177: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12178: 	return @uniq;
                   12179:     }
1.1074    raeburn  12180: 
                   12181:     sub internet_dom {
                   12182:         &load_hosts_tab() if (!$loaded);
                   12183: 
                   12184:         my ($lonid) = @_;
                   12185:         return $internetdom{$lonid};
                   12186:     }
1.1107    raeburn  12187: 
                   12188:     sub is_LC_dns {
                   12189:         &load_hosts_tab() if (!$loaded);
                   12190: 
                   12191:         my ($hostname) = @_;
                   12192:         return exists($LC_dns_serv{$hostname});
                   12193:     }
                   12194: 
1.1       albertel 12195: }
                   12196: 
1.847     albertel 12197: { 
                   12198:     my %iphost;
1.856     albertel 12199:     my %name_to_ip;
                   12200:     my %lonid_to_ip;
1.869     albertel 12201: 
1.847     albertel 12202:     sub get_hosts_from_ip {
                   12203: 	my ($ip) = @_;
                   12204: 	my %iphosts = &get_iphost();
                   12205: 	if (ref($iphosts{$ip})) {
                   12206: 	    return @{$iphosts{$ip}};
                   12207: 	}
                   12208: 	return;
1.839     albertel 12209:     }
1.864     albertel 12210:     
                   12211:     sub reset_hosts_ip_info {
                   12212: 	undef(%iphost);
                   12213: 	undef(%name_to_ip);
                   12214: 	undef(%lonid_to_ip);
                   12215:     }
1.856     albertel 12216: 
                   12217:     sub get_host_ip {
                   12218: 	my ($lonid) = @_;
                   12219: 	if (exists($lonid_to_ip{$lonid})) {
                   12220: 	    return $lonid_to_ip{$lonid};
                   12221: 	}
                   12222: 	my $name=&hostname($lonid);
                   12223:    	my $ip = gethostbyname($name);
                   12224: 	return if (!$ip || length($ip) ne 4);
                   12225: 	$ip=inet_ntoa($ip);
                   12226: 	$name_to_ip{$name}   = $ip;
                   12227: 	$lonid_to_ip{$lonid} = $ip;
                   12228: 	return $ip;
                   12229:     }
1.847     albertel 12230:     
                   12231:     sub get_iphost {
1.869     albertel 12232: 	my ($ignore_cache) = @_;
1.894     albertel 12233: 
1.869     albertel 12234: 	if (!$ignore_cache) {
                   12235: 	    if (%iphost) {
                   12236: 		return %iphost;
                   12237: 	    }
                   12238: 	    my ($ip_info,$cached)=
                   12239: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12240: 	    if ($cached) {
                   12241: 		%iphost      = %{$ip_info->[0]};
                   12242: 		%name_to_ip  = %{$ip_info->[1]};
                   12243: 		%lonid_to_ip = %{$ip_info->[2]};
                   12244: 		return %iphost;
                   12245: 	    }
                   12246: 	}
1.894     albertel 12247: 
                   12248: 	# get yesterday's info for fallback
                   12249: 	my %old_name_to_ip;
                   12250: 	my ($ip_info,$cached)=
                   12251: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12252: 	if ($cached) {
                   12253: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12254: 	}
                   12255: 
1.888     albertel 12256: 	my %name_to_host = &all_names();
                   12257: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12258: 	    my $ip;
                   12259: 	    if (!exists($name_to_ip{$name})) {
                   12260: 		$ip = gethostbyname($name);
                   12261: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12262: 		    if (defined($old_name_to_ip{$name})) {
                   12263: 			$ip = $old_name_to_ip{$name};
                   12264: 			&logthis("Can't find $name defaulting to old $ip");
                   12265: 		    } else {
                   12266: 			&logthis("Name $name no IP found");
                   12267: 			next;
                   12268: 		    }
                   12269: 		} else {
                   12270: 		    $ip=inet_ntoa($ip);
1.847     albertel 12271: 		}
                   12272: 		$name_to_ip{$name} = $ip;
                   12273: 	    } else {
                   12274: 		$ip = $name_to_ip{$name};
1.653     albertel 12275: 	    }
1.888     albertel 12276: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12277: 		$lonid_to_ip{$id} = $ip;
                   12278: 	    }
                   12279: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12280: 	}
1.1172.2.23  raeburn  12281: 	&do_cache_new('iphost','iphost',
                   12282: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12283: 		      48*60*60);
1.869     albertel 12284: 
1.847     albertel 12285: 	return %iphost;
1.598     albertel 12286:     }
                   12287: 
1.992     raeburn  12288:     #
                   12289:     #  Given a DNS returns the loncapa host name for that DNS 
                   12290:     # 
                   12291:     sub host_from_dns {
                   12292:         my ($dns) = @_;
                   12293:         my @hosts;
                   12294:         my $ip;
                   12295: 
1.993     raeburn  12296:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12297:             $ip = $name_to_ip{$dns};
                   12298:         }
                   12299:         if (!$ip) {
                   12300:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12301:             if (length($ip) == 4) { 
                   12302: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12303:             }
                   12304:         }
                   12305:         if ($ip) {
                   12306: 	    @hosts = get_hosts_from_ip($ip);
                   12307: 	    return $hosts[0];
                   12308:         }
                   12309:         return undef;
1.986     foxr     12310:     }
1.992     raeburn  12311: 
1.1074    raeburn  12312:     sub get_internet_names {
                   12313:         my ($lonid) = @_;
                   12314:         return if ($lonid eq '');
                   12315:         my ($idnref,$cached)=
                   12316:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12317:         if ($cached) {
                   12318:             return $idnref;
                   12319:         }
                   12320:         my $ip = &get_host_ip($lonid);
                   12321:         my @hosts = &get_hosts_from_ip($ip);
                   12322:         my %iphost = &get_iphost();
                   12323:         my (@idns,%seen);
                   12324:         foreach my $id (@hosts) {
                   12325:             my $dom = &host_domain($id);
                   12326:             my $prim_id = &domain($dom,'primary');
                   12327:             my $prim_ip = &get_host_ip($prim_id);
                   12328:             next if ($seen{$prim_ip});
                   12329:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12330:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12331:                     my $intdom = &internet_dom($id);
                   12332:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12333:                         push(@idns,$intdom);
                   12334:                     }
                   12335:                 }
                   12336:             }
                   12337:             $seen{$prim_ip} = 1;
                   12338:         }
1.1172.2.23  raeburn  12339:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12340:     }
                   12341: 
1.986     foxr     12342: }
                   12343: 
1.1079    raeburn  12344: sub all_loncaparevs {
1.1172.2.39  raeburn  12345:     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  12346: }
                   12347: 
1.1172.2.27  raeburn  12348: # ------------------------------------------------------- Read loncaparev table
                   12349: {
                   12350:     sub load_loncaparevs {
                   12351:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12352:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12353:                 while (my $configline=<$config>) {
                   12354:                     chomp($configline);
                   12355:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12356:                     $loncaparevs{$hostid}=$loncaparev;
                   12357:                 }
                   12358:                 close($config);
                   12359:             }
                   12360:         }
                   12361:     }
                   12362: }
                   12363: 
                   12364: # ----------------------------------------------------- Read serverhostID table
                   12365: {
                   12366:     sub load_serverhomeIDs {
                   12367:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12368:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12369:                 while (my $configline=<$config>) {
                   12370:                     chomp($configline);
                   12371:                     my ($name,$id)=split(/:/,$configline);
                   12372:                     $serverhomeIDs{$name}=$id;
                   12373:                 }
                   12374:                 close($config);
                   12375:             }
                   12376:         }
                   12377:     }
                   12378: }
                   12379: 
                   12380: 
1.862     albertel 12381: BEGIN {
                   12382: 
                   12383: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12384:     unless ($readit) {
                   12385: {
                   12386:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12387:     %perlvar = (%perlvar,%{$configvars});
                   12388: }
                   12389: 
                   12390: 
1.1       albertel 12391: # ------------------------------------------------------ Read spare server file
                   12392: {
1.448     albertel 12393:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12394: 
                   12395:     while (my $configline=<$config>) {
                   12396:        chomp($configline);
1.284     matthew  12397:        if ($configline) {
1.784     albertel 12398: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12399: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12400: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12401:        }
                   12402:     }
1.448     albertel 12403:     close($config);
1.1       albertel 12404: }
1.11      www      12405: # ------------------------------------------------------------ Read permissions
                   12406: {
1.448     albertel 12407:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12408: 
                   12409:     while (my $configline=<$config>) {
1.448     albertel 12410: 	chomp($configline);
                   12411: 	if ($configline) {
                   12412: 	    my ($role,$perm)=split(/ /,$configline);
                   12413: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12414: 	}
1.11      www      12415:     }
1.448     albertel 12416:     close($config);
1.11      www      12417: }
                   12418: 
                   12419: # -------------------------------------------- Read plain texts for permissions
                   12420: {
1.448     albertel 12421:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12422: 
                   12423:     while (my $configline=<$config>) {
1.448     albertel 12424: 	chomp($configline);
                   12425: 	if ($configline) {
1.742     raeburn  12426: 	    my ($short,@plain)=split(/:/,$configline);
                   12427:             %{$prp{$short}} = ();
                   12428: 	    if (@plain > 0) {
                   12429:                 $prp{$short}{'std'} = $plain[0];
                   12430:                 for (my $i=1; $i<@plain; $i++) {
                   12431:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12432:                 }
                   12433:             }
1.448     albertel 12434: 	}
1.135     www      12435:     }
1.448     albertel 12436:     close($config);
1.135     www      12437: }
                   12438: 
                   12439: # ---------------------------------------------------------- Read package table
                   12440: {
1.448     albertel 12441:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12442: 
                   12443:     while (my $configline=<$config>) {
1.483     albertel 12444: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12445: 	chomp($configline);
                   12446: 	my ($short,$plain)=split(/:/,$configline);
                   12447: 	my ($pack,$name)=split(/\&/,$short);
                   12448: 	if ($plain ne '') {
                   12449: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12450: 	    $packagetab{$short}=$plain; 
                   12451: 	}
1.11      www      12452:     }
1.448     albertel 12453:     close($config);
1.329     matthew  12454: }
                   12455: 
1.1172.2.27  raeburn  12456: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12457: 
1.1172.2.27  raeburn  12458: &load_loncaparevs();
                   12459: 
                   12460: # ------------------------------------------------------- Read serverhostID table
                   12461: 
                   12462: &load_serverhomeIDs();
1.1074    raeburn  12463: 
1.1172.2.27  raeburn  12464: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12465: {
                   12466:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12467:     if (-e $file) {
                   12468:         my $parser = HTML::LCParser->new($file);
                   12469:         while (my $token = $parser->get_token()) {
                   12470:             if ($token->[0] eq 'S') {
                   12471:                 my $item = $token->[1];
                   12472:                 my $name = $token->[2]{'name'};
                   12473:                 my $value = $token->[2]{'value'};
                   12474:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12475:                     my $release = $parser->get_text();
                   12476:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12477:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12478:                 }
                   12479:             }
                   12480:         }
                   12481:     }
1.1073    raeburn  12482: }
                   12483: 
1.1138    raeburn  12484: # ---------------------------------------------------------- Read managers table
                   12485: {
                   12486:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12487:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12488:             while (my $configline=<$config>) {
                   12489:                 chomp($configline);
                   12490:                 next if ($configline =~ /^\#/);
                   12491:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12492:                     $managerstab{$configline} = 1;
                   12493:                 }
                   12494:             }
                   12495:             close($config);
                   12496:         }
                   12497:     }
                   12498: }
                   12499: 
1.329     matthew  12500: # ------------- set up temporary directory
                   12501: {
1.1117    foxr     12502:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12503: 
1.11      www      12504: }
                   12505: 
1.794     albertel 12506: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12507: 				'compress_threshold'=> 20_000,
                   12508:  			        });
1.185     www      12509: 
1.281     www      12510: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12511: $dumpcount=0;
1.958     www      12512: $locknum=0;
1.22      www      12513: 
1.163     harris41 12514: &logtouch();
1.672     albertel 12515: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12516: $readit=1;
1.564     albertel 12517:     {
                   12518: 	use integer;
                   12519: 	my $test=(2**32)+1;
1.568     albertel 12520: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12521: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12522:     }
1.195     www      12523: }
1.1       albertel 12524: }
1.179     www      12525: 
1.1       albertel 12526: 1;
1.191     harris41 12527: __END__
                   12528: 
1.243     albertel 12529: =pod
                   12530: 
1.191     harris41 12531: =head1 NAME
                   12532: 
1.243     albertel 12533: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12534: 
                   12535: =head1 SYNOPSIS
                   12536: 
1.243     albertel 12537: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12538: 
                   12539:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12540: 
1.243     albertel 12541: Common parameters:
                   12542: 
                   12543: =over 4
                   12544: 
                   12545: =item *
                   12546: 
                   12547: $uname : an internal username (if $cname expecting a course Id specifically)
                   12548: 
                   12549: =item *
                   12550: 
                   12551: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12552: 
                   12553: =item *
                   12554: 
                   12555: $symb : a resource instance identifier
                   12556: 
                   12557: =item *
                   12558: 
                   12559: $namespace : the name of a .db file that contains the data needed or
                   12560: being set.
                   12561: 
                   12562: =back
                   12563: 
1.394     bowersj2 12564: =head1 OVERVIEW
1.191     harris41 12565: 
1.394     bowersj2 12566: lonnet provides subroutines which interact with the
                   12567: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12568: about classes, users, and resources.
1.243     albertel 12569: 
                   12570: For many of these objects you can also use this to store data about
                   12571: them or modify them in various ways.
1.191     harris41 12572: 
1.394     bowersj2 12573: =head2 Symbs
1.191     harris41 12574: 
1.394     bowersj2 12575: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12576: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12577: map, the resource number of the resource in the map, and the URL of
                   12578: the resource itself. The latter is somewhat redundant, but might help
                   12579: if maps change.
                   12580: 
                   12581: An example is
                   12582: 
                   12583:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12584: 
                   12585: The respective map entry is
                   12586: 
                   12587:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12588:   title="Problem 2">
                   12589:  </resource>
                   12590: 
                   12591: Symbs are used by the random number generator, as well as to store and
                   12592: restore data specific to a certain instance of for example a problem.
                   12593: 
                   12594: =head2 Storing And Retrieving Data
                   12595: 
                   12596: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12597: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12598: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12599: is is the non-critical message twin of cstore. These functions are for
                   12600: handlers to store a perl hash to a user's permanent data space in an
                   12601: easy manner, and to retrieve it again on another call. It is expected
                   12602: that a handler would use this once at the beginning to retrieve data,
                   12603: and then again once at the end to send only the new data back.
                   12604: 
                   12605: The data is stored in the user's data directory on the user's
                   12606: homeserver under the ID of the course.
                   12607: 
                   12608: The hash that is returned by restore will have all of the previous
                   12609: value for all of the elements of the hash.
                   12610: 
                   12611: Example:
                   12612: 
                   12613:  #creating a hash
                   12614:  my %hash;
                   12615:  $hash{'foo'}='bar';
                   12616: 
                   12617:  #storing it
                   12618:  &Apache::lonnet::cstore(\%hash);
                   12619: 
                   12620:  #changing a value
                   12621:  $hash{'foo'}='notbar';
                   12622: 
                   12623:  #adding a new value
                   12624:  $hash{'bar'}='foo';
                   12625:  &Apache::lonnet::cstore(\%hash);
                   12626: 
                   12627:  #retrieving the hash
                   12628:  my %history=&Apache::lonnet::restore();
                   12629: 
                   12630:  #print the hash
                   12631:  foreach my $key (sort(keys(%history))) {
                   12632:    print("\%history{$key} = $history{$key}");
                   12633:  }
                   12634: 
                   12635: Will print out:
1.191     harris41 12636: 
1.394     bowersj2 12637:  %history{1:foo} = bar
                   12638:  %history{1:keys} = foo:timestamp
                   12639:  %history{1:timestamp} = 990455579
                   12640:  %history{2:bar} = foo
                   12641:  %history{2:foo} = notbar
                   12642:  %history{2:keys} = foo:bar:timestamp
                   12643:  %history{2:timestamp} = 990455580
                   12644:  %history{bar} = foo
                   12645:  %history{foo} = notbar
                   12646:  %history{timestamp} = 990455580
                   12647:  %history{version} = 2
                   12648: 
                   12649: Note that the special hash entries C<keys>, C<version> and
                   12650: C<timestamp> were added to the hash. C<version> will be equal to the
                   12651: total number of versions of the data that have been stored. The
                   12652: C<timestamp> attribute will be the UNIX time the hash was
                   12653: stored. C<keys> is available in every historical section to list which
                   12654: keys were added or changed at a specific historical revision of a
                   12655: hash.
                   12656: 
                   12657: B<Warning>: do not store the hash that restore returns directly. This
                   12658: will cause a mess since it will restore the historical keys as if the
                   12659: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12660: 
1.394     bowersj2 12661: Calling convention:
1.191     harris41 12662: 
1.1172.2.27  raeburn  12663:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12664:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12665: 
1.394     bowersj2 12666: For more detailed information, see lonnet specific documentation.
1.191     harris41 12667: 
1.394     bowersj2 12668: =head1 RETURN MESSAGES
1.191     harris41 12669: 
1.394     bowersj2 12670: =over 4
1.191     harris41 12671: 
1.394     bowersj2 12672: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12673: 
1.394     bowersj2 12674: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12675: when the connection is brought back up
1.191     harris41 12676: 
1.394     bowersj2 12677: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12678: for later delivery
1.191     harris41 12679: 
1.967     bisitz   12680: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12681: 
1.394     bowersj2 12682: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12683: that was requested
1.191     harris41 12684: 
1.243     albertel 12685: =back
1.191     harris41 12686: 
1.243     albertel 12687: =head1 PUBLIC SUBROUTINES
1.191     harris41 12688: 
1.243     albertel 12689: =head2 Session Environment Functions
1.191     harris41 12690: 
1.243     albertel 12691: =over 4
1.191     harris41 12692: 
1.394     bowersj2 12693: =item * 
                   12694: X<appenv()>
1.949     raeburn  12695: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12696: the user envirnoment file, and will be restored for each access this
1.620     albertel 12697: user makes during this session, also modifies the %env for the current
1.949     raeburn  12698: process. Optional rolesarrayref - if defined contains a reference to an array
                   12699: of roles which are exempt from the restriction on modifying user.role entries 
                   12700: in the user's environment.db and in %env.    
1.191     harris41 12701: 
                   12702: =item *
1.394     bowersj2 12703: X<delenv()>
1.987     raeburn  12704: B<delenv($delthis,$regexp)>: removes all items from the session
                   12705: environment file that begin with $delthis. If the 
                   12706: optional second arg - $regexp - is true, $delthis is treated as a 
                   12707: regular expression, otherwise \Q$delthis\E is used. 
                   12708: The values are also deleted from the current processes %env.
1.191     harris41 12709: 
1.795     albertel 12710: =item * get_env_multiple($name) 
                   12711: 
                   12712: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12713: values may be defined and end up as an array ref.
                   12714: 
                   12715: returns an array of values
                   12716: 
1.243     albertel 12717: =back
                   12718: 
                   12719: =head2 User Information
1.191     harris41 12720: 
1.243     albertel 12721: =over 4
1.191     harris41 12722: 
                   12723: =item *
1.394     bowersj2 12724: X<queryauthenticate()>
                   12725: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12726: authentication scheme
                   12727: 
                   12728: =item *
1.394     bowersj2 12729: X<authenticate()>
1.1073    raeburn  12730: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12731: authenticate user from domain's lib servers (first use the current
                   12732: one). C<$upass> should be the users password.
1.1073    raeburn  12733: $checkdefauth is optional (value is 1 if a check should be made to
                   12734:    authenticate user using default authentication method, and allow
                   12735:    account creation if username does not have account in the domain).
                   12736: $clientcancheckhost is optional (value is 1 if checking whether the
                   12737:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12738: 
                   12739: =item *
1.394     bowersj2 12740: X<homeserver()>
                   12741: B<homeserver($uname,$udom)>: find the server which has
                   12742: the user's directory and files (there must be only one), this caches
                   12743: the answer, and also caches if there is a borken connection.
1.191     harris41 12744: 
                   12745: =item *
1.394     bowersj2 12746: X<idget()>
                   12747: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12748: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12749: username, and only 1 username per ID in a specific domain) (returns
                   12750: hash: id=>name,id=>name)
1.191     harris41 12751: 
                   12752: =item *
1.394     bowersj2 12753: X<idrget()>
                   12754: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12755: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12756: 
                   12757: =item *
1.394     bowersj2 12758: X<idput()>
                   12759: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12760: 
                   12761: =item *
1.394     bowersj2 12762: X<rolesinit()>
1.1169    droeschl 12763: B<rolesinit($udom,$username)>: get user privileges.
                   12764: returns user role, first access and timer interval hashes
1.243     albertel 12765: 
                   12766: =item *
1.1171    droeschl 12767: X<privileged()>
                   12768: B<privileged($username,$domain)>: returns a true if user has a
                   12769: privileged and active role (i.e. su or dc), false otherwise.
                   12770: 
                   12771: =item *
1.551     albertel 12772: X<getsection()>
                   12773: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12774: course $cname, return section name/number or '' for "not in course"
                   12775: and '-1' for "no section"
                   12776: 
                   12777: =item *
1.394     bowersj2 12778: X<userenvironment()>
                   12779: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12780: passed in @what from the requested user's environment, returns a hash
                   12781: 
1.858     raeburn  12782: =item * 
                   12783: X<userlog_query()>
1.859     albertel 12784: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12785: activity.log file. %filters defines filters applied when parsing the
                   12786: log file. These can be start or end timestamps, or the type of action
                   12787: - log to look for Login or Logout events, check for Checkin or
                   12788: Checkout, role for role selection. The response is in the form
                   12789: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12790: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12791: 
1.243     albertel 12792: =back
                   12793: 
                   12794: =head2 User Roles
                   12795: 
                   12796: =over 4
                   12797: 
                   12798: =item *
                   12799: 
1.810     raeburn  12800: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12801:  F: full access
                   12802:  U,I,K: authentication modes (cxx only)
                   12803:  '': forbidden
                   12804:  1: user needs to choose course
                   12805:  2: browse allowed
1.766     albertel 12806:  A: passphrase authentication needed
1.243     albertel 12807: 
                   12808: =item *
                   12809: 
1.1172.2.13  raeburn  12810: constructaccess($url,$setpriv) : check for access to construction space URL
                   12811: 
                   12812: See if the owner domain and name in the URL match those in the
                   12813: expected environment.  If so, return three element list
                   12814: ($ownername,$ownerdomain,$ownerhome).
                   12815: 
                   12816: Otherwise return the null string.
                   12817: 
                   12818: If second argument 'setpriv' is true, it assigns the privileges,
                   12819: and returns the same three element list, unless the owner has
                   12820: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12821: in which case the null string is returned.
                   12822: 
                   12823: =item *
                   12824: 
1.243     albertel 12825: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12826: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12827: and course level
                   12828: 
                   12829: =item *
                   12830: 
1.988     raeburn  12831: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12832: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12833: $type is Course (default) or Community.
1.988     raeburn  12834: If $forcedefault evaluates to true, text returned will be default 
                   12835: text for $type. Otherwise, if this is a course, the text returned 
                   12836: will be a custom name for the role (if defined in the course's 
                   12837: environment).  If no custom name is defined the default is returned.
                   12838:    
1.832     raeburn  12839: =item *
                   12840: 
1.1172.2.23  raeburn  12841: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12842: All arguments are optional. Returns a hash of a roles, either for
                   12843: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12844: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12845: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12846: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12847: For each key, value is set to colon-separated start and end times for
                   12848: the role.  If no username and domain are specified, will default to
1.934     raeburn  12849: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12850: of role statuses (active, future or previous), roles 
                   12851: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12852: to restrict the list of roles reported. If no array ref is 
                   12853: provided for types, will default to return only active roles.
1.834     albertel 12854: 
1.1172.2.13  raeburn  12855: =item *
                   12856: 
                   12857: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12858: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12859: 
                   12860: Additional optional arguments are: $type (if role checking is to be restricted
                   12861: to certain user status types -- previous (expired roles), active (currently
                   12862: available roles) or future (roles available in the future), and
                   12863: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  12864: have active Domain Coordinator role in course's domain or in additional
                   12865: domains (specified in 'Domains to check for privileged users' in course
                   12866: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12867: 
                   12868: =item *
                   12869: 
                   12870: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12871: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12872: $possdomains and $possroles are optional array refs -- to domains to check and
                   12873: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12874: users' roles.db to check for a dc or su role in any domain. This can be
                   12875: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12876: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12877: this then allows &privileged_by_domain() to be used, which caches the identity
                   12878: of privileged users, eliminating the need for repeated calls to &dump().
                   12879: 
                   12880: =item *
                   12881: 
                   12882: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12883: where the outer hash keys are domains specified in the $possdomains array ref,
                   12884: next inner hash keys are privileged roles specified in the $roles array ref,
                   12885: and the innermost hash contains key = value pairs for username:domain = end:start
                   12886: for active or future "privileged" users with that role in that domain. To avoid
                   12887: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12888: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  12889: 
1.243     albertel 12890: =back
                   12891: 
                   12892: =head2 User Modification
                   12893: 
                   12894: =over 4
                   12895: 
                   12896: =item *
                   12897: 
1.957     raeburn  12898: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12899: user for the level given by URL.  Optional start and end dates (leave empty
                   12900: string or zero for "no date")
1.191     harris41 12901: 
                   12902: =item *
                   12903: 
1.243     albertel 12904: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12905: change a users, password, possible return values are: ok,
                   12906: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12907: refused
1.191     harris41 12908: 
                   12909: =item *
                   12910: 
1.243     albertel 12911: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12912: 
                   12913: =item *
                   12914: 
1.1058    raeburn  12915: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12916:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12917: 
                   12918: will update user information (firstname,middlename,lastname,generation,
                   12919: permanentemail), and if forceid is true, student/employee ID also.
                   12920: A user's institutional affiliation(s) can also be updated.
                   12921: User information fields will not be overwritten with empty entries 
                   12922: unless the field is included in the $candelete array reference.
                   12923: This array is included when a single user is modified via "Manage Users",
                   12924: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12925: 
                   12926: =item *
                   12927: 
1.286     matthew  12928: modifystudent
                   12929: 
1.957     raeburn  12930: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  12931: The course id is resolved based on the current user's environment.  
                   12932: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12933: associated with a course.
                   12934: 
1.297     matthew  12935: This call is essentially a wrapper for lonnet::modifyuser and
                   12936: lonnet::modify_student_enrollment
1.286     matthew  12937: 
                   12938: Inputs: 
                   12939: 
                   12940: =over 4
                   12941: 
1.957     raeburn  12942: =item B<$udom> Student's loncapa domain
1.286     matthew  12943: 
1.957     raeburn  12944: =item B<$uname> Student's loncapa login name
1.286     matthew  12945: 
1.964     bisitz   12946: =item B<$uid> Student/Employee ID
1.286     matthew  12947: 
1.957     raeburn  12948: =item B<$umode> Student's authentication mode
1.286     matthew  12949: 
1.957     raeburn  12950: =item B<$upass> Student's password
1.286     matthew  12951: 
1.957     raeburn  12952: =item B<$first> Student's first name
1.286     matthew  12953: 
1.957     raeburn  12954: =item B<$middle> Student's middle name
1.286     matthew  12955: 
1.957     raeburn  12956: =item B<$last> Student's last name
1.286     matthew  12957: 
1.957     raeburn  12958: =item B<$gene> Student's generation
1.286     matthew  12959: 
1.957     raeburn  12960: =item B<$usec> Student's section in course
1.286     matthew  12961: 
                   12962: =item B<$end> Unix time of the roles expiration
                   12963: 
                   12964: =item B<$start> Unix time of the roles start date
                   12965: 
                   12966: =item B<$forceid> If defined, allow $uid to be changed
                   12967: 
                   12968: =item B<$desiredhome> server to use as home server for student
                   12969: 
1.957     raeburn  12970: =item B<$email> Student's permanent e-mail address
                   12971: 
                   12972: =item B<$type> Type of enrollment (auto or manual)
                   12973: 
1.963     raeburn  12974: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12975: 
                   12976: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12977: 
1.963     raeburn  12978: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12979: 
1.963     raeburn  12980: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12981: 
1.1172.2.19  raeburn  12982: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12983: 
                   12984: =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  12985: 
1.286     matthew  12986: =back
1.297     matthew  12987: 
                   12988: =item *
                   12989: 
                   12990: modify_student_enrollment
                   12991: 
1.1172.2.31  raeburn  12992: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  12993: 'role.request.course' must be defined for this function to proceed.
                   12994: 
                   12995: Inputs:
                   12996: 
                   12997: =over 4
                   12998: 
1.1172.2.31  raeburn  12999: =item $udom, student's domain
1.297     matthew  13000: 
1.1172.2.31  raeburn  13001: =item $uname, student's name
1.297     matthew  13002: 
1.1172.2.31  raeburn  13003: =item $uid, student's user id
1.297     matthew  13004: 
1.1172.2.31  raeburn  13005: =item $first, student's first name
1.297     matthew  13006: 
                   13007: =item $middle
                   13008: 
                   13009: =item $last
                   13010: 
                   13011: =item $gene
                   13012: 
                   13013: =item $usec
                   13014: 
                   13015: =item $end
                   13016: 
                   13017: =item $start
                   13018: 
1.957     raeburn  13019: =item $type
                   13020: 
                   13021: =item $locktype
                   13022: 
                   13023: =item $cid
                   13024: 
                   13025: =item $selfenroll
                   13026: 
                   13027: =item $context
                   13028: 
1.1172.2.19  raeburn  13029: =item $credits, number of credits student will earn from this class
                   13030: 
1.297     matthew  13031: =back
                   13032: 
1.191     harris41 13033: 
                   13034: =item *
                   13035: 
1.243     albertel 13036: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13037: custom role; give a custom role to a user for the level given by URL.  Specify
                   13038: name and domain of role author, and role name
1.191     harris41 13039: 
                   13040: =item *
                   13041: 
1.243     albertel 13042: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13043: 
                   13044: =item *
                   13045: 
1.243     albertel 13046: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13047: 
                   13048: =back
                   13049: 
                   13050: =head2 Course Infomation
                   13051: 
                   13052: =over 4
1.191     harris41 13053: 
                   13054: =item *
                   13055: 
1.1118    foxr     13056: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13057: specified course id, including all environment settings for the
                   13058: course, the description of the course will be in the hash under the
                   13059: key 'description'
1.191     harris41 13060: 
1.1118    foxr     13061: $options is an optional parameter that if supplied is a hash reference that controls
                   13062: what how this function works.  It has the following key/values:
                   13063: 
                   13064: =over 4
                   13065: 
                   13066: =item freshen_cache
                   13067: 
                   13068: If defined, and the environment cache for the course is valid, it is 
                   13069: returned in the returned hash.
                   13070: 
                   13071: =item one_time
                   13072: 
                   13073: If defined, the last cache time is set to _now_
                   13074: 
                   13075: =item user
                   13076: 
                   13077: If defined, the supplied username is used instead of the current user.
                   13078: 
                   13079: 
                   13080: =back
                   13081: 
1.191     harris41 13082: =item *
                   13083: 
1.624     albertel 13084: resdata($name,$domain,$type,@which) : request for current parameter
                   13085: setting for a specific $type, where $type is either 'course' or 'user',
                   13086: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  13087: answers for 10 minutes.
1.243     albertel 13088: 
1.877     foxr     13089: =item *
                   13090: 
                   13091: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13092: data base, returning a hash that is keyed by the resource name and has
                   13093: values that are the resource value.  I believe that the timestamps and
                   13094: versions are also returned.
                   13095: 
1.1172.2.31  raeburn  13096: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13097: supplemental content area. This routine caches the number of files for
                   13098: 10 minutes.
                   13099: 
1.243     albertel 13100: =back
                   13101: 
                   13102: =head2 Course Modification
                   13103: 
                   13104: =over 4
1.191     harris41 13105: 
                   13106: =item *
                   13107: 
1.243     albertel 13108: writecoursepref($courseid,%prefs) : write preferences (environment
                   13109: database) for a course
1.191     harris41 13110: 
                   13111: =item *
                   13112: 
1.1011    raeburn  13113: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13114: 
                   13115: =item *
                   13116: 
1.1038    raeburn  13117: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13118: 
1.1167    droeschl 13119: =item *
                   13120: 
                   13121: is_course($courseid), is_course($cdom, $cnum)
                   13122: 
                   13123: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13124: two component version $cdom, $cnum. It checks if the specified course exists.
                   13125: 
                   13126: Returns:
                   13127:     undef if the course doesn't exist, otherwise
                   13128:     in scalar context the combined courseid.
                   13129:     in list context the two components of the course identifier, domain and 
                   13130:     courseid.    
                   13131: 
1.243     albertel 13132: =back
                   13133: 
                   13134: =head2 Resource Subroutines
                   13135: 
                   13136: =over 4
1.191     harris41 13137: 
                   13138: =item *
                   13139: 
1.243     albertel 13140: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13141: 
                   13142: =item *
                   13143: 
1.243     albertel 13144: repcopy($filename) : subscribes to the requested file, and attempts to
                   13145: replicate from the owning library server, Might return
1.607     raeburn  13146: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13147: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13148: resource. Expects the local filesystem pathname
                   13149: (/home/httpd/html/res/....)
                   13150: 
                   13151: =back
                   13152: 
                   13153: =head2 Resource Information
                   13154: 
                   13155: =over 4
1.191     harris41 13156: 
                   13157: =item *
                   13158: 
1.1172.2.28  raeburn  13159: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13160: and returns the value of a variety of different possible values,
                   13161: $varname should be a request string, and the other parameters can be
                   13162: used to specify who and what one is asking about. Ordinarily, $cid 
                   13163: does not need to be specified, as it is retrived from 
                   13164: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13165: within lonuserstate::loadmap() when initializing a course, before
                   13166: $env{'request.course.id'} has been set, so it needs to be provided
                   13167: in that one case.
1.243     albertel 13168: 
                   13169: Possible values for $varname are environment.lastname (or other item
                   13170: from the envirnment hash), user.name (or someother aspect about the
                   13171: user), resource.0.maxtries (or some other part and parameter of a
                   13172: resource)
1.204     albertel 13173: 
                   13174: =item *
                   13175: 
1.243     albertel 13176: directcondval($number) : get current value of a condition; reads from a state
                   13177: string
1.204     albertel 13178: 
                   13179: =item *
                   13180: 
1.243     albertel 13181: condval($condidx) : value of condition index based on state
1.204     albertel 13182: 
                   13183: =item *
                   13184: 
1.243     albertel 13185: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13186: resource's metadata, $what should be either a specific key, or either
                   13187: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13188: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13189: 
                   13190: this function automatically caches all requests
1.191     harris41 13191: 
                   13192: =item *
                   13193: 
1.243     albertel 13194: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13195: network of library servers; returns file handle of where SQL and regex results
                   13196: will be stored for query
1.191     harris41 13197: 
                   13198: =item *
                   13199: 
1.243     albertel 13200: symbread($filename) : return symbolic list entry (filename argument optional);
                   13201: returns the data handle
1.191     harris41 13202: 
                   13203: =item *
                   13204: 
1.1172.2.17  raeburn  13205: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13206: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13207: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13208: on failure, user must be in a course, as it assumes the existence of
                   13209: the course initial hash, and uses $env('request.course.id'}.  The third
                   13210: arg is an optional reference to a scalar.  If this arg is passed in the
                   13211: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13212: encrypted; otherwise it will be null.
1.243     albertel 13213: 
1.191     harris41 13214: =item *
                   13215: 
1.243     albertel 13216: symbclean($symb) : removes versions numbers from a symb, returns the
                   13217: cleaned symb
1.191     harris41 13218: 
                   13219: =item *
                   13220: 
1.243     albertel 13221: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13222: course map, user must be in a course for it to work.
1.191     harris41 13223: 
                   13224: =item *
                   13225: 
1.243     albertel 13226: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13227: 
                   13228: =item *
                   13229: 
1.243     albertel 13230: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13231: a random seed, all arguments are optional, if they aren't sent it uses the
                   13232: environment to derive them. Note: if symb isn't sent and it can't get one
                   13233: from &symbread it will use the current time as its return value
1.191     harris41 13234: 
                   13235: =item *
                   13236: 
1.243     albertel 13237: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13238: unfakeable, receipt
1.191     harris41 13239: 
                   13240: =item *
                   13241: 
1.620     albertel 13242: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13243: 
                   13244: =item *
                   13245: 
1.243     albertel 13246: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13247: 
                   13248: =item *
                   13249: 
1.243     albertel 13250: 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 13251: 
                   13252: =item *
                   13253: 
1.243     albertel 13254: 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 13255: 
                   13256: =item *
                   13257: 
1.243     albertel 13258: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13259: 
                   13260: =item *
                   13261: 
1.243     albertel 13262: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13263: forcing spreadsheet to reevaluate the resource scores next time.
                   13264: 
1.1172.2.13  raeburn  13265: =item *
                   13266: 
                   13267: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13268: when viewing in course context.
                   13269: 
                   13270:  input: six args -- filename (decluttered), course number, course domain,
                   13271:                     url, symb (if registered) and group (if this is a
                   13272:                     group item -- e.g., bulletin board, group page etc.).
                   13273: 
                   13274:  output: array of five scalars --
                   13275:          $cfile -- url for file editing if editable on current server
                   13276:          $home -- homeserver of resource (i.e., for author if published,
                   13277:                                           or course if uploaded.).
                   13278:          $switchserver --  1 if server switch will be needed.
                   13279:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13280:          $forceview -- 1 if icon/link should be to go to view mode
                   13281: 
                   13282: =item *
                   13283: 
                   13284: is_course_upload($file,$cnum,$cdom)
                   13285: 
                   13286: Used in course context to determine if current file was uploaded to
                   13287: the course (i.e., would be found in /userfiles/docs on the course's
                   13288: homeserver.
                   13289: 
                   13290:   input: 3 args -- filename (decluttered), course number and course domain.
                   13291:   output: boolean -- 1 if file was uploaded.
                   13292: 
1.243     albertel 13293: =back
                   13294: 
                   13295: =head2 Storing/Retreiving Data
                   13296: 
                   13297: =over 4
1.191     harris41 13298: 
                   13299: =item *
                   13300: 
1.243     albertel 13301: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13302: for this url; hashref needs to be given and should be a \%hashname; the
                   13303: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13304: be derived from the env
1.191     harris41 13305: 
                   13306: =item *
                   13307: 
1.243     albertel 13308: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13309: uses critical subroutine
1.191     harris41 13310: 
                   13311: =item *
                   13312: 
1.243     albertel 13313: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13314: all args are optional
1.191     harris41 13315: 
                   13316: =item *
                   13317: 
1.717     albertel 13318: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13319: dumps the complete (or key matching regexp) namespace into a hash
                   13320: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13321: normally &store()ed into
                   13322: 
                   13323: $range should be either an integer '100' (give me the first 100
                   13324:                                            matching records)
                   13325:               or be  two integers sperated by a - with no spaces
                   13326:                  '30-50' (give me the 30th through the 50th matching
                   13327:                           records)
                   13328: 
                   13329: 
                   13330: =item *
                   13331: 
                   13332: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13333: replaces a &store() version of data with a replacement set of data
                   13334: for a particular resource in a namespace passed in the $storehash hash 
                   13335: reference
                   13336: 
                   13337: =item *
                   13338: 
1.243     albertel 13339: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13340: works very similar to store/cstore, but all data is stored in a
                   13341: temporary location and can be reset using tmpreset, $storehash should
                   13342: be a hash reference, returns nothing on success
1.191     harris41 13343: 
                   13344: =item *
                   13345: 
1.243     albertel 13346: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13347: similar to restore, but all data is stored in a temporary location and
                   13348: can be reset using tmpreset. Returns a hash of values on success,
                   13349: error string otherwise.
1.191     harris41 13350: 
                   13351: =item *
                   13352: 
1.243     albertel 13353: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13354: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13355: 
                   13356: =item *
                   13357: 
1.243     albertel 13358: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13359: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13360: 
                   13361: =item *
                   13362: 
1.243     albertel 13363: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13364: namesp ($udom and $uname are optional)
1.191     harris41 13365: 
                   13366: =item *
                   13367: 
1.702     albertel 13368: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13369: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13370: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13371: 
1.702     albertel 13372: $range should be either an integer '100' (give me the first 100
                   13373:                                            matching records)
                   13374:               or be  two integers sperated by a - with no spaces
                   13375:                  '30-50' (give me the 30th through the 50th matching
                   13376:                           records)
1.449     matthew  13377: =item *
                   13378: 
                   13379: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13380: $store can be a scalar, an array reference, or if the amount to be 
                   13381: incremented is > 1, a hash reference.
                   13382: 
                   13383: ($udom and $uname are optional)
1.191     harris41 13384: 
                   13385: =item *
                   13386: 
1.243     albertel 13387: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13388: ($udom and $uname are optional)
1.191     harris41 13389: 
                   13390: =item *
                   13391: 
1.243     albertel 13392: cput($namespace,$storehash,$udom,$uname) : critical put
                   13393: ($udom and $uname are optional)
1.191     harris41 13394: 
                   13395: =item *
                   13396: 
1.748     albertel 13397: newput($namespace,$storehash,$udom,$uname) :
                   13398: 
                   13399: Attempts to store the items in the $storehash, but only if they don't
                   13400: currently exist, if this succeeds you can be certain that you have 
                   13401: successfully created a new key value pair in the $namespace db.
                   13402: 
                   13403: 
                   13404: Args:
                   13405:  $namespace: name of database to store values to
                   13406:  $storehash: hashref to store to the db
                   13407:  $udom: (optional) domain of user containing the db
                   13408:  $uname: (optional) name of user caontaining the db
                   13409: 
                   13410: Returns:
                   13411:  'ok' -> succeeded in storing all keys of $storehash
                   13412:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13413:                         least <key> already existed in the db (other
                   13414:                         requested keys may also already exist)
1.967     bisitz   13415:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13416:  'con_lost' -> unable to contact request server
                   13417:  'refused' -> action was not allowed by remote machine
                   13418: 
                   13419: 
                   13420: =item *
                   13421: 
1.243     albertel 13422: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13423: reference filled in from namesp (encrypts the return communication)
                   13424: ($udom and $uname are optional)
1.191     harris41 13425: 
                   13426: =item *
                   13427: 
1.243     albertel 13428: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13429: critical subroutine
                   13430: 
1.806     raeburn  13431: =item *
                   13432: 
1.860     raeburn  13433: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13434: array reference filled in from namespace found in domain level on either
                   13435: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13436: 
                   13437: =item *
                   13438: 
1.860     raeburn  13439: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13440: domain level either on specified domain server ($uhome) or primary domain 
                   13441: server ($udom and $uhome are optional)
1.806     raeburn  13442: 
1.943     raeburn  13443: =item * 
                   13444: 
1.1172.2.35  raeburn  13445: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   13446: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13447: the target domain.
                   13448: 
                   13449: May also include additional key => value pairs for the following groups:
                   13450: 
                   13451: =over
                   13452: 
                   13453: =item
                   13454: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13455: 
                   13456: =over
                   13457: 
                   13458: =item defaultquota, authorquota
                   13459: 
                   13460: =back
                   13461: 
                   13462: =item
                   13463: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13464: portfolio for users).
                   13465: 
                   13466: =over
                   13467: 
                   13468: =item
                   13469: aboutme, blog, webdav, portfolio
                   13470: 
                   13471: =back
                   13472: 
                   13473: =item
                   13474: requestcourses: ability to request courses, and how requests are processed.
                   13475: 
                   13476: =over
                   13477: 
                   13478: =item
1.1172.2.37  raeburn  13479: official, unofficial, community, textbook
1.1172.2.35  raeburn  13480: 
                   13481: =back
                   13482: 
                   13483: =item
                   13484: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13485: 
                   13486: =over
                   13487: 
                   13488: =item
1.1172.2.44  raeburn  13489: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  13490: 
                   13491: =back
                   13492: 
                   13493: =item
                   13494: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13495: for course's uploaded content.
                   13496: 
                   13497: =over
                   13498: 
                   13499: =item
1.1172.2.37  raeburn  13500: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35  raeburn  13501: 
                   13502: =back
                   13503: 
                   13504: =item
                   13505: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13506: on your servers.
                   13507: 
                   13508: =over
                   13509: 
                   13510: =item
                   13511: remotesessions, hostedsessions
                   13512: 
                   13513: =back
                   13514: 
                   13515: =back
                   13516: 
                   13517: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13518: utility to create a configuration.db file on a domain's primary library server
                   13519: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13520: -- corresponding values are authentication type (internal, krb4, krb5,
                   13521: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   13522: will be available. Values are retrieved from cache (if current), unless the
                   13523: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13524: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13525: 
                   13526: Typical usage:
1.943     raeburn  13527: 
1.1172.2.35  raeburn  13528: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13529: 
1.243     albertel 13530: =back
                   13531: 
                   13532: =head2 Network Status Functions
                   13533: 
                   13534: =over 4
1.191     harris41 13535: 
                   13536: =item *
                   13537: 
1.1137    raeburn  13538: dirlist() : return directory list based on URI (first arg).
                   13539: 
                   13540: Inputs: 1 required, 5 optional.
                   13541: 
                   13542: =over
                   13543: 
                   13544: =item 
                   13545: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13546: 
                   13547: =item
                   13548: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13549: 
                   13550: =item
                   13551: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13552: 
                   13553: =item
                   13554: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13555: 
                   13556: =item
                   13557: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13558: 
                   13559: =item 
                   13560: $alternateRoot - path to prepend in place of path from $uri.
                   13561: 
                   13562: =back
                   13563: 
                   13564: Returns: Array of up to two items.
                   13565: 
                   13566: =over
                   13567: 
                   13568: a reference to an array of files/subdirectories
                   13569: 
                   13570: =over
                   13571: 
                   13572: Each element in the array of files/subdirectories is a & separated list of
                   13573: item name and the result of running stat on the item.  If dirlist was requested
                   13574: for a file instead of a directory, the item name will be ''. For a directory 
                   13575: listing, if the item is a metadata file, the element will end &N&M 
                   13576: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13577: default copyright set (1).  
                   13578: 
                   13579: =back
                   13580: 
                   13581: a scalar containing error condition (if encountered).
                   13582: 
                   13583: =over
                   13584: 
                   13585: =item 
                   13586: no_host (no homeserver identified for $username:$domain).
                   13587: 
                   13588: =item 
                   13589: no_such_host (server contacted for listing not identified as valid host).
                   13590: 
                   13591: =item 
                   13592: con_lost (connection to remote server failed).
                   13593: 
                   13594: =item 
                   13595: refused (invalid $username:$domain received on lond side).
                   13596: 
                   13597: =item 
                   13598: no_such_dir (directory at specified path on lond side does not exist). 
                   13599: 
                   13600: =item 
                   13601: empty (directory at specified path on lond side is empty).
                   13602: 
                   13603: =over
                   13604: 
                   13605: This is currently not encountered because the &ls3, &ls2, 
                   13606: &ls (_handler) routines on the lond side do not filter out
                   13607: . and .. from a directory listing. 
                   13608: 
                   13609: =back
                   13610: 
                   13611: =back
                   13612: 
                   13613: =back
1.191     harris41 13614: 
                   13615: =item *
                   13616: 
1.243     albertel 13617: spareserver() : find server with least workload from spare.tab
                   13618: 
1.986     foxr     13619: 
                   13620: =item *
                   13621: 
                   13622: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13623: if there is no corresponding loncapa host.
                   13624: 
1.243     albertel 13625: =back
                   13626: 
1.986     foxr     13627: 
1.243     albertel 13628: =head2 Apache Request
                   13629: 
                   13630: =over 4
1.191     harris41 13631: 
                   13632: =item *
                   13633: 
1.243     albertel 13634: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13635: localhost, posts hash
                   13636: 
                   13637: =back
                   13638: 
                   13639: =head2 Data to String to Data
                   13640: 
                   13641: =over 4
1.191     harris41 13642: 
                   13643: =item *
                   13644: 
1.243     albertel 13645: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13646: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13647: 
                   13648: =item *
                   13649: 
1.243     albertel 13650: hashref2str($hashref) : convert a hashref into a string complete with
                   13651: escaping and '=' and '&' separators, supports elements that are
                   13652: arrayrefs and hashrefs
1.191     harris41 13653: 
                   13654: =item *
                   13655: 
1.243     albertel 13656: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13657: with escaping and '&' separators, supports elements that are arrayrefs
                   13658: and hashrefs
1.191     harris41 13659: 
                   13660: =item *
                   13661: 
1.243     albertel 13662: str2hash($string) : convert string to hash using unescaping and
                   13663: splitting on '=' and '&', supports elements that are arrayrefs and
                   13664: hashrefs
1.191     harris41 13665: 
                   13666: =item *
                   13667: 
1.243     albertel 13668: str2array($string) : convert string to hash using unescaping and
                   13669: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13670: 
                   13671: =back
                   13672: 
                   13673: =head2 Logging Routines
                   13674: 
                   13675: 
                   13676: These routines allow one to make log messages in the lonnet.log and
                   13677: lonnet.perm logfiles.
1.191     harris41 13678: 
1.1119    foxr     13679: =over 4
                   13680: 
1.191     harris41 13681: =item *
                   13682: 
1.243     albertel 13683: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13684: 
                   13685: =item *
                   13686: 
1.243     albertel 13687: logthis() : append message to the normal lonnet.log file, it gets
                   13688: preiodically rolled over and deleted.
1.191     harris41 13689: 
                   13690: =item *
                   13691: 
1.243     albertel 13692: logperm() : append a permanent message to lonnet.perm.log, this log
                   13693: file never gets deleted by any automated portion of the system, only
                   13694: messages of critical importance should go in here.
                   13695: 
1.1119    foxr     13696: 
1.243     albertel 13697: =back
                   13698: 
                   13699: =head2 General File Helper Routines
                   13700: 
                   13701: =over 4
1.191     harris41 13702: 
                   13703: =item *
                   13704: 
1.481     raeburn  13705: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13706: (a) files in /uploaded
                   13707:   (i) If a local copy of the file exists - 
                   13708:       compares modification date of local copy with last-modified date for 
                   13709:       definitive version stored on home server for course. If local copy is 
                   13710:       stale, requests a new version from the home server and stores it. 
                   13711:       If the original has been removed from the home server, then local copy 
                   13712:       is unlinked.
                   13713:   (ii) If local copy does not exist -
                   13714:       requests the file from the home server and stores it. 
                   13715:   
                   13716:   If $caller is 'uploadrep':  
                   13717:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13718:     for request for files originally uploaded via DOCS. 
                   13719:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13720:   
                   13721:   Otherwise:
                   13722:      This indicates a call from the content generation phase of the request.
                   13723:      -  returns the entire contents of the file or -1.
                   13724:      
                   13725: (b) files in /res
                   13726:    - returns the entire contents of a file or -1; 
                   13727:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13728: 
1.712     albertel 13729: 
                   13730: =item *
                   13731: 
                   13732: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13733:                   reference
                   13734: 
                   13735: returns either a stat() list of data about the file or an empty list
                   13736: if the file doesn't exist or couldn't find out about it (connection
                   13737: problems or user unknown)
                   13738: 
1.191     harris41 13739: =item *
                   13740: 
1.243     albertel 13741: filelocation($dir,$file) : returns file system location of a file
                   13742: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13743: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13744: and a file of ../bob will become /a/bob)
1.191     harris41 13745: 
                   13746: =item *
                   13747: 
                   13748: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13749: filelocation except for hrefs
                   13750: 
                   13751: =item *
                   13752: 
1.1172.2.49  raeburn  13753: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   13754: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 13755: 
1.243     albertel 13756: =back
                   13757: 
1.608     albertel 13758: =head2 Usererfile file routines (/uploaded*)
                   13759: 
                   13760: =over 4
                   13761: 
                   13762: =item *
                   13763: 
                   13764: userfileupload(): main rotine for putting a file in a user or course's
                   13765:                   filespace, arguments are,
                   13766: 
1.620     albertel 13767:  formname - required - this is the name of the element in $env where the
1.608     albertel 13768:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13769:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13770:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13771:  context - if coursedoc, store the file in the course of the active role
                   13772:              of the current user; 
                   13773:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13774:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13775:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13776:          if undefined, it will be placed in "unknown"
                   13777: 
                   13778:  (This routine calls clean_filename() to remove any dangerous
                   13779:  characters from the filename, and then calls finuserfileupload() to
                   13780:  complete the transaction)
                   13781: 
                   13782:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13783:  and /adm/notfound.html if unsuccessful
                   13784: 
                   13785: =item *
                   13786: 
                   13787: clean_filename(): routine for cleaing a filename up for storage in
                   13788:                  userfile space, argument is:
                   13789: 
                   13790:  filename - proposed filename
                   13791: 
                   13792: returns: the new clean filename
                   13793: 
                   13794: =item *
                   13795: 
1.1090    raeburn  13796: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13797: userspace, probably shouldn't be called directly
                   13798: 
                   13799:   docuname: username or courseid of destination for the file
                   13800:   docudom: domain of user/course of destination for the file
                   13801:   formname: same as for userfileupload()
1.1090    raeburn  13802:   fname: filename (including subdirectories) for the file
                   13803:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13804:   allfiles: reference to hash used to store objects found by parser
                   13805:   codebase: reference to hash used for codebases of java objects found by parser
                   13806:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13807:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13808:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13809:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13810:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13811:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13812:   mimetype: reference to scalar to accommodate mime type determined
                   13813:             from File::MMagic if $parser = parse.
1.608     albertel 13814: 
                   13815:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13816:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13817:  was 'overwrite').
                   13818:  
1.608     albertel 13819: 
                   13820: =item *
                   13821: 
                   13822: renameuserfile(): renames an existing userfile to a new name
                   13823: 
                   13824:   Args:
                   13825:    docuname: username or courseid of destination for the file
                   13826:    docudom: domain of user/course of destination for the file
                   13827:    old: current file name (including any subdirs under userfiles)
                   13828:    new: desired file name (including any subdirs under userfiles)
                   13829: 
                   13830: =item *
                   13831: 
                   13832: mkdiruserfile(): creates a directory is a userfiles dir
                   13833: 
                   13834:   Args:
                   13835:    docuname: username or courseid of destination for the file
                   13836:    docudom: domain of user/course of destination for the file
                   13837:    dir: dir to create (including any subdirs under userfiles)
                   13838: 
                   13839: =item *
                   13840: 
                   13841: removeuserfile(): removes a file that exists in userfiles
                   13842: 
                   13843:   Args:
                   13844:    docuname: username or courseid of destination for the file
                   13845:    docudom: domain of user/course of destination for the file
                   13846:    fname: filname to delete (including any subdirs under userfiles)
                   13847: 
                   13848: =item *
                   13849: 
                   13850: removeuploadedurl(): convience function for removeuserfile()
                   13851: 
                   13852:   Args:
                   13853:    url:  a full /uploaded/... url to delete
                   13854: 
1.747     albertel 13855: =item * 
                   13856: 
                   13857: get_portfile_permissions():
                   13858:   Args:
                   13859:     domain: domain of user or course contain the portfolio files
                   13860:     user: name of user or num of course contain the portfolio files
                   13861:   Returns:
                   13862:     hashref of a dump of the proper file_permissions.db
                   13863:    
                   13864: 
                   13865: =item * 
                   13866: 
                   13867: get_access_controls():
                   13868: 
                   13869: Args:
                   13870:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13871:   group: (optional) the group you want the files associated with
                   13872:   file: (optional) the file you want access info on
                   13873: 
                   13874: Returns:
1.749     raeburn  13875:     a hash (keys are file names) of hashes containing
                   13876:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13877:         values are XML containing access control settings (see below) 
1.747     albertel 13878: 
                   13879: Internal notes:
                   13880: 
1.749     raeburn  13881:  access controls are stored in file_permissions.db as key=value pairs.
                   13882:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13883:         where scope -> public,guest,course,group,domains or users.
                   13884:               end -> UNIX time for end of access (0 -> no end date)
                   13885:               start -> UNIX time for start of access
                   13886: 
                   13887:     value -> XML description of access control
                   13888:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13889:             <start></start>
                   13890:             <end></end>
                   13891: 
                   13892:             <password></password>  for scope type = guest
                   13893: 
                   13894:             <domain></domain>     for scope type = course or group
                   13895:             <number></number>
                   13896:             <roles id="">
                   13897:              <role></role>
                   13898:              <access></access>
                   13899:              <section></section>
                   13900:              <group></group>
                   13901:             </roles>
                   13902: 
                   13903:             <dom></dom>         for scope type = domains
                   13904: 
                   13905:             <users>             for scope type = users
                   13906:              <user>
                   13907:               <uname></uname>
                   13908:               <udom></udom>
                   13909:              </user>
                   13910:             </users>
                   13911:            </scope> 
                   13912:               
                   13913:  Access data is also aggregated for each file in an additional key=value pair:
                   13914:  key -> path to file/file_name\0accesscontrol 
                   13915:  value -> reference to hash
                   13916:           hash contains key = value pairs
                   13917:           where key = uniqueID:scope_end_start
                   13918:                 value = UNIX time record was last updated
                   13919: 
                   13920:           Used to improve speed of look-ups of access controls for each file.  
                   13921:  
                   13922:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13923: 
1.1172.2.13  raeburn  13924: =item *
                   13925: 
1.749     raeburn  13926: modify_access_controls():
                   13927: 
                   13928: Modifies access controls for a portfolio file
                   13929: Args
                   13930: 1. file name
                   13931: 2. reference to hash of required changes,
                   13932: 3. domain
                   13933: 4. username
                   13934:   where domain,username are the domain of the portfolio owner 
                   13935:   (either a user or a course) 
                   13936: 
                   13937: Returns:
                   13938: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13939: 2. result of deletions ('ok' or 'error', with error message).
                   13940: 3. reference to hash of any new or updated access controls.
                   13941: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13942:    key = integer (inbound ID)
1.1172.2.13  raeburn  13943:    value = uniqueID
                   13944: 
                   13945: =item *
                   13946: 
                   13947: get_timebased_id():
                   13948: 
                   13949: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13950: course via the Course Editor (e.g., folders, composite pages,
                   13951: group bulletin boards).
                   13952: 
                   13953: Args: (first three required; six others optional)
                   13954: 
                   13955: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13956:    docssequence, or name of group
                   13957: 
                   13958: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13959:    e.g., num, boardids
                   13960: 
                   13961: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13962:    file will be named nohist_namespace.db
                   13963: 
                   13964: 4. cdom: domain of course; default is current course domain from %env
                   13965: 
                   13966: 5. cnum: course number; default is current course number from %env
                   13967: 
                   13968: 6. idtype: set to concat if an additional digit is to be appended to the
                   13969:    unix timestamp to form the suffix, if the plain timestamp is already
                   13970:    in use.  Default is to not do this, but simply increment the unix
                   13971:    timestamp by 1 until a unique key is obtained.
                   13972: 
                   13973: 7. who: holder of locking key; defaults to user:domain for user.
                   13974: 
                   13975: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13976:    retrying); default is 3.
                   13977: 
                   13978: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13979: 
                   13980: Returns:
                   13981: 
                   13982: 1. suffix obtained (numeric)
                   13983: 
                   13984: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13985: 
                   13986: 3. error: contains (localized) error message if an error occurred.
                   13987: 
1.747     albertel 13988: 
1.608     albertel 13989: =back
                   13990: 
1.243     albertel 13991: =head2 HTTP Helper Routines
                   13992: 
                   13993: =over 4
                   13994: 
1.191     harris41 13995: =item *
                   13996: 
                   13997: escape() : unpack non-word characters into CGI-compatible hex codes
                   13998: 
                   13999: =item *
                   14000: 
                   14001: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14002: 
1.243     albertel 14003: =back
                   14004: 
                   14005: =head1 PRIVATE SUBROUTINES
                   14006: 
                   14007: =head2 Underlying communication routines (Shouldn't call)
                   14008: 
                   14009: =over 4
                   14010: 
                   14011: =item *
                   14012: 
                   14013: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14014: 
                   14015: =item *
                   14016: 
                   14017: reply() : uses subreply to send a message to remote machine, logs all failures
                   14018: 
                   14019: =item *
                   14020: 
                   14021: critical() : passes a critical message to another server; if cannot
                   14022: get through then place message in connection buffer directory and
                   14023: returns con_delayed, if incapable of saving message, returns
                   14024: con_failed
                   14025: 
                   14026: =item *
                   14027: 
                   14028: reconlonc() : tries to reconnect lonc client processes.
                   14029: 
                   14030: =back
                   14031: 
                   14032: =head2 Resource Access Logging
                   14033: 
                   14034: =over 4
                   14035: 
                   14036: =item *
                   14037: 
                   14038: flushcourselogs() : flush (save) buffer logs and access logs
                   14039: 
                   14040: =item *
                   14041: 
                   14042: courselog($what) : save message for course in hash
                   14043: 
                   14044: =item *
                   14045: 
                   14046: courseacclog($what) : save message for course using &courselog().  Perform
                   14047: special processing for specific resource types (problems, exams, quizzes, etc).
                   14048: 
1.191     harris41 14049: =item *
                   14050: 
                   14051: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14052: as a PerlChildExitHandler
1.243     albertel 14053: 
                   14054: =back
                   14055: 
                   14056: =head2 Other
                   14057: 
                   14058: =over 4
                   14059: 
                   14060: =item *
                   14061: 
                   14062: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14063: 
                   14064: =back
                   14065: 
                   14066: =cut
1.877     foxr     14067: 

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