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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.108! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.107 2019/08/01 19:13:26 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;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     81:             %managerstab);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.807     albertel   98: use LONCAPA qw(:DEFAULT :match);
1.740     www        99: use LONCAPA::Configuration;
1.1160    www       100: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   101: use LONCAPA::Lond;
1.1117    foxr      102: 
1.1090    raeburn   103: use File::Copy;
1.676     albertel  104: 
1.195     www       105: my $readit;
1.1172.2.79  raeburn   106: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  107: 
1.619     albertel  108: require Exporter;
                    109: 
                    110: our @ISA = qw (Exporter);
                    111: our @EXPORT = qw(%env);
                    112: 
1.1172.2.9  raeburn   113: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       114: {
                    115:     my $logid;
1.1172.2.9  raeburn   116:     sub write_log {
                    117: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    118:         if ($context eq 'course') {
                    119:             if (($cnum eq '') || ($cdom eq '')) {
                    120:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    121:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    122:             }
1.957     raeburn   123:         }
1.1172.2.13  raeburn   124: 	$logid ++;
1.957     raeburn   125:         my $now = time();
                    126: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   127:         my $logentry = {
                    128:                          $id => {
                    129:                                   'exe_uname' => $env{'user.name'},
                    130:                                   'exe_udom'  => $env{'user.domain'},
                    131:                                   'exe_time'  => $now,
                    132:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    133:                                   'delflag'   => $delflag,
                    134:                                   'logentry'  => $storehash,
                    135:                                   'uname'     => $uname,
                    136:                                   'udom'      => $udom,
                    137:                                 }
                    138:                        };
                    139:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       140:     }
                    141: }
1.1       albertel  142: 
1.163     harris41  143: sub logtouch {
                    144:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  145:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   146: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  147: 	close $fh;
                    148:     }
                    149:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    150:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    151: }
                    152: 
1.1       albertel  153: sub logthis {
                    154:     my $message=shift;
                    155:     my $execdir=$perlvar{'lonDaemons'};
                    156:     my $now=time;
                    157:     my $local=localtime($now);
1.1172.2.96  raeburn   158:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      159: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    160: 	print $fh $logstring;
1.448     albertel  161: 	close($fh);
                    162:     }
1.1       albertel  163:     return 1;
                    164: }
                    165: 
                    166: sub logperm {
                    167:     my $message=shift;
                    168:     my $execdir=$perlvar{'lonDaemons'};
                    169:     my $now=time;
                    170:     my $local=localtime($now);
1.1172.2.96  raeburn   171:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  172: 	print $fh "$now:$message:$local\n";
                    173: 	close($fh);
                    174:     }
1.1       albertel  175:     return 1;
                    176: }
                    177: 
1.850     albertel  178: sub create_connection {
1.853     albertel  179:     my ($hostname,$lonid) = @_;
1.851     albertel  180:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  181: 				     Type    => SOCK_STREAM,
                    182: 				     Timeout => 10);
                    183:     return 0 if (!$client);
1.890     albertel  184:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  185:     my $result = <$client>;
                    186:     chomp($result);
                    187:     return 1 if ($result eq 'done');
                    188:     return 0;
                    189: }
                    190: 
1.983     raeburn   191: sub get_server_timezone {
                    192:     my ($cnum,$cdom) = @_;
                    193:     my $home=&homeserver($cnum,$cdom);
                    194:     if ($home ne 'no_host') {
                    195:         my $cachetime = 24*3600;
                    196:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    197:         if (defined($cached)) {
                    198:             return $timezone;
                    199:         } else {
                    200:             my $timezone = &reply('servertimezone',$home);
                    201:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    202:         }
                    203:     }
                    204: }
1.850     albertel  205: 
1.1106    raeburn   206: sub get_server_distarch {
                    207:     my ($lonhost,$ignore_cache) = @_;
                    208:     if (defined($lonhost)) {
                    209:         if (!defined(&hostname($lonhost))) {
                    210:             return;
                    211:         }
                    212:         my $cachetime = 12*3600;
                    213:         if (!$ignore_cache) {
                    214:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    215:             if (defined($cached)) {
                    216:                 return $distarch;
                    217:             }
                    218:         }
                    219:         my $rep = &reply('serverdistarch',$lonhost);
                    220:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    221:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    222:                 $rep eq '') {
                    223:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    224:         }
                    225:     }
                    226:     return;
                    227: }
                    228: 
1.993     raeburn   229: sub get_server_loncaparev {
1.1073    raeburn   230:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   231:     if (defined($lonhost)) {
                    232:         if (!defined(&hostname($lonhost))) {
                    233:             undef($lonhost);
                    234:         }
                    235:     }
                    236:     if (!defined($lonhost)) {
                    237:         if (defined(&domain($dom,'primary'))) {
                    238:             $lonhost=&domain($dom,'primary');
                    239:             if ($lonhost eq 'no_host') {
                    240:                 undef($lonhost);
                    241:             }
                    242:         }
                    243:     }
                    244:     if (defined($lonhost)) {
1.1073    raeburn   245:         my $cachetime = 12*3600;
                    246:         if (!$ignore_cache) {
                    247:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    248:             if (defined($cached)) {
                    249:                 return $loncaparev;
                    250:             }
                    251:         }
                    252:         my ($answer,$loncaparev);
                    253:         my @ids=&current_machine_ids();
                    254:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    255:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   256:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   257:                 $loncaparev = $1;
                    258:             }
                    259:         } else {
                    260:             $answer = &reply('serverloncaparev',$lonhost);
                    261:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    262:                 if ($caller eq 'loncron') {
                    263:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   264:                     $ua->timeout(4);
1.1073    raeburn   265:                     my $protocol = $protocol{$lonhost};
                    266:                     $protocol = 'http' if ($protocol ne 'https');
                    267:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    268:                     my $request=new HTTP::Request('GET',$url);
                    269:                     my $response=$ua->request($request);
                    270:                     unless ($response->is_error()) {
                    271:                         my $content = $response->content;
1.1081    raeburn   272:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   273:                             $loncaparev = $1;
                    274:                         }
                    275:                     }
                    276:                 } else {
                    277:                     $loncaparev = $loncaparevs{$lonhost};
                    278:                 }
1.1081    raeburn   279:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   280:                 $loncaparev = $1;
                    281:             }
1.993     raeburn   282:         }
1.1073    raeburn   283:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   284:     }
                    285: }
                    286: 
1.1074    raeburn   287: sub get_server_homeID {
                    288:     my ($hostname,$ignore_cache,$caller) = @_;
                    289:     unless ($ignore_cache) {
                    290:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    291:         if (defined($cached)) {
                    292:             return $serverhomeID;
                    293:         }
                    294:     }
                    295:     my $cachetime = 12*3600;
                    296:     my $serverhomeID;
                    297:     if ($caller eq 'loncron') { 
                    298:         my @machine_ids = &machine_ids($hostname);
                    299:         foreach my $id (@machine_ids) {
                    300:             my $response = &reply('serverhomeID',$id);
                    301:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    302:                 $serverhomeID = $response;
                    303:                 last;
                    304:             }
                    305:         }
                    306:         if ($serverhomeID eq '') {
                    307:             $serverhomeID = $machine_ids[-1];
                    308:         }
                    309:     } else {
                    310:         $serverhomeID = $serverhomeIDs{$hostname};
                    311:     }
                    312:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    313: }
                    314: 
1.1121    raeburn   315: sub get_remote_globals {
                    316:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   317:     my ($result,%returnhash,%whatneeded);
                    318:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   319:         foreach my $what (sort(keys(%{$whathash}))) {
                    320:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   321:             my ($response,$cached);
1.1121    raeburn   322:             unless ($ignore_cache) {
1.1125    raeburn   323:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   324:             }
                    325:             if (defined($cached)) {
1.1125    raeburn   326:                 $returnhash{$what} = $response;
1.1121    raeburn   327:             } else {
1.1125    raeburn   328:                 $whatneeded{$what} = 1;
1.1121    raeburn   329:             }
                    330:         }
1.1125    raeburn   331:         if (keys(%whatneeded) == 0) {
                    332:             $result = 'ok';
                    333:         } else {
1.1121    raeburn   334:             my $requested = &freeze_escape(\%whatneeded);
                    335:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   336:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    337:                 ($rep eq 'unknown_cmd')) {
                    338:                 $result = $rep;
                    339:             } else {
                    340:                 $result = 'ok';
1.1121    raeburn   341:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   342:                 foreach my $item (@pairs) {
                    343:                     my ($key,$value)=split(/=/,$item,2);
                    344:                     my $what = &unescape($key);
                    345:                     my $hashid = $lonhost.'-'.$what;
                    346:                     $returnhash{$what}=&thaw_unescape($value);
                    347:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   348:                 }
                    349:             }
                    350:         }
                    351:     }
1.1125    raeburn   352:     return ($result,\%returnhash);
1.1121    raeburn   353: }
                    354: 
1.1124    raeburn   355: sub remote_devalidate_cache {
1.1172.2.35  raeburn   356:     my ($lonhost,$cachekeys) = @_;
                    357:     my $items;
                    358:     return unless (ref($cachekeys) eq 'ARRAY');
                    359:     my $cachestr = join('&',@{$cachekeys});
                    360:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   361: }
                    362: 
1.1       albertel  363: # -------------------------------------------------- Non-critical communication
                    364: sub subreply {
                    365:     my ($cmd,$server)=@_;
1.838     albertel  366:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      367:     #
                    368:     #  With loncnew process trimming, there's a timing hole between lonc server
                    369:     #  process exit and the master server picking up the listen on the AF_UNIX
                    370:     #  socket.  In that time interval, a lock file will exist:
                    371: 
                    372:     my $lockfile=$peerfile.".lock";
                    373:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   374: 	sleep(0.1);
1.549     foxr      375:     }
                    376:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      377:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      378:     #
1.550     foxr      379:     #   We'll give the connection a few tries before abandoning it.  If
                    380:     #   connection is not possible, we'll con_lost back to the client.
                    381:     #   
                    382:     my $client;
                    383:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    384: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    385: 				      Type    => SOCK_STREAM,
                    386: 				      Timeout => 10);
1.869     albertel  387: 	if ($client) {
1.550     foxr      388: 	    last;		# Connected!
1.850     albertel  389: 	} else {
1.853     albertel  390: 	    &create_connection(&hostname($server),$server);
1.550     foxr      391: 	}
1.1172.2.79  raeburn   392:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      393:     }
                    394:     my $answer;
                    395:     if ($client) {
1.704     albertel  396: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      397: 	$answer=<$client>;
                    398: 	if (!$answer) { $answer="con_lost"; }
                    399: 	chomp($answer);
                    400:     } else {
                    401: 	$answer = 'con_lost';	# Failed connection.
                    402:     }
1.1       albertel  403:     return $answer;
                    404: }
                    405: 
                    406: sub reply {
                    407:     my ($cmd,$server)=@_;
1.838     albertel  408:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  409:     my $answer=subreply($cmd,$server);
1.65      www       410:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  411:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       412:                 " $cmd to $server returned $answer</font>");
                    413:     }
1.1       albertel  414:     return $answer;
                    415: }
                    416: 
                    417: # ----------------------------------------------------------- Send USR1 to lonc
                    418: 
                    419: sub reconlonc {
1.891     albertel  420:     my ($lonid) = @_;
                    421:     if ($lonid) {
1.1172.2.72  raeburn   422:         my $hostname = &hostname($lonid);
1.891     albertel  423: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    424: 	if ($hostname && -e $peerfile) {
                    425: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    426: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    427: 					     Type    => SOCK_STREAM,
                    428: 					     Timeout => 10);
                    429: 	    if ($client) {
                    430: 		print $client ("reset_retries\n");
                    431: 		my $answer=<$client>;
                    432: 		#reset just this one.
                    433: 	    }
                    434: 	}
                    435: 	return;
                    436:     }
                    437: 
1.836     www       438:     &logthis("Trying to reconnect lonc");
1.1       albertel  439:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   440:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  441: 	my $loncpid=<$fh>;
                    442:         chomp($loncpid);
                    443:         if (kill 0 => $loncpid) {
                    444: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    445:             kill USR1 => $loncpid;
                    446:             sleep 1;
1.836     www       447:          } else {
1.12      www       448: 	    &logthis(
1.672     albertel  449:                "<font color=\"blue\">WARNING:".
1.12      www       450:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  451:         }
                    452:     } else {
1.836     www       453: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  454:     }
                    455: }
                    456: 
                    457: # ------------------------------------------------------ Critical communication
1.12      www       458: 
1.1       albertel  459: sub critical {
                    460:     my ($cmd,$server)=@_;
1.838     albertel  461:     unless (&hostname($server)) {
1.672     albertel  462:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       463:                " Critical message to unknown server ($server)</font>");
                    464:         return 'no_such_host';
                    465:     }
1.1       albertel  466:     my $answer=reply($cmd,$server);
                    467:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   468: 	&reconlonc($server);
1.589     albertel  469: 	my $answer=reply($cmd,$server);
1.1       albertel  470:         if ($answer eq 'con_lost') {
                    471:             my $now=time;
                    472:             my $middlename=$cmd;
1.5       www       473:             $middlename=substr($middlename,0,16);
1.1       albertel  474:             $middlename=~s/\W//g;
                    475:             my $dfilename=
1.305     www       476:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    477:             $dumpcount++;
1.1       albertel  478:             {
1.448     albertel  479: 		my $dfh;
1.1172.2.96  raeburn   480: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  481: 		    print $dfh "$cmd\n"; 
                    482: 		    close($dfh);
                    483: 		}
1.1       albertel  484:             }
1.1172.2.79  raeburn   485:             sleep 1;
1.1       albertel  486:             my $wcmd='';
                    487:             {
1.448     albertel  488: 		my $dfh;
1.1172.2.96  raeburn   489: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  490: 		    $wcmd=<$dfh>; 
                    491: 		    close($dfh);
                    492: 		}
1.1       albertel  493:             }
                    494:             chomp($wcmd);
1.7       www       495:             if ($wcmd eq $cmd) {
1.672     albertel  496: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       497:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  498:                 &logperm("D:$server:$cmd");
                    499: 	        return 'con_delayed';
                    500:             } else {
1.672     albertel  501:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       502:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  503:                 &logperm("F:$server:$cmd");
                    504:                 return 'con_failed';
                    505:             }
                    506:         }
                    507:     }
                    508:     return $answer;
1.405     albertel  509: }
                    510: 
1.755     albertel  511: # ------------------------------------------- check if return value is an error
                    512: 
                    513: sub error {
                    514:     my ($result) = @_;
1.756     albertel  515:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  516: 	if ($2 == 2) { return undef; }
                    517: 	return $1;
                    518:     }
                    519:     return undef;
                    520: }
                    521: 
1.783     albertel  522: sub convert_and_load_session_env {
                    523:     my ($lonidsdir,$handle)=@_;
                    524:     my @profile;
                    525:     {
1.917     albertel  526: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    527: 	if (!$opened) {
1.915     albertel  528: 	    return 0;
                    529: 	}
1.783     albertel  530: 	flock($idf,LOCK_SH);
                    531: 	@profile=<$idf>;
                    532: 	close($idf);
                    533:     }
                    534:     my %temp_env;
                    535:     foreach my $line (@profile) {
1.786     albertel  536: 	if ($line !~ m/=/) {
                    537: 	    return 0;
                    538: 	}
1.783     albertel  539: 	chomp($line);
                    540: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    541: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    542:     }
                    543:     unlink("$lonidsdir/$handle.id");
                    544:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    545: 	    0640)) {
                    546: 	%disk_env = %temp_env;
                    547: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    548: 	untie(%disk_env);
                    549:     }
1.786     albertel  550:     return 1;
1.783     albertel  551: }
                    552: 
1.374     www       553: # ------------------------------------------- Transfer profile into environment
1.780     albertel  554: my $env_loaded;
                    555: sub transfer_profile_to_env {
1.788     albertel  556:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    557:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       558: 
1.720     albertel  559:     if (!defined($lonidsdir)) {
                    560: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    561:     }
                    562:     if (!defined($handle)) {
                    563:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    564:     }
                    565: 
1.786     albertel  566:     my $convert;
                    567:     {
1.917     albertel  568:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    569: 	if (!$opened) {
1.915     albertel  570: 	    return;
                    571: 	}
1.786     albertel  572: 	flock($idf,LOCK_SH);
                    573: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    574: 		&GDBM_READER(),0640)) {
                    575: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    576: 	    untie(%disk_env);
                    577: 	} else {
                    578: 	    $convert = 1;
                    579: 	}
                    580:     }
                    581:     if ($convert) {
                    582: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    583: 	    &logthis("Failed to load session, or convert session.");
                    584: 	}
1.374     www       585:     }
1.783     albertel  586: 
1.786     albertel  587:     my %remove;
1.783     albertel  588:     while ( my $envname = each(%env) ) {
1.433     matthew   589:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    590:             if ($time < time-300) {
1.783     albertel  591:                 $remove{$key}++;
1.433     matthew   592:             }
                    593:         }
                    594:     }
1.783     albertel  595: 
1.619     albertel  596:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  597:     $env_loaded=1;
1.783     albertel  598:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   599:         &delenv($expired_key);
1.374     www       600:     }
1.1       albertel  601: }
                    602: 
1.916     albertel  603: # ---------------------------------------------------- Check for valid session 
                    604: sub check_for_valid_session {
1.1172.2.96  raeburn   605:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  606:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108! raeburn   607:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   608:     if ($name eq 'lonDAV') {
                    609:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    610:     } else {
                    611:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108! raeburn   612:         if ($name eq '') {
        !           613:             $name = 'lonID';
        !           614:         }
        !           615:     }
        !           616:     if ($name eq 'lonID') {
        !           617:         $secure = 'lonSID';
        !           618:         $linkname = 'lonLinkID';
        !           619:         $pubname = 'lonPubID';
        !           620:         if (exists($cookies{$secure})) {
        !           621:             $lonid=$cookies{$secure};
        !           622:         } elsif (exists($cookies{$name})) {
        !           623:             $lonid=$cookies{$name};
        !           624:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
        !           625:             $lonid=$cookies{$linkname};
        !           626:         } elsif (exists($cookies{$pubname})) {
        !           627:             $lonid=$cookies{$pubname};
        !           628:         }
        !           629:     } else {
        !           630:         $lonid=$cookies{$name};
        !           631:     }
        !           632:     return undef if (!$lonid);
        !           633: 
        !           634:     my $handle=&LONCAPA::clean_handle($lonid->value);
        !           635:     if (-l "$lonidsdir/$handle.id") {
        !           636:         my $link = readlink("$lonidsdir/$handle.id");
        !           637:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
        !           638:             $handle = $1;
        !           639:         }
1.1155    raeburn   640:     }
1.1172.2.96  raeburn   641:     if (!-e "$lonidsdir/$handle.id") {
                    642:         if ((ref($domref)) && ($name eq 'lonID') &&
                    643:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    644:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    645:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    646:                 $$domref = $possudom;
                    647:             }
                    648:         }
                    649:         return undef;
                    650:     }
1.916     albertel  651: 
1.917     albertel  652:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    653:     return undef if (!$opened);
1.916     albertel  654: 
                    655:     flock($idf,LOCK_SH);
                    656:     my %disk_env;
                    657:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    658: 	    &GDBM_READER(),0640)) {
                    659: 	return undef;	
                    660:     }
                    661: 
                    662:     if (!defined($disk_env{'user.name'})
                    663: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   664:         untie(%disk_env);
1.916     albertel  665: 	return undef;
                    666:     }
1.1172.2.18  raeburn   667: 
1.1172.2.36  raeburn   668:     if (ref($userhashref) eq 'HASH') {
                    669:         $userhashref->{'name'} = $disk_env{'user.name'};
                    670:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   671:     }
1.1172.2.107  raeburn   672:     untie(%disk_env);
1.1172.2.18  raeburn   673: 
1.916     albertel  674:     return $handle;
                    675: }
                    676: 
1.830     albertel  677: sub timed_flock {
                    678:     my ($file,$lock_type) = @_;
                    679:     my $failed=0;
                    680:     eval {
                    681: 	local $SIG{__DIE__}='DEFAULT';
                    682: 	local $SIG{ALRM}=sub {
                    683: 	    $failed=1;
                    684: 	    die("failed lock");
                    685: 	};
                    686: 	alarm(13);
                    687: 	flock($file,$lock_type);
                    688: 	alarm(0);
                    689:     };
                    690:     if ($failed) {
                    691: 	return undef;
                    692:     } else {
                    693: 	return 1;
                    694:     }
                    695: }
                    696: 
1.1172.2.107  raeburn   697: sub get_sessionfile_vars {
                    698:     my ($handle,$lonidsdir,$storearr) = @_;
                    699:     my %returnhash;
                    700:     unless (ref($storearr) eq 'ARRAY') {
                    701:         return %returnhash;
                    702:     }
                    703:     if (-l "$lonidsdir/$handle.id") {
                    704:         my $link = readlink("$lonidsdir/$handle.id");
                    705:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    706:             $handle = $1;
                    707:         }
                    708:     }
                    709:     if ((-e "$lonidsdir/$handle.id") &&
                    710:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    711:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    712:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    713:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    714:                 flock($idf,LOCK_SH);
                    715:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    716:                         &GDBM_READER(),0640)) {
                    717:                     foreach my $item (@{$storearr}) {
                    718:                         $returnhash{$item} = $disk_env{$item};
                    719:                     }
                    720:                     untie(%disk_env);
                    721:                 }
                    722:             }
                    723:         }
                    724:     }
                    725:     return %returnhash;
                    726: }
                    727: 
1.5       www       728: # ---------------------------------------------------------- Append Environment
                    729: 
                    730: sub appenv {
1.949     raeburn   731:     my ($newenv,$roles) = @_;
                    732:     if (ref($newenv) eq 'HASH') {
                    733:         foreach my $key (keys(%{$newenv})) {
                    734:             my $refused = 0;
                    735: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    736:                 $refused = 1;
                    737:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   738:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   739:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    740:                         $refused = 0;
                    741:                     }
                    742:                 }
                    743:             }
                    744:             if ($refused) {
                    745:                 &logthis("<font color=\"blue\">WARNING: ".
                    746:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    747:                          .'</font>');
                    748: 	        delete($newenv->{$key});
                    749:             } else {
                    750:                 $env{$key}=$newenv->{$key};
                    751:             }
                    752:         }
1.1172.2.96  raeburn   753:         my $lonids = $perlvar{'lonIDsDir'};
                    754:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    755:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    756:             if ($opened
                    757: 	        && &timed_flock($env_file,LOCK_EX)
                    758: 	        &&
                    759: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    760: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    761: 	        while (my ($key,$value) = each(%{$newenv})) {
                    762: 	            $disk_env{$key} = $value;
                    763: 	        }
                    764: 	        untie(%disk_env);
                    765:             }
1.35      www       766:         }
1.191     harris41  767:     }
1.56      www       768:     return 'ok';
                    769: }
                    770: # ----------------------------------------------------- Delete from Environment
                    771: 
                    772: sub delenv {
1.1104    raeburn   773:     my ($delthis,$regexp,$roles) = @_;
                    774:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    775:         my $refused = 1;
                    776:         if (ref($roles) eq 'ARRAY') {
                    777:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    778:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    779:                 $refused = 0;
                    780:             }
                    781:         }
                    782:         if ($refused) {
                    783:             &logthis("<font color=\"blue\">WARNING: ".
                    784:                      "Attempt to delete from environment ".$delthis);
                    785:             return 'error';
                    786:         }
1.56      www       787:     }
1.917     albertel  788:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    789:     if ($opened
1.915     albertel  790: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  791: 	&&
                    792: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    793: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  794: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   795: 	    if ($regexp) {
                    796:                 if ($key=~/^$delthis/) {
                    797:                     delete($env{$key});
                    798:                     delete($disk_env{$key});
                    799:                 } 
                    800:             } else {
                    801:                 if ($key=~/^\Q$delthis\E/) {
                    802: 		    delete($env{$key});
                    803: 		    delete($disk_env{$key});
                    804: 	        }
                    805:             }
1.448     albertel  806: 	}
1.783     albertel  807: 	untie(%disk_env);
1.5       www       808:     }
                    809:     return 'ok';
1.369     albertel  810: }
                    811: 
1.790     albertel  812: sub get_env_multiple {
                    813:     my ($name) = @_;
                    814:     my @values;
                    815:     if (defined($env{$name})) {
                    816:         # exists is it an array
                    817:         if (ref($env{$name})) {
                    818:             @values=@{ $env{$name} };
                    819:         } else {
                    820:             $values[0]=$env{$name};
                    821:         }
                    822:     }
                    823:     return(@values);
                    824: }
                    825: 
1.958     www       826: # ------------------------------------------------------------------- Locking
                    827: 
                    828: sub set_lock {
                    829:     my ($text)=@_;
                    830:     $locknum++;
                    831:     my $id=$$.'-'.$locknum;
                    832:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    833:              'session.lock.'.$id => $text});
                    834:     return $id;
                    835: }
                    836: 
                    837: sub get_locks {
                    838:     my $num=0;
                    839:     my %texts=();
                    840:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    841:        if ($lock=~/\w/) {
                    842:           $num++;
                    843:           $texts{$lock}=$env{'session.lock.'.$lock};
                    844:        }
                    845:    }
                    846:    return ($num,%texts);
                    847: }
                    848: 
                    849: sub remove_lock {
                    850:     my ($id)=@_;
                    851:     my $newlocks='';
                    852:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    853:        if (($lock=~/\w/) && ($lock ne $id)) {
                    854:           $newlocks.=','.$lock;
                    855:        }
                    856:     }
                    857:     &appenv({'session.locks' => $newlocks});
                    858:     &delenv('session.lock.'.$id);
                    859: }
                    860: 
                    861: sub remove_all_locks {
                    862:     my $activelocks=$env{'session.locks'};
                    863:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    864:        if ($lock=~/\w/) {
                    865:           &remove_lock($lock);
                    866:        }
                    867:     }
                    868: }
                    869: 
                    870: 
1.369     albertel  871: # ------------------------------------------ Find out current server userload
                    872: sub userload {
                    873:     my $numusers=0;
                    874:     {
                    875: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    876: 	my $filename;
                    877: 	my $curtime=time;
                    878: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  879: 	    next if ($filename eq '.' || $filename eq '..');
                    880: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  881: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  882: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  883: 	}
                    884: 	closedir(LONIDS);
                    885:     }
                    886:     my $userloadpercent=0;
                    887:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    888:     if ($maxuserload) {
1.371     albertel  889: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  890:     }
1.372     albertel  891:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  892:     return $userloadpercent;
1.283     www       893: }
                    894: 
1.1       albertel  895: # ------------------------------ Find server with least workload from spare.tab
1.11      www       896: 
1.1       albertel  897: sub spareserver {
1.1083    raeburn   898:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  899:     my $spare_server;
1.370     albertel  900:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  901:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    902:                                                      :  $userloadpercent;
1.1083    raeburn   903:     my ($uint_dom,$remotesessions);
                    904:     if (($udom ne '') && (&domain($udom) ne '')) {
                    905:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    906:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    907:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    908:         $remotesessions = $udomdefaults{'remotesessions'};
                    909:     }
1.1123    raeburn   910:     my $spareshash = &this_host_spares($udom);
                    911:     if (ref($spareshash) eq 'HASH') {
                    912:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    913:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   914:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    915:                                              $try_server));
1.1123    raeburn   916: 	        ($spare_server, $lowest_load) =
                    917: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    918:             }
1.1083    raeburn   919:         }
1.784     albertel  920: 
1.1123    raeburn   921:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    922: 
                    923:         if (!$found_server) {
                    924:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    925: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   926:                     next unless (&spare_can_host($udom,$uint_dom,
                    927:                                                  $remotesessions,$try_server));
1.1123    raeburn   928: 	            ($spare_server, $lowest_load) =
                    929: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    930:                 }
                    931: 	    }
                    932:         }
1.784     albertel  933:     }
                    934: 
                    935:     if (!$want_server_name) {
1.968     raeburn   936:         my $protocol = 'http';
                    937:         if ($protocol{$spare_server} eq 'https') {
                    938:             $protocol = $protocol{$spare_server};
                    939:         }
1.1001    raeburn   940:         if (defined($spare_server)) {
                    941:             my $hostname = &hostname($spare_server);
1.1083    raeburn   942:             if (defined($hostname)) {
1.1001    raeburn   943: 	        $spare_server = $protocol.'://'.$hostname;
                    944:             }
                    945:         }
1.784     albertel  946:     }
                    947:     return $spare_server;
                    948: }
                    949: 
                    950: sub compare_server_load {
1.1172.2.41  raeburn   951:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    952: 
                    953:     if ($required) {
                    954:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    955:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    956:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    957:         if (($major eq '' && $minor eq '') ||
                    958:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    959:             return ($spare_server,$lowest_load);
                    960:         }
                    961:     }
1.784     albertel  962: 
                    963:     my $loadans     = &reply('load',    $try_server);
                    964:     my $userloadans = &reply('userload',$try_server);
                    965: 
                    966:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   967: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  968:     }
                    969: 
                    970:     my $load;
                    971:     if ($loadans =~ /\d/) {
                    972: 	if ($userloadans =~ /\d/) {
                    973: 	    #both are numbers, pick the bigger one
                    974: 	    $load = ($loadans > $userloadans) ? $loadans 
                    975: 		                              : $userloadans;
1.411     albertel  976: 	} else {
1.784     albertel  977: 	    $load = $loadans;
1.411     albertel  978: 	}
1.784     albertel  979:     } else {
                    980: 	$load = $userloadans;
                    981:     }
                    982: 
                    983:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    984: 	$spare_server = $try_server;
                    985: 	$lowest_load  = $load;
1.370     albertel  986:     }
1.784     albertel  987:     return ($spare_server,$lowest_load);
1.202     matthew   988: }
1.914     albertel  989: 
                    990: # --------------------------- ask offload servers if user already has a session
                    991: sub find_existing_session {
                    992:     my ($udom,$uname) = @_;
1.1123    raeburn   993:     my $spareshash = &this_host_spares($udom);
                    994:     if (ref($spareshash) eq 'HASH') {
                    995:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    996:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    997:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    998:             }
                    999:         }
                   1000:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1001:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1002:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1003:             }
                   1004:         }
1.914     albertel 1005:     }
                   1006:     return;
                   1007: }
                   1008: 
1.1172.2.107  raeburn  1009: # check if user's browser sent load balancer cookie and server still has session
                   1010: # and is not overloaded.
                   1011: sub check_for_balancer_cookie {
                   1012:     my ($r,$update_mtime) = @_;
                   1013:     my ($otherserver,$cookie);
                   1014:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1015:     if (exists($cookies{'balanceID'})) {
                   1016:         my $balid = $cookies{'balanceID'};
                   1017:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1018:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1019:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1020:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1021:                 my ($possudom,$possuname) = ($1,$2);
                   1022:                 my $has_session = 0;
                   1023:                 if ((&domain($possudom) ne '') &&
                   1024:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1025:                     my $try_server;
                   1026:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1027:                     if ($opened) {
                   1028:                         flock($idf,LOCK_SH);
                   1029:                         while (my $line = <$idf>) {
                   1030:                             chomp($line);
                   1031:                             if (&hostname($line) ne '') {
                   1032:                                 $try_server = $line;
                   1033:                                 last;
                   1034:                             }
                   1035:                         }
                   1036:                         close($idf);
                   1037:                         if (($try_server) &&
                   1038:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1039:                             my $lowest_load = 30000;
                   1040:                             ($otherserver,$lowest_load) =
                   1041:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1042:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1043:                                 $has_session = 1;
                   1044:                             } else {
                   1045:                                 undef($otherserver);
                   1046:                             }
                   1047:                         }
                   1048:                     }
                   1049:                 }
                   1050:                 if ($has_session) {
                   1051:                     if ($update_mtime) {
                   1052:                         my $atime = my $mtime = time;
                   1053:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1054:                     }
                   1055:                 } else {
                   1056:                     unlink("$balancedir/$cookie.id");
                   1057:                 }
                   1058:             }
                   1059:         }
                   1060:     }
                   1061:     return ($otherserver,$cookie);
                   1062: }
                   1063: 
                   1064: sub delbalcookie {
                   1065:     my ($cookie,$balancer) =@_;
                   1066:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1067:         my ($udom,$uname) = ($1,$2);
                   1068:         my $uprimary_id = &domain($udom,'primary');
                   1069:         my $uintdom = &internet_dom($uprimary_id);
                   1070:         my $intdom = &internet_dom($balancer);
                   1071:         my $serverhomedom = &host_domain($balancer);
                   1072:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1073:             return &reply("delbalcookie:$cookie",$balancer);
                   1074:         }
                   1075:     }
                   1076: }
                   1077: 
1.914     albertel 1078: # -------------------------------- ask if server already has a session for user
                   1079: sub has_user_session {
                   1080:     my ($lonid,$udom,$uname) = @_;
                   1081:     my $result = &reply(join(':','userhassession',
                   1082: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1083:     return 1 if ($result eq 'ok');
                   1084: 
                   1085:     return 0;
                   1086: }
                   1087: 
1.1076    raeburn  1088: # --------- determine least loaded server in a user's domain which allows login
                   1089: 
                   1090: sub choose_server {
1.1172.2.47  raeburn  1091:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1092:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1093:     my %servers = &get_servers($udom);
1.1076    raeburn  1094:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1095:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1096:     if ($skiploadbal) {
                   1097:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1098:         unless (defined($cached)) {
                   1099:             my $cachetime = 60*60*24;
                   1100:             my %domconfig =
                   1101:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1102:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1103:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1104:                                            $cachetime);
                   1105:             }
                   1106:         }
                   1107:     }
1.1076    raeburn  1108:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1109:         my $loginvia;
1.1172.2.47  raeburn  1110:         if ($skiploadbal) {
                   1111:             if (ref($balancers) eq 'HASH') {
                   1112:                 next if (exists($balancers->{$lonhost}));
                   1113:             }
                   1114:         }
1.1115    raeburn  1115:         if ($checkloginvia) {
                   1116:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1117:             if ($loginvia) {
                   1118:                 my ($server,$path) = split(/:/,$loginvia);
                   1119:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1120:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1121:                 if ($login_host eq $server) {
                   1122:                     $portal_path = $path;
1.1151    raeburn  1123:                     $isredirect = 1;
1.1116    raeburn  1124:                 }
                   1125:             } else {
                   1126:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1127:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1128:                 if ($login_host eq $lonhost) {
                   1129:                     $portal_path = '';
1.1151    raeburn  1130:                     $isredirect = ''; 
1.1116    raeburn  1131:                 }
                   1132:             }
                   1133:         } else {
1.1076    raeburn  1134:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1135:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1136:         }
                   1137:     }
                   1138:     if ($login_host ne '') {
1.1116    raeburn  1139:         $hostname = &hostname($login_host);
1.1076    raeburn  1140:     }
1.1172.2.88  raeburn  1141:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1142: }
                   1143: 
1.202     matthew  1144: # --------------------------------------------- Try to change a user's password
                   1145: 
                   1146: sub changepass {
1.799     raeburn  1147:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1148:     $currentpass = &escape($currentpass);
                   1149:     $newpass     = &escape($newpass);
1.1030    raeburn  1150:     my $lonhost = $perlvar{'lonHostID'};
                   1151:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1152: 		       $server);
                   1153:     if (! $answer) {
                   1154: 	&logthis("No reply on password change request to $server ".
                   1155: 		 "by $uname in domain $udom.");
                   1156:     } elsif ($answer =~ "^ok") {
                   1157:         &logthis("$uname in $udom successfully changed their password ".
                   1158: 		 "on $server.");
                   1159:     } elsif ($answer =~ "^pwchange_failure") {
                   1160: 	&logthis("$uname in $udom was unable to change their password ".
                   1161: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1162: 		 "or pwchange");
                   1163:     } elsif ($answer =~ "^non_authorized") {
                   1164:         &logthis("$uname in $udom did not get their password correct when ".
                   1165: 		 "attempting to change it on $server.");
                   1166:     } elsif ($answer =~ "^auth_mode_error") {
                   1167:         &logthis("$uname in $udom attempted to change their password despite ".
                   1168: 		 "not being locally or internally authenticated on $server.");
                   1169:     } elsif ($answer =~ "^unknown_user") {
                   1170:         &logthis("$uname in $udom attempted to change their password ".
                   1171: 		 "on $server but were unable to because $server is not ".
                   1172: 		 "their home server.");
                   1173:     } elsif ($answer =~ "^refused") {
                   1174: 	&logthis("$server refused to change $uname in $udom password because ".
                   1175: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1176:     } elsif ($answer =~ "invalid_client") {
                   1177:         &logthis("$server refused to change $uname in $udom password because ".
                   1178:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1179:     }
                   1180:     return $answer;
1.1       albertel 1181: }
                   1182: 
1.169     harris41 1183: # ----------------------- Try to determine user's current authentication scheme
                   1184: 
                   1185: sub queryauthenticate {
                   1186:     my ($uname,$udom)=@_;
1.456     albertel 1187:     my $uhome=&homeserver($uname,$udom);
                   1188:     if (!$uhome) {
                   1189: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1190: 	return 'no_host';
                   1191:     }
                   1192:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1193:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1194: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1195:     }
1.456     albertel 1196:     return $answer;
1.169     harris41 1197: }
                   1198: 
1.1       albertel 1199: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1200: 
1.1       albertel 1201: sub authenticate {
1.1073    raeburn  1202:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1203:     $upass=&escape($upass);
                   1204:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1205:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1206:     my $newhome;
1.836     www      1207:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1208: # Maybe the machine was offline and only re-appeared again recently?
                   1209:         &reconlonc();
                   1210: # One more
1.952     raeburn  1211: 	$uhome=&homeserver($uname,$udom,1);
                   1212:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1213:             if (defined(&domain($udom,'primary'))) {
                   1214:                 $newhome=&domain($udom,'primary');
                   1215:             }
                   1216:             if ($newhome ne '') {
                   1217:                 $uhome = $newhome;
                   1218:             }
                   1219:         }
1.836     www      1220: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1221: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1222: 	    return 'no_host';
                   1223:         }
1.1       albertel 1224:     }
1.1073    raeburn  1225:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1226:     if ($answer eq 'authorized') {
1.952     raeburn  1227:         if ($newhome) {
                   1228:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1229:             return 'no_account_on_host'; 
                   1230:         } else {
                   1231:             &logthis("User $uname at $udom authorized by $uhome");
                   1232:             return $uhome;
                   1233:         }
1.471     albertel 1234:     }
                   1235:     if ($answer eq 'non_authorized') {
                   1236: 	&logthis("User $uname at $udom rejected by $uhome");
                   1237: 	return 'no_host'; 
1.9       www      1238:     }
1.471     albertel 1239:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1240:     return 'no_host';
                   1241: }
                   1242: 
1.1073    raeburn  1243: sub can_host_session {
1.1074    raeburn  1244:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1245:     my $canhost = 1;
1.1074    raeburn  1246:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1247:     if (ref($remotesessions) eq 'HASH') {
                   1248:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1249:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1250:                 $canhost = 0;
                   1251:             } else {
                   1252:                 $canhost = 1;
                   1253:             }
                   1254:         }
                   1255:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1256:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1257:                 $canhost = 1;
                   1258:             } else {
                   1259:                 $canhost = 0;
                   1260:             }
                   1261:         }
                   1262:         if ($canhost) {
                   1263:             if ($remotesessions->{'version'} ne '') {
                   1264:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1265:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1266:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1267:                         my $major = $1;
                   1268:                         my $minor = $2;
                   1269:                         if (($major < $reqmajor ) ||
                   1270:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1271:                             $canhost = 0;
                   1272:                         }
                   1273:                     } else {
                   1274:                         $canhost = 0;
                   1275:                     }
                   1276:                 }
                   1277:             }
                   1278:         }
                   1279:     }
                   1280:     if ($canhost) {
                   1281:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1282:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1283:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1284:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1285:                 if (($uint_dom ne '') && 
                   1286:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1287:                     $canhost = 0;
                   1288:                 } else {
                   1289:                     $canhost = 1;
                   1290:                 }
                   1291:             }
                   1292:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1293:                 if (($uint_dom ne '') && 
                   1294:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1295:                     $canhost = 1;
                   1296:                 } else {
                   1297:                     $canhost = 0;
                   1298:                 }
                   1299:             }
                   1300:         }
                   1301:     }
                   1302:     return $canhost;
                   1303: }
                   1304: 
1.1083    raeburn  1305: sub spare_can_host {
                   1306:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1307:     my $canhost=1;
1.1172.2.62  raeburn  1308:     my $try_server_hostname = &hostname($try_server);
                   1309:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1310:     my $serverhomedom = &host_domain($serverhomeID);
                   1311:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1312:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1313:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1314:             $canhost = 0;
                   1315:         }
                   1316:     }
                   1317:     if (($canhost) && ($uint_dom)) {
                   1318:         my @intdoms;
                   1319:         my $internet_names = &get_internet_names($try_server);
                   1320:         if (ref($internet_names) eq 'ARRAY') {
                   1321:             @intdoms = @{$internet_names};
                   1322:         }
                   1323:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1324:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1325:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1326:                                          $remotesessions,
                   1327:                                          $defdomdefaults{'hostedsessions'});
                   1328:         }
1.1083    raeburn  1329:     }
                   1330:     return $canhost;
                   1331: }
                   1332: 
1.1123    raeburn  1333: sub this_host_spares {
                   1334:     my ($dom) = @_;
1.1126    raeburn  1335:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1336:     my @hosts = &current_machine_ids();
                   1337:     foreach my $lonhost (@hosts) {
                   1338:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1339:             $dom_in_use = $dom;
                   1340:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1341:             last;
                   1342:         }
                   1343:     }
1.1126    raeburn  1344:     if ($dom_in_use ne '') {
                   1345:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1346:     }
                   1347:     if (ref($result) ne 'HASH') {
                   1348:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1349:         $dom_in_use = &host_domain($lonhost_in_use);
                   1350:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1351:         if (ref($result) ne 'HASH') {
                   1352:             $result = \%spareid;
                   1353:         }
                   1354:     }
                   1355:     return $result;
                   1356: }
                   1357: 
                   1358: sub spares_for_offload  {
                   1359:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1360:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1361:     if (defined($cached)) {
                   1362:         return $result;
                   1363:     } else {
1.1126    raeburn  1364:         my $cachetime = 60*60*24;
                   1365:         my %domconfig =
                   1366:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1367:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1368:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1369:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1370:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1371:                 }
                   1372:             }
                   1373:         }
                   1374:     }
1.1126    raeburn  1375:     return;
1.1123    raeburn  1376: }
                   1377: 
1.1129    raeburn  1378: sub get_lonbalancer_config {
                   1379:     my ($servers) = @_;
                   1380:     my ($currbalancer,$currtargets);
                   1381:     if (ref($servers) eq 'HASH') {
                   1382:         foreach my $server (keys(%{$servers})) {
                   1383:             my %what = (
                   1384:                          spareid => 1,
                   1385:                          perlvar => 1,
                   1386:                        );
                   1387:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1388:             if ($result eq 'ok') {
                   1389:                 if (ref($returnhash) eq 'HASH') {
                   1390:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1391:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1392:                             $currbalancer = $server;
                   1393:                             $currtargets = {};
                   1394:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1395:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1396:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1397:                                 }
                   1398:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1399:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1400:                                 }
                   1401:                             }
                   1402:                             last;
                   1403:                         }
                   1404:                     }
                   1405:                 }
                   1406:             }
                   1407:         }
                   1408:     }
                   1409:     return ($currbalancer,$currtargets);
                   1410: }
                   1411: 
                   1412: sub check_loadbalancing {
1.1172.2.88  raeburn  1413:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1414:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1415:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1416:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1417:     my @hosts = &current_machine_ids();
1.1129    raeburn  1418:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1419:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1420:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1421:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1422:     my $domneedscache; 
1.1129    raeburn  1423:     my $cachetime = 60*60*24;
                   1424: 
                   1425:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1426:         $dom_in_use = $udom;
                   1427:         $homeintdom = 1;
                   1428:     } else {
                   1429:         $dom_in_use = $serverhomedom;
                   1430:     }
                   1431:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1432:     unless (defined($cached)) {
                   1433:         my %domconfig =
                   1434:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1435:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1436:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1437:         } else {
                   1438:             $domneedscache = $dom_in_use;
1.1129    raeburn  1439:         }
                   1440:     }
                   1441:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1442:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1443:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1444:         if ($is_balancer) {
                   1445:             if (ref($currrules) eq 'HASH') {
                   1446:                 if ($homeintdom) {
                   1447:                     if ($uname ne '') {
                   1448:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1449:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1450:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1451:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1452:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1453:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1454:                             }
                   1455:                         }
                   1456:                         if ($rule_in_effect eq '') {
                   1457:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1458:                             if ($userenv{'inststatus'} ne '') {
                   1459:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1460:                                 my ($othertitle,$usertypes,$types) =
                   1461:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1462:                                 if (ref($types) eq 'ARRAY') {
                   1463:                                     foreach my $type (@{$types}) {
                   1464:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1465:                                             if (exists($currrules->{$type})) {
                   1466:                                                 $rule_in_effect = $currrules->{$type};
                   1467:                                             }
                   1468:                                         }
                   1469:                                     }
                   1470:                                 }
                   1471:                             } else {
                   1472:                                 if (exists($currrules->{'default'})) {
                   1473:                                     $rule_in_effect = $currrules->{'default'};
                   1474:                                 }
                   1475:                             }
                   1476:                         }
                   1477:                     } else {
                   1478:                         if (exists($currrules->{'default'})) {
                   1479:                             $rule_in_effect = $currrules->{'default'};
                   1480:                         }
                   1481:                     }
                   1482:                 } else {
                   1483:                     if ($currrules->{'_LC_external'} ne '') {
                   1484:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1485:                     }
                   1486:                 }
                   1487:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1488:                                                        $uname,$udom);
                   1489:             }
                   1490:         }
                   1491:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1492:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1493:         unless (defined($cached)) {
                   1494:             my %domconfig =
                   1495:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1496:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1497:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1498:             } else {
                   1499:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1500:             }
                   1501:         }
                   1502:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1503:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1504:                 &check_balancer_result($result,@hosts);
                   1505:             if ($is_balancer) {
1.1129    raeburn  1506:                 if (ref($currrules) eq 'HASH') {
                   1507:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1508:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1509:                     }
                   1510:                 }
                   1511:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1512:                                                        $uname,$udom);
                   1513:             }
                   1514:         } else {
                   1515:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1516:                 $is_balancer = 1;
                   1517:                 $offloadto = &this_host_spares($dom_in_use);
                   1518:             }
1.1172.2.75  raeburn  1519:             unless (defined($cached)) {
                   1520:                 $domneedscache = $serverhomedom;
                   1521:             }
1.1129    raeburn  1522:         }
                   1523:     } else {
                   1524:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1525:             $is_balancer = 1;
                   1526:             $offloadto = &this_host_spares($dom_in_use);
                   1527:         }
1.1172.2.75  raeburn  1528:         unless (defined($cached)) {
                   1529:             $domneedscache = $serverhomedom;
                   1530:         }
                   1531:     }
                   1532:     if ($domneedscache) {
                   1533:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1534:     }
1.1172.2.5  raeburn  1535:     if ($is_balancer) {
                   1536:         my $lowest_load = 30000;
                   1537:         if (ref($offloadto) eq 'HASH') {
                   1538:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1539:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1540:                     ($otherserver,$lowest_load) =
                   1541:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1542:                 }
1.1129    raeburn  1543:             }
1.1172.2.5  raeburn  1544:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1545: 
1.1172.2.5  raeburn  1546:             if (!$found_server) {
                   1547:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1548:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1549:                         ($otherserver,$lowest_load) =
                   1550:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1551:                     }
                   1552:                 }
                   1553:             }
                   1554:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1555:             if (@{$offloadto} == 1) {
                   1556:                 $otherserver = $offloadto->[0];
                   1557:             } elsif (@{$offloadto} > 1) {
                   1558:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1559:                     ($otherserver,$lowest_load) =
                   1560:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1561:                 }
                   1562:             }
                   1563:         }
1.1172.2.88  raeburn  1564:         unless ($caller eq 'login') {
                   1565:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1566:                 $is_balancer = 0;
                   1567:                 if ($uname ne '' && $udom ne '') {
                   1568:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1569:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1570:                                  'user.loadbalcheck.time' => time});
                   1571:                     }
1.1172.2.5  raeburn  1572:                 }
1.1129    raeburn  1573:             }
                   1574:         }
1.1172.2.107  raeburn  1575:         unless ($homeintdom) {
                   1576:             undef($setcookie);
                   1577:         }
1.1129    raeburn  1578:     }
1.1172.2.107  raeburn  1579:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1580: }
                   1581: 
1.1172.2.12  raeburn  1582: sub check_balancer_result {
                   1583:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1584:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1585:     if (ref($result) eq 'HASH') {
                   1586:         if ($result->{'lonhost'} ne '') {
                   1587:             my $currbalancer = $result->{'lonhost'};
                   1588:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1589:                 $is_balancer = 1;
                   1590:                 $currtargets = $result->{'targets'};
                   1591:                 $currrules = $result->{'rules'};
                   1592:             }
                   1593:         } else {
                   1594:             foreach my $key (keys(%{$result})) {
                   1595:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1596:                     (ref($result->{$key}) eq 'HASH')) {
                   1597:                     $is_balancer = 1;
                   1598:                     $currrules = $result->{$key}{'rules'};
                   1599:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1600:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1601:                     last;
                   1602:                 }
                   1603:             }
                   1604:         }
                   1605:     }
1.1172.2.107  raeburn  1606:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1607: }
                   1608: 
1.1129    raeburn  1609: sub get_loadbalancer_targets {
                   1610:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1611:     my $offloadto;
1.1172.2.4  raeburn  1612:     if ($rule_in_effect eq 'none') {
                   1613:         return [$perlvar{'lonHostID'}];
                   1614:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1615:         $offloadto = $currtargets;
                   1616:     } else {
                   1617:         if ($rule_in_effect eq 'homeserver') {
                   1618:             my $homeserver = &homeserver($uname,$udom);
                   1619:             if ($homeserver ne 'no_host') {
                   1620:                 $offloadto = [$homeserver];
                   1621:             }
                   1622:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1623:             my %domconfig =
                   1624:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1625:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1626:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1627:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1628:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1629:                     }
                   1630:                 }
                   1631:             } else {
1.1172.2.7  raeburn  1632:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1633:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1634:                 if (&hostname($remotebalancer) ne '') {
                   1635:                     $offloadto = [$remotebalancer];
                   1636:                 }
                   1637:             }
                   1638:         } elsif (&hostname($rule_in_effect) ne '') {
                   1639:             $offloadto = [$rule_in_effect];
                   1640:         }
                   1641:     }
                   1642:     return $offloadto;
                   1643: }
                   1644: 
1.1127    raeburn  1645: sub internet_dom_servers {
                   1646:     my ($dom) = @_;
                   1647:     my (%uniqservers,%servers);
                   1648:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1649:     my @machinedoms = &machine_domains($primaryserver);
                   1650:     foreach my $mdom (@machinedoms) {
                   1651:         my %currservers = %servers;
                   1652:         my %server = &get_servers($mdom);
                   1653:         %servers = (%currservers,%server);
                   1654:     }
                   1655:     my %by_hostname;
                   1656:     foreach my $id (keys(%servers)) {
                   1657:         push(@{$by_hostname{$servers{$id}}},$id);
                   1658:     }
                   1659:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1660:         if (@{$by_hostname{$hostname}} > 1) {
                   1661:             my $match = 0;
                   1662:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1663:                 if (&host_domain($id) eq $dom) {
                   1664:                     $uniqservers{$id} = $hostname;
                   1665:                     $match = 1;
                   1666:                 }
                   1667:             }
                   1668:             unless ($match) {
                   1669:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1670:             }
                   1671:         } else {
                   1672:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1673:         }
                   1674:     }
                   1675:     return %uniqservers;
                   1676: }
                   1677: 
1.1       albertel 1678: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1679: 
1.599     albertel 1680: my %homecache;
1.1       albertel 1681: sub homeserver {
1.230     stredwic 1682:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1683:     my $index="$uname:$udom";
1.426     albertel 1684: 
1.599     albertel 1685:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1686: 
                   1687:     my %servers = &get_servers($udom,'library');
                   1688:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1689:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1690: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1691: 
                   1692: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1693: 	if ($answer eq 'found') {
                   1694: 	    delete($badServerCache{$tryserver}); 
                   1695: 	    return $homecache{$index}=$tryserver;
                   1696: 	} elsif ($answer eq 'no_host') {
                   1697: 	    $badServerCache{$tryserver}=1;
                   1698: 	}
1.1       albertel 1699:     }    
                   1700:     return 'no_host';
1.70      www      1701: }
                   1702: 
                   1703: # ------------------------------------- Find the usernames behind a list of IDs
                   1704: 
                   1705: sub idget {
                   1706:     my ($udom,@ids)=@_;
                   1707:     my %returnhash=();
                   1708:     
1.841     albertel 1709:     my %servers = &get_servers($udom,'library');
                   1710:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1711: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1712: 	$idlist=~tr/A-Z/a-z/; 
                   1713: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1714: 	my @answer=();
                   1715: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1716: 	    @answer=split(/\&/,$reply);
                   1717: 	}                    ;
                   1718: 	my $i;
                   1719: 	for ($i=0;$i<=$#ids;$i++) {
                   1720: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1721: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1722: 	    } 
                   1723: 	}
                   1724:     } 
1.70      www      1725:     return %returnhash;
                   1726: }
                   1727: 
                   1728: # ------------------------------------- Find the IDs behind a list of usernames
                   1729: 
                   1730: sub idrget {
                   1731:     my ($udom,@unames)=@_;
                   1732:     my %returnhash=();
1.800     albertel 1733:     foreach my $uname (@unames) {
                   1734:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1735:     }
1.70      www      1736:     return %returnhash;
                   1737: }
                   1738: 
                   1739: # ------------------------------- Store away a list of names and associated IDs
                   1740: 
                   1741: sub idput {
                   1742:     my ($udom,%ids)=@_;
                   1743:     my %servers=();
1.800     albertel 1744:     foreach my $uname (keys(%ids)) {
                   1745: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1746:         my $uhom=&homeserver($uname,$udom);
1.70      www      1747:         if ($uhom ne 'no_host') {
1.800     albertel 1748:             my $id=&escape($ids{$uname});
1.70      www      1749:             $id=~tr/A-Z/a-z/;
1.800     albertel 1750:             my $esc_unam=&escape($uname);
1.70      www      1751: 	    if ($servers{$uhom}) {
1.800     albertel 1752: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1753:             } else {
1.800     albertel 1754:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1755:             }
                   1756:         }
1.191     harris41 1757:     }
1.800     albertel 1758:     foreach my $server (keys(%servers)) {
                   1759:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1760:     }
1.344     www      1761: }
                   1762: 
1.1172.2.30  raeburn  1763: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1764: 
                   1765: sub iddel {
                   1766:     my ($udom,$idshashref,$uhome)=@_;
                   1767:     my %result=();
                   1768:     unless (ref($idshashref) eq 'HASH') {
                   1769:         return %result;
                   1770:     }
                   1771:     my %servers=();
                   1772:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1773:         my $uhom;
                   1774:         if ($uhome) {
                   1775:             $uhom = $uhome;
                   1776:         } else {
                   1777:             $uhom=&homeserver($uname,$udom);
                   1778:         }
                   1779:         if ($uhom ne 'no_host') {
                   1780:             if ($servers{$uhom}) {
                   1781:                 $servers{$uhom}.='&'.&escape($id);
                   1782:             } else {
                   1783:                 $servers{$uhom}=&escape($id);
                   1784:             }
                   1785:         }
                   1786:     }
                   1787:     foreach my $server (keys(%servers)) {
                   1788:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1789:     }
                   1790:     return %result;
                   1791: }
                   1792: 
1.1023    raeburn  1793: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1794: sub dump_dom {
1.1165    droeschl 1795:     my ($namespace, $udom, $regexp) = @_;
                   1796: 
                   1797:     $udom ||= $env{'user.domain'};
                   1798: 
                   1799:     return () unless $udom;
                   1800: 
                   1801:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1802: }
                   1803: 
1.1023    raeburn  1804: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1805: 
                   1806: sub get_dom {
1.860     raeburn  1807:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1808:     return if ($udom eq 'public');
1.806     raeburn  1809:     my $items='';
                   1810:     foreach my $item (@$storearr) {
                   1811:         $items.=&escape($item).'&';
                   1812:     }
                   1813:     $items=~s/\&$//;
1.860     raeburn  1814:     if (!$udom) {
                   1815:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1816:         return if ($udom eq 'public');
1.860     raeburn  1817:         if (defined(&domain($udom,'primary'))) {
                   1818:             $uhome=&domain($udom,'primary');
                   1819:         } else {
1.874     albertel 1820:             undef($uhome);
1.860     raeburn  1821:         }
                   1822:     } else {
                   1823:         if (!$uhome) {
                   1824:             if (defined(&domain($udom,'primary'))) {
                   1825:                 $uhome=&domain($udom,'primary');
                   1826:             }
                   1827:         }
                   1828:     }
                   1829:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1830:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1831:         my %returnhash;
1.875     albertel 1832:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1833:             return %returnhash;
                   1834:         }
1.806     raeburn  1835:         my @pairs=split(/\&/,$rep);
                   1836:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1837:             return @pairs;
                   1838:         }
                   1839:         my $i=0;
                   1840:         foreach my $item (@$storearr) {
                   1841:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1842:             $i++;
                   1843:         }
                   1844:         return %returnhash;
                   1845:     } else {
1.880     banghart 1846:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1847:     }
                   1848: }
                   1849: 
                   1850: # -------------------------------------------- put items in domain db files 
                   1851: 
                   1852: sub put_dom {
1.860     raeburn  1853:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1854:     if (!$udom) {
                   1855:         $udom=$env{'user.domain'};
                   1856:         if (defined(&domain($udom,'primary'))) {
                   1857:             $uhome=&domain($udom,'primary');
                   1858:         } else {
1.874     albertel 1859:             undef($uhome);
1.860     raeburn  1860:         }
                   1861:     } else {
                   1862:         if (!$uhome) {
                   1863:             if (defined(&domain($udom,'primary'))) {
                   1864:                 $uhome=&domain($udom,'primary');
                   1865:             }
                   1866:         }
                   1867:     } 
                   1868:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1869:         my $items='';
                   1870:         foreach my $item (keys(%$storehash)) {
                   1871:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1872:         }
                   1873:         $items=~s/\&$//;
                   1874:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1875:     } else {
1.860     raeburn  1876:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1877:     }
                   1878: }
                   1879: 
1.1023    raeburn  1880: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1881: sub newput_dom {
1.1023    raeburn  1882:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1883:     my $result;
                   1884:     if (!$udom) {
                   1885:         $udom=$env{'user.domain'};
                   1886:     }
1.1023    raeburn  1887:     if ($udom) {
                   1888:         my $uname = &get_domainconfiguser($udom);
                   1889:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1890:     }
                   1891:     return $result;
                   1892: }
                   1893: 
1.1023    raeburn  1894: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1895: sub del_dom {
1.1023    raeburn  1896:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1897:     if (ref($storearr) eq 'ARRAY') {
                   1898:         if (!$udom) {
                   1899:             $udom=$env{'user.domain'};
                   1900:         }
1.1023    raeburn  1901:         if ($udom) {
                   1902:             my $uname = &get_domainconfiguser($udom); 
                   1903:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1904:         }
                   1905:     }
                   1906: }
                   1907: 
1.1023    raeburn  1908: # ----------------------------------construct domainconfig user for a domain 
                   1909: sub get_domainconfiguser {
                   1910:     my ($udom) = @_;
                   1911:     return $udom.'-domainconfig';
                   1912: }
                   1913: 
1.837     raeburn  1914: sub retrieve_inst_usertypes {
                   1915:     my ($udom) = @_;
                   1916:     my (%returnhash,@order);
1.989     raeburn  1917:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1918:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1919:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1920:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1921:     } else {
                   1922:         if (defined(&domain($udom,'primary'))) {
                   1923:             my $uhome=&domain($udom,'primary');
                   1924:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1925:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1926:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1927:                 return (\%returnhash,\@order);
                   1928:             }
                   1929:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1930:             my @pairs=split(/\&/,$hashitems);
                   1931:             foreach my $item (@pairs) {
                   1932:                 my ($key,$value)=split(/=/,$item,2);
                   1933:                 $key = &unescape($key);
                   1934:                 next if ($key =~ /^error: 2 /);
                   1935:                 $returnhash{$key}=&thaw_unescape($value);
                   1936:             }
                   1937:             my @esc_order = split(/\&/,$orderitems);
                   1938:             foreach my $item (@esc_order) {
                   1939:                 push(@order,&unescape($item));
                   1940:             }
                   1941:         } else {
1.1172.2.44  raeburn  1942:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1943:         }
1.1172.2.44  raeburn  1944:         return (\%returnhash,\@order);
1.837     raeburn  1945:     }
                   1946: }
                   1947: 
1.868     raeburn  1948: sub is_domainimage {
                   1949:     my ($url) = @_;
1.1172.2.74  raeburn  1950:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1951:         if (&domain($1) ne '') {
                   1952:             return '1';
                   1953:         }
                   1954:     }
                   1955:     return;
                   1956: }
                   1957: 
1.899     raeburn  1958: sub inst_directory_query {
                   1959:     my ($srch) = @_;
                   1960:     my $udom = $srch->{'srchdomain'};
                   1961:     my %results;
                   1962:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1963:     my $outcome;
1.899     raeburn  1964:     if ($homeserver ne '') {
1.904     albertel 1965: 	my $queryid=&reply("querysend:instdirsearch:".
                   1966: 			   &escape($srch->{'srchby'}).':'.
                   1967: 			   &escape($srch->{'srchterm'}).':'.
                   1968: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1969: 	my $host=&hostname($homeserver);
                   1970: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  1971: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1972: 	    return;
                   1973: 	}
                   1974: 	my $response = &get_query_reply($queryid);
                   1975: 	my $maxtries = 5;
                   1976: 	my $tries = 1;
                   1977: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1978: 	    $response = &get_query_reply($queryid);
                   1979: 	    $tries ++;
                   1980: 	}
                   1981: 
                   1982:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1983:             if ($response eq 'unavailable') {
                   1984:                 $outcome = $response;
                   1985:             } else {
                   1986:                 $outcome = 'ok';
                   1987:                 my @matches = split(/\n/,$response);
                   1988:                 foreach my $match (@matches) {
                   1989:                     my ($key,$value) = split(/=/,$match);
                   1990:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1991:                 }
1.899     raeburn  1992:             }
                   1993:         }
                   1994:     }
1.909     raeburn  1995:     return ($outcome,%results);
1.899     raeburn  1996: }
                   1997: 
                   1998: sub usersearch {
                   1999:     my ($srch) = @_;
                   2000:     my $dom = $srch->{'srchdomain'};
                   2001:     my %results;
                   2002:     my %libserv = &all_library();
                   2003:     my $query = 'usersearch';
                   2004:     foreach my $tryserver (keys(%libserv)) {
                   2005:         if (&host_domain($tryserver) eq $dom) {
                   2006:             my $host=&hostname($tryserver);
                   2007:             my $queryid=
1.911     raeburn  2008:                 &reply("querysend:".&escape($query).':'.
                   2009:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2010:                        &escape($srch->{'srchtype'}).':'.
                   2011:                        &escape($srch->{'srchterm'}),$tryserver);
                   2012:             if ($queryid !~/^\Q$host\E\_/) {
                   2013:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2014:                 next;
1.899     raeburn  2015:             }
                   2016:             my $reply = &get_query_reply($queryid);
                   2017:             my $maxtries = 1;
                   2018:             my $tries = 1;
                   2019:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2020:                 $reply = &get_query_reply($queryid);
                   2021:                 $tries ++;
                   2022:             }
                   2023:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2024:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2025:             } else {
1.911     raeburn  2026:                 my @matches;
                   2027:                 if ($reply =~ /\n/) {
                   2028:                     @matches = split(/\n/,$reply);
                   2029:                 } else {
                   2030:                     @matches = split(/\&/,$reply);
                   2031:                 }
1.899     raeburn  2032:                 foreach my $match (@matches) {
                   2033:                     my ($uname,$udom,%userhash);
1.911     raeburn  2034:                     foreach my $entry (split(/:/,$match)) {
                   2035:                         my ($key,$value) =
                   2036:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2037:                         $userhash{$key} = $value;
                   2038:                         if ($key eq 'username') {
                   2039:                             $uname = $value;
                   2040:                         } elsif ($key eq 'domain') {
                   2041:                             $udom = $value;
1.911     raeburn  2042:                         }
1.899     raeburn  2043:                     }
                   2044:                     $results{$uname.':'.$udom} = \%userhash;
                   2045:                 }
                   2046:             }
                   2047:         }
                   2048:     }
                   2049:     return %results;
                   2050: }
                   2051: 
1.912     raeburn  2052: sub get_instuser {
                   2053:     my ($udom,$uname,$id) = @_;
                   2054:     my $homeserver = &domain($udom,'primary');
                   2055:     my ($outcome,%results);
                   2056:     if ($homeserver ne '') {
                   2057:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2058:                            &escape($id).':'.&escape($udom),$homeserver);
                   2059:         my $host=&hostname($homeserver);
                   2060:         if ($queryid !~/^\Q$host\E\_/) {
                   2061:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2062:             return;
                   2063:         }
                   2064:         my $response = &get_query_reply($queryid);
                   2065:         my $maxtries = 5;
                   2066:         my $tries = 1;
                   2067:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2068:             $response = &get_query_reply($queryid);
                   2069:             $tries ++;
                   2070:         }
                   2071:         if (!&error($response) && $response ne 'refused') {
                   2072:             if ($response eq 'unavailable') {
                   2073:                 $outcome = $response;
                   2074:             } else {
                   2075:                 $outcome = 'ok';
                   2076:                 my @matches = split(/\n/,$response);
                   2077:                 foreach my $match (@matches) {
                   2078:                     my ($key,$value) = split(/=/,$match);
                   2079:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2080:                 }
                   2081:             }
                   2082:         }
                   2083:     }
                   2084:     my %userinfo;
                   2085:     if (ref($results{$uname}) eq 'HASH') {
                   2086:         %userinfo = %{$results{$uname}};
                   2087:     } 
                   2088:     return ($outcome,%userinfo);
                   2089: }
                   2090: 
1.1172.2.69  raeburn  2091: sub get_multiple_instusers {
                   2092:     my ($udom,$users,$caller) = @_;
                   2093:     my ($outcome,$results);
                   2094:     if (ref($users) eq 'HASH') {
                   2095:         my $count = keys(%{$users});
                   2096:         my $requested = &freeze_escape($users);
                   2097:         my $homeserver = &domain($udom,'primary');
                   2098:         if ($homeserver ne '') {
                   2099:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2100:             my $host=&hostname($homeserver);
                   2101:             if ($queryid !~/^\Q$host\E\_/) {
                   2102:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2103:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2104:                 return ($outcome,$results);
                   2105:             }
                   2106:             my $response = &get_query_reply($queryid);
                   2107:             my $maxtries = 5;
                   2108:             if ($count > 100) {
                   2109:                 $maxtries = 1+int($count/20);
                   2110:             }
                   2111:             my $tries = 1;
                   2112:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2113:                 $response = &get_query_reply($queryid);
                   2114:                 $tries ++;
                   2115:             }
                   2116:             if ($response eq '') {
                   2117:                 $results = {};
                   2118:                 foreach my $key (keys(%{$users})) {
                   2119:                     my ($uname,$id);
                   2120:                     if ($caller eq 'id') {
                   2121:                         $id = $key;
                   2122:                     } else {
                   2123:                         $uname = $key;
                   2124:                     }
                   2125:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2126:                     $outcome = $resp;
                   2127:                     if ($resp eq 'ok') {
                   2128:                         %{$results} = (%{$results}, %info);
                   2129:                     } else {
                   2130:                         last;
                   2131:                     }
                   2132:                 }
                   2133:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2134:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2135:                     $outcome = $response;
                   2136:                 } else {
                   2137:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2138:                     if ($outcome eq 'ok') {
                   2139:                         $results = &thaw_unescape($userdata);
                   2140:                     }
                   2141:                 }
                   2142:             }
                   2143:         }
                   2144:     }
                   2145:     return ($outcome,$results);
                   2146: }
                   2147: 
1.912     raeburn  2148: sub inst_rulecheck {
1.923     raeburn  2149:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2150:     my %returnhash;
                   2151:     if ($udom ne '') {
                   2152:         if (ref($rules) eq 'ARRAY') {
                   2153:             @{$rules} = map {&escape($_);} (@{$rules});
                   2154:             my $rulestr = join(':',@{$rules});
                   2155:             my $homeserver=&domain($udom,'primary');
                   2156:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2157:                 my $response;
                   2158:                 if ($item eq 'username') {                
                   2159:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2160:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2161:                                               $homeserver));
1.923     raeburn  2162:                 } elsif ($item eq 'id') {
                   2163:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2164:                                               ':'.&escape($id).':'.$rulestr,
                   2165:                                               $homeserver));
1.945     raeburn  2166:                 } elsif ($item eq 'selfcreate') {
                   2167:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2168:                                                &escape($udom).':'.&escape($uname).
                   2169:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2170:                 }
1.912     raeburn  2171:                 if ($response ne 'refused') {
                   2172:                     my @pairs=split(/\&/,$response);
                   2173:                     foreach my $item (@pairs) {
                   2174:                         my ($key,$value)=split(/=/,$item,2);
                   2175:                         $key = &unescape($key);
                   2176:                         next if ($key =~ /^error: 2 /);
                   2177:                         $returnhash{$key}=&thaw_unescape($value);
                   2178:                     }
                   2179:                 }
                   2180:             }
                   2181:         }
                   2182:     }
                   2183:     return %returnhash;
                   2184: }
                   2185: 
                   2186: sub inst_userrules {
1.923     raeburn  2187:     my ($udom,$check) = @_;
1.912     raeburn  2188:     my (%ruleshash,@ruleorder);
                   2189:     if ($udom ne '') {
                   2190:         my $homeserver=&domain($udom,'primary');
                   2191:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2192:             my $response;
                   2193:             if ($check eq 'id') {
                   2194:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2195:                                  $homeserver);
1.943     raeburn  2196:             } elsif ($check eq 'email') {
                   2197:                 $response=&reply('instemailrules:'.&escape($udom),
                   2198:                                  $homeserver);
1.923     raeburn  2199:             } else {
                   2200:                 $response=&reply('instuserrules:'.&escape($udom),
                   2201:                                  $homeserver);
                   2202:             }
1.912     raeburn  2203:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2204:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2205:                 ($response ne 'no_such_host')) {
                   2206:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2207:                 my @pairs=split(/\&/,$hashitems);
                   2208:                 foreach my $item (@pairs) {
                   2209:                     my ($key,$value)=split(/=/,$item,2);
                   2210:                     $key = &unescape($key);
                   2211:                     next if ($key =~ /^error: 2 /);
                   2212:                     $ruleshash{$key}=&thaw_unescape($value);
                   2213:                 }
                   2214:                 my @esc_order = split(/\&/,$orderitems);
                   2215:                 foreach my $item (@esc_order) {
                   2216:                     push(@ruleorder,&unescape($item));
                   2217:                 }
                   2218:             }
                   2219:         }
                   2220:     }
                   2221:     return (\%ruleshash,\@ruleorder);
                   2222: }
                   2223: 
1.976     raeburn  2224: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2225: 
                   2226: sub get_domain_defaults {
1.1172.2.35  raeburn  2227:     my ($domain,$ignore_cache) = @_;
                   2228:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2229:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2230:     unless ($ignore_cache) {
                   2231:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2232:         if (defined($cached)) {
                   2233:             if (ref($result) eq 'HASH') {
                   2234:                 return %{$result};
                   2235:             }
1.943     raeburn  2236:         }
                   2237:     }
                   2238:     my %domdefaults;
                   2239:     my %domconfig =
1.989     raeburn  2240:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2241:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2242:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2243:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2244:                                   'coursecategories','autoenroll',
                   2245:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2246:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2247:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2248:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2249:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2250:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2251:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2252:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2253:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2254:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2255:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2256:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2257:     } else {
                   2258:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2259:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2260:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2261:     }
1.976     raeburn  2262:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2263:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2264:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2265:         } else {
                   2266:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2267:         }
1.1172.2.6  raeburn  2268:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2269:         foreach my $item (@usertools) {
                   2270:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2271:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2272:             }
                   2273:         }
1.1172.2.29  raeburn  2274:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2275:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2276:         }
1.976     raeburn  2277:     }
1.985     raeburn  2278:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2279:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2280:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2281:         }
                   2282:     }
1.1172.2.9  raeburn  2283:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2284:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2285:     }
1.989     raeburn  2286:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2287:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2288:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2289:         }
                   2290:     }
1.1047    raeburn  2291:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2292:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2293:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2294:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2295:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2296:         }
1.1172.2.41  raeburn  2297:         foreach my $type (@coursetypes) {
                   2298:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2299:                 unless ($type eq 'community') {
                   2300:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2301:                 }
                   2302:             }
                   2303:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2304:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2305:             }
1.1172.2.60  raeburn  2306:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2307:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2308:                     $domdefaults{$type.'postsubtimeout'} =
                   2309:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2310:                 }
                   2311:             }
1.1172.2.30  raeburn  2312:         }
1.1172.2.67  raeburn  2313:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2314:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2315:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2316:                 if (@clonecodes) {
                   2317:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2318:                 }
                   2319:             }
                   2320:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2321:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2322:         }
1.1172.2.103  raeburn  2323:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2324:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2325:         }
1.1047    raeburn  2326:     }
1.1073    raeburn  2327:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2328:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2329:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2330:         }
                   2331:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2332:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2333:         }
1.1172.2.62  raeburn  2334:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2335:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2336:         }
1.1073    raeburn  2337:     }
1.1172.2.41  raeburn  2338:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2339:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2340:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2341:                             'approval','limit');
                   2342:             foreach my $type (@coursetypes) {
                   2343:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2344:                     my @mgrdc = ();
                   2345:                     foreach my $item (@settings) {
                   2346:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2347:                             push(@mgrdc,$item);
                   2348:                         }
                   2349:                     }
                   2350:                     if (@mgrdc) {
                   2351:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2352:                     }
                   2353:                 }
                   2354:             }
                   2355:         }
                   2356:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2357:             foreach my $type (@coursetypes) {
                   2358:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2359:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2360:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2361:                     }
                   2362:                 }
                   2363:             }
                   2364:         }
                   2365:     }
1.1172.2.46  raeburn  2366:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2367:         $domdefaults{'catauth'} = 'std';
                   2368:         $domdefaults{'catunauth'} = 'std';
                   2369:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2370:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2371:         }
                   2372:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2373:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2374:         }
                   2375:     }
1.1172.2.76  raeburn  2376:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2377:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2378:     }
1.1172.2.89  raeburn  2379:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2380:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2381:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2382:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2383:         }
                   2384:     }
1.1172.2.23  raeburn  2385:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2386:     return %domdefaults;
                   2387: }
                   2388: 
1.1172.2.106  raeburn  2389: sub get_dom_cats {
                   2390:     my ($dom) = @_;
                   2391:     return unless (&domain($dom));
                   2392:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2393:     unless (defined($cached)) {
                   2394:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2395:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2396:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2397:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2398:             } else {
                   2399:                 $cats = {};
                   2400:             }
                   2401:         } else {
                   2402:             $cats = {};
                   2403:         }
                   2404:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2405:     }
                   2406:     return $cats;
                   2407: }
                   2408: 
                   2409: sub get_dom_instcats {
                   2410:     my ($dom) = @_;
                   2411:     return unless (&domain($dom));
                   2412:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2413:     unless (defined($cached)) {
                   2414:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2415:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2416:         if ($totcodes > 0) {
                   2417:             my $caller = 'global';
                   2418:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2419:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2420:                 $instcats = {
                   2421:                                 codes => \%codes,
                   2422:                                 codetitles => \@codetitles,
                   2423:                                 cat_titles => \%cat_titles,
                   2424:                                 cat_order => \%cat_order,
                   2425:                             };
                   2426:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2427:             }
                   2428:         }
                   2429:     }
                   2430:     return $instcats;
                   2431: }
                   2432: 
                   2433: sub retrieve_instcodes {
                   2434:     my ($coursecodes,$dom) = @_;
                   2435:     my $totcodes;
                   2436:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2437:     foreach my $course (keys(%courses)) {
                   2438:         if (ref($courses{$course}) eq 'HASH') {
                   2439:             if ($courses{$course}{'inst_code'} ne '') {
                   2440:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2441:                 $totcodes ++;
                   2442:             }
                   2443:         }
                   2444:     }
                   2445:     return $totcodes;
                   2446: }
                   2447: 
1.344     www      2448: # --------------------------------------------------- Assign a key to a student
                   2449: 
                   2450: sub assign_access_key {
1.364     www      2451: #
                   2452: # a valid key looks like uname:udom#comments
                   2453: # comments are being appended
                   2454: #
1.498     www      2455:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2456:     $kdom=
1.620     albertel 2457:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2458:     $knum=
1.620     albertel 2459:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2460:     $cdom=
1.620     albertel 2461:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2462:     $cnum=
1.620     albertel 2463:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2464:     $udom=$env{'user.name'} unless (defined($udom));
                   2465:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2466:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2467:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2468:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2469:                                                   # assigned to this person
                   2470:                                                   # - this should not happen,
1.345     www      2471:                                                   # unless something went wrong
                   2472:                                                   # the first time around
                   2473: # ready to assign
1.364     www      2474:         $logentry=$1.'; '.$logentry;
1.496     www      2475:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2476:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2477: # key now belongs to user
1.346     www      2478: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2479:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2480:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2481:                 return 'ok';
                   2482:             } else {
                   2483:                 return 
                   2484:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2485: 	    }
                   2486:         } else {
                   2487:             return 'error: Could not assign key, try again later.';
                   2488:         }
1.364     www      2489:     } elsif (!$existing{$ckey}) {
1.345     www      2490: # the key does not exist
                   2491: 	return 'error: The key does not exist';
                   2492:     } else {
                   2493: # the key is somebody else's
                   2494: 	return 'error: The key is already in use';
                   2495:     }
1.344     www      2496: }
                   2497: 
1.364     www      2498: # ------------------------------------------ put an additional comment on a key
                   2499: 
                   2500: sub comment_access_key {
                   2501: #
                   2502: # a valid key looks like uname:udom#comments
                   2503: # comments are being appended
                   2504: #
                   2505:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2506:     $cdom=
1.620     albertel 2507:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2508:     $cnum=
1.620     albertel 2509:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2510:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2511:     if ($existing{$ckey}) {
                   2512:         $existing{$ckey}.='; '.$logentry;
                   2513: # ready to assign
1.367     www      2514:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2515:                                                  $cdom,$cnum) eq 'ok') {
                   2516: 	    return 'ok';
                   2517:         } else {
                   2518: 	    return 'error: Count not store comment.';
                   2519:         }
                   2520:     } else {
                   2521: # the key does not exist
                   2522: 	return 'error: The key does not exist';
                   2523:     }
                   2524: }
                   2525: 
1.344     www      2526: # ------------------------------------------------------ Generate a set of keys
                   2527: 
                   2528: sub generate_access_keys {
1.364     www      2529:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2530:     $cdom=
1.620     albertel 2531:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2532:     $cnum=
1.620     albertel 2533:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2534:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2535:     unless (($cdom) && ($cnum)) { return 0; }
                   2536:     if ($number>10000) { return 0; }
                   2537:     sleep(2); # make sure don't get same seed twice
                   2538:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2539:     my $total=0;
                   2540:     for (my $i=1;$i<=$number;$i++) {
                   2541:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2542:                   sprintf("%lx",int(100000*rand)).'-'.
                   2543:                   sprintf("%lx",int(100000*rand));
                   2544:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2545:        $newkey=~s/0/h/g; # and also 0 and O
                   2546:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2547:        if ($existing{$newkey}) {
                   2548:            $i--;
                   2549:        } else {
1.364     www      2550: 	  if (&put('accesskeys',
                   2551:               { $newkey => '# generated '.localtime().
1.620     albertel 2552:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2553:                            '; '.$logentry },
                   2554: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2555:               $total++;
                   2556: 	  }
                   2557:        }
                   2558:     }
1.620     albertel 2559:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2560:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2561:     return $total;
                   2562: }
                   2563: 
                   2564: # ------------------------------------------------------- Validate an accesskey
                   2565: 
                   2566: sub validate_access_key {
                   2567:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2568:     $cdom=
1.620     albertel 2569:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2570:     $cnum=
1.620     albertel 2571:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2572:     $udom=$env{'user.domain'} unless (defined($udom));
                   2573:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2574:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2575:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2576: }
                   2577: 
                   2578: # ------------------------------------- Find the section of student in a course
1.652     albertel 2579: sub devalidate_getsection_cache {
                   2580:     my ($udom,$unam,$courseid)=@_;
                   2581:     my $hashid="$udom:$unam:$courseid";
                   2582:     &devalidate_cache_new('getsection',$hashid);
                   2583: }
1.298     matthew  2584: 
1.815     albertel 2585: sub courseid_to_courseurl {
                   2586:     my ($courseid) = @_;
                   2587:     #already url style courseid
                   2588:     return $courseid if ($courseid =~ m{^/});
                   2589: 
                   2590:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2591: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2592: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2593: 	return "/$cdom/$cnum";
                   2594:     }
                   2595: 
                   2596:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2597:     if (exists($courseinfo{'num'})) {
                   2598: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2599:     }
                   2600: 
                   2601:     return undef;
                   2602: }
                   2603: 
1.298     matthew  2604: sub getsection {
                   2605:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2606:     my $cachetime=1800;
1.551     albertel 2607: 
                   2608:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2609:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2610:     if (defined($cached)) { return $result; }
                   2611: 
1.298     matthew  2612:     my %Pending; 
                   2613:     my %Expired;
                   2614:     #
                   2615:     # Each role can either have not started yet (pending), be active, 
                   2616:     #    or have expired.
                   2617:     #
                   2618:     # If there is an active role, we are done.
                   2619:     #
                   2620:     # If there is more than one role which has not started yet, 
                   2621:     #     choose the one which will start sooner
                   2622:     # If there is one role which has not started yet, return it.
                   2623:     #
                   2624:     # If there is more than one expired role, choose the one which ended last.
                   2625:     # If there is a role which has expired, return it.
                   2626:     #
1.815     albertel 2627:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2628:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2629:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2630:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2631:         my $section=$1;
                   2632:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2633:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2634:         my $now=time;
1.548     albertel 2635:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2636:             $Expired{$end}=$section;
                   2637:             next;
                   2638:         }
1.548     albertel 2639:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2640:             $Pending{$start}=$section;
                   2641:             next;
                   2642:         }
1.599     albertel 2643:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2644:     }
                   2645:     #
                   2646:     # Presumedly there will be few matching roles from the above
                   2647:     # loop and the sorting time will be negligible.
                   2648:     if (scalar(keys(%Pending))) {
                   2649:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2650:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2651:     } 
                   2652:     if (scalar(keys(%Expired))) {
                   2653:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2654:         my $time = pop(@sorted);
1.599     albertel 2655:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2656:     }
1.599     albertel 2657:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2658: }
1.70      www      2659: 
1.599     albertel 2660: sub save_cache {
                   2661:     &purge_remembered();
1.722     albertel 2662:     #&Apache::loncommon::validate_page();
1.620     albertel 2663:     undef(%env);
1.780     albertel 2664:     undef($env_loaded);
1.599     albertel 2665: }
1.452     albertel 2666: 
1.599     albertel 2667: my $to_remember=-1;
                   2668: my %remembered;
                   2669: my %accessed;
                   2670: my $kicks=0;
                   2671: my $hits=0;
1.849     albertel 2672: sub make_key {
                   2673:     my ($name,$id) = @_;
1.872     albertel 2674:     if (length($id) > 65 
                   2675: 	&& length(&escape($id)) > 200) {
                   2676: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2677:     }
1.849     albertel 2678:     return &escape($name.':'.$id);
                   2679: }
                   2680: 
1.599     albertel 2681: sub devalidate_cache_new {
                   2682:     my ($name,$id,$debug) = @_;
                   2683:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2684:     my $remembered_id=$name.':'.$id;
1.849     albertel 2685:     $id=&make_key($name,$id);
1.599     albertel 2686:     $memcache->delete($id);
1.1172.2.81  raeburn  2687:     delete($remembered{$remembered_id});
                   2688:     delete($accessed{$remembered_id});
1.599     albertel 2689: }
                   2690: 
                   2691: sub is_cached_new {
                   2692:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2693:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2694:                                      # keys in %remembered hash, which persists for
                   2695:                                      # duration of request (no restriction on key length).
                   2696:     if (exists($remembered{$remembered_id})) {
                   2697: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2698: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2699: 	$hits++;
1.1172.2.81  raeburn  2700: 	return ($remembered{$remembered_id},1);
1.599     albertel 2701:     }
1.1172.2.81  raeburn  2702:     $id=&make_key($name,$id);
1.599     albertel 2703:     my $value = $memcache->get($id);
                   2704:     if (!(defined($value))) {
                   2705: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2706: 	return (undef,undef);
1.416     albertel 2707:     }
1.599     albertel 2708:     if ($value eq '__undef__') {
                   2709: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2710: 	$value=undef;
                   2711:     }
1.1172.2.81  raeburn  2712:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2713:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2714:     return ($value,1);
                   2715: }
                   2716: 
                   2717: sub do_cache_new {
                   2718:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2719:     my $remembered_id=$name.':'.$id;
1.849     albertel 2720:     $id=&make_key($name,$id);
1.599     albertel 2721:     my $setvalue=$value;
                   2722:     if (!defined($setvalue)) {
                   2723: 	$setvalue='__undef__';
                   2724:     }
1.623     albertel 2725:     if (!defined($time) ) {
                   2726: 	$time=600;
                   2727:     }
1.599     albertel 2728:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2729:     my $result = $memcache->set($id,$setvalue,$time);
                   2730:     if (! $result) {
1.872     albertel 2731: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2732: 	$memcache->disconnect_all();
1.872     albertel 2733:     }
1.600     albertel 2734:     # need to make a copy of $value
1.1172.2.81  raeburn  2735:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2736:     return $value;
                   2737: }
                   2738: 
                   2739: sub make_room {
1.1172.2.81  raeburn  2740:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2741: 
1.1172.2.81  raeburn  2742:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2743:                                     : $value;
1.599     albertel 2744:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2745:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2746:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2747:     my $to_kick;
                   2748:     my $max_time=0;
                   2749:     foreach my $other (keys(%accessed)) {
                   2750: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2751: 	    $to_kick=$other;
                   2752: 	    $max_time=&tv_interval($accessed{$other});
                   2753: 	}
                   2754:     }
                   2755:     delete($remembered{$to_kick});
                   2756:     delete($accessed{$to_kick});
                   2757:     $kicks++;
                   2758:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2759:     return;
                   2760: }
                   2761: 
1.599     albertel 2762: sub purge_remembered {
1.604     albertel 2763:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2764:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2765:     undef(%remembered);
                   2766:     undef(%accessed);
1.428     albertel 2767: }
1.70      www      2768: # ------------------------------------- Read an entry from a user's environment
                   2769: 
                   2770: sub userenvironment {
                   2771:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2772:     my $items;
                   2773:     foreach my $item (@what) {
                   2774:         $items.=&escape($item).'&';
                   2775:     }
                   2776:     $items=~s/\&$//;
1.70      www      2777:     my %returnhash=();
1.1009    raeburn  2778:     my $uhome = &homeserver($unam,$udom);
                   2779:     unless ($uhome eq 'no_host') {
                   2780:         my @answer=split(/\&/, 
                   2781:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2782:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2783:             return %returnhash;
                   2784:         }
1.1009    raeburn  2785:         my $i;
                   2786:         for ($i=0;$i<=$#what;$i++) {
                   2787: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2788:         }
1.70      www      2789:     }
                   2790:     return %returnhash;
1.1       albertel 2791: }
                   2792: 
1.617     albertel 2793: # ---------------------------------------------------------- Get a studentphoto
                   2794: sub studentphoto {
                   2795:     my ($udom,$unam,$ext) = @_;
                   2796:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2797:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2798:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2799:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2800:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2801:             } else {
                   2802:                 my ($result,$perm_reqd)=
1.707     albertel 2803: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2804:                 if ($result eq 'ok') {
                   2805:                     if (!($perm_reqd eq 'yes')) {
                   2806:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2807:                     }
                   2808:                 }
                   2809:             }
                   2810:         }
                   2811:     } else {
                   2812:         my ($result,$perm_reqd) = 
1.707     albertel 2813: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2814:         if ($result eq 'ok') {
                   2815:             if (!($perm_reqd eq 'yes')) {
                   2816:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2817:             }
                   2818:         }
                   2819:     }
                   2820:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2821: }
                   2822: 
                   2823: sub retrievestudentphoto {
                   2824:     my ($udom,$unam,$ext,$type) = @_;
                   2825:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2826:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2827:     if ($ret eq 'ok') {
                   2828:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2829:         if ($type eq 'thumbnail') {
                   2830:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2831:         }
                   2832:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2833:         return $tokenurl;
                   2834:     } else {
                   2835:         if ($type eq 'thumbnail') {
                   2836:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2837:         } else { 
                   2838:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2839:         }
1.617     albertel 2840:     }
                   2841: }
                   2842: 
1.263     www      2843: # -------------------------------------------------------------------- New chat
                   2844: 
                   2845: sub chatsend {
1.724     raeburn  2846:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2847:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2848:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2849:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2850:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2851: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2852: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2853: }
                   2854: 
                   2855: # ------------------------------------------ Find current version of a resource
                   2856: 
                   2857: sub getversion {
                   2858:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2859:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2860:     return &currentversion(&filelocation('',$fname));
                   2861: }
                   2862: 
                   2863: sub currentversion {
                   2864:     my $fname=shift;
                   2865:     my $author=$fname;
                   2866:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2867:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2868:     my $home=&homeserver($uname,$udom);
1.292     www      2869:     if ($home eq 'no_host') { 
                   2870:         return -1; 
                   2871:     }
1.1112    www      2872:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2873:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2874: 	return -1;
                   2875:     }
1.1112    www      2876:     return $answer;
1.263     www      2877: }
                   2878: 
1.1111    www      2879: #
                   2880: # Return special version number of resource if set by override, empty otherwise
                   2881: #
                   2882: sub usedversion {
                   2883:     my $fname=shift;
                   2884:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2885:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2886:     if ($urlversion) { return $urlversion; }
                   2887:     return '';
                   2888: }
                   2889: 
1.1       albertel 2890: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2891: 
1.1       albertel 2892: sub subscribe {
                   2893:     my $fname=shift;
1.761     raeburn  2894:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2895:     $fname=~s/[\n\r]//g;
1.1       albertel 2896:     my $author=$fname;
                   2897:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2898:     my ($udom,$uname)=split(/\//,$author);
                   2899:     my $home=homeserver($uname,$udom);
1.335     albertel 2900:     if ($home eq 'no_host') {
                   2901:         return 'not_found';
1.1       albertel 2902:     }
                   2903:     my $answer=reply("sub:$fname",$home);
1.64      www      2904:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2905: 	$answer.=' by '.$home;
                   2906:     }
1.1       albertel 2907:     return $answer;
                   2908: }
                   2909:     
1.8       www      2910: # -------------------------------------------------------------- Replicate file
                   2911: 
                   2912: sub repcopy {
                   2913:     my $filename=shift;
1.23      www      2914:     $filename=~s/\/+/\//g;
1.1142    raeburn  2915:     my $londocroot = $perlvar{'lonDocRoot'};
                   2916:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2917:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2918:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2919: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2920: 	return &repcopy_userfile($filename);
                   2921:     }
1.532     albertel 2922:     $filename=~s/[\n\r]//g;
1.8       www      2923:     my $transname="$filename.in.transfer";
1.828     www      2924: # FIXME: this should flock
1.607     raeburn  2925:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2926:     my $remoteurl=subscribe($filename);
1.64      www      2927:     if ($remoteurl =~ /^con_lost by/) {
                   2928: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2929:            return 'unavailable';
1.8       www      2930:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2931: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2932: 	   return 'not_found';
1.64      www      2933:     } elsif ($remoteurl =~ /^rejected by/) {
                   2934: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2935:            return 'forbidden';
1.20      www      2936:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2937:            return 'ok';
1.8       www      2938:     } else {
1.290     www      2939:         my $author=$filename;
                   2940:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2941:         my ($udom,$uname)=split(/\//,$author);
                   2942:         my $home=homeserver($uname,$udom);
                   2943:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2944:            my @parts=split(/\//,$filename);
                   2945:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2946:            if ($path ne "$londocroot/res") {
1.8       www      2947:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2948: 	       return 'bad_request';
1.8       www      2949:            }
                   2950:            my $count;
                   2951:            for ($count=5;$count<$#parts;$count++) {
                   2952:                $path.="/$parts[$count]";
                   2953:                if ((-e $path)!=1) {
                   2954: 		   mkdir($path,0777);
                   2955:                }
                   2956:            }
                   2957:            my $ua=new LWP::UserAgent;
                   2958:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2959:            my $response=$ua->request($request,$transname);
                   2960:            if ($response->is_error()) {
                   2961: 	       unlink($transname);
                   2962:                my $message=$response->status_line;
1.672     albertel 2963:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2964:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2965:                return 'unavailable';
1.8       www      2966:            } else {
1.16      www      2967: 	       if ($remoteurl!~/\.meta$/) {
                   2968:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2969:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2970:                   if ($mresponse->is_error()) {
                   2971: 		      unlink($filename.'.meta');
                   2972:                       &logthis(
1.672     albertel 2973:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2974:                   }
                   2975: 	       }
1.8       www      2976:                rename($transname,$filename);
1.607     raeburn  2977:                return 'ok';
1.8       www      2978:            }
1.290     www      2979:        }
1.8       www      2980:     }
1.330     www      2981: }
                   2982: 
                   2983: # ------------------------------------------------ Get server side include body
                   2984: sub ssi_body {
1.381     albertel 2985:     my ($filelink,%form)=@_;
1.606     matthew  2986:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2987:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2988:     }
1.953     www      2989:     my $output='';
                   2990:     my $response;
1.980     raeburn  2991:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2992:        ($output,$response)=&externalssi($filelink);
1.953     www      2993:     } else {
1.1004    droeschl 2994:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2995:        $filelink .= 'inhibitmenu=yes';
1.953     www      2996:        ($output,$response)=&ssi($filelink,%form);
                   2997:     }
1.778     albertel 2998:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2999:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3000:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3001:     if (wantarray) {
                   3002:         return ($output, $response);
                   3003:     } else {
                   3004:         return $output;
                   3005:     }
1.8       www      3006: }
                   3007: 
1.15      www      3008: # --------------------------------------------------------- Server Side Include
                   3009: 
1.782     albertel 3010: sub absolute_url {
                   3011:     my ($host_name) = @_;
                   3012:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3013:     if ($host_name eq '') {
                   3014: 	$host_name = $ENV{'SERVER_NAME'};
                   3015:     }
                   3016:     return $protocol.$host_name;
                   3017: }
                   3018: 
1.942     foxr     3019: #
                   3020: #   Server side include.
                   3021: # Parameters:
                   3022: #  fn     Possibly encrypted resource name/id.
                   3023: #  form   Hash that describes how the rendering should be done
                   3024: #         and other things.
1.944     foxr     3025: # Returns:
1.950     raeburn  3026: #   Scalar context: The content of the response.
                   3027: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3028: #     
1.15      www      3029: sub ssi {
                   3030: 
1.944     foxr     3031:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3032:     my ($request,$response);
1.711     albertel 3033: 
                   3034:     $form{'no_update_last_known'}=1;
1.895     albertel 3035:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3036:     if (%form) {
1.782     albertel 3037:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3038:       $request->content(join('&',map {
                   3039:             my $name = escape($_);
                   3040:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3041:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3042:             : &escape($form{$_}) );
                   3043:         } keys(%form)));
1.23      www      3044:     } else {
1.782     albertel 3045:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3046:     }
                   3047: 
1.15      www      3048:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3049: 
1.1172.2.101  raeburn  3050:     if (($env{'request.course.id'}) &&
                   3051:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3052:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3053:         ($form{'grade_symb'} ne '') &&
                   3054:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3055:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3056:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3057:             my $ua=new LWP::UserAgent;
                   3058:             $ua->local_address('127.0.0.1');
                   3059:             $response = $ua->request($request);
                   3060:         } else {
                   3061:             {
                   3062:                 require LWP::Protocol::http;
                   3063:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3064:                 my $ua=new LWP::UserAgent;
                   3065:                 $response = $ua->request($request);
                   3066:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3067:             }
                   3068:         }
                   3069:     } else {
                   3070:         my $ua=new LWP::UserAgent;
                   3071:         $response = $ua->request($request);
                   3072:     }
1.944     foxr     3073:     if (wantarray) {
1.1172.2.3  raeburn  3074: 	return ($response->content, $response);
1.944     foxr     3075:     } else {
1.1172.2.3  raeburn  3076: 	return $response->content;
1.942     foxr     3077:     }
1.324     www      3078: }
                   3079: 
                   3080: sub externalssi {
                   3081:     my ($url)=@_;
                   3082:     my $ua=new LWP::UserAgent;
                   3083:     my $request=new HTTP::Request('GET',$url);
                   3084:     my $response=$ua->request($request);
1.954     raeburn  3085:     if (wantarray) {
                   3086:         return ($response->content, $response);
                   3087:     } else {
                   3088:         return $response->content;
                   3089:     }
1.15      www      3090: }
1.254     www      3091: 
1.1172.2.98  raeburn  3092: # If the local copy of a replicated resource is outdated, trigger a
                   3093: # connection from the homeserver to flush the delayed queue. If no update
                   3094: # happens, remove local copies of outdated resource (and corresponding
                   3095: # metadata file).
                   3096: 
                   3097: sub remove_stale_resfile {
                   3098:     my ($url) = @_;
                   3099:     my $removed;
                   3100:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3101:         my $audom = $1;
                   3102:         my $auname = $2;
                   3103:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3104:             my $homeserver = &homeserver($auname,$audom);
                   3105:             unless (($homeserver eq 'no_host') ||
                   3106:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3107:                 my $fname = &filelocation('',$url);
                   3108:                 if (-e $fname) {
                   3109:                     my $ua=new LWP::UserAgent;
                   3110:                     $ua->timeout(5);
                   3111:                     my $protocol = $protocol{$homeserver};
                   3112:                     $protocol = 'http' if ($protocol ne 'https');
                   3113:                     my $hostname = &hostname($homeserver);
                   3114:                     if ($hostname) {
                   3115:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
                   3116:                         my $request=new HTTP::Request('HEAD',$uri);
                   3117:                         my $response=$ua->request($request);
                   3118:                         if ($response->is_success()) {
                   3119:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3120:                             my $locmodtime = (stat($fname))[9];
                   3121:                             if ($locmodtime < $remmodtime) {
                   3122:                                 my $stale;
                   3123:                                 my $answer = &reply('pong',$homeserver);
                   3124:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3125:                                     sleep(0.2);
                   3126:                                     $locmodtime = (stat($fname))[9];
                   3127:                                     if ($locmodtime < $remmodtime) {
                   3128:                                         my $posstransfer = $fname.'.in.transfer';
                   3129:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3130:                                             $removed = 1;
                   3131:                                         } else {
                   3132:                                             $stale = 1;
                   3133:                                         }
                   3134:                                     } else {
                   3135:                                         $removed = 1;
                   3136:                                     }
                   3137:                                 } else {
                   3138:                                     $stale = 1;
                   3139:                                 }
                   3140:                                 if ($stale) {
                   3141:                                     unlink($fname);
                   3142:                                     if ($uri!~/\.meta$/) {
                   3143:                                         unlink($fname.'.meta');
                   3144:                                     }
                   3145:                                     &reply("unsub:$fname",$homeserver);
                   3146:                                     $removed = 1;
                   3147:                                 }
                   3148:                             }
                   3149:                         }
                   3150:                     }
                   3151:                 }
                   3152:             }
                   3153:         }
                   3154:     }
                   3155:     return $removed;
                   3156: }
                   3157: 
1.492     albertel 3158: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3159: 
                   3160: sub allowuploaded {
                   3161:     my ($srcurl,$url)=@_;
                   3162:     $url=&clutter(&declutter($url));
                   3163:     my $dir=$url;
                   3164:     $dir=~s/\/[^\/]+$//;
                   3165:     my %httpref=();
                   3166:     my $httpurl=&hreflocation('',$url);
                   3167:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3168:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3169: }
1.477     raeburn  3170: 
1.1172.2.13  raeburn  3171: #
                   3172: # Determine if the current user should be able to edit a particular resource,
                   3173: # when viewing in course context.
                   3174: # (a) When viewing resource used to determine if "Edit" item is included in
                   3175: #     Functions.
                   3176: # (b) When displaying folder contents in course editor, used to determine if
                   3177: #     "Edit" link will be displayed alongside resource.
                   3178: #
                   3179: #  input: six args -- filename (decluttered), course number, course domain,
                   3180: #                   url, symb (if registered) and group (if this is a group
                   3181: #                   item -- e.g., bulletin board, group page etc.).
                   3182: #  output: array of five scalars --
                   3183: #          $cfile -- url for file editing if editable on current server
                   3184: #          $home -- homeserver of resource (i.e., for author if published,
                   3185: #                                           or course if uploaded.).
                   3186: #          $switchserver --  1 if server switch will be needed.
                   3187: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3188: #          $forceview -- 1 if icon/link should be to go to view mode
                   3189: #
                   3190: 
                   3191: sub can_edit_resource {
                   3192:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3193:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3194: #
                   3195: # For aboutme pages user can only edit his/her own.
                   3196: #
                   3197:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3198:         my ($sdom,$sname) = ($1,$2);
                   3199:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3200:             $home = $env{'user.home'};
                   3201:             $cfile = $resurl;
                   3202:             if ($env{'form.forceedit'}) {
                   3203:                 $forceview = 1;
                   3204:             } else {
                   3205:                 $forceedit = 1;
                   3206:             }
                   3207:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3208:         } else {
                   3209:             return;
                   3210:         }
                   3211:     }
                   3212: 
                   3213:     if ($env{'request.course.id'}) {
                   3214:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3215:         if ($group ne '') {
                   3216: # if this is a group homepage or group bulletin board, check group privs
                   3217:             my $allowed = 0;
                   3218:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3219:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3220:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3221:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3222:                     $allowed = 1;
                   3223:                 }
                   3224:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3225:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3226:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3227:                     $allowed = 1;
                   3228:                 }
                   3229:             }
                   3230:             if ($allowed) {
                   3231:                 $home=&homeserver($cnum,$cdom);
                   3232:                 if ($env{'form.forceedit'}) {
                   3233:                     $forceview = 1;
                   3234:                 } else {
                   3235:                     $forceedit = 1;
                   3236:                 }
                   3237:                 $cfile = $resurl;
                   3238:             } else {
                   3239:                 return;
                   3240:             }
                   3241:         } else {
1.1172.2.15  raeburn  3242:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3243:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3244:                     return;
                   3245:                 }
                   3246:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3247: #
                   3248: # No edit allowed where CC has switched to student role.
                   3249: #
                   3250:                 return;
                   3251:             }
                   3252:         }
                   3253:     }
                   3254: 
                   3255:     if ($file ne '') {
                   3256:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3257:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3258:                 $uploaded = 1;
                   3259:                 $incourse = 1;
                   3260:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3261:                     $cfile = &hreflocation('',$file);
                   3262:                     if ($env{'form.forceedit'}) {
                   3263:                         $forceview = 1;
                   3264:                     } else {
                   3265:                         $forceedit = 1;
                   3266:                     }
                   3267:                 }
                   3268:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3269:                 $incourse = 1;
                   3270:                 if ($env{'form.forceedit'}) {
                   3271:                     $forceview = 1;
                   3272:                 } else {
                   3273:                     $forceedit = 1;
                   3274:                 }
                   3275:                 $cfile = $resurl;
                   3276:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3277:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3278:                     $incourse = 1;
                   3279:                     if ($env{'form.forceedit'}) {
                   3280:                         $forceview = 1;
                   3281:                     } else {
                   3282:                         $forceedit = 1;
                   3283:                     }
                   3284:                     $cfile = $resurl;
                   3285:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3286:                     $incourse = 1;
                   3287:                     $cfile = $resurl.'/smpedit';
                   3288:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3289:                     $incourse = 1;
                   3290:                     if ($env{'form.forceedit'}) {
                   3291:                         $forceview = 1;
                   3292:                     } else {
                   3293:                         $forceedit = 1;
                   3294:                     }
                   3295:                     $cfile = $resurl;
1.1172.2.15  raeburn  3296:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3297:                     $incourse = 1;
                   3298:                     if ($env{'form.forceedit'}) {
                   3299:                         $forceview = 1;
                   3300:                     } else {
                   3301:                         $forceedit = 1;
                   3302:                     }
                   3303:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3304:                 }
                   3305:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3306:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3307:                 if (&is_on_map($template)) {
                   3308:                     $incourse = 1;
                   3309:                     $forceview = 1;
                   3310:                     $cfile = $template;
                   3311:                 }
                   3312:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3313:                     $incourse = 1;
                   3314:                     if ($env{'form.forceedit'}) {
                   3315:                         $forceview = 1;
                   3316:                     } else {
                   3317:                         $forceedit = 1;
                   3318:                     }
                   3319:                     $cfile = $resurl;
                   3320:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3321:                 $incourse = 1;
                   3322:                 $forceview = 1;
                   3323:                 if ($symb) {
                   3324:                     my ($map,$id,$res)=&decode_symb($symb);
                   3325:                     $env{'request.symb'} = $symb;
                   3326:                     $cfile = &clutter($res);
                   3327:                 } else {
                   3328:                     $cfile = $env{'form.suppurl'};
                   3329:                     $cfile =~ s{^http://}{};
                   3330:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3331:                 }
1.1172.2.31  raeburn  3332:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3333:                 if ($env{'form.forceedit'}) {
                   3334:                     $forceview = 1;
                   3335:                 } else {
                   3336:                     $forceedit = 1;
                   3337:                 }
                   3338:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3339:             }
                   3340:         }
                   3341:         if ($uploaded || $incourse) {
                   3342:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3343:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3344:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3345:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3346:             # Check that the user has permission to edit this resource
                   3347:             my $setpriv = 1;
                   3348:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3349:             if (defined($cfudom)) {
                   3350:                 $home=&homeserver($cfuname,$cfudom);
                   3351:                 $cfile=$file;
                   3352:             }
                   3353:         }
                   3354:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3355:             (($home ne '') && ($home ne 'no_host'))) {
                   3356:             my @ids=&current_machine_ids();
                   3357:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3358:                 $switchserver=1;
                   3359:             }
                   3360:         }
                   3361:     }
                   3362:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3363: }
                   3364: 
                   3365: sub is_course_upload {
                   3366:     my ($file,$cnum,$cdom) = @_;
                   3367:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3368:     $uploadpath =~ s{^\/}{};
                   3369:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3370:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3371:         return 1;
                   3372:     }
                   3373:     return;
                   3374: }
                   3375: 
                   3376: sub in_course {
                   3377:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3378:     if ($hideprivileged) {
                   3379:         my $skipuser;
1.1172.2.23  raeburn  3380:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3381:         my @possdoms = ($cdom);
                   3382:         if ($coursehash{'checkforpriv'}) {
                   3383:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3384:         }
                   3385:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3386:             $skipuser = 1;
                   3387:             if ($coursehash{'nothideprivileged'}) {
                   3388:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3389:                     my $user;
                   3390:                     if ($item =~ /:/) {
                   3391:                         $user = $item;
                   3392:                     } else {
                   3393:                         $user = join(':',split(/[\@]/,$item));
                   3394:                     }
                   3395:                     if ($user eq $uname.':'.$udom) {
                   3396:                         undef($skipuser);
                   3397:                         last;
                   3398:                     }
                   3399:                 }
                   3400:             }
                   3401:             if ($skipuser) {
                   3402:                 return 0;
                   3403:             }
                   3404:         }
                   3405:     }
                   3406:     $type ||= 'any';
                   3407:     if (!defined($cdom) || !defined($cnum)) {
                   3408:         my $cid  = $env{'request.course.id'};
                   3409:         $cdom = $env{'course.'.$cid.'.domain'};
                   3410:         $cnum = $env{'course.'.$cid.'.num'};
                   3411:     }
                   3412:     my $typesref;
                   3413:     if (($type eq 'any') || ($type eq 'all')) {
                   3414:         $typesref = ['active','previous','future'];
                   3415:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3416:         $typesref = [$type];
                   3417:     }
                   3418:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3419:                               $typesref,undef,[$cdom]);
                   3420:     my ($tmp) = keys(%roles);
                   3421:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3422:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3423:     if (@course_roles > 0) {
                   3424:         return 1;
                   3425:     }
                   3426:     return 0;
                   3427: }
                   3428: 
1.478     albertel 3429: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3430: # input: action, courseID, current domain, intended
1.637     raeburn  3431: #        path to file, source of file, instruction to parse file for objects,
                   3432: #        ref to hash for embedded objects,
                   3433: #        ref to hash for codebase of java objects.
1.1095    raeburn  3434: #        reference to scalar to accommodate mime type determined
                   3435: #          from File::MMagic if $parser = parse.
1.637     raeburn  3436: #
1.485     raeburn  3437: # output: url to file (if action was uploaddoc), 
                   3438: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3439: #
1.478     albertel 3440: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3441: # course.
1.477     raeburn  3442: #
1.478     albertel 3443: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3444: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3445: #          course's home server.
1.477     raeburn  3446: #
1.478     albertel 3447: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3448: #          be copied from $source (current location) to 
                   3449: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3450: #         and will then be copied to
                   3451: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3452: #         course's home server.
1.485     raeburn  3453: #
1.481     raeburn  3454: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3455: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3456: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3457: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3458: #         in course's home server.
1.637     raeburn  3459: #
1.477     raeburn  3460: 
                   3461: sub process_coursefile {
1.1095    raeburn  3462:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3463:         $mimetype)=@_;
1.477     raeburn  3464:     my $fetchresult;
1.638     albertel 3465:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3466:     if ($action eq 'propagate') {
1.638     albertel 3467:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3468: 			     $home);
1.481     raeburn  3469:     } else {
1.477     raeburn  3470:         my $fpath = '';
                   3471:         my $fname = $file;
1.478     albertel 3472:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3473:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3474:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3475:         if ($action eq 'copy') {
                   3476:             if ($source eq '') {
                   3477:                 $fetchresult = 'no source file';
                   3478:                 return $fetchresult;
                   3479:             } else {
                   3480:                 my $destination = $filepath.'/'.$fname;
                   3481:                 rename($source,$destination);
                   3482:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3483:                                  $home);
1.481     raeburn  3484:             }
                   3485:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3486:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3487:             print $fh $env{'form.'.$source};
1.481     raeburn  3488:             close($fh);
1.637     raeburn  3489:             if ($parser eq 'parse') {
1.1024    raeburn  3490:                 my $mm = new File::MMagic;
1.1095    raeburn  3491:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3492:                 if ($type eq 'text/html') {
1.1024    raeburn  3493:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3494:                     unless ($parse_result eq 'ok') {
                   3495:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3496:                     }
1.637     raeburn  3497:                 }
1.1095    raeburn  3498:                 if (ref($mimetype)) {
                   3499:                     $$mimetype = $type;
                   3500:                 } 
1.637     raeburn  3501:             }
1.477     raeburn  3502:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3503:                                  $home);
1.481     raeburn  3504:             if ($fetchresult eq 'ok') {
                   3505:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3506:             } else {
                   3507:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3508:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3509:                 return '/adm/notfound.html';
                   3510:             }
1.477     raeburn  3511:         }
                   3512:     }
1.485     raeburn  3513:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3514:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3515:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3516:     }
                   3517:     return $fetchresult;
                   3518: }
                   3519: 
1.637     raeburn  3520: sub build_filepath {
                   3521:     my ($fpath) = @_;
                   3522:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3523:     unless ($fpath eq '') {
                   3524:         my @parts=split('/',$fpath);
                   3525:         foreach my $part (@parts) {
                   3526:             $filepath.= '/'.$part;
                   3527:             if ((-e $filepath)!=1) {
                   3528:                 mkdir($filepath,0777);
                   3529:             }
                   3530:         }
                   3531:     }
                   3532:     return $filepath;
                   3533: }
                   3534: 
                   3535: sub store_edited_file {
1.638     albertel 3536:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3537:     my $file = $primary_url;
                   3538:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3539:     my $fpath = '';
                   3540:     my $fname = $file;
                   3541:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3542:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3543:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3544:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3545:     print $fh $content;
                   3546:     close($fh);
1.638     albertel 3547:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3548:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3549: 			  $home);
1.637     raeburn  3550:     if ($$fetchresult eq 'ok') {
                   3551:         return '/uploaded/'.$fpath.'/'.$fname;
                   3552:     } else {
1.638     albertel 3553:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3554: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3555:         return '/adm/notfound.html';
                   3556:     }
                   3557: }
                   3558: 
1.531     albertel 3559: sub clean_filename {
1.831     albertel 3560:     my ($fname,$args)=@_;
1.315     www      3561: # Replace Windows backslashes by forward slashes
1.257     www      3562:     $fname=~s/\\/\//g;
1.831     albertel 3563:     if (!$args->{'keep_path'}) {
                   3564:         # Get rid of everything but the actual filename
                   3565: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3566:     }
1.315     www      3567: # Replace spaces by underscores
                   3568:     $fname=~s/\s+/\_/g;
                   3569: # Replace all other weird characters by nothing
1.831     albertel 3570:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3571: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3572: # numbers
                   3573:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3574:     return $fname;
                   3575: }
1.1051    raeburn  3576: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3577: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3578: # image with the same aspect ratio as the original, but with dimensions which do 
                   3579: # not exceed $resizewidth and $resizeheight.
                   3580:  
1.984     neumanie 3581: sub resizeImage {
1.1051    raeburn  3582:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3583:     my $ima = Image::Magick->new;
                   3584:     my $resized;
                   3585:     if (-e $img_path) {
                   3586:         $ima->Read($img_path);
                   3587:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3588:             my $width = $ima->Get('width');
                   3589:             my $height = $ima->Get('height');
                   3590:             if ($width > $resizewidth) {
                   3591: 	        my $factor = $width/$resizewidth;
                   3592:                 my $newheight = $height/$factor;
                   3593:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3594:                 $resized = 1;
                   3595:             }
                   3596:         }
                   3597:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3598:             my $width = $ima->Get('width');
                   3599:             my $height = $ima->Get('height');
                   3600:             if ($height > $resizeheight) {
                   3601:                 my $factor = $height/$resizeheight;
                   3602:                 my $newwidth = $width/$factor;
                   3603:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3604:                 $resized = 1;
                   3605:             }
                   3606:         }
                   3607:         if ($resized) {
                   3608:             $ima->Write($img_path);
                   3609:         }
                   3610:     }
                   3611:     return;
1.977     amueller 3612: }
                   3613: 
1.608     albertel 3614: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3615: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3616: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3617: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3618: #                                    canceloverwrite, or ''. 
                   3619: #                   if 'coursedoc': upload to the current course
                   3620: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3621: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3622: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3623: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3624: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3625: #        $allfiles - reference to hash for embedded objects
                   3626: #        $codebase - reference to hash for codebase of java objects
                   3627: #        $desuname - username for permanent storage of uploaded file
                   3628: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3629: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3630: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3631: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3632: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3633: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3634: #                    from File::MMagic.
1.858     raeburn  3635: # 
1.686     albertel 3636: # output: url of file in userspace, or error: <message> 
                   3637: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3638: 
1.531     albertel 3639: sub userfileupload {
1.1090    raeburn  3640:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3641:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3642:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3643:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3644:     $fname=&clean_filename($fname);
1.1090    raeburn  3645:     # See if there is anything left
1.257     www      3646:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3647:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3648:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3649:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3650:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3651:         my $now = time;
1.1090    raeburn  3652:         my $filepath;
1.1095    raeburn  3653:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3654:              $filepath = 'tmp/helprequests/'.$now;
                   3655:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3656:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3657:                          '_'.$env{'user.domain'}.'/pending';
                   3658:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3659:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3660:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3661:                 $docudom = $destudom;
                   3662:             } else {
                   3663:                 $docudom = $env{'user.domain'};
                   3664:             }
1.1172.2.96  raeburn  3665:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3666:                 $docuname = $destuname;
                   3667:             } else {
                   3668:                 $docuname = $env{'user.name'};
                   3669:             }
                   3670:             if (exists($env{'form.group'})) {
                   3671:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3672:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3673:             }
                   3674:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3675:             if ($context eq 'canceloverwrite') {
                   3676:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3677:                 if (-e  $tempfile) {
                   3678:                     my @info = stat($tempfile);
                   3679:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3680:                         unlink($tempfile);
                   3681:                     }
                   3682:                 }
                   3683:                 return;
1.523     raeburn  3684:             }
                   3685:         }
1.1090    raeburn  3686:         # Create the directory if not present
1.741     raeburn  3687:         my @parts=split(/\//,$filepath);
                   3688:         my $fullpath = $perlvar{'lonDaemons'};
                   3689:         for (my $i=0;$i<@parts;$i++) {
                   3690:             $fullpath .= '/'.$parts[$i];
                   3691:             if ((-e $fullpath)!=1) {
                   3692:                 mkdir($fullpath,0777);
                   3693:             }
                   3694:         }
1.1172.2.96  raeburn  3695:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3696:         print $fh $env{'form.'.$formname};
                   3697:         close($fh);
1.1090    raeburn  3698:         if ($context eq 'existingfile') {
                   3699:             my @info = stat($fullpath.'/'.$fname);
                   3700:             return ($fullpath.'/'.$fname,$info[9]);
                   3701:         } else {
                   3702:             return $fullpath.'/'.$fname;
                   3703:         }
1.523     raeburn  3704:     }
1.995     raeburn  3705:     if ($subdir eq 'scantron') {
                   3706:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3707:     } else {
1.995     raeburn  3708:         $fname="$subdir/$fname";
                   3709:     }
1.1090    raeburn  3710:     if ($context eq 'coursedoc') {
1.638     albertel 3711: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3712: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3713:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3714:             return &finishuserfileupload($docuname,$docudom,
                   3715: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3716: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3717:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3718:         } else {
1.1172.2.21  raeburn  3719:             if ($env{'form.folder'}) {
                   3720:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3721:             }
1.638     albertel 3722:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3723: 				       $fname,$formname,$parser,
1.1095    raeburn  3724: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3725:         }
1.719     banghart 3726:     } elsif (defined($destuname)) {
                   3727:         my $docuname=$destuname;
                   3728:         my $docudom=$destudom;
1.860     raeburn  3729: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3730: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3731:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3732:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3733:     } else {
1.638     albertel 3734:         my $docuname=$env{'user.name'};
                   3735:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3736:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3737:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3738:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3739:         }
1.860     raeburn  3740: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3741: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3742:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3743:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3744:     }
1.271     www      3745: }
                   3746: 
                   3747: sub finishuserfileupload {
1.860     raeburn  3748:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3749:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3750:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3751:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3752:   
1.860     raeburn  3753:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3754:     $file=$fname;
                   3755:     if ($fname=~m|/|) {
                   3756:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3757: 	$path.=$fnamepath.'/';
                   3758:     }
1.259     www      3759:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3760:     my $count;
                   3761:     for ($count=4;$count<=$#parts;$count++) {
                   3762:         $filepath.="/$parts[$count]";
                   3763:         if ((-e $filepath)!=1) {
                   3764: 	    mkdir($filepath,0777);
                   3765:         }
                   3766:     }
1.984     neumanie 3767: 
1.258     www      3768: # Save the file
                   3769:     {
1.1172.2.96  raeburn  3770: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3771: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3772: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3773: 	    return '/adm/notfound.html';
                   3774: 	}
1.1090    raeburn  3775:         if ($context eq 'overwrite') {
1.1117    foxr     3776:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3777:             my $target = $filepath.'/'.$file;
                   3778:             if (-e $source) {
                   3779:                 my @info = stat($source);
                   3780:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3781:                     unless (&File::Copy::move($source,$target)) {
                   3782:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3783:                         return "Moving from $source failed";
                   3784:                     }
                   3785:                 } else {
                   3786:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3787:                 }
                   3788:             } else {
                   3789:                 return "Temporary file: $source missing";
                   3790:             }
                   3791:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3792: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3793: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3794: 	    return '/adm/notfound.html';
                   3795: 	}
1.570     albertel 3796: 	close(FH);
1.1051    raeburn  3797:         if ($resizewidth && $resizeheight) {
                   3798:             my $mm = new File::MMagic;
                   3799:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3800:             if ($mime_type =~ m{^image/}) {
                   3801: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3802:             }  
1.977     amueller 3803: 	}
1.258     www      3804:     }
1.1152    raeburn  3805:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3806:         if (ref($mimetype)) {
                   3807:             if ($$mimetype eq '') {
                   3808:                 my $mm = new File::MMagic;
                   3809:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3810:                 $$mimetype = $type;
                   3811:             }
                   3812:         }
                   3813:     }
1.637     raeburn  3814:     if ($parser eq 'parse') {
1.1152    raeburn  3815:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3816:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3817:                                                        $allfiles,$codebase);
                   3818:             unless ($parse_result eq 'ok') {
                   3819:                 &logthis('Failed to parse '.$filepath.$file.
                   3820: 	   	         ' for embedded media: '.$parse_result); 
                   3821:             }
1.637     raeburn  3822:         }
                   3823:     }
1.860     raeburn  3824:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3825:         my $input = $filepath.'/'.$file;
                   3826:         my $output = $filepath.'/'.'tn-'.$file;
                   3827:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3828:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3829:         system({$args[0]} @args);
1.860     raeburn  3830:         if (-e $filepath.'/'.'tn-'.$file) {
                   3831:             $fetchthumb  = 1; 
                   3832:         }
                   3833:     }
1.858     raeburn  3834:  
1.259     www      3835: # Notify homeserver to grep it
                   3836: #
1.984     neumanie 3837:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3838:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3839:     if ($fetchresult eq 'ok') {
1.860     raeburn  3840:         if ($fetchthumb) {
                   3841:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3842:             if ($thumbresult ne 'ok') {
                   3843:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3844:                          $docuhome.': '.$thumbresult);
                   3845:             }
                   3846:         }
1.259     www      3847: #
1.258     www      3848: # Return the URL to it
1.494     albertel 3849:         return '/uploaded/'.$path.$file;
1.263     www      3850:     } else {
1.494     albertel 3851:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3852: 		 ': '.$fetchresult);
1.263     www      3853:         return '/adm/notfound.html';
1.858     raeburn  3854:     }
1.493     albertel 3855: }
                   3856: 
1.637     raeburn  3857: sub extract_embedded_items {
1.961     raeburn  3858:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3859:     my @state = ();
1.1164    raeburn  3860:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3861:     my %javafiles = (
                   3862:                       codebase => '',
                   3863:                       code => '',
                   3864:                       archive => ''
                   3865:                     );
                   3866:     my %mediafiles = (
                   3867:                       src => '',
                   3868:                       movie => '',
                   3869:                      );
1.648     raeburn  3870:     my $p;
                   3871:     if ($content) {
                   3872:         $p = HTML::LCParser->new($content);
                   3873:     } else {
1.961     raeburn  3874:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3875:     }
1.641     albertel 3876:     while (my $t=$p->get_token()) {
1.640     albertel 3877: 	if ($t->[0] eq 'S') {
                   3878: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3879: 	    push(@state, $tagname);
1.648     raeburn  3880:             if (lc($tagname) eq 'allow') {
                   3881:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3882:             }
1.640     albertel 3883: 	    if (lc($tagname) eq 'img') {
                   3884: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3885: 	    }
1.886     albertel 3886: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3887:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3888: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3889:                 }
1.886     albertel 3890: 	    }
1.645     raeburn  3891:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3892:                 my $src;
1.645     raeburn  3893:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3894:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3895:                 } else {
1.1164    raeburn  3896:                     if ($attr->{'src'} ne '') {
                   3897:                         $src = $attr->{'src'};
                   3898:                         &add_filetype($allfiles,$src,'src');
                   3899:                     }
                   3900:                 }
                   3901:                 my $text = $p->get_trimmed_text();
                   3902:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3903:                     my @swfargs = split(/,/,$1);
                   3904:                     foreach my $item (@swfargs) {
                   3905:                         $item =~ s/["']//g;
                   3906:                         $item =~ s/^\s+//;
                   3907:                         $item =~ s/\s+$//;
                   3908:                     }
                   3909:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3910:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3911:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3912:                         } else {
                   3913:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3914:                         }
                   3915:                     }
1.645     raeburn  3916:                 }
                   3917:             }
                   3918:             if (lc($tagname) eq 'link') {
                   3919:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3920:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3921:                 }
                   3922:             }
1.640     albertel 3923: 	    if (lc($tagname) eq 'object' ||
                   3924: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3925: 		foreach my $item (keys(%javafiles)) {
                   3926: 		    $javafiles{$item} = '';
                   3927: 		}
1.1164    raeburn  3928:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3929:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3930:                 }
1.640     albertel 3931: 	    }
                   3932: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3933: 		my $name = lc($attr->{'name'});
                   3934: 		foreach my $item (keys(%javafiles)) {
                   3935: 		    if ($name eq $item) {
                   3936: 			$javafiles{$item} = $attr->{'value'};
                   3937: 			last;
                   3938: 		    }
                   3939: 		}
1.1164    raeburn  3940:                 my $pathfrom;
1.640     albertel 3941: 		foreach my $item (keys(%mediafiles)) {
                   3942: 		    if ($name eq $item) {
1.1164    raeburn  3943:                         $pathfrom = $attr->{'value'};
                   3944:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3945: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3946: 			last;
                   3947: 		    }
                   3948: 		}
1.1164    raeburn  3949:                 if ($name eq 'flashvars') {
                   3950:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3951:                 }
                   3952:                 if ($pathfrom ne '') {
                   3953:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3954:                                          $pathfrom);
                   3955:                 }
1.640     albertel 3956: 	    }
                   3957: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3958: 		foreach my $item (keys(%javafiles)) {
                   3959: 		    if ($attr->{$item}) {
                   3960: 			$javafiles{$item} = $attr->{$item};
                   3961: 			last;
                   3962: 		    }
                   3963: 		}
                   3964: 		foreach my $item (keys(%mediafiles)) {
                   3965: 		    if ($attr->{$item}) {
                   3966: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3967: 			last;
                   3968: 		    }
                   3969: 		}
1.1164    raeburn  3970:                 if (lc($tagname) eq 'embed') {
                   3971:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3972:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3973:                                              $attr->{'src'});
                   3974:                     }
                   3975:                 }
1.640     albertel 3976: 	    }
1.1172.2.35  raeburn  3977:             if (lc($tagname) eq 'iframe') {
                   3978:                 my $src = $attr->{'src'} ;
                   3979:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3980:                     &add_filetype($allfiles,$src,'src');
                   3981:                 } elsif ($src =~ m{^/}) {
                   3982:                     if ($env{'request.course.id'}) {
                   3983:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3984:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3985:                         my $url = &hreflocation('',$fullpath);
                   3986:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3987:                             my $relpath = $1;
                   3988:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3989:                                 &add_filetype($allfiles,$1,'src');
                   3990:                             }
                   3991:                         }
                   3992:                     }
                   3993:                 }
                   3994:             }
1.1164    raeburn  3995:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3996:                 pop(@state);
1.1164    raeburn  3997:             }
1.640     albertel 3998: 	} elsif ($t->[0] eq 'E') {
                   3999: 	    my ($tagname) = ($t->[1]);
                   4000: 	    if ($javafiles{'codebase'} ne '') {
                   4001: 		$javafiles{'codebase'} .= '/';
                   4002: 	    }  
                   4003: 	    if (lc($tagname) eq 'applet' ||
                   4004: 		lc($tagname) eq 'object' ||
                   4005: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4006: 		) {
                   4007: 		foreach my $item (keys(%javafiles)) {
                   4008: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4009: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4010: 			&add_filetype($allfiles,$file,$item);
                   4011: 		    }
                   4012: 		}
                   4013: 	    } 
                   4014: 	    pop @state;
                   4015: 	}
                   4016:     }
1.1164    raeburn  4017:     foreach my $id (sort(keys(%flashvars))) {
                   4018:         if ($shockwave{$id} ne '') {
                   4019:             my @pairs = split(/\&/,$flashvars{$id});
                   4020:             foreach my $pair (@pairs) {
                   4021:                 my ($key,$value) = split(/\=/,$pair);
                   4022:                 if ($key eq 'thumb') {
                   4023:                     &add_filetype($allfiles,$value,$key);
                   4024:                 } elsif ($key eq 'content') {
                   4025:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4026:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4027:                     if ($ext ne '') {
                   4028:                         &add_filetype($allfiles,$path.$value,$ext);
                   4029:                     }
                   4030:                 }
                   4031:             }
                   4032:         }
                   4033:     }
1.637     raeburn  4034:     return 'ok';
                   4035: }
                   4036: 
1.639     albertel 4037: sub add_filetype {
                   4038:     my ($allfiles,$file,$type)=@_;
                   4039:     if (exists($allfiles->{$file})) {
                   4040: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4041: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4042: 	}
                   4043:     } else {
                   4044: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4045:     }
                   4046: }
                   4047: 
1.1164    raeburn  4048: sub embedded_dependency {
                   4049:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4050:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4051:         if (($identifier ne '') &&
                   4052:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4053:             ($pathfrom ne '')) {
                   4054:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4055:             foreach my $dep (@{$related->{$identifier}}) {
                   4056:                 &add_filetype($allfiles,$path.$dep,'object');
                   4057:             }
                   4058:         }
                   4059:     }
                   4060:     return;
                   4061: }
                   4062: 
1.493     albertel 4063: sub removeuploadedurl {
1.984     neumanie 4064:     my ($url)=@_;	
                   4065:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4066:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4067: }
                   4068: 
                   4069: sub removeuserfile {
                   4070:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4071:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4072:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4073:     if ($result eq 'ok') {	
1.798     raeburn  4074:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4075:             my $metafile = $fname.'.meta';
                   4076:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4077: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4078:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4079:             my $sqlresult = 
1.823     albertel 4080:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4081:                                         'portfolio_metadata',$group,
                   4082:                                         'delete');
1.798     raeburn  4083:         }
                   4084:     }
                   4085:     return $result;
1.257     www      4086: }
1.15      www      4087: 
1.530     albertel 4088: sub mkdiruserfile {
                   4089:     my ($docuname,$docudom,$dir)=@_;
                   4090:     my $home=&homeserver($docuname,$docudom);
                   4091:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4092: }
                   4093: 
1.531     albertel 4094: sub renameuserfile {
                   4095:     my ($docuname,$docudom,$old,$new)=@_;
                   4096:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4097:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4098:                         &escape("$old").':'.&escape("$new"),$home);
                   4099:     if ($result eq 'ok') {
                   4100:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4101:             my $oldmeta = $old.'.meta';
                   4102:             my $newmeta = $new.'.meta';
                   4103:             my $metaresult = 
                   4104:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4105: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4106:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4107:             my $sqlresult = 
1.823     albertel 4108:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4109:                                         'portfolio_metadata',$group,
                   4110:                                         'delete');
1.798     raeburn  4111:         }
                   4112:     }
                   4113:     return $result;
1.531     albertel 4114: }
                   4115: 
1.14      www      4116: # ------------------------------------------------------------------------- Log
                   4117: 
                   4118: sub log {
                   4119:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4120:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4121: }
                   4122: 
                   4123: # ------------------------------------------------------------------ Course Log
1.352     www      4124: #
                   4125: # This routine flushes several buffers of non-mission-critical nature
                   4126: #
1.157     www      4127: 
                   4128: sub flushcourselogs {
1.352     www      4129:     &logthis('Flushing log buffers');
                   4130: #
                   4131: # course logs
                   4132: # This is a log of all transactions in a course, which can be used
                   4133: # for data mining purposes
                   4134: #
                   4135: # It also collects the courseid database, which lists last transaction
                   4136: # times and course titles for all courseids
                   4137: #
                   4138:     my %courseidbuffer=();
1.921     raeburn  4139:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4140:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4141: 		          &escape($courselogs{$crsid}),
                   4142: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4143: 	    delete $courselogs{$crsid};
                   4144:         } else {
                   4145:             &logthis('Failed to flush log buffer for '.$crsid);
                   4146:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4147:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4148:                         " exceeded maximum size, deleting.</font>");
                   4149:                delete $courselogs{$crsid};
                   4150:             }
1.352     www      4151:         }
1.920     raeburn  4152:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4153:             'description' => $coursedescrbuf{$crsid},
                   4154:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4155:             'type'        => $coursetypebuf{$crsid},
                   4156:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4157:         };
1.191     harris41 4158:     }
1.352     www      4159: #
                   4160: # Write course id database (reverse lookup) to homeserver of courses 
                   4161: # Is used in pickcourse
                   4162: #
1.840     albertel 4163:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4164:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4165:                                     $courseidbuffer{$crs_home},
                   4166:                                     $crs_home,'timeonly');
1.352     www      4167:     }
                   4168: #
                   4169: # File accesses
                   4170: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4171: #
1.449     matthew  4172:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4173:         if ($entry =~ /___count$/) {
                   4174:             my ($dom,$name);
1.807     albertel 4175:             ($dom,$name,undef)=
1.811     albertel 4176: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4177:             if (! defined($dom) || $dom eq '' || 
                   4178:                 ! defined($name) || $name eq '') {
1.620     albertel 4179:                 my $cid = $env{'request.course.id'};
                   4180:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4181:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4182:             }
1.450     matthew  4183:             my $value = $accesshash{$entry};
                   4184:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4185:             my %temphash=($url => $value);
1.449     matthew  4186:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4187:             if ($result eq 'ok') {
                   4188:                 delete $accesshash{$entry};
                   4189:             }
                   4190:         } else {
1.811     albertel 4191:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4192:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4193:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4194:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4195:                 delete $accesshash{$entry};
                   4196:             }
1.185     www      4197:         }
1.191     harris41 4198:     }
1.352     www      4199: #
                   4200: # Roles
                   4201: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4202: #
1.800     albertel 4203:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4204:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4205: 	    split(/\:/,$entry);
                   4206:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4207:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4208:                 $rudom,$runame) eq 'ok') {
                   4209: 	    delete $userrolehash{$entry};
                   4210:         }
                   4211:     }
1.662     raeburn  4212: #
1.1172.2.90  raeburn  4213: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4214: #
                   4215:     my %domrolebuffer = ();
1.1000    raeburn  4216:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4217:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4218:         if ($domrolebuffer{$rudom}) {
                   4219:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4220:                       '='.&escape($domainrolehash{$entry});
                   4221:         } else {
                   4222:             $domrolebuffer{$rudom}.=&escape($entry).
                   4223:                       '='.&escape($domainrolehash{$entry});
                   4224:         }
                   4225:         delete $domainrolehash{$entry};
                   4226:     }
                   4227:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4228:         my %servers;
                   4229:         if (defined(&domain($dom,'primary'))) {
                   4230:             my $primary=&domain($dom,'primary');
                   4231:             my $hostname=&hostname($primary);
                   4232:             $servers{$primary} = $hostname;
                   4233:         } else {
                   4234:             %servers = &get_servers($dom,'library');
                   4235:         }
1.841     albertel 4236: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4237: 	    if (&reply('domroleput:'.$dom.':'.
                   4238: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4239: 	        last;
                   4240: 	    } else {
1.841     albertel 4241: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4242: 	    }
1.662     raeburn  4243:         }
                   4244:     }
1.186     www      4245:     $dumpcount++;
1.157     www      4246: }
                   4247: 
                   4248: sub courselog {
                   4249:     my $what=shift;
1.158     www      4250:     $what=time.':'.$what;
1.620     albertel 4251:     unless ($env{'request.course.id'}) { return ''; }
                   4252:     $coursedombuf{$env{'request.course.id'}}=
                   4253:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4254:     $coursenumbuf{$env{'request.course.id'}}=
                   4255:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4256:     $coursehombuf{$env{'request.course.id'}}=
                   4257:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4258:     $coursedescrbuf{$env{'request.course.id'}}=
                   4259:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4260:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4261:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4262:     $courseownerbuf{$env{'request.course.id'}}=
                   4263:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4264:     $coursetypebuf{$env{'request.course.id'}}=
                   4265:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4266:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4267: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4268:     } else {
1.620     albertel 4269: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4270:     }
1.620     albertel 4271:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4272: 	&flushcourselogs();
                   4273:     }
1.158     www      4274: }
                   4275: 
                   4276: sub courseacclog {
                   4277:     my $fnsymb=shift;
1.620     albertel 4278:     unless ($env{'request.course.id'}) { return ''; }
                   4279:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4280:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4281:         $what.=':POST';
1.583     matthew  4282:         # FIXME: Probably ought to escape things....
1.800     albertel 4283: 	foreach my $key (keys(%env)) {
                   4284:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4285:                 my $formitem = $1;
                   4286:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4287:                     $what.=':'.$formitem.'='.$env{$key};
                   4288:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4289:                     $what.=':'.$formitem.'='.$env{$key};
                   4290:                 }
1.158     www      4291:             }
1.191     harris41 4292:         }
1.583     matthew  4293:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4294:         # FIXME: We should not be depending on a form parameter that someone
                   4295:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4296:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4297:             $what.= ':POST';
                   4298:             # FIXME: Probably ought to escape things....
                   4299:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4300:                                  'crsdiscuss') {
1.620     albertel 4301:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4302:             }
                   4303:         }
1.158     www      4304:     }
                   4305:     &courselog($what);
1.149     www      4306: }
                   4307: 
1.185     www      4308: sub countacc {
                   4309:     my $url=&declutter(shift);
1.458     matthew  4310:     return if (! defined($url) || $url eq '');
1.620     albertel 4311:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4312: #
                   4313: # Mark that this url was used in this course
                   4314: #
1.620     albertel 4315:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4316: #
                   4317: # Increase the access count for this resource in this child process
                   4318: #
1.281     www      4319:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4320:     $accesshash{$key}++;
1.185     www      4321: }
1.349     www      4322: 
1.361     www      4323: sub linklog {
                   4324:     my ($from,$to)=@_;
                   4325:     $from=&declutter($from);
                   4326:     $to=&declutter($to);
                   4327:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4328:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4329: }
1.1160    www      4330: 
                   4331: sub statslog {
                   4332:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4333:     if ($users<2) { return; }
                   4334:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4335:             'course'       => $env{'request.course.id'},
                   4336:             'sections'     => '"all"',
                   4337:             'num_students' => $users,
                   4338:             'part'         => $part,
                   4339:             'symb'         => $symb,
                   4340:             'mean_tries'   => $av_attempts,
                   4341:             'deg_of_diff'  => $degdiff});
                   4342:     foreach my $key (keys(%dynstore)) {
                   4343:         $accesshash{$key}=$dynstore{$key};
                   4344:     }
                   4345: }
1.361     www      4346:   
1.349     www      4347: sub userrolelog {
                   4348:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4349:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4350:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4351:        $userrolehash
                   4352:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4353:                     =$tend.':'.$tstart;
1.662     raeburn  4354:     }
1.1169    droeschl 4355:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4356:        $userrolehash
                   4357:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4358:                     =$tend.':'.$tstart;
                   4359:     }
1.1172.2.90  raeburn  4360:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4361:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4362:        $domainrolehash
                   4363:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4364:                     = $tend.':'.$tstart;
                   4365:     }
1.351     www      4366: }
                   4367: 
1.957     raeburn  4368: sub courserolelog {
                   4369:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4370:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4371:         my $cdom = $1;
                   4372:         my $cnum = $2;
                   4373:         my $sec = $3;
                   4374:         my $namespace = 'rolelog';
                   4375:         my %storehash = (
                   4376:                            role    => $trole,
                   4377:                            start   => $tstart,
                   4378:                            end     => $tend,
                   4379:                            selfenroll => $selfenroll,
                   4380:                            context    => $context,
                   4381:                         );
                   4382:         if ($trole eq 'gr') {
                   4383:             $namespace = 'groupslog';
                   4384:             $storehash{'group'} = $sec;
                   4385:         } else {
                   4386:             $storehash{'section'} = $sec;
                   4387:         }
                   4388:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4389:                    $domain,$cnum,$cdom);
                   4390:         if (($trole ne 'st') || ($sec ne '')) {
                   4391:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4392:         }
                   4393:     }
                   4394:     return;
                   4395: }
                   4396: 
1.1172.2.9  raeburn  4397: sub domainrolelog {
                   4398:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4399:     if ($area =~ m{^/($match_domain)/$}) {
                   4400:         my $cdom = $1;
                   4401:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4402:         my $namespace = 'rolelog';
                   4403:         my %storehash = (
                   4404:                            role    => $trole,
                   4405:                            start   => $tstart,
                   4406:                            end     => $tend,
                   4407:                            context => $context,
                   4408:                         );
                   4409:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4410:                    $domain,$domconfiguser,$cdom);
                   4411:     }
                   4412:     return;
                   4413: 
                   4414: }
                   4415: 
                   4416: sub coauthorrolelog {
                   4417:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4418:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4419:         my $audom = $1;
                   4420:         my $auname = $2;
                   4421:         my $namespace = 'rolelog';
                   4422:         my %storehash = (
                   4423:                            role    => $trole,
                   4424:                            start   => $tstart,
                   4425:                            end     => $tend,
                   4426:                            context => $context,
                   4427:                         );
                   4428:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4429:                    $domain,$auname,$audom);
                   4430:     }
                   4431:     return;
                   4432: }
                   4433: 
1.351     www      4434: sub get_course_adv_roles {
1.948     raeburn  4435:     my ($cid,$codes) = @_;
1.620     albertel 4436:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4437:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4438:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4439:     my %nothide=();
1.800     albertel 4440:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4441:         if ($user !~ /:/) {
                   4442: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4443:         } else {
                   4444:             $nothide{$user}=1;
                   4445:         }
1.470     www      4446:     }
1.1172.2.23  raeburn  4447:     my @possdoms = ($coursehash{'domain'});
                   4448:     if ($coursehash{'checkforpriv'}) {
                   4449:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4450:     }
1.351     www      4451:     my %returnhash=();
                   4452:     my %dumphash=
                   4453:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4454:     my $now=time;
1.997     raeburn  4455:     my %privileged;
1.1000    raeburn  4456:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4457: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4458:         if (($tstart) && ($tstart<0)) { next; }
                   4459:         if (($tend) && ($tend<$now)) { next; }
                   4460:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4461:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4462: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4463:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4464:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4465: 	if ($role eq 'cr') { next; }
1.948     raeburn  4466:         if ($codes) {
                   4467:             if ($section) { $role .= ':'.$section; }
                   4468:             if ($returnhash{$role}) {
                   4469:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4470:             } else {
                   4471:                 $returnhash{$role}=$username.':'.$domain;
                   4472:             }
1.351     www      4473:         } else {
1.988     raeburn  4474:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4475:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4476:             if ($returnhash{$key}) {
                   4477: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4478:             } else {
                   4479:                 $returnhash{$key}=$username.':'.$domain;
                   4480:             }
1.351     www      4481:         }
1.948     raeburn  4482:     }
1.400     www      4483:     return %returnhash;
                   4484: }
                   4485: 
                   4486: sub get_my_roles {
1.937     raeburn  4487:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4488:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4489:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4490:     my (%dumphash,%nothide);
1.1086    raeburn  4491:     if ($context eq 'userroles') {
1.1166    raeburn  4492:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4493:     } else {
1.1172.2.23  raeburn  4494:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4495:         if ($hidepriv) {
                   4496:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4497:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4498:                 if ($user !~ /:/) {
                   4499:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4500:                 } else {
                   4501:                     $nothide{$user} = 1;
                   4502:                 }
                   4503:             }
                   4504:         }
1.858     raeburn  4505:     }
1.400     www      4506:     my %returnhash=();
                   4507:     my $now=time;
1.999     raeburn  4508:     my %privileged;
1.800     albertel 4509:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4510:         my ($role,$tend,$tstart);
                   4511:         if ($context eq 'userroles') {
1.1149    raeburn  4512:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4513: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4514:         } else {
                   4515:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4516:         }
1.400     www      4517:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4518:         my $status = 'active';
1.939     raeburn  4519:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4520:             $status = 'previous';
                   4521:         } 
                   4522:         if (($tstart) && ($now<$tstart)) {
                   4523:             $status = 'future';
                   4524:         }
                   4525:         if (ref($types) eq 'ARRAY') {
                   4526:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4527:                 next;
                   4528:             } 
                   4529:         } else {
                   4530:             if ($status ne 'active') {
                   4531:                 next;
                   4532:             }
                   4533:         }
1.867     raeburn  4534:         my ($rolecode,$username,$domain,$section,$area);
                   4535:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4536:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4537:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4538:         } else {
                   4539:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4540:         }
1.832     raeburn  4541:         if (ref($roledoms) eq 'ARRAY') {
                   4542:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4543:                 next;
                   4544:             }
                   4545:         }
                   4546:         if (ref($roles) eq 'ARRAY') {
                   4547:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4548:                 if ($role =~ /^cr\//) {
                   4549:                     if (!grep(/^cr$/,@{$roles})) {
                   4550:                         next;
                   4551:                     }
1.1104    raeburn  4552:                 } elsif ($role =~ /^gr\//) {
                   4553:                     if (!grep(/^gr$/,@{$roles})) {
                   4554:                         next;
                   4555:                     }
1.922     raeburn  4556:                 } else {
                   4557:                     next;
                   4558:                 }
1.832     raeburn  4559:             }
1.867     raeburn  4560:         }
1.937     raeburn  4561:         if ($hidepriv) {
1.1172.2.23  raeburn  4562:             my @privroles = ('dc','su');
1.999     raeburn  4563:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4564:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4565:             } else {
1.1172.2.23  raeburn  4566:                 my $possdoms = [$domain];
                   4567:                 if (ref($roledoms) eq 'ARRAY') {
                   4568:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4569:                 }
1.1172.2.23  raeburn  4570:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4571:                     if (!$nothide{$username.':'.$domain}) {
                   4572:                         next;
                   4573:                     }
                   4574:                 }
1.937     raeburn  4575:             }
                   4576:         }
1.933     raeburn  4577:         if ($withsec) {
                   4578:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4579:                 $tstart.':'.$tend;
                   4580:         } else {
                   4581:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4582:         }
1.832     raeburn  4583:     }
1.373     www      4584:     return %returnhash;
1.399     www      4585: }
                   4586: 
1.1172.2.89  raeburn  4587: sub get_all_adhocroles {
                   4588:     my ($dom) = @_;
                   4589:     my @roles_by_num = ();
                   4590:     my %domdefaults = &get_domain_defaults($dom);
                   4591:     my (%description,%access_in_dom,%access_info);
                   4592:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4593:         my $count = 0;
                   4594:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4595:         my %ordered;
                   4596:         foreach my $role (sort(keys(%domcurrent))) {
                   4597:             my ($order,$desc,$access_in_dom);
                   4598:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4599:                 $order = $domcurrent{$role}{'order'};
                   4600:                 $desc = $domcurrent{$role}{'desc'};
                   4601:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4602:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4603:             }
                   4604:             if ($order eq '') {
                   4605:                 $order = $count;
                   4606:             }
                   4607:             $ordered{$order} = $role;
                   4608:             if ($desc ne '') {
                   4609:                 $description{$role} = $desc;
                   4610:             } else {
                   4611:                 $description{$role}= $role;
                   4612:             }
                   4613:             $count++;
                   4614:         }
                   4615:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4616:             push(@roles_by_num,$ordered{$item});
                   4617:         }
                   4618:     }
                   4619:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4620: }
                   4621: 
                   4622: sub get_my_adhocroles {
                   4623:     my ($cid,$checkreg) = @_;
                   4624:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4625:     if ($env{'request.course.id'} eq $cid) {
                   4626:         $cdom = $env{'course.'.$cid.'.domain'};
                   4627:         $cnum = $env{'course.'.$cid.'.num'};
                   4628:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4629:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4630:         $cdom = $1;
                   4631:         $cnum = $2;
                   4632:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4633:                                      $cdom,$cnum);
                   4634:     }
                   4635:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4636:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4637:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4638:         if ($rosterhash{$user} ne '') {
                   4639:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4640:             return ([],{}) if ($type eq 'auto');
                   4641:         }
                   4642:     }
                   4643:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4644:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4645:             my $then=$env{'user.login.time'};
                   4646:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4647:             if (!$update) {
                   4648:                 $update = $then;
                   4649:             }
                   4650:             my @liveroles;
                   4651:             foreach my $role ('dh','da') {
                   4652:                 if ($env{"user.role.$role./$cdom/"}) {
                   4653:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4654:                     my $limit = $update;
                   4655:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4656:                         $limit = $then;
                   4657:                     }
                   4658:                     my $activerole = 1;
                   4659:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4660:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4661:                     if ($activerole) {
                   4662:                         push(@liveroles,$role);
                   4663:                     }
                   4664:                 }
                   4665:             }
                   4666:             if (@liveroles) {
1.1172.2.89  raeburn  4667:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4668:                     my ($accessref,$accessinfo,%access_in_dom);
                   4669:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4670:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4671:                         if (@{$roles_by_num}) {
                   4672:                             my %settings;
                   4673:                             if ($env{'request.course.id'} eq $cid) {
                   4674:                                 foreach my $envkey (keys(%env)) {
                   4675:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4676:                                         $settings{$1} = $env{$envkey};
                   4677:                                     }
                   4678:                                 }
                   4679:                             } else {
                   4680:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4681:                             }
                   4682:                             my %setincrs;
                   4683:                             if ($settings{'internal.adhocaccess'}) {
                   4684:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4685:                             }
                   4686:                             my @statuses;
                   4687:                             if ($env{'environment.inststatus'}) {
                   4688:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4689:                             }
                   4690:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4691:                             if (ref($accessref) eq 'HASH') {
                   4692:                                 %access_in_dom = %{$accessref};
                   4693:                             }
                   4694:                             foreach my $role (@{$roles_by_num}) {
                   4695:                                 my ($curraccess,@okstatus,@personnel);
                   4696:                                 if ($setincrs{$role}) {
                   4697:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4698:                                     if ($curraccess eq 'status') {
                   4699:                                         @okstatus = split(/\&/,$rest);
                   4700:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4701:                                         @personnel = split(/\&/,$rest);
                   4702:                                     }
                   4703:                                 } else {
                   4704:                                     $curraccess = $access_in_dom{$role};
                   4705:                                     if (ref($accessinfo) eq 'HASH') {
                   4706:                                         if ($curraccess eq 'status') {
                   4707:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4708:                                                 @okstatus = @{$accessinfo->{$role}};
                   4709:                                             }
                   4710:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4711:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4712:                                                 @personnel = @{$accessinfo->{$role}};
                   4713:                                             }
                   4714:                                         }
                   4715:                                     }
                   4716:                                 }
                   4717:                                 if ($curraccess eq 'none') {
                   4718:                                     next;
                   4719:                                 } elsif ($curraccess eq 'all') {
                   4720:                                     push(@possroles,$role);
1.1172.2.90  raeburn  4721:                                 } elsif ($curraccess eq 'dh') {
                   4722:                                     if (grep(/^dh$/,@liveroles)) {
                   4723:                                         push(@possroles,$role);
                   4724:                                     } else {
                   4725:                                         next;
                   4726:                                     }
                   4727:                                 } elsif ($curraccess eq 'da') {
                   4728:                                     if (grep(/^da$/,@liveroles)) {
                   4729:                                         push(@possroles,$role);
                   4730:                                     } else {
                   4731:                                         next;
                   4732:                                     }
1.1172.2.89  raeburn  4733:                                 } elsif ($curraccess eq 'status') {
                   4734:                                     if (@okstatus) {
                   4735:                                         if (!@statuses) {
                   4736:                                             if (grep(/^default$/,@okstatus)) {
                   4737:                                                 push(@possroles,$role);
                   4738:                                             }
                   4739:                                         } else {
                   4740:                                             foreach my $status (@okstatus) {
                   4741:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4742:                                                     push(@possroles,$role);
                   4743:                                                     last;
                   4744:                                                 }
                   4745:                                             }
                   4746:                                         }
                   4747:                                     }
                   4748:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4749:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4750:                                         if ($curraccess eq 'exc') {
                   4751:                                             push(@possroles,$role);
                   4752:                                         }
                   4753:                                     } elsif ($curraccess eq 'inc') {
                   4754:                                         push(@possroles,$role);
                   4755:                                     }
                   4756:                                 }
                   4757:                             }
                   4758:                         }
                   4759:                     }
                   4760:                 }
                   4761:             }
                   4762:         }
                   4763:     }
                   4764:     unless (ref($description) eq 'HASH') {
                   4765:         if (ref($roles_by_num) eq 'ARRAY') {
                   4766:             my %desc;
                   4767:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4768:             $description = \%desc;
                   4769:         } else {
                   4770:             $description = {};
                   4771:         }
                   4772:     }
                   4773:     return (\@possroles,$description);
                   4774: }
                   4775: 
1.399     www      4776: # ----------------------------------------------------- Frontpage Announcements
                   4777: #
                   4778: #
                   4779: 
                   4780: sub postannounce {
                   4781:     my ($server,$text)=@_;
1.844     albertel 4782:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4783:     unless ($text=~/\w/) { $text=''; }
                   4784:     return &reply('setannounce:'.&escape($text),$server);
                   4785: }
                   4786: 
                   4787: sub getannounce {
1.448     albertel 4788: 
1.1172.2.96  raeburn  4789:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4790: 	my $announcement='';
1.800     albertel 4791: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4792: 	close($fh);
1.399     www      4793: 	if ($announcement=~/\w/) { 
                   4794: 	    return 
                   4795:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4796:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4797: 	} else {
                   4798: 	    return '';
                   4799: 	}
                   4800:     } else {
                   4801: 	return '';
                   4802:     }
1.351     www      4803: }
1.353     www      4804: 
                   4805: # ---------------------------------------------------------- Course ID routines
                   4806: # Deal with domain's nohist_courseid.db files
                   4807: #
                   4808: 
                   4809: sub courseidput {
1.921     raeburn  4810:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4811:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4812:     my $outcome;
                   4813:     if ($caller eq 'timeonly') {
                   4814:         my $cids = '';
                   4815:         foreach my $item (keys(%$storehash)) {
                   4816:             $cids.=&escape($item).'&';
                   4817:         }
                   4818:         $cids=~s/\&$//;
                   4819:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4820:                           $coursehome);       
                   4821:     } else {
                   4822:         my $items = '';
                   4823:         foreach my $item (keys(%$storehash)) {
                   4824:             $items.= &escape($item).'='.
                   4825:                      &freeze_escape($$storehash{$item}).'&';
                   4826:         }
                   4827:         $items=~s/\&$//;
                   4828:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4829:                           $coursehome);
1.918     raeburn  4830:     }
                   4831:     if ($outcome eq 'unknown_cmd') {
                   4832:         my $what;
                   4833:         foreach my $cid (keys(%$storehash)) {
                   4834:             $what .= &escape($cid).'=';
1.921     raeburn  4835:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4836:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4837:             }
                   4838:             $what =~ s/\:$/&/;
                   4839:         }
                   4840:         $what =~ s/\&$//;  
                   4841:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4842:     } else {
                   4843:         return $outcome;
                   4844:     }
1.353     www      4845: }
                   4846: 
                   4847: sub courseiddump {
1.921     raeburn  4848:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4849:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4850:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4851:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4852:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4853:     my $as_hash = 1;
                   4854:     my %returnhash;
                   4855:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4856:     my %libserv = &all_library();
                   4857:     foreach my $tryserver (keys(%libserv)) {
                   4858:         if ( (  $hostidflag == 1 
                   4859: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4860: 	     || (!defined($hostidflag)) ) {
                   4861: 
1.918     raeburn  4862: 	    if (($domfilter eq '') ||
                   4863: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4864:                 my $rep;
                   4865:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4866:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4867:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4868:                                 &escape($descfilter), &escape($instcodefilter),
                   4869:                                 &escape($ownerfilter), &escape($coursefilter),
                   4870:                                 &escape($typefilter), &escape($regexp_ok),
                   4871:                                 $as_hash, &escape($selfenrollonly),
                   4872:                                 &escape($catfilter), $showhidden, $caller,
                   4873:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4874:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4875:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4876:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4877:                 } else {
                   4878:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4879:                              $sincefilter.':'.&escape($descfilter).':'.
                   4880:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4881:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4882:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4883:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4884:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4885:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4886:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4887:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4888:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4889:                 }
                   4890: 
1.918     raeburn  4891:                 my @pairs=split(/\&/,$rep);
                   4892:                 foreach my $item (@pairs) {
                   4893:                     my ($key,$value)=split(/\=/,$item,2);
                   4894:                     $key = &unescape($key);
                   4895:                     next if ($key =~ /^error: 2 /);
                   4896:                     my $result = &thaw_unescape($value);
                   4897:                     if (ref($result) eq 'HASH') {
                   4898:                         $returnhash{$key}=$result;
                   4899:                     } else {
1.921     raeburn  4900:                         my @responses = split(/:/,$value);
                   4901:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4902:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4903:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4904:                         }
1.1008    raeburn  4905:                     }
1.353     www      4906:                 }
                   4907:             }
                   4908:         }
                   4909:     }
                   4910:     return %returnhash;
                   4911: }
                   4912: 
1.1055    raeburn  4913: sub courselastaccess {
                   4914:     my ($cdom,$cnum,$hostidref) = @_;
                   4915:     my %returnhash;
                   4916:     if ($cdom && $cnum) {
                   4917:         my $chome = &homeserver($cnum,$cdom);
                   4918:         if ($chome ne 'no_host') {
                   4919:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4920:             &extract_lastaccess(\%returnhash,$rep);
                   4921:         }
                   4922:     } else {
                   4923:         if (!$cdom) { $cdom=''; }
                   4924:         my %libserv = &all_library();
                   4925:         foreach my $tryserver (keys(%libserv)) {
                   4926:             if (ref($hostidref) eq 'ARRAY') {
                   4927:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4928:             } 
                   4929:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4930:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4931:                 &extract_lastaccess(\%returnhash,$rep);
                   4932:             }
                   4933:         }
                   4934:     }
                   4935:     return %returnhash;
                   4936: }
                   4937: 
                   4938: sub extract_lastaccess {
                   4939:     my ($returnhash,$rep) = @_;
                   4940:     if (ref($returnhash) eq 'HASH') {
                   4941:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4942:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4943:                  $rep eq '') {
                   4944:             my @pairs=split(/\&/,$rep);
                   4945:             foreach my $item (@pairs) {
                   4946:                 my ($key,$value)=split(/\=/,$item,2);
                   4947:                 $key = &unescape($key);
                   4948:                 next if ($key =~ /^error: 2 /);
                   4949:                 $returnhash->{$key} = &thaw_unescape($value);
                   4950:             }
                   4951:         }
                   4952:     }
                   4953:     return;
                   4954: }
                   4955: 
1.658     raeburn  4956: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4957: 
                   4958: sub dcmailput {
1.685     raeburn  4959:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4960:     my $status = &Apache::lonnet::critical(
1.740     www      4961:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4962:        &escape($message),$server);
1.662     raeburn  4963:     return $status;
                   4964: }
                   4965: 
1.658     raeburn  4966: sub dcmaildump {
                   4967:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4968:     my %returnhash=();
1.846     albertel 4969: 
                   4970:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4971:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4972:                                                          &escape($enddate).':';
                   4973: 	my @esc_senders=map { &escape($_)} @$senders;
                   4974: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4975: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4976:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4977:             if (($key) && ($value)) {
                   4978:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4979:             }
                   4980:         }
                   4981:     }
                   4982:     return %returnhash;
                   4983: }
1.662     raeburn  4984: # ---------------------------------------------------------- Domain roles
                   4985: 
                   4986: sub get_domain_roles {
                   4987:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4988:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4989:         $startdate = '.';
                   4990:     }
1.1018    raeburn  4991:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4992:         $enddate = '.';
                   4993:     }
1.922     raeburn  4994:     my $rolelist;
                   4995:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4996:         $rolelist = join('&',@{$roles});
1.922     raeburn  4997:     }
1.662     raeburn  4998:     my %personnel = ();
1.841     albertel 4999: 
                   5000:     my %servers = &get_servers($dom,'library');
                   5001:     foreach my $tryserver (keys(%servers)) {
                   5002: 	%{$personnel{$tryserver}}=();
                   5003: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5004: 					    &escape($startdate).':'.
                   5005: 					    &escape($enddate).':'.
                   5006: 					    &escape($rolelist), $tryserver))) {
                   5007: 	    my ($key,$value) = split(/\=/,$line,2);
                   5008: 	    if (($key) && ($value)) {
                   5009: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5010: 	    }
                   5011: 	}
1.662     raeburn  5012:     }
                   5013:     return %personnel;
                   5014: }
1.658     raeburn  5015: 
1.1172.2.89  raeburn  5016: sub get_active_domroles {
                   5017:     my ($dom,$roles) = @_;
                   5018:     return () unless (ref($roles) eq 'ARRAY');
                   5019:     my $now = time;
                   5020:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5021:     my %domroles;
                   5022:     foreach my $server (keys(%dompersonnel)) {
                   5023:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5024:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5025:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5026:         }
                   5027:     }
                   5028:     return %domroles;
                   5029: }
                   5030: 
1.1057    www      5031: # ----------------------------------------------------------- Interval timing 
1.149     www      5032: 
1.1153    www      5033: {
                   5034: # Caches needed for speedup of navmaps
                   5035: # We don't want to cache this for very long at all (5 seconds at most)
                   5036: # 
                   5037: # The user for whom we cache
                   5038: my $cachedkey='';
                   5039: # The cached times for this user
                   5040: my %cachedtimes=();
                   5041: # When this was last done
1.1172.2.66  raeburn  5042: my $cachedtime='';
1.1153    www      5043: 
                   5044: sub load_all_first_access {
1.1154    raeburn  5045:     my ($uname,$udom)=@_;
1.1156    www      5046:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5047:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5048:         return;
                   5049:     }
                   5050:     $cachedtime=time;
                   5051:     $cachedkey=$uname.':'.$udom;
                   5052:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5053: }
                   5054: 
1.504     albertel 5055: sub get_first_access {
1.1162    raeburn  5056:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5057:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5058:     if ($argsymb) { $symb=$argsymb; }
                   5059:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5060:     if ($argmap) { $map = $argmap; }
1.926     albertel 5061:     if ($type eq 'course') {
                   5062: 	$res='course';
                   5063:     } elsif ($type eq 'map') {
1.588     albertel 5064: 	$res=&symbread($map);
                   5065:     } else {
                   5066: 	$res=$symb;
                   5067:     }
1.1153    www      5068:     &load_all_first_access($uname,$udom);
                   5069:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5070: }
                   5071: 
                   5072: sub set_first_access {
1.1162    raeburn  5073:     my ($type,$interval)=@_;
1.790     albertel 5074:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5075:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5076:     if ($type eq 'course') {
                   5077: 	$res='course';
                   5078:     } elsif ($type eq 'map') {
1.588     albertel 5079: 	$res=&symbread($map);
                   5080:     } else {
                   5081: 	$res=$symb;
                   5082:     }
1.1153    www      5083:     $cachedkey='';
1.1162    raeburn  5084:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5085:     if ($firstaccess) {
                   5086:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5087:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5088:                  "in $courseid");
                   5089:         return 'already_set';
                   5090:     } else {
1.1162    raeburn  5091:         my $start = time;
                   5092: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5093:                           $udom,$uname);
                   5094:         if ($putres eq 'ok') {
                   5095:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5096:                  $udom,$uname); 
                   5097:             &appenv(
                   5098:                      {
                   5099:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5100:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5101:                      }
                   5102:                   );
1.1172.2.97  raeburn  5103:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5104:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5105:             }
1.1172.2.102  raeburn  5106:         } elsif ($putres ne 'refused') {
                   5107:             &logthis("Result: $putres when attempting to set first access time ".
                   5108:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5109:         }
                   5110:         return $putres;
1.505     albertel 5111:     }
                   5112:     return 'already_set';
1.504     albertel 5113: }
1.1153    www      5114: }
1.1172.2.32  raeburn  5115: 
                   5116: sub checkout {
                   5117:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5118:     my $now=time;
                   5119:     my $lonhost=$perlvar{'lonHostID'};
                   5120:     my $infostr=&escape(
                   5121:                  'CHECKOUTTOKEN&'.
                   5122:                  $tuname.'&'.
                   5123:                  $tudom.'&'.
                   5124:                  $tcrsid.'&'.
                   5125:                  $symb.'&'.
                   5126:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5127:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5128:     if ($token=~/^error\:/) {
                   5129:         &logthis("<font color=\"blue\">WARNING: ".
                   5130:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5131:                  "</font>");
                   5132:         return '';
                   5133:     }
                   5134: 
                   5135:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5136:     $token=~tr/a-z/A-Z/;
                   5137: 
                   5138:     my %infohash=('resource.0.outtoken' => $token,
                   5139:                   'resource.0.checkouttime' => $now,
                   5140:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5141: 
                   5142:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5143:        return '';
                   5144:     } else {
                   5145:         &logthis("<font color=\"blue\">WARNING: ".
                   5146:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5147:                  "</font>");
                   5148:     }
                   5149: 
                   5150:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5151:                          &escape('Checkout '.$infostr.' - '.
                   5152:                                                  $token)) ne 'ok') {
                   5153:         return '';
                   5154:     } else {
                   5155:         &logthis("<font color=\"blue\">WARNING: ".
                   5156:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5157:                  "</font>");
                   5158:     }
                   5159:     return $token;
                   5160: }
                   5161: 
                   5162: # ------------------------------------------------------------ Check in an item
                   5163: 
                   5164: sub checkin {
                   5165:     my $token=shift;
                   5166:     my $now=time;
                   5167:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5168:     $lonhost=~tr/A-Z/a-z/;
                   5169:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5170:     $dtoken=~s/\W/\_/g;
                   5171:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5172:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5173: 
                   5174:     unless (($tuname) && ($tudom)) {
                   5175:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5176:         return '';
                   5177:     }
                   5178: 
                   5179:     unless (&allowed('mgr',$tcrsid)) {
                   5180:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5181:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5182:         return '';
                   5183:     }
                   5184: 
                   5185:     my %infohash=('resource.0.intoken' => $token,
                   5186:                   'resource.0.checkintime' => $now,
                   5187:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5188: 
                   5189:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5190:        return '';
                   5191:     }
                   5192: 
                   5193:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5194:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5195:         return '';
                   5196:     }
                   5197: 
                   5198:     return ($symb,$tuname,$tudom,$tcrsid);
                   5199: }
                   5200: 
1.110     www      5201: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5202: 
                   5203: sub expirespread {
                   5204:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5205:     my $cid=$env{'request.course.id'}; 
1.110     www      5206:     if ($cid) {
                   5207:        my $now=time;
                   5208:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5209:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5210:                             $env{'course.'.$cid.'.num'}.
1.110     www      5211: 	        	    ':nohist_expirationdates:'.
                   5212:                             &escape($key).'='.$now,
1.620     albertel 5213:                             $env{'course.'.$cid.'.home'})
1.110     www      5214:     }
                   5215:     return 'ok';
1.14      www      5216: }
                   5217: 
1.109     www      5218: # ----------------------------------------------------- Devalidate Spreadsheets
                   5219: 
                   5220: sub devalidate {
1.325     www      5221:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5222:     my $cid=$env{'request.course.id'}; 
1.109     www      5223:     if ($cid) {
1.391     matthew  5224:         # delete the stored spreadsheets for
                   5225:         # - the student level sheet of this user in course's homespace
                   5226:         # - the assessment level sheet for this resource 
                   5227:         #   for this user in user's homespace
1.553     albertel 5228: 	# - current conditional state info
1.325     www      5229: 	my $key=$uname.':'.$udom.':';
1.109     www      5230:         my $status=
1.299     matthew  5231: 	    &del('nohist_calculatedsheets',
1.391     matthew  5232: 		 [$key.'studentcalc:'],
1.620     albertel 5233: 		 $env{'course.'.$cid.'.domain'},
                   5234: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5235: 		.' '.
                   5236: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5237: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5238:         unless ($status eq 'ok ok') {
                   5239:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5240:                     $uname.' at '.$udom.' for '.
1.109     www      5241: 		    $symb.': '.$status);
1.133     albertel 5242:         }
1.553     albertel 5243: 	&delenv('user.state.'.$cid);
1.109     www      5244:     }
                   5245: }
                   5246: 
1.265     albertel 5247: sub get_scalar {
                   5248:     my ($string,$end) = @_;
                   5249:     my $value;
                   5250:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5251: 	$value = $1;
                   5252:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5253: 	$value = $1;
                   5254:     }
                   5255:     return &unescape($value);
                   5256: }
                   5257: 
                   5258: sub array2str {
                   5259:   my (@array) = @_;
                   5260:   my $result=&arrayref2str(\@array);
                   5261:   $result=~s/^__ARRAY_REF__//;
                   5262:   $result=~s/__END_ARRAY_REF__$//;
                   5263:   return $result;
                   5264: }
                   5265: 
1.204     albertel 5266: sub arrayref2str {
                   5267:   my ($arrayref) = @_;
1.265     albertel 5268:   my $result='__ARRAY_REF__';
1.204     albertel 5269:   foreach my $elem (@$arrayref) {
1.265     albertel 5270:     if(ref($elem) eq 'ARRAY') {
                   5271:       $result.=&arrayref2str($elem).'&';
                   5272:     } elsif(ref($elem) eq 'HASH') {
                   5273:       $result.=&hashref2str($elem).'&';
                   5274:     } elsif(ref($elem)) {
                   5275:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5276:     } else {
                   5277:       $result.=&escape($elem).'&';
                   5278:     }
                   5279:   }
                   5280:   $result=~s/\&$//;
1.265     albertel 5281:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5282:   return $result;
                   5283: }
                   5284: 
1.168     albertel 5285: sub hash2str {
1.204     albertel 5286:   my (%hash) = @_;
                   5287:   my $result=&hashref2str(\%hash);
1.265     albertel 5288:   $result=~s/^__HASH_REF__//;
                   5289:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5290:   return $result;
                   5291: }
                   5292: 
                   5293: sub hashref2str {
                   5294:   my ($hashref)=@_;
1.265     albertel 5295:   my $result='__HASH_REF__';
1.800     albertel 5296:   foreach my $key (sort(keys(%$hashref))) {
                   5297:     if (ref($key) eq 'ARRAY') {
                   5298:       $result.=&arrayref2str($key).'=';
                   5299:     } elsif (ref($key) eq 'HASH') {
                   5300:       $result.=&hashref2str($key).'=';
                   5301:     } elsif (ref($key)) {
1.265     albertel 5302:       $result.='=';
1.800     albertel 5303:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5304:     } else {
1.1132    raeburn  5305: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5306:     }
                   5307: 
1.800     albertel 5308:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5309:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5310:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5311:       $result.=&hashref2str($hashref->{$key}).'&';
                   5312:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5313:        $result.='&';
1.800     albertel 5314:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5315:     } else {
1.800     albertel 5316:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5317:     }
                   5318:   }
1.168     albertel 5319:   $result=~s/\&$//;
1.265     albertel 5320:   $result .= '__END_HASH_REF__';
1.168     albertel 5321:   return $result;
                   5322: }
                   5323: 
                   5324: sub str2hash {
1.265     albertel 5325:     my ($string)=@_;
                   5326:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5327:     return %$hash;
                   5328: }
                   5329: 
                   5330: sub str2hashref {
1.168     albertel 5331:   my ($string) = @_;
1.265     albertel 5332: 
                   5333:   my %hash;
                   5334: 
                   5335:   if($string !~ /^__HASH_REF__/) {
                   5336:       if (! ($string eq '' || !defined($string))) {
                   5337: 	  $hash{'error'}='Not hash reference';
                   5338:       }
                   5339:       return (\%hash, $string);
                   5340:   }
                   5341: 
                   5342:   $string =~ s/^__HASH_REF__//;
                   5343: 
                   5344:   while($string !~ /^__END_HASH_REF__/) {
                   5345:       #key
                   5346:       my $key='';
                   5347:       if($string =~ /^__HASH_REF__/) {
                   5348:           ($key, $string)=&str2hashref($string);
                   5349:           if(defined($key->{'error'})) {
                   5350:               $hash{'error'}='Bad data';
                   5351:               return (\%hash, $string);
                   5352:           }
                   5353:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5354:           ($key, $string)=&str2arrayref($string);
                   5355:           if($key->[0] eq 'Array reference error') {
                   5356:               $hash{'error'}='Bad data';
                   5357:               return (\%hash, $string);
                   5358:           }
                   5359:       } else {
                   5360:           $string =~ s/^(.*?)=//;
1.267     albertel 5361: 	  $key=&unescape($1);
1.265     albertel 5362:       }
                   5363:       $string =~ s/^=//;
                   5364: 
                   5365:       #value
                   5366:       my $value='';
                   5367:       if($string =~ /^__HASH_REF__/) {
                   5368:           ($value, $string)=&str2hashref($string);
                   5369:           if(defined($value->{'error'})) {
                   5370:               $hash{'error'}='Bad data';
                   5371:               return (\%hash, $string);
                   5372:           }
                   5373:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5374:           ($value, $string)=&str2arrayref($string);
                   5375:           if($value->[0] eq 'Array reference error') {
                   5376:               $hash{'error'}='Bad data';
                   5377:               return (\%hash, $string);
                   5378:           }
                   5379:       } else {
                   5380: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5381:       }
                   5382:       $string =~ s/^&//;
                   5383: 
                   5384:       $hash{$key}=$value;
1.204     albertel 5385:   }
1.265     albertel 5386: 
                   5387:   $string =~ s/^__END_HASH_REF__//;
                   5388: 
                   5389:   return (\%hash, $string);
1.204     albertel 5390: }
                   5391: 
                   5392: sub str2array {
1.265     albertel 5393:     my ($string)=@_;
                   5394:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5395:     return @$array;
                   5396: }
                   5397: 
                   5398: sub str2arrayref {
1.204     albertel 5399:   my ($string) = @_;
1.265     albertel 5400:   my @array;
                   5401: 
                   5402:   if($string !~ /^__ARRAY_REF__/) {
                   5403:       if (! ($string eq '' || !defined($string))) {
                   5404: 	  $array[0]='Array reference error';
                   5405:       }
                   5406:       return (\@array, $string);
                   5407:   }
                   5408: 
                   5409:   $string =~ s/^__ARRAY_REF__//;
                   5410: 
                   5411:   while($string !~ /^__END_ARRAY_REF__/) {
                   5412:       my $value='';
                   5413:       if($string =~ /^__HASH_REF__/) {
                   5414:           ($value, $string)=&str2hashref($string);
                   5415:           if(defined($value->{'error'})) {
                   5416:               $array[0] ='Array reference error';
                   5417:               return (\@array, $string);
                   5418:           }
                   5419:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5420:           ($value, $string)=&str2arrayref($string);
                   5421:           if($value->[0] eq 'Array reference error') {
                   5422:               $array[0] ='Array reference error';
                   5423:               return (\@array, $string);
                   5424:           }
                   5425:       } else {
                   5426: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5427:       }
                   5428:       $string =~ s/^&//;
                   5429: 
                   5430:       push(@array, $value);
1.191     harris41 5431:   }
1.265     albertel 5432: 
                   5433:   $string =~ s/^__END_ARRAY_REF__//;
                   5434: 
                   5435:   return (\@array, $string);
1.168     albertel 5436: }
                   5437: 
1.167     albertel 5438: # -------------------------------------------------------------------Temp Store
                   5439: 
1.168     albertel 5440: sub tmpreset {
                   5441:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5442:   if (!$symb) {
                   5443:     $symb=&symbread();
1.620     albertel 5444:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5445:   }
                   5446:   $symb=escape($symb);
                   5447: 
1.620     albertel 5448:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5449:   $namespace=~s/\//\_/g;
                   5450:   $namespace=~s/\W//g;
                   5451: 
1.620     albertel 5452:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5453:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5454:   if ($domain eq 'public' && $stuname eq 'public') {
                   5455:       $stuname=$ENV{'REMOTE_ADDR'};
                   5456:   }
1.1117    foxr     5457:   my $path=LONCAPA::tempdir();
1.168     albertel 5458:   my %hash;
                   5459:   if (tie(%hash,'GDBM_File',
                   5460: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5461: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5462:     foreach my $key (keys(%hash)) {
1.180     albertel 5463:       if ($key=~ /:$symb/) {
1.168     albertel 5464: 	delete($hash{$key});
                   5465:       }
                   5466:     }
                   5467:   }
                   5468: }
                   5469: 
1.167     albertel 5470: sub tmpstore {
1.168     albertel 5471:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5472: 
                   5473:   if (!$symb) {
                   5474:     $symb=&symbread();
1.620     albertel 5475:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5476:   }
                   5477:   $symb=escape($symb);
                   5478: 
                   5479:   if (!$namespace) {
                   5480:     # I don't think we would ever want to store this for a course.
                   5481:     # it seems this will only be used if we don't have a course.
1.620     albertel 5482:     #$namespace=$env{'request.course.id'};
1.168     albertel 5483:     #if (!$namespace) {
1.620     albertel 5484:       $namespace=$env{'request.state'};
1.168     albertel 5485:     #}
                   5486:   }
                   5487:   $namespace=~s/\//\_/g;
                   5488:   $namespace=~s/\W//g;
1.620     albertel 5489:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5490:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5491:   if ($domain eq 'public' && $stuname eq 'public') {
                   5492:       $stuname=$ENV{'REMOTE_ADDR'};
                   5493:   }
1.168     albertel 5494:   my $now=time;
                   5495:   my %hash;
1.1117    foxr     5496:   my $path=LONCAPA::tempdir();
1.168     albertel 5497:   if (tie(%hash,'GDBM_File',
                   5498: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5499: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5500:     $hash{"version:$symb"}++;
                   5501:     my $version=$hash{"version:$symb"};
                   5502:     my $allkeys=''; 
                   5503:     foreach my $key (keys(%$storehash)) {
                   5504:       $allkeys.=$key.':';
1.591     albertel 5505:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5506:     }
                   5507:     $hash{"$version:$symb:timestamp"}=$now;
                   5508:     $allkeys.='timestamp';
                   5509:     $hash{"$version:keys:$symb"}=$allkeys;
                   5510:     if (untie(%hash)) {
                   5511:       return 'ok';
                   5512:     } else {
                   5513:       return "error:$!";
                   5514:     }
                   5515:   } else {
                   5516:     return "error:$!";
                   5517:   }
                   5518: }
1.167     albertel 5519: 
1.168     albertel 5520: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5521: 
1.168     albertel 5522: sub tmprestore {
                   5523:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5524: 
1.168     albertel 5525:   if (!$symb) {
                   5526:     $symb=&symbread();
1.620     albertel 5527:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5528:   }
                   5529:   $symb=escape($symb);
                   5530: 
1.620     albertel 5531:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5532: 
1.620     albertel 5533:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5534:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5535:   if ($domain eq 'public' && $stuname eq 'public') {
                   5536:       $stuname=$ENV{'REMOTE_ADDR'};
                   5537:   }
1.168     albertel 5538:   my %returnhash;
                   5539:   $namespace=~s/\//\_/g;
                   5540:   $namespace=~s/\W//g;
                   5541:   my %hash;
1.1117    foxr     5542:   my $path=LONCAPA::tempdir();
1.168     albertel 5543:   if (tie(%hash,'GDBM_File',
                   5544: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5545: 	  &GDBM_READER(),0640)) {
1.168     albertel 5546:     my $version=$hash{"version:$symb"};
                   5547:     $returnhash{'version'}=$version;
                   5548:     my $scope;
                   5549:     for ($scope=1;$scope<=$version;$scope++) {
                   5550:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5551:       my @keys=split(/:/,$vkeys);
                   5552:       my $key;
                   5553:       $returnhash{"$scope:keys"}=$vkeys;
                   5554:       foreach $key (@keys) {
1.591     albertel 5555: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5556: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5557:       }
                   5558:     }
1.168     albertel 5559:     if (!(untie(%hash))) {
                   5560:       return "error:$!";
                   5561:     }
                   5562:   } else {
                   5563:     return "error:$!";
                   5564:   }
                   5565:   return %returnhash;
1.167     albertel 5566: }
                   5567: 
1.9       www      5568: # ----------------------------------------------------------------------- Store
                   5569: 
                   5570: sub store {
1.1172.2.64  raeburn  5571:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5572:     my $home='';
                   5573: 
1.168     albertel 5574:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5575: 
1.213     www      5576:     $symb=&symbclean($symb);
1.122     albertel 5577:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5578: 
1.620     albertel 5579:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5580:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5581: 
                   5582:     &devalidate($symb,$stuname,$domain);
1.109     www      5583: 
                   5584:     $symb=escape($symb);
1.187     www      5585:     if (!$namespace) { 
1.620     albertel 5586:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5587:           return ''; 
                   5588:        } 
                   5589:     }
1.620     albertel 5590:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5591: 
                   5592:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5593:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5594: 
1.12      www      5595:     my $namevalue='';
1.800     albertel 5596:     foreach my $key (keys(%$storehash)) {
                   5597:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5598:     }
1.12      www      5599:     $namevalue=~s/\&$//;
1.187     www      5600:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5601:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5602: }
                   5603: 
1.47      www      5604: # -------------------------------------------------------------- Critical Store
                   5605: 
                   5606: sub cstore {
1.1172.2.64  raeburn  5607:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5608:     my $home='';
                   5609: 
1.168     albertel 5610:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5611: 
1.213     www      5612:     $symb=&symbclean($symb);
1.122     albertel 5613:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5614: 
1.620     albertel 5615:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5616:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5617: 
                   5618:     &devalidate($symb,$stuname,$domain);
1.109     www      5619: 
                   5620:     $symb=escape($symb);
1.187     www      5621:     if (!$namespace) { 
1.620     albertel 5622:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5623:           return ''; 
                   5624:        } 
                   5625:     }
1.620     albertel 5626:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5627: 
                   5628:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5629:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5630: 
1.47      www      5631:     my $namevalue='';
1.800     albertel 5632:     foreach my $key (keys(%$storehash)) {
                   5633:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5634:     }
1.47      www      5635:     $namevalue=~s/\&$//;
1.187     www      5636:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5637:     return critical
1.1172.2.64  raeburn  5638:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5639: }
                   5640: 
1.9       www      5641: # --------------------------------------------------------------------- Restore
                   5642: 
                   5643: sub restore {
1.124     www      5644:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5645:     my $home='';
                   5646: 
1.168     albertel 5647:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5648: 
1.122     albertel 5649:     if (!$symb) {
1.1172.2.26  raeburn  5650:         return if ($namespace eq 'courserequests');
                   5651:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5652:     } else {
1.1172.2.26  raeburn  5653:         unless ($namespace eq 'courserequests') {
                   5654:             $symb=&escape(&symbclean($symb));
                   5655:         }
1.122     albertel 5656:     }
1.188     www      5657:     if (!$namespace) { 
1.620     albertel 5658:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5659:           return ''; 
                   5660:        } 
                   5661:     }
1.620     albertel 5662:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5663:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5664:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5665:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5666: 
1.12      www      5667:     my %returnhash=();
1.800     albertel 5668:     foreach my $line (split(/\&/,$answer)) {
                   5669: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5670:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5671:     }
1.75      www      5672:     my $version;
                   5673:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5674:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5675:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5676:        }
1.75      www      5677:     }
1.13      www      5678:     return %returnhash;
1.34      www      5679: }
                   5680: 
                   5681: # ---------------------------------------------------------- Course Description
1.1118    foxr     5682: #
                   5683: #  
1.34      www      5684: 
                   5685: sub coursedescription {
1.731     albertel 5686:     my ($courseid,$args)=@_;
1.34      www      5687:     $courseid=~s/^\///;
1.49      www      5688:     $courseid=~s/\_/\//g;
1.34      www      5689:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5690:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5691:     my $normalid=$cdomain.'_'.$cnum;
                   5692:     # need to always cache even if we get errors otherwise we keep 
                   5693:     # trying and trying and trying to get the course description.
                   5694:     my %envhash=();
                   5695:     my %returnhash=();
1.731     albertel 5696:     
                   5697:     my $expiretime=600;
                   5698:     if ($env{'request.course.id'} eq $normalid) {
                   5699: 	$expiretime=120;
                   5700:     }
                   5701: 
                   5702:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5703:     if (!$args->{'freshen_cache'}
                   5704: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5705: 	foreach my $key (keys(%env)) {
                   5706: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5707: 	    my ($setting) = $1;
                   5708: 	    $returnhash{$setting} = $env{$key};
                   5709: 	}
                   5710: 	return %returnhash;
                   5711:     }
                   5712: 
1.1118    foxr     5713:     # get the data again
                   5714: 
1.731     albertel 5715:     if (!$args->{'one_time'}) {
                   5716: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5717:     }
1.811     albertel 5718: 
1.34      www      5719:     if ($chome ne 'no_host') {
1.302     albertel 5720:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5721:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5722: 	   my $username = $env{'user.name'}; # Defult username
                   5723: 	   if(defined $args->{'user'}) {
                   5724: 	       $username = $args->{'user'};
                   5725: 	   }
1.129     albertel 5726:            $returnhash{'home'}= $chome;
                   5727: 	   $returnhash{'domain'} = $cdomain;
                   5728: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5729:            if (!defined($returnhash{'type'})) {
                   5730:                $returnhash{'type'} = 'Course';
                   5731:            }
1.130     albertel 5732:            while (my ($name,$value) = each %returnhash) {
1.53      www      5733:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5734:            }
1.270     www      5735:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5736:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5737: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5738:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5739:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5740:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5741:        }
                   5742:     }
1.731     albertel 5743:     if (!$args->{'one_time'}) {
1.949     raeburn  5744: 	&appenv(\%envhash);
1.731     albertel 5745:     }
1.302     albertel 5746:     return %returnhash;
1.461     www      5747: }
                   5748: 
1.1080    raeburn  5749: sub update_released_required {
                   5750:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5751:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5752:         $cid = $env{'request.course.id'};
                   5753:         $cdom = $env{'course.'.$cid.'.domain'};
                   5754:         $cnum = $env{'course.'.$cid.'.num'};
                   5755:         $chome = $env{'course.'.$cid.'.home'};
                   5756:     }
                   5757:     if ($needsrelease) {
                   5758:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5759:         my $needsupdate;
                   5760:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5761:             $needsupdate = 1;
                   5762:         } else {
                   5763:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5764:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5765:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5766:                 $needsupdate = 1;
                   5767:             }
                   5768:         }
                   5769:         if ($needsupdate) {
                   5770:             my %needshash = (
                   5771:                              'internal.releaserequired' => $needsrelease,
                   5772:                             );
                   5773:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5774:             if ($putresult eq 'ok') {
                   5775:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5776:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5777:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5778:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5779:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5780:                 }
                   5781:             }
                   5782:         }
                   5783:     }
                   5784:     return;
                   5785: }
                   5786: 
1.461     www      5787: # -------------------------------------------------See if a user is privileged
                   5788: 
                   5789: sub privileged {
1.1172.2.23  raeburn  5790:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5791:     my $now = time;
1.1172.2.23  raeburn  5792:     my $roles;
                   5793:     if (ref($possroles) eq 'ARRAY') {
                   5794:         $roles = $possroles;
                   5795:     } else {
                   5796:         $roles = ['dc','su'];
                   5797:     }
                   5798:     if (ref($possdomains) eq 'ARRAY') {
                   5799:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5800:         foreach my $dom (@{$possdomains}) {
                   5801:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5802:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5803:                 foreach my $role (@{$roles}) {
                   5804:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5805:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5806:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5807:                             return 1 unless (($end && $end < $now) ||
                   5808:                                              ($start && $start > $now));
                   5809:                         }
                   5810:                     }
                   5811:                 }
                   5812:             }
                   5813:         }
                   5814:     } else {
                   5815:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5816:         my $now = time;
1.1170    droeschl 5817: 
1.1172.2.58  raeburn  5818:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5819:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5820:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5821:                 return 1 unless ($tend && $tend < $now)
                   5822:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5823:             }
1.1172.2.23  raeburn  5824:         }
                   5825:     }
1.461     www      5826:     return 0;
1.9       www      5827: }
1.1       albertel 5828: 
1.1172.2.23  raeburn  5829: sub privileged_by_domain {
                   5830:     my ($domains,$roles) = @_;
                   5831:     my %privileged = ();
                   5832:     my $cachetime = 60*60*24;
                   5833:     my $now = time;
                   5834:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5835:         return %privileged;
                   5836:     }
                   5837:     foreach my $dom (@{$domains}) {
                   5838:         next if (ref($privileged{$dom}) eq 'HASH');
                   5839:         my $needroles;
                   5840:         foreach my $role (@{$roles}) {
                   5841:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5842:             if (defined($cached)) {
                   5843:                 if (ref($result) eq 'HASH') {
                   5844:                     $privileged{$dom}{$role} = $result;
                   5845:                 }
                   5846:             } else {
                   5847:                 $needroles = 1;
                   5848:             }
                   5849:         }
                   5850:         if ($needroles) {
                   5851:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5852:             $privileged{$dom} = {};
                   5853:             foreach my $server (keys(%dompersonnel)) {
                   5854:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5855:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5856:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5857:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5858:                         next if ($end && $end < $now);
                   5859:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5860:                             $dompersonnel{$server}{$item};
                   5861:                     }
                   5862:                 }
                   5863:             }
                   5864:             if (ref($privileged{$dom}) eq 'HASH') {
                   5865:                 foreach my $role (@{$roles}) {
                   5866:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5867:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5868:                     } else {
                   5869:                         my %hash = ();
                   5870:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5871:                     }
                   5872:                 }
                   5873:             }
                   5874:         }
                   5875:     }
                   5876:     return %privileged;
                   5877: }
                   5878: 
1.103     harris41 5879: # -------------------------------------------------------- Get user privileges
1.11      www      5880: 
                   5881: sub rolesinit {
1.1169    droeschl 5882:     my ($domain, $username) = @_;
                   5883:     my %userroles = ('user.login.time' => time);
                   5884:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5885: 
                   5886:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5887:     # also, blocking can be triggered by an activating timer
                   5888:     # it's saved in the user's %env.
                   5889:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5890:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5891:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5892:         %timerintchk, %timerintenv);
                   5893: 
1.1162    raeburn  5894:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5895:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5896:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5897:     }
1.1169    droeschl 5898: 
1.1162    raeburn  5899:     foreach my $key (keys(%timerinterval)) {
                   5900:         my ($cid,$rest) = split(/\0/,$key);
                   5901:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5902:     }
1.1169    droeschl 5903: 
1.11      www      5904:     my %allroles=();
1.1162    raeburn  5905:     my %allgroups=();
1.11      www      5906: 
1.1172.2.58  raeburn  5907:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5908:         my $role = $rolesdump{$area};
                   5909:         $area =~ s/\_\w\w$//;
                   5910: 
                   5911:         my ($trole, $tend, $tstart, $group_privs);
                   5912: 
                   5913:         if ($role =~ /^cr/) {
                   5914:         # Custom role, defined by a user 
                   5915:         # e.g., user.role.cr/msu/smith/mynewrole
                   5916:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5917:                 $trole = $1;
                   5918:                 ($tend, $tstart) = split('_', $2);
                   5919:             } else {
                   5920:                 $trole = $role;
                   5921:             }
                   5922:         } elsif ($role =~ m|^gr/|) {
                   5923:         # Role of member in a group, defined within a course/community
                   5924:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5925:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5926:             next if $tstart eq '-1';
                   5927:             ($trole, $group_privs) = split(/\//, $trole);
                   5928:             $group_privs = &unescape($group_privs);
                   5929:         } else {
                   5930:         # Just a normal role, defined in roles.tab
                   5931:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5932:         }
                   5933: 
                   5934:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5935:                  $username);
                   5936:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5937: 
                   5938:         # role expired or not available yet?
                   5939:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5940:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5941: 
                   5942:         next if $area eq '' or $trole eq '';
                   5943: 
                   5944:         my $spec = "$trole.$area";
                   5945:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5946: 
                   5947:         if ($trole =~ /^cr\//) {
                   5948:         # Custom role, defined by a user
                   5949:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5950:         } elsif ($trole eq 'gr') {
                   5951:         # Role of a member in a group, defined within a course/community
                   5952:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5953:             next;
                   5954:         } else {
                   5955:         # Normal role, defined in roles.tab
                   5956:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5957:         }
                   5958: 
                   5959:         my $cid = $tdomain.'_'.$trest;
                   5960:         unless ($firstaccchk{$cid}) {
                   5961:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5962:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5963:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5964:                         $coursetimerstarts{$cid}{$item}; 
                   5965:                 }
                   5966:             }
                   5967:             $firstaccchk{$cid} = 1;
                   5968:         }
                   5969:         unless ($timerintchk{$cid}) {
                   5970:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5971:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5972:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5973:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5974:                 }
1.12      www      5975:             }
1.1169    droeschl 5976:             $timerintchk{$cid} = 1;
1.191     harris41 5977:         }
1.11      www      5978:     }
1.1169    droeschl 5979: 
1.1172.2.91  raeburn  5980:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   5981:                                                           \%allroles, \%allgroups);
1.1169    droeschl 5982:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  5983:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 5984: 
1.1162    raeburn  5985:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5986: }
                   5987: 
1.567     raeburn  5988: sub set_arearole {
1.1172.2.19  raeburn  5989:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5990:     unless ($nolog) {
1.567     raeburn  5991: # log the associated role with the area
1.1172.2.19  raeburn  5992:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5993:     }
1.743     albertel 5994:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5995: }
                   5996: 
                   5997: sub custom_roleprivs {
                   5998:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5999:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6000:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6001:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6002:         my ($rdummy,$roledef)=
                   6003:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6004:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6005:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6006:             if (defined($syspriv)) {
1.1043    raeburn  6007:                 if ($trest =~ /^$match_community$/) {
                   6008:                     $syspriv =~ s/bre\&S//; 
                   6009:                 }
1.567     raeburn  6010:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6011:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6012:             }
                   6013:             if ($tdomain ne '') {
                   6014:                 if (defined($dompriv)) {
                   6015:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6016:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6017:                 }
                   6018:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6019:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6020:                         my $rolename = $1;
                   6021:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6022:                     }
1.567     raeburn  6023:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6024:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6025:                 }
                   6026:             }
                   6027:         }
                   6028:     }
                   6029: }
                   6030: 
1.1172.2.89  raeburn  6031: sub course_adhocrole_privs {
                   6032:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6033:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6034:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6035:         my (%currprivs,%storeprivs);
                   6036:         foreach my $item (split(/:/,$coursepriv)) {
                   6037:             my ($priv,$restrict) = split(/\&/,$item);
                   6038:             $currprivs{$priv} = $restrict;
                   6039:         }
                   6040:         my (%possadd,%possremove,%full);
                   6041:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6042:             my ($priv,$restrict)=split(/\&/,$item);
                   6043:             $full{$priv} = $restrict;
                   6044:         }
                   6045:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6046:              next if ($item eq '');
                   6047:              my ($rule,$rest) = split(/=/,$item);
                   6048:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6049:              foreach my $priv (split(/:/,$rest)) {
                   6050:                  if ($priv ne '') {
                   6051:                      if ($rule eq 'off') {
                   6052:                          $possremove{$priv} = 1;
                   6053:                      } else {
                   6054:                          $possadd{$priv} = 1;
                   6055:                      }
                   6056:                  }
                   6057:              }
                   6058:          }
                   6059:          foreach my $priv (sort(keys(%full))) {
                   6060:              if (exists($currprivs{$priv})) {
                   6061:                  unless (exists($possremove{$priv})) {
                   6062:                      $storeprivs{$priv} = $currprivs{$priv};
                   6063:                  }
                   6064:              } elsif (exists($possadd{$priv})) {
                   6065:                  $storeprivs{$priv} = $full{$priv};
                   6066:              }
                   6067:          }
                   6068:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6069:      }
                   6070:      return $coursepriv;
                   6071: }
                   6072: 
1.678     raeburn  6073: sub group_roleprivs {
                   6074:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6075:     my $access = 1;
                   6076:     my $now = time;
                   6077:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6078:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6079:     if ($access) {
1.811     albertel 6080:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6081:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6082:     }
                   6083: }
1.567     raeburn  6084: 
                   6085: sub standard_roleprivs {
                   6086:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6087:     if (defined($pr{$trole.':s'})) {
                   6088:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6089:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6090:     }
                   6091:     if ($tdomain ne '') {
                   6092:         if (defined($pr{$trole.':d'})) {
                   6093:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6094:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6095:         }
                   6096:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6097:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6098:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6099:         }
                   6100:     }
                   6101: }
                   6102: 
                   6103: sub set_userprivs {
1.1064    raeburn  6104:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6105:     my $author=0;
                   6106:     my $adv=0;
1.1172.2.91  raeburn  6107:     my $rar=0;
1.678     raeburn  6108:     my %grouproles = ();
                   6109:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6110:         my @groupkeys; 
1.1000    raeburn  6111:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6112:             push(@groupkeys,$role);
                   6113:         }
                   6114:         if (ref($groups_roles) eq 'HASH') {
                   6115:             foreach my $key (keys(%{$groups_roles})) {
                   6116:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6117:                     push(@groupkeys,$key);
                   6118:                 }
                   6119:             }
                   6120:         }
                   6121:         if (@groupkeys > 0) {
                   6122:             foreach my $role (@groupkeys) {
                   6123:                 my ($trole,$area,$sec,$extendedarea);
                   6124:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6125:                     $trole = $1;
                   6126:                     $area = $2;
                   6127:                     $sec = $3;
                   6128:                     $extendedarea = $area.$sec;
                   6129:                     if (exists($$allgroups{$area})) {
                   6130:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6131:                             my $spec = $trole.'.'.$extendedarea;
                   6132:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6133:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6134:                         }
1.678     raeburn  6135:                     }
                   6136:                 }
                   6137:             }
                   6138:         }
                   6139:     }
1.800     albertel 6140:     foreach my $group (keys(%grouproles)) {
                   6141:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6142:     }
1.800     albertel 6143:     foreach my $role (keys(%{$allroles})) {
                   6144:         my %thesepriv;
1.941     raeburn  6145:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6146:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6147:             if ($item ne '') {
                   6148:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6149:                 if ($restrictions eq '') {
                   6150:                     $thesepriv{$privilege}='F';
                   6151:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6152:                     $thesepriv{$privilege}.=$restrictions;
                   6153:                 }
                   6154:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6155:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6156:             }
                   6157:         }
                   6158:         my $thesestr='';
1.1104    raeburn  6159:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6160: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6161: 	}
                   6162:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6163:     }
1.1172.2.91  raeburn  6164:     return ($author,$adv,$rar);
1.567     raeburn  6165: }
                   6166: 
1.994     raeburn  6167: sub role_status {
1.1104    raeburn  6168:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6169:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6170:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6171:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6172:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6173:             $$where = '/'.$two;
1.994     raeburn  6174:             $$trolecode=$$role.'.'.$$where;
                   6175:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6176:             $$tstatus='is';
1.1104    raeburn  6177:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6178:                 $$tstatus='future';
1.1034    raeburn  6179:                 if ($$tstart<$now) {
                   6180:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6181:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6182:                             my (%allroles,%allgroups,$group_privs,
                   6183:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6184:                             my %userroles = (
                   6185:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6186:                             );
1.1064    raeburn  6187:                             @rolecodes = ('cm'); 
1.1002    raeburn  6188:                             my $spec=$$role.'.'.$$where;
                   6189:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6190:                             if ($$role =~ /^cr\//) {
                   6191:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6192:                                 push(@rolecodes,'cr');
1.1002    raeburn  6193:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6194:                                 push(@rolecodes,$$role);
1.1002    raeburn  6195:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6196:                                                     $env{'user.name'});
1.1064    raeburn  6197:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6198:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6199:                                 $group_privs = &unescape($group_privs);
                   6200:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6201:                                 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  6202:                                 &get_groups_roles($tdomain,$trest,
                   6203:                                                   \%course_roles,\@rolecodes,
                   6204:                                                   \%groups_roles);
1.1002    raeburn  6205:                             } else {
1.1064    raeburn  6206:                                 push(@rolecodes,$$role);
1.1002    raeburn  6207:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6208:                             }
1.1172.2.91  raeburn  6209:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6210:                                                                    \%groups_roles);
1.1064    raeburn  6211:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6212:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6213:                         }
                   6214:                     }
1.1034    raeburn  6215:                     $$tstatus = 'is';
1.1002    raeburn  6216:                 }
1.994     raeburn  6217:             }
                   6218:             if ($$tend) {
1.1104    raeburn  6219:                 if ($$tend<$update) {
1.994     raeburn  6220:                     $$tstatus='expired';
                   6221:                 } elsif ($$tend<$now) {
                   6222:                     $$tstatus='will_not';
                   6223:                 }
                   6224:             }
                   6225:         }
                   6226:     }
                   6227: }
                   6228: 
1.1104    raeburn  6229: sub get_groups_roles {
                   6230:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6231:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6232:                   (ref($rolecodes) eq 'ARRAY') && 
                   6233:                   (ref($groups_roles) eq 'HASH')); 
                   6234:     if (keys(%{$cdom_courseroles}) > 0) {
                   6235:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6236:         if ($cdom ne '' && $cnum ne '') {
                   6237:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6238:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6239:                     my $crsrole = $1;
                   6240:                     my $crssec = $2;
                   6241:                     if ($crsrole =~ /^cr/) {
                   6242:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6243:                             push(@{$rolecodes},'cr');
                   6244:                         }
                   6245:                     } else {
                   6246:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6247:                             push(@{$rolecodes},$crsrole);
                   6248:                         }
                   6249:                     }
                   6250:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6251:                     if ($crssec ne '') {
                   6252:                         $rolekey .= "/$crssec";
                   6253:                     }
                   6254:                     $rolekey .= './';
                   6255:                     $groups_roles->{$rolekey} = $rolecodes;
                   6256:                 }
                   6257:             }
                   6258:         }
                   6259:     }
                   6260:     return;
                   6261: }
                   6262: 
                   6263: sub delete_env_groupprivs {
                   6264:     my ($where,$courseroles,$possroles) = @_;
                   6265:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6266:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6267:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6268:         %{$courseroles->{$udom}} =
                   6269:             &get_my_roles('','','userroles',['active'],
                   6270:                           $possroles,[$udom],1);
                   6271:     }
                   6272:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6273:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6274:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6275:             my $area = '/'.$cdom.'/'.$cnum;
                   6276:             my $privkey = "user.priv.$crsrole.$area";
                   6277:             if ($crssec ne '') {
                   6278:                 $privkey .= '/'.$crssec;
                   6279:             }
                   6280:             $privkey .= ".$area/$group";
                   6281:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6282:         }
                   6283:     }
                   6284:     return;
                   6285: }
                   6286: 
1.994     raeburn  6287: sub check_adhoc_privs {
1.1172.2.86  raeburn  6288:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6289:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6290:     if ($sec) {
                   6291:         $cckey .= '/'.$sec;
                   6292:     }
1.1172.2.9  raeburn  6293:     my $setprivs;
1.994     raeburn  6294:     if ($env{$cckey}) {
                   6295:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6296:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6297:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6298:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6299:             $setprivs = 1;
1.994     raeburn  6300:         }
                   6301:     } else {
1.1172.2.87  raeburn  6302:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6303:         $setprivs = 1;
1.994     raeburn  6304:     }
1.1172.2.9  raeburn  6305:     return $setprivs;
1.994     raeburn  6306: }
                   6307: 
                   6308: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6309: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6310:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6311:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6312:     if ($sec ne '') {
                   6313:         $area .= '/'.$sec;
                   6314:     }
1.994     raeburn  6315:     my $spec = $role.'.'.$area;
                   6316:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6317:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6318:     my %rolehash = ();
1.1172.2.89  raeburn  6319:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6320:         my $rolename = $1;
1.1172.2.84  raeburn  6321:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6322:         my %domdef = &get_domain_defaults($dcdom);
                   6323:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6324:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6325:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6326:             }
                   6327:         }
1.1172.2.84  raeburn  6328:     } else {
                   6329:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6330:     }
1.1172.2.91  raeburn  6331:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6332:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6333:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6334:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6335:         &appenv( {'request.role'        => $spec,
                   6336:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6337:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6338:                  }
                   6339:                );
                   6340:         my $tadv=0;
                   6341:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6342:         &appenv({'request.role.adv'    => $tadv});
                   6343:     }
1.994     raeburn  6344: }
                   6345: 
1.12      www      6346: # --------------------------------------------------------------- get interface
                   6347: 
                   6348: sub get {
1.131     albertel 6349:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6350:    my $items='';
1.800     albertel 6351:    foreach my $item (@$storearr) {
                   6352:        $items.=&escape($item).'&';
1.191     harris41 6353:    }
1.12      www      6354:    $items=~s/\&$//;
1.620     albertel 6355:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6356:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6357:    my $uhome=&homeserver($uname,$udomain);
                   6358: 
1.133     albertel 6359:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6360:    my @pairs=split(/\&/,$rep);
1.273     albertel 6361:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6362:      return @pairs;
                   6363:    }
1.15      www      6364:    my %returnhash=();
1.42      www      6365:    my $i=0;
1.800     albertel 6366:    foreach my $item (@$storearr) {
                   6367:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6368:       $i++;
1.191     harris41 6369:    }
1.15      www      6370:    return %returnhash;
1.27      www      6371: }
                   6372: 
                   6373: # --------------------------------------------------------------- del interface
                   6374: 
                   6375: sub del {
1.133     albertel 6376:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6377:    my $items='';
1.800     albertel 6378:    foreach my $item (@$storearr) {
                   6379:        $items.=&escape($item).'&';
1.191     harris41 6380:    }
1.984     neumanie 6381: 
1.27      www      6382:    $items=~s/\&$//;
1.620     albertel 6383:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6384:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6385:    my $uhome=&homeserver($uname,$udomain);
                   6386:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6387: }
                   6388: 
                   6389: # -------------------------------------------------------------- dump interface
                   6390: 
1.1172.2.22  raeburn  6391: sub unserialize {
                   6392:     my ($rep, $escapedkeys) = @_;
                   6393: 
                   6394:     return {} if $rep =~ /^error/;
                   6395: 
                   6396:     my %returnhash=();
                   6397:     foreach my $item (split(/\&/,$rep)) {
                   6398:         my ($key, $value) = split(/=/, $item, 2);
                   6399:         $key = unescape($key) unless $escapedkeys;
                   6400:         next if $key =~ /^error: 2 /;
                   6401:         $returnhash{$key} = &thaw_unescape($value);
                   6402:     }
                   6403:     return \%returnhash;
                   6404: }
                   6405: 
                   6406: # see Lond::dump_with_regexp
                   6407: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6408: sub dump {
1.1172.2.22  raeburn  6409:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6410:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6411:     if (!$uname) { $uname=$env{'user.name'}; }
                   6412:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6413: 
1.1172.2.55  raeburn  6414:     if ($regexp) {
                   6415:         $regexp=&escape($regexp);
                   6416:     } else {
                   6417:         $regexp='.';
                   6418:     }
1.1172.2.22  raeburn  6419:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6420:         # user is hosted on this machine
1.1172.2.55  raeburn  6421:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6422:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6423:         return %{&unserialize($reply, $escapedkeys)};
                   6424:     }
1.1166    raeburn  6425:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6426:     my @pairs=split(/\&/,$rep);
                   6427:     my %returnhash=();
1.1098    foxr     6428:     if (!($rep =~ /^error/ )) {
                   6429: 	foreach my $item (@pairs) {
                   6430: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6431:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6432: 	    next if ($key =~ /^error: 2 /);
                   6433: 	    $returnhash{$key}=&thaw_unescape($value);
                   6434: 	}
1.755     albertel 6435:     }
                   6436:     return %returnhash;
1.407     www      6437: }
                   6438: 
1.1098    foxr     6439: 
1.717     albertel 6440: # --------------------------------------------------------- dumpstore interface
                   6441: 
                   6442: sub dumpstore {
                   6443:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6444:    # same as dump but keys must be escaped. They may contain colon separated
                   6445:    # lists of values that may themself contain colons (e.g. symbs).
                   6446:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6447: }
                   6448: 
1.407     www      6449: # -------------------------------------------------------------- keys interface
                   6450: 
                   6451: sub getkeys {
                   6452:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6453:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6454:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6455:    my $uhome=&homeserver($uname,$udomain);
                   6456:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6457:    my @keyarray=();
1.800     albertel 6458:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6459:       next if ($key =~ /^error: 2 /);
1.800     albertel 6460:       push(@keyarray,&unescape($key));
1.407     www      6461:    }
                   6462:    return @keyarray;
1.318     matthew  6463: }
                   6464: 
1.319     matthew  6465: # --------------------------------------------------------------- currentdump
                   6466: sub currentdump {
1.328     matthew  6467:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6468:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6469:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6470:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6471:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6472:    my $rep;
                   6473: 
                   6474:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6475:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6476:                    $courseid)));
                   6477:    } else {
                   6478:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6479:    }
                   6480: 
1.318     matthew  6481:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6482:    #
1.318     matthew  6483:    my %returnhash=();
1.319     matthew  6484:    #
                   6485:    if ($rep eq "unknown_cmd") { 
                   6486:        # an old lond will not know currentdump
                   6487:        # Do a dump and make it look like a currentdump
1.822     albertel 6488:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6489:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6490:        my %hash = @tmp;
                   6491:        @tmp=();
1.424     matthew  6492:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6493:    } else {
                   6494:        my @pairs=split(/\&/,$rep);
1.800     albertel 6495:        foreach my $pair (@pairs) {
                   6496:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6497:            my ($symb,$param) = split(/:/,$key);
                   6498:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6499:                                                         &thaw_unescape($value);
1.319     matthew  6500:        }
1.191     harris41 6501:    }
1.12      www      6502:    return %returnhash;
1.424     matthew  6503: }
                   6504: 
                   6505: sub convert_dump_to_currentdump{
                   6506:     my %hash = %{shift()};
                   6507:     my %returnhash;
                   6508:     # Code ripped from lond, essentially.  The only difference
                   6509:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6510:     # we might run in to problems with parameter names =~ /^v\./
                   6511:     while (my ($key,$value) = each(%hash)) {
                   6512:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6513: 	$symb  = &unescape($symb);
                   6514: 	$param = &unescape($param);
1.424     matthew  6515:         next if ($v eq 'version' || $symb eq 'keys');
                   6516:         next if (exists($returnhash{$symb}) &&
                   6517:                  exists($returnhash{$symb}->{$param}) &&
                   6518:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6519:         $returnhash{$symb}->{$param}=$value;
                   6520:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6521:     }
                   6522:     #
                   6523:     # Remove all of the keys in the hashes which keep track of
                   6524:     # the version of the parameter.
                   6525:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6526:         # use a foreach because we are going to delete from the hash.
                   6527:         foreach my $key (keys(%$param_hash)) {
                   6528:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6529:         }
                   6530:     }
                   6531:     return \%returnhash;
1.12      www      6532: }
                   6533: 
1.627     albertel 6534: # ------------------------------------------------------ critical inc interface
                   6535: 
                   6536: sub cinc {
                   6537:     return &inc(@_,'critical');
                   6538: }
                   6539: 
1.449     matthew  6540: # --------------------------------------------------------------- inc interface
                   6541: 
                   6542: sub inc {
1.627     albertel 6543:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6544:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6545:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6546:     my $uhome=&homeserver($uname,$udomain);
                   6547:     my $items='';
                   6548:     if (! ref($store)) {
                   6549:         # got a single value, so use that instead
                   6550:         $items = &escape($store).'=&';
                   6551:     } elsif (ref($store) eq 'SCALAR') {
                   6552:         $items = &escape($$store).'=&';        
                   6553:     } elsif (ref($store) eq 'ARRAY') {
                   6554:         $items = join('=&',map {&escape($_);} @{$store});
                   6555:     } elsif (ref($store) eq 'HASH') {
                   6556:         while (my($key,$value) = each(%{$store})) {
                   6557:             $items.= &escape($key).'='.&escape($value).'&';
                   6558:         }
                   6559:     }
                   6560:     $items=~s/\&$//;
1.627     albertel 6561:     if ($critical) {
                   6562: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6563:     } else {
                   6564: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6565:     }
1.449     matthew  6566: }
                   6567: 
1.12      www      6568: # --------------------------------------------------------------- put interface
                   6569: 
                   6570: sub put {
1.134     albertel 6571:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6572:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6573:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6574:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6575:    my $items='';
1.800     albertel 6576:    foreach my $item (keys(%$storehash)) {
                   6577:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6578:    }
1.12      www      6579:    $items=~s/\&$//;
1.134     albertel 6580:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6581: }
                   6582: 
1.631     albertel 6583: # ------------------------------------------------------------ newput interface
                   6584: 
                   6585: sub newput {
                   6586:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6587:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6588:    if (!$uname) { $uname=$env{'user.name'}; }
                   6589:    my $uhome=&homeserver($uname,$udomain);
                   6590:    my $items='';
                   6591:    foreach my $key (keys(%$storehash)) {
                   6592:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6593:    }
                   6594:    $items=~s/\&$//;
                   6595:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6596: }
                   6597: 
                   6598: # ---------------------------------------------------------  putstore interface
                   6599: 
1.524     raeburn  6600: sub putstore {
1.1172.2.59  raeburn  6601:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6602:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6603:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6604:    my $uhome=&homeserver($uname,$udomain);
                   6605:    my $items='';
1.715     albertel 6606:    foreach my $key (keys(%$storehash)) {
                   6607:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6608:    }
1.715     albertel 6609:    $items=~s/\&$//;
1.716     albertel 6610:    my $esc_symb=&escape($symb);
                   6611:    my $esc_v=&escape($version);
1.715     albertel 6612:    my $reply =
1.716     albertel 6613:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6614: 	      $uhome);
1.1172.2.59  raeburn  6615:    if (($tolog) && ($reply eq 'ok')) {
                   6616:        my $namevalue='';
                   6617:        foreach my $key (keys(%{$storehash})) {
                   6618:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6619:        }
                   6620:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6621:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6622:                      '&version='.$esc_v.
                   6623:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6624:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6625:    }
1.715     albertel 6626:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6627:        # gfall back to way things use to be done
1.715     albertel 6628:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6629: 			    $uname);
1.524     raeburn  6630:    }
1.715     albertel 6631:    return $reply;
                   6632: }
                   6633: 
                   6634: sub old_putstore {
1.716     albertel 6635:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6636:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6637:     if (!$uname) { $uname=$env{'user.name'}; }
                   6638:     my $uhome=&homeserver($uname,$udomain);
                   6639:     my %newstorehash;
1.800     albertel 6640:     foreach my $item (keys(%$storehash)) {
                   6641: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6642: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6643:     }
                   6644:     my $items='';
                   6645:     my %allitems = ();
1.800     albertel 6646:     foreach my $item (keys(%newstorehash)) {
                   6647: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6648: 	    my $key = $1.':keys:'.$2;
                   6649: 	    $allitems{$key} .= $3.':';
                   6650: 	}
1.800     albertel 6651: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6652:     }
1.800     albertel 6653:     foreach my $item (keys(%allitems)) {
                   6654: 	$allitems{$item} =~ s/\:$//;
                   6655: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6656:     }
                   6657:     $items=~s/\&$//;
                   6658:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6659: }
                   6660: 
1.47      www      6661: # ------------------------------------------------------ critical put interface
                   6662: 
                   6663: sub cput {
1.134     albertel 6664:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6665:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6666:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6667:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6668:    my $items='';
1.800     albertel 6669:    foreach my $item (keys(%$storehash)) {
                   6670:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6671:    }
1.47      www      6672:    $items=~s/\&$//;
1.134     albertel 6673:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6674: }
                   6675: 
                   6676: # -------------------------------------------------------------- eget interface
                   6677: 
                   6678: sub eget {
1.133     albertel 6679:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6680:    my $items='';
1.800     albertel 6681:    foreach my $item (@$storearr) {
                   6682:        $items.=&escape($item).'&';
1.191     harris41 6683:    }
1.12      www      6684:    $items=~s/\&$//;
1.620     albertel 6685:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6686:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6687:    my $uhome=&homeserver($uname,$udomain);
                   6688:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6689:    my @pairs=split(/\&/,$rep);
                   6690:    my %returnhash=();
1.42      www      6691:    my $i=0;
1.800     albertel 6692:    foreach my $item (@$storearr) {
                   6693:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6694:       $i++;
1.191     harris41 6695:    }
1.12      www      6696:    return %returnhash;
                   6697: }
                   6698: 
1.667     albertel 6699: # ------------------------------------------------------------ tmpput interface
                   6700: sub tmpput {
1.802     raeburn  6701:     my ($storehash,$server,$context)=@_;
1.667     albertel 6702:     my $items='';
1.800     albertel 6703:     foreach my $item (keys(%$storehash)) {
                   6704: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6705:     }
                   6706:     $items=~s/\&$//;
1.802     raeburn  6707:     if (defined($context)) {
                   6708:         $items .= ':'.&escape($context);
                   6709:     }
1.667     albertel 6710:     return &reply("tmpput:$items",$server);
                   6711: }
                   6712: 
                   6713: # ------------------------------------------------------------ tmpget interface
                   6714: sub tmpget {
1.688     albertel 6715:     my ($token,$server)=@_;
                   6716:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6717:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6718:     my %returnhash;
1.1172.2.85  raeburn  6719:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6720:         return %returnhash;
                   6721:     }
1.667     albertel 6722:     foreach my $item (split(/\&/,$rep)) {
                   6723: 	my ($key,$value)=split(/=/,$item);
                   6724: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6725:     }
                   6726:     return %returnhash;
                   6727: }
                   6728: 
1.1113    raeburn  6729: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6730: sub tmpdel {
                   6731:     my ($token,$server)=@_;
                   6732:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6733:     return &reply("tmpdel:$token",$server);
                   6734: }
                   6735: 
1.1172.2.13  raeburn  6736: # ------------------------------------------------------------ get_timebased_id
                   6737: 
                   6738: sub get_timebased_id {
                   6739:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6740:         $maxtries) = @_;
                   6741:     my ($newid,$error,$dellock);
                   6742:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6743:         return ('','ok','invalid call to get suffix');
                   6744:     }
                   6745: 
                   6746: # set defaults for any optional args for which values were not supplied
                   6747:     if ($who eq '') {
                   6748:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6749:     }
                   6750:     if (!$locktries) {
                   6751:         $locktries = 3;
                   6752:     }
                   6753:     if (!$maxtries) {
                   6754:         $maxtries = 10;
                   6755:     }
                   6756: 
                   6757:     if (($cdom eq '') || ($cnum eq '')) {
                   6758:         if ($env{'request.course.id'}) {
                   6759:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6760:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6761:         }
                   6762:         if (($cdom eq '') || ($cnum eq '')) {
                   6763:             return ('','ok','call to get suffix not in course context');
                   6764:         }
                   6765:     }
                   6766: 
                   6767: # construct locking item
                   6768:     my $lockhash = {
                   6769:                       $prefix."\0".'locked_'.$keyid => $who,
                   6770:                    };
                   6771:     my $tries = 0;
                   6772: 
                   6773: # attempt to get lock on nohist_$namespace file
                   6774:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6775:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6776:         $tries ++;
                   6777:         sleep 1;
                   6778:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6779:     }
                   6780: 
                   6781: # attempt to get unique identifier, based on current timestamp
                   6782:     if ($gotlock eq 'ok') {
                   6783:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6784:         my $id = time;
                   6785:         $newid = $id;
1.1172.2.56  raeburn  6786:         if ($idtype eq 'addcode') {
                   6787:             $newid .= &sixnum_code();
                   6788:         }
1.1172.2.13  raeburn  6789:         my $idtries = 0;
                   6790:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6791:             if ($idtype eq 'concat') {
                   6792:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6793:             } elsif ($idtype eq 'addcode') {
                   6794:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6795:             } else {
                   6796:                 $newid ++;
                   6797:             }
                   6798:             $idtries ++;
                   6799:         }
                   6800:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6801:             my %new_item =  (
                   6802:                               $prefix."\0".$newid => $who,
                   6803:                             );
                   6804:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6805:                                                  $cdom,$cnum);
                   6806:             if ($putresult ne 'ok') {
                   6807:                 undef($newid);
                   6808:                 $error = 'error saving new item: '.$putresult;
                   6809:             }
                   6810:         } else {
1.1172.2.56  raeburn  6811:              undef($newid);
1.1172.2.13  raeburn  6812:              $error = ('error: no unique suffix available for the new item ');
                   6813:         }
                   6814: #  remove lock
                   6815:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6816:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6817:     } else {
                   6818:         $error = "error: could not obtain lockfile\n";
                   6819:         $dellock = 'ok';
1.1172.2.58  raeburn  6820:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6821:             $dellock = 'nolock';
                   6822:         }
1.1172.2.13  raeburn  6823:     }
                   6824:     return ($newid,$dellock,$error);
                   6825: }
                   6826: 
1.1172.2.56  raeburn  6827: sub sixnum_code {
                   6828:     my $code;
                   6829:     for (0..6) {
                   6830:         $code .= int( rand(9) );
                   6831:     }
                   6832:     return $code;
                   6833: }
                   6834: 
1.765     albertel 6835: # -------------------------------------------------- portfolio access checking
                   6836: 
                   6837: sub portfolio_access {
1.1172.2.77  raeburn  6838:     my ($requrl,$clientip) = @_;
1.765     albertel 6839:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6840:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6841:     if ($result) {
                   6842:         my %setters;
                   6843:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6844:             my ($startblock,$endblock) =
                   6845:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6846:             if ($startblock && $endblock) {
                   6847:                 return 'B';
                   6848:             }
                   6849:         } else {
                   6850:             my ($startblock,$endblock) =
                   6851:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6852:             if ($startblock && $endblock) {
                   6853:                 return 'B';
                   6854:             }
                   6855:         }
                   6856:     }
1.765     albertel 6857:     if ($result eq 'ok') {
1.766     albertel 6858:        return 'F';
1.765     albertel 6859:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6860:        return 'A';
1.765     albertel 6861:     }
1.766     albertel 6862:     return '';
1.765     albertel 6863: }
                   6864: 
                   6865: sub get_portfolio_access {
1.1172.2.77  raeburn  6866:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6867: 
                   6868:     if (!ref($access_hash)) {
                   6869: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6870: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6871: 						   $file_name);
                   6872: 	$access_hash = $access_controls{$file_name};
                   6873:     }
                   6874: 
1.1172.2.77  raeburn  6875:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6876:     my $now = time;
                   6877:     if (ref($access_hash) eq 'HASH') {
                   6878:         foreach my $key (keys(%{$access_hash})) {
                   6879:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6880:             if ($start > $now) {
                   6881:                 next;
                   6882:             }
                   6883:             if ($end && $end<$now) {
                   6884:                 next;
                   6885:             }
                   6886:             if ($scope eq 'public') {
                   6887:                 $public = $key;
                   6888:                 last;
                   6889:             } elsif ($scope eq 'guest') {
                   6890:                 $guest = $key;
                   6891:             } elsif ($scope eq 'domains') {
                   6892:                 push(@domains,$key);
                   6893:             } elsif ($scope eq 'users') {
                   6894:                 push(@users,$key);
                   6895:             } elsif ($scope eq 'course') {
                   6896:                 push(@courses,$key);
                   6897:             } elsif ($scope eq 'group') {
                   6898:                 push(@groups,$key);
1.1172.2.77  raeburn  6899:             } elsif ($scope eq 'ip') {
                   6900:                 push(@ips,$key);
1.765     albertel 6901:             }
                   6902:         }
                   6903:         if ($public) {
                   6904:             return 'ok';
1.1172.2.77  raeburn  6905:         } elsif (@ips > 0) {
                   6906:             my $allowed;
                   6907:             foreach my $ipkey (@ips) {
                   6908:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6909:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6910:                         $allowed = 1;
                   6911:                         last;
                   6912:                     }
                   6913:                 }
                   6914:             }
                   6915:             if ($allowed) {
                   6916:                 return 'ok';
                   6917:             }
1.765     albertel 6918:         }
                   6919:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6920:             if ($guest) {
                   6921:                 return $guest;
                   6922:             }
                   6923:         } else {
                   6924:             if (@domains > 0) {
                   6925:                 foreach my $domkey (@domains) {
                   6926:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6927:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6928:                             return 'ok';
                   6929:                         }
                   6930:                     }
                   6931:                 }
                   6932:             }
                   6933:             if (@users > 0) {
                   6934:                 foreach my $userkey (@users) {
1.865     raeburn  6935:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6936:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6937:                             if (ref($item) eq 'HASH') {
                   6938:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6939:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6940:                                     return 'ok';
                   6941:                                 }
                   6942:                             }
                   6943:                         }
                   6944:                     } 
1.765     albertel 6945:                 }
                   6946:             }
                   6947:             my %roleshash;
                   6948:             my @courses_and_groups = @courses;
                   6949:             push(@courses_and_groups,@groups); 
                   6950:             if (@courses_and_groups > 0) {
                   6951:                 my (%allgroups,%allroles); 
                   6952:                 my ($start,$end,$role,$sec,$group);
                   6953:                 foreach my $envkey (%env) {
1.1060    raeburn  6954:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6955:                         my $cid = $2.'_'.$3; 
                   6956:                         if ($1 eq 'gr') {
                   6957:                             $group = $4;
                   6958:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6959:                         } else {
                   6960:                             if ($4 eq '') {
                   6961:                                 $sec = 'none';
                   6962:                             } else {
                   6963:                                 $sec = $4;
                   6964:                             }
                   6965:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6966:                         }
1.811     albertel 6967:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6968:                         my $cid = $2.'_'.$3;
                   6969:                         if ($4 eq '') {
                   6970:                             $sec = 'none';
                   6971:                         } else {
                   6972:                             $sec = $4;
                   6973:                         }
                   6974:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6975:                     }
                   6976:                 }
                   6977:                 if (keys(%allroles) == 0) {
                   6978:                     return;
                   6979:                 }
                   6980:                 foreach my $key (@courses_and_groups) {
                   6981:                     my %content = %{$$access_hash{$key}};
                   6982:                     my $cnum = $content{'number'};
                   6983:                     my $cdom = $content{'domain'};
                   6984:                     my $cid = $cdom.'_'.$cnum;
                   6985:                     if (!exists($allroles{$cid})) {
                   6986:                         next;
                   6987:                     }    
                   6988:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6989:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6990:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6991:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6992:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6993:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6994:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6995:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6996:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6997:                                         if (grep/^all$/,@sections) {
                   6998:                                             return 'ok';
                   6999:                                         } else {
                   7000:                                             if (grep/^$sec$/,@sections) {
                   7001:                                                 return 'ok';
                   7002:                                             }
                   7003:                                         }
                   7004:                                     }
                   7005:                                 }
                   7006:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7007:                                     if (grep/^none$/,@groups) {
                   7008:                                         return 'ok';
                   7009:                                     }
                   7010:                                 } else {
                   7011:                                     if (grep/^all$/,@groups) {
                   7012:                                         return 'ok';
                   7013:                                     } 
                   7014:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7015:                                         if (grep/^$group$/,@groups) {
                   7016:                                             return 'ok';
                   7017:                                         }
                   7018:                                     }
                   7019:                                 } 
                   7020:                             }
                   7021:                         }
                   7022:                     }
                   7023:                 }
                   7024:             }
                   7025:             if ($guest) {
                   7026:                 return $guest;
                   7027:             }
                   7028:         }
                   7029:     }
                   7030:     return;
                   7031: }
                   7032: 
                   7033: sub course_group_datechecker {
                   7034:     my ($dates,$now,$status) = @_;
                   7035:     my ($start,$end) = split(/\./,$dates);
                   7036:     if (!$start && !$end) {
                   7037:         return 'ok';
                   7038:     }
                   7039:     if (grep/^active$/,@{$status}) {
                   7040:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7041:             return 'ok';
                   7042:         }
                   7043:     }
                   7044:     if (grep/^previous$/,@{$status}) {
                   7045:         if ($end > $now ) {
                   7046:             return 'ok';
                   7047:         }
                   7048:     }
                   7049:     if (grep/^future$/,@{$status}) {
                   7050:         if ($start > $now) {
                   7051:             return 'ok';
                   7052:         }
                   7053:     }
                   7054:     return; 
                   7055: }
                   7056: 
                   7057: sub parse_portfolio_url {
                   7058:     my ($url) = @_;
                   7059: 
                   7060:     my ($type,$udom,$unum,$group,$file_name);
                   7061:     
1.823     albertel 7062:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7063: 	$type = 1;
                   7064:         $udom = $1;
                   7065:         $unum = $2;
                   7066:         $file_name = $3;
1.823     albertel 7067:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7068: 	$type = 2;
                   7069:         $udom = $1;
                   7070:         $unum = $2;
                   7071:         $group = $3;
                   7072:         $file_name = $3.'/'.$4;
                   7073:     }
                   7074:     if (wantarray) {
                   7075: 	return ($type,$udom,$unum,$file_name,$group);
                   7076:     }
                   7077:     return $type;
                   7078: }
                   7079: 
                   7080: sub is_portfolio_url {
                   7081:     my ($url) = @_;
                   7082:     return scalar(&parse_portfolio_url($url));
                   7083: }
                   7084: 
1.798     raeburn  7085: sub is_portfolio_file {
                   7086:     my ($file) = @_;
1.820     raeburn  7087:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7088:         return 1;
                   7089:     }
                   7090:     return;
                   7091: }
                   7092: 
1.976     raeburn  7093: sub usertools_access {
1.1084    raeburn  7094:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7095:     my ($access,%tools);
                   7096:     if ($context eq '') {
                   7097:         $context = 'tools';
                   7098:     }
                   7099:     if ($context eq 'requestcourses') {
                   7100:         %tools = (
                   7101:                       official   => 1,
                   7102:                       unofficial => 1,
1.1006    raeburn  7103:                       community  => 1,
1.1172.2.37  raeburn  7104:                       textbook   => 1,
1.985     raeburn  7105:                  );
1.1172.2.9  raeburn  7106:     } elsif ($context eq 'requestauthor') {
                   7107:         %tools = (
                   7108:                       requestauthor => 1,
                   7109:                  );
1.985     raeburn  7110:     } else {
                   7111:         %tools = (
                   7112:                       aboutme   => 1,
                   7113:                       blog      => 1,
1.1172.2.6  raeburn  7114:                       webdav    => 1,
1.985     raeburn  7115:                       portfolio => 1,
                   7116:                  );
                   7117:     }
1.976     raeburn  7118:     return if (!defined($tools{$tool}));
                   7119: 
1.1172.2.35  raeburn  7120:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7121:         $udom = $env{'user.domain'};
                   7122:         $uname = $env{'user.name'};
                   7123:     }
                   7124: 
1.978     raeburn  7125:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7126:         if ($action ne 'reload') {
1.985     raeburn  7127:             if ($context eq 'requestcourses') {
                   7128:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7129:             } elsif ($context eq 'requestauthor') {
                   7130:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7131:             } else {
                   7132:                 return $env{'environment.availabletools.'.$tool};
                   7133:             }
                   7134:         }
1.976     raeburn  7135:     }
                   7136: 
1.1172.2.9  raeburn  7137:     my ($toolstatus,$inststatus,$envkey);
                   7138:     if ($context eq 'requestauthor') {
                   7139:         $envkey = $context;
                   7140:     } else {
                   7141:         $envkey = $context.'.'.$tool;
                   7142:     }
1.976     raeburn  7143: 
1.985     raeburn  7144:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7145:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7146:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7147:         $inststatus = $env{'environment.inststatus'};
                   7148:     } else {
1.1084    raeburn  7149:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7150:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7151:             $inststatus = $userenvref->{'inststatus'};
                   7152:         } else {
1.1172.2.9  raeburn  7153:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7154:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7155:             $inststatus = $userenv{'inststatus'};
                   7156:         }
1.976     raeburn  7157:     }
                   7158: 
                   7159:     if ($toolstatus ne '') {
                   7160:         if ($toolstatus) {
                   7161:             $access = 1;
                   7162:         } else {
                   7163:             $access = 0;
                   7164:         }
                   7165:         return $access;
                   7166:     }
                   7167: 
1.1084    raeburn  7168:     my ($is_adv,%domdef);
                   7169:     if (ref($is_advref) eq 'HASH') {
                   7170:         $is_adv = $is_advref->{'is_adv'};
                   7171:     } else {
                   7172:         $is_adv = &is_advanced_user($udom,$uname);
                   7173:     }
                   7174:     if (ref($domdefref) eq 'HASH') {
                   7175:         %domdef = %{$domdefref};
                   7176:     } else {
                   7177:         %domdef = &get_domain_defaults($udom);
                   7178:     }
1.976     raeburn  7179:     if (ref($domdef{$tool}) eq 'HASH') {
                   7180:         if ($is_adv) {
                   7181:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7182:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7183:                     $access = 1;
                   7184:                 } else {
                   7185:                     $access = 0;
                   7186:                 }
                   7187:                 return $access;
                   7188:             }
                   7189:         }
                   7190:         if ($inststatus ne '') {
                   7191:             my ($hasaccess,$hasnoaccess);
                   7192:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7193:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7194:                     if ($domdef{$tool}{$affiliation}) {
                   7195:                         $hasaccess = 1;
                   7196:                     } else {
                   7197:                         $hasnoaccess = 1;
                   7198:                     }
                   7199:                 }
                   7200:             }
                   7201:             if ($hasaccess || $hasnoaccess) {
                   7202:                 if ($hasaccess) {
                   7203:                     $access = 1;
                   7204:                 } elsif ($hasnoaccess) {
                   7205:                     $access = 0; 
                   7206:                 }
                   7207:                 return $access;
                   7208:             }
                   7209:         } else {
                   7210:             if ($domdef{$tool}{'default'} ne '') {
                   7211:                 if ($domdef{$tool}{'default'}) {
                   7212:                     $access = 1;
                   7213:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7214:                     $access = 0;
                   7215:                 }
                   7216:                 return $access;
                   7217:             }
                   7218:         }
                   7219:     } else {
1.1172.2.6  raeburn  7220:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7221:             $access = 1;
                   7222:         } else {
                   7223:             $access = 0;
                   7224:         }
1.976     raeburn  7225:         return $access;
                   7226:     }
                   7227: }
                   7228: 
1.1050    raeburn  7229: sub is_course_owner {
                   7230:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7231:     if (($udom eq '') || ($uname eq '')) {
                   7232:         $udom = $env{'user.domain'};
                   7233:         $uname = $env{'user.name'};
                   7234:     }
                   7235:     unless (($udom eq '') || ($uname eq '')) {
                   7236:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7237:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7238:                 return 1;
                   7239:             } else {
                   7240:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7241:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7242:                     return 1;
                   7243:                 }
                   7244:             }
                   7245:         }
                   7246:     }
                   7247:     return;
                   7248: }
                   7249: 
1.976     raeburn  7250: sub is_advanced_user {
                   7251:     my ($udom,$uname) = @_;
1.1085    raeburn  7252:     if ($udom ne '' && $uname ne '') {
                   7253:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7254:             if (wantarray) {
                   7255:                 return ($env{'user.adv'},$env{'user.author'});
                   7256:             } else {
                   7257:                 return $env{'user.adv'};
                   7258:             }
1.1085    raeburn  7259:         }
                   7260:     }
1.976     raeburn  7261:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7262:     my %allroles;
1.1128    raeburn  7263:     my ($is_adv,$is_author);
1.976     raeburn  7264:     foreach my $role (keys(%roleshash)) {
                   7265:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7266:         my $area = '/'.$tdomain.'/'.$trest;
                   7267:         if ($sec ne '') {
                   7268:             $area .= '/'.$sec;
                   7269:         }
                   7270:         if (($area ne '') && ($trole ne '')) {
                   7271:             my $spec=$trole.'.'.$area;
                   7272:             if ($trole =~ /^cr\//) {
                   7273:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7274:             } elsif ($trole ne 'gr') {
                   7275:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7276:             }
1.1128    raeburn  7277:             if ($trole eq 'au') {
                   7278:                 $is_author = 1;
                   7279:             }
1.976     raeburn  7280:         }
                   7281:     }
                   7282:     foreach my $role (keys(%allroles)) {
                   7283:         last if ($is_adv);
                   7284:         foreach my $item (split(/:/,$allroles{$role})) {
                   7285:             if ($item ne '') {
                   7286:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7287:                 if ($privilege eq 'adv') {
                   7288:                     $is_adv = 1;
                   7289:                     last;
                   7290:                 }
                   7291:             }
                   7292:         }
                   7293:     }
1.1128    raeburn  7294:     if (wantarray) {
                   7295:         return ($is_adv,$is_author);
                   7296:     }
1.976     raeburn  7297:     return $is_adv;
                   7298: }
1.798     raeburn  7299: 
1.1035    raeburn  7300: sub check_can_request {
1.1036    raeburn  7301:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7302:     my $canreq = 0;
                   7303:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7304:     my @options = ('approval','validate','autolimit');
                   7305:     my $optregex = join('|',@options);
                   7306:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7307:         foreach my $type (@{$types}) {
                   7308:             if (&usertools_access($env{'user.name'},
                   7309:                                   $env{'user.domain'},
                   7310:                                   $type,undef,'requestcourses')) {
                   7311:                 $canreq ++;
1.1036    raeburn  7312:                 if (ref($request_domains) eq 'HASH') {
                   7313:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7314:                 }
1.1035    raeburn  7315:                 if ($dom eq $env{'user.domain'}) {
                   7316:                     $can_request->{$type} = 1;
                   7317:                 }
                   7318:             }
                   7319:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7320:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7321:                 if (@curr > 0) {
1.1036    raeburn  7322:                     foreach my $item (@curr) {
                   7323:                         if (ref($request_domains) eq 'HASH') {
                   7324:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7325:                             if ($otherdom ne '') {
                   7326:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7327:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7328:                                         push(@{$request_domains->{$type}},$otherdom);
                   7329:                                     }
                   7330:                                 } else {
                   7331:                                     push(@{$request_domains->{$type}},$otherdom);
                   7332:                                 }
                   7333:                             }
                   7334:                         }
                   7335:                     }
                   7336:                     unless($dom eq $env{'user.domain'}) {
                   7337:                         $canreq ++;
1.1035    raeburn  7338:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7339:                             $can_request->{$type} = 1;
                   7340:                         }
                   7341:                     }
                   7342:                 }
                   7343:             }
                   7344:         }
                   7345:     }
                   7346:     return $canreq;
                   7347: }
                   7348: 
1.341     www      7349: # ---------------------------------------------- Custom access rule evaluation
                   7350: 
                   7351: sub customaccess {
                   7352:     my ($priv,$uri)=@_;
1.807     albertel 7353:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7354:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7355:     $udom = &LONCAPA::clean_domain($udom);
                   7356:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7357:     my $access=0;
1.800     albertel 7358:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7359: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7360: 	if ($type eq 'user') {
                   7361: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7362: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7363: 		if ($tdom) {
                   7364: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7365: 		}
1.896     albertel 7366: 		if ($tuname) {
                   7367: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7368: 		}
                   7369: 		$access=($effect eq 'allow');
                   7370: 		last;
                   7371: 	    }
                   7372: 	} else {
                   7373: 	    if ($role) {
                   7374: 		if ($role ne $urole) { next; }
                   7375: 	    }
                   7376: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7377: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7378: 		if ($tdom) {
                   7379: 		    if ($tdom ne $udom) { next; }
                   7380: 		}
                   7381: 		if ($tcrs) {
                   7382: 		    if ($tcrs ne $ucrs) { next; }
                   7383: 		}
                   7384: 		if ($tsec) {
                   7385: 		    if ($tsec ne $usec) { next; }
                   7386: 		}
                   7387: 		$access=($effect eq 'allow');
                   7388: 		last;
                   7389: 	    }
                   7390: 	    if ($realm eq '' && $role eq '') {
                   7391: 		$access=($effect eq 'allow');
                   7392: 	    }
1.402     bowersj2 7393: 	}
1.341     www      7394:     }
                   7395:     return $access;
                   7396: }
                   7397: 
1.103     harris41 7398: # ------------------------------------------------- Check for a user privilege
1.12      www      7399: 
                   7400: sub allowed {
1.1172.2.65  raeburn  7401:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7402:     my $ver_orguri=$uri;
1.439     www      7403:     $uri=&deversion($uri);
1.152     www      7404:     my $orguri=$uri;
1.52      www      7405:     $uri=&declutter($uri);
1.809     raeburn  7406: 
1.810     raeburn  7407:     if ($priv eq 'evb') {
                   7408: # Evade communication block restrictions for specified role in a course
                   7409:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7410:             return $1;
                   7411:         } else {
                   7412:             return;
                   7413:         }
                   7414:     }
                   7415: 
1.620     albertel 7416:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7417: # Free bre access to adm and meta resources
1.775     albertel 7418:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7419: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7420: 	&& ($priv eq 'bre')) {
1.14      www      7421: 	return 'F';
1.159     www      7422:     }
                   7423: 
1.545     banghart 7424: # Free bre access to user's own portfolio contents
1.714     raeburn  7425:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7426:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7427: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7428:         my %setters;
                   7429:         my ($startblock,$endblock) = 
                   7430:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7431:         if ($startblock && $endblock) {
                   7432:             return 'B';
                   7433:         } else {
                   7434:             return 'F';
                   7435:         }
1.545     banghart 7436:     }
                   7437: 
1.762     raeburn  7438: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7439:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7440:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7441:         if (exists($env{'request.course.id'})) {
                   7442:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7443:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7444:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7445:                 my $courseprivid=$env{'request.course.id'};
                   7446:                 $courseprivid=~s/\_/\//;
                   7447:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7448:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7449:                     return $1; 
1.762     raeburn  7450:                 } else {
                   7451:                     if ($env{'request.course.sec'}) {
                   7452:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7453:                     }
                   7454:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7455:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7456:                         return $2;
                   7457:                     }
1.714     raeburn  7458:                 }
                   7459:             }
                   7460:         }
                   7461:     }
                   7462: 
1.159     www      7463: # Free bre to public access
                   7464: 
                   7465:     if ($priv eq 'bre') {
1.238     www      7466:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7467: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7468:            return 'F'; 
                   7469:         }
1.238     www      7470:         if ($copyright eq 'priv') {
                   7471:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7472: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7473: 		return '';
                   7474:             }
                   7475:         }
                   7476:         if ($copyright eq 'domain') {
                   7477:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7478: 	    unless (($env{'user.domain'} eq $1) ||
                   7479:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7480: 		return '';
                   7481:             }
1.262     matthew  7482:         }
1.620     albertel 7483:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7484:             # Library role, so allow browsing of resources in this domain.
                   7485:             return 'F';
1.238     www      7486:         }
1.341     www      7487:         if ($copyright eq 'custom') {
                   7488: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7489:         }
1.14      www      7490:     }
1.264     matthew  7491:     # Domain coordinator is trying to create a course
1.620     albertel 7492:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7493:         # uri is the requested domain in this case.
                   7494:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7495:         # a role of dc for the domain in question.
1.620     albertel 7496:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7497:     }
1.29      www      7498: 
1.52      www      7499:     my $thisallowed='';
                   7500:     my $statecond=0;
                   7501:     my $courseprivid='';
                   7502: 
1.1039    raeburn  7503:     my $ownaccess;
1.1043    raeburn  7504:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7505:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7506:         if ($uri eq '') {
                   7507:             $ownaccess = 1;
                   7508:         } else {
                   7509:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7510:                 my $udom = $env{'user.domain'};
                   7511:                 my $uname = $env{'user.name'};
                   7512:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7513:                     $ownaccess = 1;
1.1040    raeburn  7514:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7515:                     unless ($uri =~ m{\.\./}) {
                   7516:                         $ownaccess = 1;
                   7517:                     }
                   7518:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7519:                     my $now = time;
                   7520:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7521:                         my $adom = $1;
                   7522:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7523:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7524:                                 my ($start,$end) = split('.',$env{$key});
                   7525:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7526:                                     $ownaccess = 1;
                   7527:                                     last;
                   7528:                                 }
                   7529:                             }
                   7530:                         }
                   7531:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7532:                         my $adom = $1;
                   7533:                         my $aname = $2;
1.1042    raeburn  7534:                         foreach my $role ('ca','aa') { 
                   7535:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7536:                                 my ($start,$end) =
                   7537:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7538:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7539:                                     $ownaccess = 1;
                   7540:                                     last;
                   7541:                                 }
1.1039    raeburn  7542:                             }
                   7543:                         }
                   7544:                     }
                   7545:                 }
                   7546:             }
                   7547:         }
                   7548:     }
                   7549: 
1.52      www      7550: # Course
                   7551: 
1.620     albertel 7552:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7553:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7554:             $thisallowed.=$1;
                   7555:         }
1.52      www      7556:     }
1.29      www      7557: 
1.52      www      7558: # Domain
                   7559: 
1.620     albertel 7560:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7561:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7562:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7563:             $thisallowed.=$1;
                   7564:         }
1.12      www      7565:     }
1.52      www      7566: 
1.1141    raeburn  7567: # User who is not author or co-author might still be able to edit
                   7568: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7569:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7570:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7571:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7572:             $thisallowed.=$1;
                   7573:         }
                   7574:     }
                   7575: 
1.52      www      7576: # Course: uri itself is a course
1.66      www      7577:     my $courseuri=$uri;
                   7578:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7579:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7580: 
1.620     albertel 7581:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7582:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7583:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7584:             $thisallowed.=$1;
                   7585:         }
1.12      www      7586:     }
1.29      www      7587: 
1.665     albertel 7588: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7589: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7590:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7591: 	$thisallowed='';
1.671     raeburn  7592:         my ($match)=&is_on_map($uri);
                   7593:         if ($match) {
                   7594:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7595:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7596:                 my $value = $1;
                   7597:                 if ($noblockcheck) {
                   7598:                     $thisallowed.=$value;
1.1162    raeburn  7599:                 } else {
1.1172.2.65  raeburn  7600:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7601:                     if (@blockers > 0) {
                   7602:                         $thisallowed = 'B';
                   7603:                     } else {
                   7604:                         $thisallowed.=$value;
                   7605:                     }
1.1162    raeburn  7606:                 }
1.671     raeburn  7607:             }
                   7608:         } else {
1.705     albertel 7609:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7610:             if ($refuri) {
                   7611:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7612:                     $thisallowed='F';
1.671     raeburn  7613:                 } else {
                   7614:                     $refuri=&declutter($refuri);
                   7615:                     my ($match) = &is_on_map($refuri);
                   7616:                     if ($match) {
1.1172.2.65  raeburn  7617:                         if ($noblockcheck) {
1.1162    raeburn  7618:                             $thisallowed='F';
1.1172.2.65  raeburn  7619:                         } else {
                   7620:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7621:                             if (@blockers > 0) {
                   7622:                                 $thisallowed = 'B';
                   7623:                             } else {
                   7624:                                 $thisallowed='F';
                   7625:                             }
1.1162    raeburn  7626:                         }
1.671     raeburn  7627:                     }
1.669     raeburn  7628:                 }
1.671     raeburn  7629:             }
                   7630:         }
1.314     www      7631:     }
1.492     albertel 7632: 
1.766     albertel 7633:     if ($priv eq 'bre'
                   7634: 	&& $thisallowed ne 'F' 
                   7635: 	&& $thisallowed ne '2'
                   7636: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7637: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7638:     }
                   7639:     
1.52      www      7640: # Full access at system, domain or course-wide level? Exit.
1.29      www      7641:     if ($thisallowed=~/F/) {
                   7642: 	return 'F';
                   7643:     }
                   7644: 
1.52      www      7645: # If this is generating or modifying users, exit with special codes
1.29      www      7646: 
1.643     www      7647:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7648: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7649: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7650: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7651: 	    unless ($auname) { return $thisallowed; }
                   7652: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7653: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7654: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7655: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7656: 	}
1.52      www      7657: 	return $thisallowed;
                   7658:     }
                   7659: #
1.103     harris41 7660: # Gathered so far: system, domain and course wide privileges
1.52      www      7661: #
                   7662: # Course: See if uri or referer is an individual resource that is part of 
                   7663: # the course
                   7664: 
1.620     albertel 7665:     if ($env{'request.course.id'}) {
1.232     www      7666: 
1.620     albertel 7667:        $courseprivid=$env{'request.course.id'};
                   7668:        if ($env{'request.course.sec'}) {
                   7669:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7670:        }
                   7671:        $courseprivid=~s/\_/\//;
                   7672:        my $checkreferer=1;
1.232     www      7673:        my ($match,$cond)=&is_on_map($uri);
                   7674:        if ($match) {
                   7675:            $statecond=$cond;
1.620     albertel 7676:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7677:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7678:                my $value = $1;
                   7679:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7680:                    if ($noblockcheck) {
1.1162    raeburn  7681:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7682:                    } else {
                   7683:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7684:                        if (@blockers > 0) {
                   7685:                            $thisallowed = 'B';
                   7686:                        } else {
                   7687:                            $thisallowed.=$value;
                   7688:                        }
1.1162    raeburn  7689:                    }
                   7690:                } else {
                   7691:                    $thisallowed.=$value;
                   7692:                }
1.52      www      7693:                $checkreferer=0;
                   7694:            }
1.29      www      7695:        }
1.83      www      7696:        
1.148     www      7697:        if ($checkreferer) {
1.620     albertel 7698: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7699:             unless ($refuri) {
1.800     albertel 7700:                 foreach my $key (keys(%env)) {
                   7701: 		    if ($key=~/^httpref\..*\*/) {
                   7702: 			my $pattern=$key;
1.156     www      7703:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7704:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7705:                         $pattern=~s/\//\\\//g;
1.152     www      7706:                         if ($orguri=~/$pattern/) {
1.800     albertel 7707: 			    $refuri=$env{$key};
1.148     www      7708:                         }
                   7709:                     }
1.191     harris41 7710:                 }
1.148     www      7711:             }
1.232     www      7712: 
1.148     www      7713:          if ($refuri) { 
1.152     www      7714: 	  $refuri=&declutter($refuri);
1.232     www      7715:           my ($match,$cond)=&is_on_map($refuri);
                   7716:             if ($match) {
                   7717:               my $refstatecond=$cond;
1.620     albertel 7718:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7719:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7720:                   my $value = $1;
                   7721:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7722:                       if ($noblockcheck) {
1.1162    raeburn  7723:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7724:                       } else {
                   7725:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7726:                           if (@blockers > 0) {
                   7727:                               $thisallowed = 'B';
                   7728:                           } else {
                   7729:                               $thisallowed.=$value;
                   7730:                           }
1.1162    raeburn  7731:                       }
                   7732:                   } else {
                   7733:                       $thisallowed.=$value;
                   7734:                   }
1.53      www      7735:                   $uri=$refuri;
                   7736:                   $statecond=$refstatecond;
1.52      www      7737:               }
                   7738:           }
1.148     www      7739:         }
1.29      www      7740:        }
1.52      www      7741:    }
1.29      www      7742: 
1.52      www      7743: #
1.103     harris41 7744: # Gathered now: all privileges that could apply, and condition number
1.52      www      7745: # 
                   7746: #
                   7747: # Full or no access?
                   7748: #
1.29      www      7749: 
1.52      www      7750:     if ($thisallowed=~/F/) {
                   7751: 	return 'F';
                   7752:     }
1.29      www      7753: 
1.52      www      7754:     unless ($thisallowed) {
                   7755:         return '';
                   7756:     }
1.29      www      7757: 
1.52      www      7758: # Restrictions exist, deal with them
                   7759: #
                   7760: #   C:according to course preferences
                   7761: #   R:according to resource settings
                   7762: #   L:unless locked
                   7763: #   X:according to user session state
                   7764: #
                   7765: 
                   7766: # Possibly locked functionality, check all courses
1.54      www      7767: # Locks might take effect only after 10 minutes cache expiration for other
                   7768: # courses, and 2 minutes for current course
1.52      www      7769: 
                   7770:     my $envkey;
                   7771:     if ($thisallowed=~/L/) {
1.1000    raeburn  7772:         foreach $envkey (keys(%env)) {
1.54      www      7773:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7774:                my $courseid=$2;
                   7775:                my $roleid=$1.'.'.$2;
1.92      www      7776:                $courseid=~s/^\///;
1.54      www      7777:                my $expiretime=600;
1.620     albertel 7778:                if ($env{'request.role'} eq $roleid) {
1.54      www      7779: 		  $expiretime=120;
                   7780:                }
                   7781: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7782:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7783:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7784: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7785:                }
1.620     albertel 7786:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7787:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7788: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7789:                        &log($env{'user.domain'},$env{'user.name'},
                   7790:                             $env{'user.home'},
1.57      www      7791:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7792:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7793:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7794: 		       return '';
                   7795:                    }
                   7796:                }
1.620     albertel 7797:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7798:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7799: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7800:                        &log($env{'user.domain'},$env{'user.name'},
                   7801:                             $env{'user.home'},
1.57      www      7802:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7803:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7804:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7805: 		       return '';
                   7806:                    }
                   7807:                }
                   7808: 	   }
1.29      www      7809:        }
1.52      www      7810:     }
                   7811:    
                   7812: #
                   7813: # Rest of the restrictions depend on selected course
                   7814: #
                   7815: 
1.620     albertel 7816:     unless ($env{'request.course.id'}) {
1.766     albertel 7817: 	if ($thisallowed eq 'A') {
                   7818: 	    return 'A';
1.814     raeburn  7819:         } elsif ($thisallowed eq 'B') {
                   7820:             return 'B';
1.766     albertel 7821: 	} else {
                   7822: 	    return '1';
                   7823: 	}
1.52      www      7824:     }
1.29      www      7825: 
1.52      www      7826: #
                   7827: # Now user is definitely in a course
                   7828: #
1.53      www      7829: 
                   7830: 
                   7831: # Course preferences
                   7832: 
                   7833:    if ($thisallowed=~/C/) {
1.620     albertel 7834:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7835:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7836:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7837: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7838: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7839: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7840: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7841: 			$env{'request.course.id'});
                   7842: 	   }
1.237     www      7843:            return '';
                   7844:        }
                   7845: 
1.620     albertel 7846:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7847: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7848: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7849: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7850: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7851: 			$env{'request.course.id'});
                   7852: 	   }
1.54      www      7853:            return '';
                   7854:        }
1.53      www      7855:    }
                   7856: 
                   7857: # Resource preferences
                   7858: 
                   7859:    if ($thisallowed=~/R/) {
1.620     albertel 7860:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7861:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7862: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7863: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7864: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7865: 	   }
                   7866: 	   return '';
1.54      www      7867:        }
1.53      www      7868:    }
1.30      www      7869: 
1.246     www      7870: # Restricted by state or randomout?
1.30      www      7871: 
1.52      www      7872:    if ($thisallowed=~/X/) {
1.620     albertel 7873:       if ($env{'acc.randomout'}) {
1.579     albertel 7874: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7875:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7876:             return ''; 
                   7877:          }
1.247     www      7878:       }
                   7879:       if (&condval($statecond)) {
1.52      www      7880: 	 return '2';
                   7881:       } else {
                   7882:          return '';
                   7883:       }
                   7884:    }
1.30      www      7885: 
1.766     albertel 7886:     if ($thisallowed eq 'A') {
                   7887: 	return 'A';
1.814     raeburn  7888:     } elsif ($thisallowed eq 'B') {
                   7889:         return 'B';
1.766     albertel 7890:     }
1.52      www      7891:    return 'F';
1.232     www      7892: }
1.1162    raeburn  7893: 
1.1172.2.13  raeburn  7894: # ------------------------------------------- Check construction space access
                   7895: 
                   7896: sub constructaccess {
                   7897:     my ($url,$setpriv)=@_;
                   7898: 
                   7899: # We do not allow editing of previous versions of files
                   7900:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7901: 
                   7902: # Get username and domain from URL
                   7903:     my ($ownername,$ownerdomain,$ownerhome);
                   7904: 
                   7905:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  7906:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  7907: 
                   7908: # The URL does not really point to any authorspace, forget it
                   7909:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7910: 
                   7911: # Now we need to see if the user has access to the authorspace of
                   7912: # $ownername at $ownerdomain
                   7913: 
                   7914:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7915: # Real author for this?
                   7916:        $ownerhome = $env{'user.home'};
                   7917:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7918:           return ($ownername,$ownerdomain,$ownerhome);
                   7919:        }
                   7920:     } else {
                   7921: # Co-author for this?
                   7922:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7923:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7924:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7925:             return ($ownername,$ownerdomain,$ownerhome);
                   7926:         }
                   7927:     }
                   7928: 
                   7929: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7930: # we might as well leave
                   7931:    unless ($setpriv) { return ''; }
                   7932: 
                   7933: # Backdoor access?
                   7934:     my $allowed=&allowed('eco',$ownerdomain);
                   7935: # Nope
                   7936:     unless ($allowed) { return ''; }
                   7937: # Looks like we may have access, but could be locked by the owner of the construction space
                   7938:     if ($allowed eq 'U') {
                   7939:         my %blocked=&get('environment',['domcoord.author'],
                   7940:                          $ownerdomain,$ownername);
                   7941: # Is blocked by owner
                   7942:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7943:     }
                   7944:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7945: # Grant temporary access
                   7946:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7947:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7948:         if (!$update) { $update = $then; }
                   7949:         my $refresh=$env{'user.refresh.time'};
                   7950:         if (!$refresh) { $refresh = $update; }
                   7951:         my $now = time;
                   7952:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7953:                            $now,'ca','constructaccess');
                   7954:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7955:         return($ownername,$ownerdomain,$ownerhome);
                   7956:     }
                   7957: # No business here
                   7958:     return '';
                   7959: }
                   7960: 
1.1172.2.66  raeburn  7961: # ----------------------------------------------------------- Content Blocking
                   7962: 
                   7963: {
                   7964: # Caches for faster Course Contents display where content blocking
                   7965: # is in operation (i.e., interval param set) for timed quiz.
                   7966: #
                   7967: # User for whom data are being temporarily cached.
                   7968: my $cacheduser='';
                   7969: # Cached blockers for this user (a hash of blocking items).
                   7970: my %cachedblockers=();
                   7971: # When the data were last cached.
                   7972: my $cachedlast='';
                   7973: 
                   7974: sub load_all_blockers {
                   7975:     my ($uname,$udom,$blocks)=@_;
                   7976:     if (($uname ne '') && ($udom ne '')) {
                   7977:         if (($cacheduser eq $uname.':'.$udom) &&
                   7978:             (abs($cachedlast-time)<5)) {
                   7979:             return;
                   7980:         }
                   7981:     }
                   7982:     $cachedlast=time;
                   7983:     $cacheduser=$uname.':'.$udom;
                   7984:     %cachedblockers = &get_commblock_resources($blocks);
                   7985: }
                   7986: 
1.1162    raeburn  7987: sub get_comm_blocks {
                   7988:     my ($cdom,$cnum) = @_;
                   7989:     if ($cdom eq '' || $cnum eq '') {
                   7990:         return unless ($env{'request.course.id'});
                   7991:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7992:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7993:     }
                   7994:     my %commblocks;
                   7995:     my $hashid=$cdom.'_'.$cnum;
                   7996:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7997:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7998:         %commblocks = %{$blocksref};
                   7999:     } else {
                   8000:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8001:         my $cachetime = 600;
                   8002:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8003:     }
                   8004:     return %commblocks;
                   8005: }
                   8006: 
1.1172.2.66  raeburn  8007: sub get_commblock_resources {
                   8008:     my ($blocks) = @_;
                   8009:     my %blockers = ();
                   8010:     return %blockers unless ($env{'request.course.id'});
                   8011:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8012:     my %commblocks;
                   8013:     if (ref($blocks) eq 'HASH') {
                   8014:         %commblocks = %{$blocks};
                   8015:     } else {
                   8016:         %commblocks = &get_comm_blocks();
                   8017:     }
1.1172.2.66  raeburn  8018:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8019:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8020:     return %blockers unless (ref($navmap));
                   8021:     my $now = time;
1.1162    raeburn  8022:     foreach my $block (keys(%commblocks)) {
                   8023:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8024:             my ($start,$end) = ($1,$2);
                   8025:             if ($start <= $now && $end >= $now) {
                   8026:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8027:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8028:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8029:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8030:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8031:                             }
                   8032:                         }
                   8033:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8034:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8035:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8036:                             }
                   8037:                         }
                   8038:                     }
                   8039:                 }
                   8040:             }
                   8041:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8042:             my $item = $1;
1.1163    raeburn  8043:             my @to_test;
1.1162    raeburn  8044:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8045:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8046:                     my @interval;
                   8047:                     my $type = 'map';
                   8048:                     if ($item eq 'course') {
                   8049:                         $type = 'course';
                   8050:                         @interval=&EXT("resource.0.interval");
                   8051:                     } else {
                   8052:                         if ($item =~ /___\d+___/) {
                   8053:                             $type = 'resource';
                   8054:                             @interval=&EXT("resource.0.interval",$item);
                   8055:                             if (ref($navmap)) {
                   8056:                                 my $res = $navmap->getBySymb($item);
                   8057:                                 push(@to_test,$res);
                   8058:                             }
1.1162    raeburn  8059:                         } else {
1.1172.2.66  raeburn  8060:                             my $mapsymb = &symbread($item,1);
                   8061:                             if ($mapsymb) {
                   8062:                                 if (ref($navmap)) {
                   8063:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8064:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8065:                                     foreach my $res (@to_test) {
                   8066:                                         my $symb = $res->symb();
                   8067:                                         next if ($symb eq $mapsymb);
                   8068:                                         if ($symb ne '') {
                   8069:                                             @interval=&EXT("resource.0.interval",$symb);
                   8070:                                             if ($interval[1] eq 'map') {
                   8071:                                                 last;
1.1162    raeburn  8072:                                             }
                   8073:                                         }
                   8074:                                     }
                   8075:                                 }
                   8076:                             }
                   8077:                         }
1.1172.2.66  raeburn  8078:                     }
                   8079:                     if ($interval[0] =~ /^\d+$/) {
                   8080:                         my $first_access;
                   8081:                         if ($type eq 'resource') {
                   8082:                             $first_access=&get_first_access($interval[1],$item);
                   8083:                         } elsif ($type eq 'map') {
                   8084:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8085:                         } else {
                   8086:                             $first_access=&get_first_access($interval[1]);
                   8087:                         }
                   8088:                         if ($first_access) {
                   8089:                             my $timesup = $first_access+$interval[0];
                   8090:                             if ($timesup > $now) {
                   8091:                                 my $activeblock;
                   8092:                                 foreach my $res (@to_test) {
                   8093:                                     if ($res->answerable()) {
                   8094:                                         $activeblock = 1;
                   8095:                                         last;
                   8096:                                     }
                   8097:                                 }
                   8098:                                 if ($activeblock) {
                   8099:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8100:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8101:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8102:                                          }
                   8103:                                     }
                   8104:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8105:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8106:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8107:                                         }
1.1162    raeburn  8108:                                     }
                   8109:                                 }
                   8110:                             }
                   8111:                         }
                   8112:                     }
                   8113:                 }
                   8114:             }
                   8115:         }
                   8116:     }
1.1172.2.66  raeburn  8117:     return %blockers;
1.1162    raeburn  8118: }
                   8119: 
1.1172.2.66  raeburn  8120: sub has_comm_blocking {
                   8121:     my ($priv,$symb,$uri,$blocks) = @_;
                   8122:     my @blockers;
                   8123:     return unless ($env{'request.course.id'});
                   8124:     return unless ($priv eq 'bre');
                   8125:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8126:     return if ($env{'request.state'} eq 'construct');
                   8127:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8128:     return unless (keys(%cachedblockers) > 0);
                   8129:     my (%possibles,@symbs);
                   8130:     if (!$symb) {
                   8131:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8132:     }
1.1172.2.66  raeburn  8133:     if ($symb) {
                   8134:         @symbs = ($symb);
                   8135:     } elsif (keys(%possibles)) {
                   8136:         @symbs = keys(%possibles);
                   8137:     }
                   8138:     my $noblock;
                   8139:     foreach my $symb (@symbs) {
                   8140:         last if ($noblock);
                   8141:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8142:         foreach my $block (keys(%cachedblockers)) {
                   8143:             if ($block =~ /^firstaccess____(.+)$/) {
                   8144:                 my $item = $1;
                   8145:                 if (($item eq $map) || ($item eq $symb)) {
                   8146:                     $noblock = 1;
                   8147:                     last;
                   8148:                 }
1.1162    raeburn  8149:             }
1.1172.2.66  raeburn  8150:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8151:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8152:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8153:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8154:                             push(@blockers,$block);
                   8155:                         }
                   8156:                     }
                   8157:                 }
                   8158:             }
                   8159:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8160:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8161:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8162:                         push(@blockers,$block);
                   8163:                     }
                   8164:                 }
1.1162    raeburn  8165:             }
                   8166:         }
                   8167:     }
1.1172.2.66  raeburn  8168:     return if ($noblock);
                   8169:     return @blockers;
                   8170: }
1.1162    raeburn  8171: }
                   8172: 
1.1172.2.66  raeburn  8173: # -------------------------------- Deversion and split uri into path an filename
                   8174: 
1.1133    foxr     8175: #
1.1172.2.66  raeburn  8176: #   Removes the version from a URI and
1.1133    foxr     8177: #   splits it in to its filename and path to the filename.
                   8178: #   Seems like File::Basename could have done this more clearly.
                   8179: #   Parameters:
                   8180: #      $uri   - input URI
                   8181: #   Returns:
                   8182: #     Two element list consisting of 
                   8183: #     $pathname  - the URI up to and excluding the trailing /
                   8184: #     $filename  - The part of the URI following the last /
                   8185: #  NOTE:
                   8186: #    Another realization of this is simply:
                   8187: #    use File::Basename;
                   8188: #    ...
                   8189: #    $uri = shift;
                   8190: #    $filename = basename($uri);
                   8191: #    $path     = dirname($uri);
                   8192: #    return ($filename, $path);
                   8193: #
                   8194: #     The implementation below is probably faster however.
                   8195: #
1.710     albertel 8196: sub split_uri_for_cond {
                   8197:     my $uri=&deversion(&declutter(shift));
                   8198:     my @uriparts=split(/\//,$uri);
                   8199:     my $filename=pop(@uriparts);
                   8200:     my $pathname=join('/',@uriparts);
                   8201:     return ($pathname,$filename);
                   8202: }
1.232     www      8203: # --------------------------------------------------- Is a resource on the map?
                   8204: 
                   8205: sub is_on_map {
1.710     albertel 8206:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8207:     #Trying to find the conditional for the file
1.620     albertel 8208:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8209: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8210:     if ($match) {
1.289     bowersj2 8211: 	return (1,$1);
                   8212:     } else {
1.434     www      8213: 	return (0,0);
1.289     bowersj2 8214:     }
1.12      www      8215: }
                   8216: 
1.427     www      8217: # --------------------------------------------------------- Get symb from alias
                   8218: 
                   8219: sub get_symb_from_alias {
                   8220:     my $symb=shift;
                   8221:     my ($map,$resid,$url)=&decode_symb($symb);
                   8222: # Already is a symb
                   8223:     if ($url) { return $symb; }
                   8224: # Must be an alias
                   8225:     my $aliassymb='';
                   8226:     my %bighash;
1.620     albertel 8227:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8228:                             &GDBM_READER(),0640)) {
                   8229:         my $rid=$bighash{'mapalias_'.$symb};
                   8230: 	if ($rid) {
                   8231: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8232: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8233: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8234: 	}
                   8235:         untie %bighash;
                   8236:     }
                   8237:     return $aliassymb;
                   8238: }
                   8239: 
1.12      www      8240: # ----------------------------------------------------------------- Define Role
                   8241: 
                   8242: sub definerole {
                   8243:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8244:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8245:     foreach my $role (split(':',$sysrole)) {
                   8246: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8247:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8248:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8249: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8250:                return "refused:s:$crole&$cqual"; 
                   8251:             }
                   8252:         }
1.191     harris41 8253:     }
1.800     albertel 8254:     foreach my $role (split(':',$domrole)) {
                   8255: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8256:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8257:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8258: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8259:                return "refused:d:$crole&$cqual"; 
                   8260:             }
                   8261:         }
1.191     harris41 8262:     }
1.800     albertel 8263:     foreach my $role (split(':',$courole)) {
                   8264: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8265:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8266:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8267: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8268:                return "refused:c:$crole&$cqual"; 
                   8269:             }
                   8270:         }
1.191     harris41 8271:     }
1.1172.2.84  raeburn  8272:     my $uhome;
                   8273:     if (($uname ne '') && ($udom ne '')) {
                   8274:         $uhome = &homeserver($uname,$udom);
                   8275:         return $uhome if ($uhome eq 'no_host');
                   8276:     } else {
                   8277:         $uname = $env{'user.name'};
                   8278:         $udom = $env{'user.domain'};
                   8279:         $uhome = $env{'user.home'};
                   8280:     }
1.620     albertel 8281:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8282:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8283:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8284:     return reply($command,$uhome);
1.12      www      8285:   } else {
                   8286:     return 'refused';
                   8287:   }
1.105     harris41 8288: }
                   8289: 
                   8290: # ---------------- Make a metadata query against the network of library servers
                   8291: 
                   8292: sub metadata_query {
1.1172.2.33  raeburn  8293:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8294:     my %rhash;
1.845     albertel 8295:     my %libserv = &all_library();
1.244     matthew  8296:     my @server_list = (defined($server_array) ? @$server_array
                   8297:                                               : keys(%libserv) );
                   8298:     for my $server (@server_list) {
1.1172.2.33  raeburn  8299:         my $domains = '';
                   8300:         if (ref($domains_hash) eq 'HASH') {
                   8301:             $domains = $domains_hash->{$server};    
                   8302:         }
1.118     harris41 8303: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8304: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8305: 	    $rhash{$server}=$reply;
                   8306: 	}
                   8307: 	else {
                   8308: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8309: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8310: 			     $server);
                   8311: 	    $rhash{$server}=$reply;
                   8312: 	}
1.112     harris41 8313:     }
1.118     harris41 8314:     return \%rhash;
1.240     www      8315: }
                   8316: 
                   8317: # ----------------------------------------- Send log queries and wait for reply
                   8318: 
                   8319: sub log_query {
                   8320:     my ($uname,$udom,$query,%filters)=@_;
                   8321:     my $uhome=&homeserver($uname,$udom);
                   8322:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8323:     my $uhost=&hostname($uhome);
1.800     albertel 8324:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8325:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8326:                        $uhome);
1.479     albertel 8327:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8328:     return get_query_reply($queryid);
                   8329: }
                   8330: 
1.818     raeburn  8331: # -------------------------- Update MySQL table for portfolio file
                   8332: 
                   8333: sub update_portfolio_table {
1.821     raeburn  8334:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8335:     if ($group ne '') {
                   8336:         $file_name =~s /^\Q$group\E//;
                   8337:     }
1.818     raeburn  8338:     my $homeserver = &homeserver($uname,$udom);
                   8339:     my $queryid=
1.821     raeburn  8340:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8341:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8342:     my $reply = &get_query_reply($queryid);
                   8343:     return $reply;
                   8344: }
                   8345: 
1.899     raeburn  8346: # -------------------------- Update MySQL allusers table
                   8347: 
                   8348: sub update_allusers_table {
                   8349:     my ($uname,$udom,$names) = @_;
                   8350:     my $homeserver = &homeserver($uname,$udom);
                   8351:     my $queryid=
                   8352:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8353:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8354:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8355:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8356:                'generation='.&escape($names->{'generation'}).'%%'.
                   8357:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8358:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8359:     return;
1.899     raeburn  8360: }
                   8361: 
1.508     raeburn  8362: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8363: 
                   8364: sub fetch_enrollment_query {
1.511     raeburn  8365:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8366:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8367:     my $maxtries = 1;
1.508     raeburn  8368:     if ($context eq 'automated') {
                   8369:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8370:         $sleep = 2;
                   8371:         $loopmax = 100;
1.547     raeburn  8372:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8373:     } else {
                   8374:         $homeserver = &homeserver($cnum,$dom);
                   8375:     }
1.838     albertel 8376:     my $host=&hostname($homeserver);
1.506     raeburn  8377:     my $cmd = '';
1.1000    raeburn  8378:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8379:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8380:     }
                   8381:     $cmd =~ s/%%$//;
                   8382:     $cmd = &escape($cmd);
                   8383:     my $query = 'fetchenrollment';
1.620     albertel 8384:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8385:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8386:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8387:         return 'error: '.$queryid;
                   8388:     }
1.1172.2.93  raeburn  8389:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8390:     my $tries = 1;
                   8391:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8392:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8393:         $tries ++;
                   8394:     }
1.526     raeburn  8395:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8396:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8397:     } else {
1.901     albertel 8398:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8399:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8400:             foreach my $line (@responses) {
                   8401:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8402:                 $$replyref{$key} = $value;
                   8403:             }
                   8404:         } else {
1.1117    foxr     8405:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8406:             foreach my $line (@responses) {
                   8407:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8408:                 $$replyref{$key} = $value;
                   8409:                 if ($value > 0) {
1.800     albertel 8410:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8411:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8412:                         my $destname = $pathname.'/'.$filename;
                   8413:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8414:                         if ($xml_classlist =~ /^error/) {
                   8415:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8416:                         } else {
1.1172.2.96  raeburn  8417:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8418:                                 print FILE &unescape($xml_classlist);
                   8419:                                 close(FILE);
1.526     raeburn  8420:                             } else {
                   8421:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8422:                             }
                   8423:                         }
                   8424:                     }
                   8425:                 }
                   8426:             }
                   8427:         }
                   8428:         return 'ok';
                   8429:     }
                   8430:     return 'error';
                   8431: }
                   8432: 
1.242     www      8433: sub get_query_reply {
1.1172.2.79  raeburn  8434:     my ($queryid,$sleep,$loopmax) = @_;
                   8435:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8436:         $sleep = 0.2;
                   8437:     }
                   8438:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8439:         $loopmax = 100;
                   8440:     }
1.1117    foxr     8441:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8442:     my $reply='';
1.1172.2.79  raeburn  8443:     for (1..$loopmax) {
                   8444: 	sleep($sleep);
1.240     www      8445:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8446: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8447: 		$reply = join('',<$fh>);
                   8448: 		close($fh);
1.240     www      8449: 	   } else { return 'error: reply_file_error'; }
1.242     www      8450:            return &unescape($reply);
                   8451: 	}
1.240     www      8452:     }
1.242     www      8453:     return 'timeout:'.$queryid;
1.240     www      8454: }
                   8455: 
                   8456: sub courselog_query {
1.241     www      8457: #
                   8458: # possible filters:
                   8459: # url: url or symb
                   8460: # username
                   8461: # domain
                   8462: # action: view, submit, grade
                   8463: # start: timestamp
                   8464: # end: timestamp
                   8465: #
1.240     www      8466:     my (%filters)=@_;
1.620     albertel 8467:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8468:     if ($filters{'url'}) {
                   8469: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8470:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8471:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8472:     }
1.620     albertel 8473:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8474:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8475:     return &log_query($cname,$cdom,'courselog',%filters);
                   8476: }
                   8477: 
                   8478: sub userlog_query {
1.858     raeburn  8479: #
                   8480: # possible filters:
                   8481: # action: log check role
                   8482: # start: timestamp
                   8483: # end: timestamp
                   8484: #
1.240     www      8485:     my ($uname,$udom,%filters)=@_;
                   8486:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8487: }
                   8488: 
1.506     raeburn  8489: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8490: 
                   8491: sub auto_run {
1.508     raeburn  8492:     my ($cnum,$cdom) = @_;
1.876     raeburn  8493:     my $response = 0;
                   8494:     my $settings;
                   8495:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8496:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8497:         $settings = $domconfig{'autoenroll'};
                   8498:         if ($settings->{'run'} eq '1') {
                   8499:             $response = 1;
                   8500:         }
                   8501:     } else {
1.934     raeburn  8502:         my $homeserver;
                   8503:         if (&is_course($cdom,$cnum)) {
                   8504:             $homeserver = &homeserver($cnum,$cdom);
                   8505:         } else {
                   8506:             $homeserver = &domain($cdom,'primary');
                   8507:         }
                   8508:         if ($homeserver ne 'no_host') {
                   8509:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8510:         }
1.876     raeburn  8511:     }
1.506     raeburn  8512:     return $response;
                   8513: }
1.776     albertel 8514: 
1.506     raeburn  8515: sub auto_get_sections {
1.508     raeburn  8516:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8517:     my $homeserver;
                   8518:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8519:         $homeserver = &homeserver($cnum,$cdom);
                   8520:     }
                   8521:     if (!defined($homeserver)) { 
                   8522:         if ($cdom =~ /^$match_domain$/) {
                   8523:             $homeserver = &domain($cdom,'primary');
                   8524:         }
                   8525:     }
                   8526:     my @secs;
                   8527:     if (defined($homeserver)) {
                   8528:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8529:         unless ($response eq 'refused') {
                   8530:             @secs = split(/:/,$response);
                   8531:         }
1.506     raeburn  8532:     }
                   8533:     return @secs;
                   8534: }
1.776     albertel 8535: 
1.506     raeburn  8536: sub auto_new_course {
1.1099    raeburn  8537:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8538:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8539:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8540:     return $response;
                   8541: }
1.776     albertel 8542: 
1.506     raeburn  8543: sub auto_validate_courseID {
1.508     raeburn  8544:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8545:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8546:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8547:     return $response;
                   8548: }
1.776     albertel 8549: 
1.1007    raeburn  8550: sub auto_validate_instcode {
1.1020    raeburn  8551:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8552:     my ($homeserver,$response);
                   8553:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8554:         $homeserver = &homeserver($cnum,$cdom);
                   8555:     }
                   8556:     if (!defined($homeserver)) {
                   8557:         if ($cdom =~ /^$match_domain$/) {
                   8558:             $homeserver = &domain($cdom,'primary');
                   8559:         }
                   8560:     }
1.1065    raeburn  8561:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8562:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8563:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8564:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8565: }
                   8566: 
1.506     raeburn  8567: sub auto_create_password {
1.873     raeburn  8568:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8569:     my ($homeserver,$response);
1.506     raeburn  8570:     my $create_passwd = 0;
                   8571:     my $authchk = '';
1.873     raeburn  8572:     if ($udom =~ /^$match_domain$/) {
                   8573:         $homeserver = &domain($udom,'primary');
                   8574:     }
                   8575:     if ($homeserver eq '') {
                   8576:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8577:             $homeserver = &homeserver($cnum,$cdom);
                   8578:         }
                   8579:     }
                   8580:     if ($homeserver eq '') {
                   8581:         $authchk = 'nodomain';
1.506     raeburn  8582:     } else {
1.873     raeburn  8583:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8584:         if ($response eq 'refused') {
                   8585:             $authchk = 'refused';
                   8586:         } else {
1.901     albertel 8587:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8588:         }
1.506     raeburn  8589:     }
                   8590:     return ($authparam,$create_passwd,$authchk);
                   8591: }
                   8592: 
1.706     raeburn  8593: sub auto_photo_permission {
                   8594:     my ($cnum,$cdom,$students) = @_;
                   8595:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8596:     my ($outcome,$perm_reqd,$conditions) = 
                   8597: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8598:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8599: 	return (undef,undef);
                   8600:     }
1.706     raeburn  8601:     return ($outcome,$perm_reqd,$conditions);
                   8602: }
                   8603: 
                   8604: sub auto_checkphotos {
                   8605:     my ($uname,$udom,$pid) = @_;
                   8606:     my $homeserver = &homeserver($uname,$udom);
                   8607:     my ($result,$resulttype);
                   8608:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8609: 				   &escape($uname).':'.&escape($pid),
                   8610: 				   $homeserver));
1.709     albertel 8611:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8612: 	return (undef,undef);
                   8613:     }
1.706     raeburn  8614:     if ($outcome) {
                   8615:         ($result,$resulttype) = split(/:/,$outcome);
                   8616:     } 
                   8617:     return ($result,$resulttype);
                   8618: }
                   8619: 
                   8620: sub auto_photochoice {
                   8621:     my ($cnum,$cdom) = @_;
                   8622:     my $homeserver = &homeserver($cnum,$cdom);
                   8623:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8624: 						       &escape($cdom),
                   8625: 						       $homeserver)));
1.709     albertel 8626:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8627: 	return (undef,undef);
                   8628:     }
1.706     raeburn  8629:     return ($update,$comment);
                   8630: }
                   8631: 
                   8632: sub auto_photoupdate {
                   8633:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8634:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8635:     my $host=&hostname($homeserver);
1.706     raeburn  8636:     my $cmd = '';
                   8637:     my $maxtries = 1;
1.800     albertel 8638:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8639:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8640:     }
                   8641:     $cmd =~ s/%%$//;
                   8642:     $cmd = &escape($cmd);
                   8643:     my $query = 'institutionalphotos';
                   8644:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8645:     unless ($queryid=~/^\Q$host\E\_/) {
                   8646:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8647:         return 'error: '.$queryid;
                   8648:     }
                   8649:     my $reply = &get_query_reply($queryid);
                   8650:     my $tries = 1;
                   8651:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8652:         $reply = &get_query_reply($queryid);
                   8653:         $tries ++;
                   8654:     }
                   8655:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8656:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8657:     } else {
                   8658:         my @responses = split(/:/,$reply);
                   8659:         my $outcome = shift(@responses); 
                   8660:         foreach my $item (@responses) {
                   8661:             my ($key,$value) = split(/=/,$item);
                   8662:             $$photo{$key} = $value;
                   8663:         }
                   8664:         return $outcome;
                   8665:     }
                   8666:     return 'error';
                   8667: }
                   8668: 
1.521     raeburn  8669: sub auto_instcode_format {
1.793     albertel 8670:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8671: 	$cat_order) = @_;
1.521     raeburn  8672:     my $courses = '';
1.772     raeburn  8673:     my @homeservers;
1.521     raeburn  8674:     if ($caller eq 'global') {
1.841     albertel 8675: 	my %servers = &get_servers($codedom,'library');
                   8676: 	foreach my $tryserver (keys(%servers)) {
                   8677: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8678: 		push(@homeservers,$tryserver);
                   8679: 	    }
1.584     raeburn  8680:         }
1.1022    raeburn  8681:     } elsif ($caller eq 'requests') {
                   8682:         if ($codedom =~ /^$match_domain$/) {
                   8683:             my $chome = &domain($codedom,'primary');
                   8684:             unless ($chome eq 'no_host') {
                   8685:                 push(@homeservers,$chome);
                   8686:             }
                   8687:         }
1.521     raeburn  8688:     } else {
1.772     raeburn  8689:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8690:     }
1.793     albertel 8691:     foreach my $code (keys(%{$instcodes})) {
                   8692:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8693:     }
                   8694:     chop($courses);
1.772     raeburn  8695:     my $ok_response = 0;
                   8696:     my $response;
                   8697:     while (@homeservers > 0 && $ok_response == 0) {
                   8698:         my $server = shift(@homeservers); 
                   8699:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8700:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8701:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8702: 		split(/:/,$response);
1.772     raeburn  8703:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8704:             push(@{$codetitles},&str2array($codetitles_str));
                   8705:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8706:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8707:             $ok_response = 1;
                   8708:         }
                   8709:     }
                   8710:     if ($ok_response) {
1.521     raeburn  8711:         return 'ok';
1.772     raeburn  8712:     } else {
                   8713:         return $response;
1.521     raeburn  8714:     }
                   8715: }
                   8716: 
1.792     raeburn  8717: sub auto_instcode_defaults {
                   8718:     my ($domain,$returnhash,$code_order) = @_;
                   8719:     my @homeservers;
1.841     albertel 8720: 
                   8721:     my %servers = &get_servers($domain,'library');
                   8722:     foreach my $tryserver (keys(%servers)) {
                   8723: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8724: 	    push(@homeservers,$tryserver);
                   8725: 	}
1.792     raeburn  8726:     }
1.841     albertel 8727: 
1.792     raeburn  8728:     my $response;
1.841     albertel 8729:     foreach my $server (@homeservers) {
1.792     raeburn  8730:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8731:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8732: 	
                   8733: 	foreach my $pair (split(/\&/,$response)) {
                   8734: 	    my ($name,$value)=split(/\=/,$pair);
                   8735: 	    if ($name eq 'code_order') {
                   8736: 		@{$code_order} = split(/\&/,&unescape($value));
                   8737: 	    } else {
                   8738: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8739: 	    }
                   8740: 	}
                   8741: 	return 'ok';
1.792     raeburn  8742:     }
1.841     albertel 8743: 
                   8744:     return $response;
1.1003    raeburn  8745: }
                   8746: 
                   8747: sub auto_possible_instcodes {
1.1007    raeburn  8748:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8749:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8750:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8751:         return;
                   8752:     }
1.1003    raeburn  8753:     my (@homeservers,$uhome);
                   8754:     if (defined(&domain($domain,'primary'))) {
                   8755:         $uhome=&domain($domain,'primary');
                   8756:         push(@homeservers,&domain($domain,'primary'));
                   8757:     } else {
                   8758:         my %servers = &get_servers($domain,'library');
                   8759:         foreach my $tryserver (keys(%servers)) {
                   8760:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8761:                 push(@homeservers,$tryserver);
                   8762:             }
                   8763:         }
                   8764:     }
                   8765:     my $response;
                   8766:     foreach my $server (@homeservers) {
                   8767:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8768:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8769:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8770:             split(':',$response);
                   8771:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8772:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8773:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8774:             my ($name,$value)=split('=',$item);
                   8775:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8776:         }
                   8777:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8778:             my ($name,$value)=split('=',$item);
                   8779:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8780:         }
                   8781:         return 'ok';
                   8782:     }
                   8783:     return $response;
                   8784: }
1.792     raeburn  8785: 
1.1010    raeburn  8786: sub auto_courserequest_checks {
                   8787:     my ($dom) = @_;
1.1020    raeburn  8788:     my ($homeserver,%validations);
                   8789:     if ($dom =~ /^$match_domain$/) {
                   8790:         $homeserver = &domain($dom,'primary');
                   8791:     }
                   8792:     unless ($homeserver eq 'no_host') {
                   8793:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8794:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8795:             my @items = split(/&/,$response);
                   8796:             foreach my $item (@items) {
                   8797:                 my ($key,$value) = split('=',$item);
                   8798:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8799:             }
                   8800:         }
                   8801:     }
1.1010    raeburn  8802:     return %validations; 
                   8803: }
                   8804: 
1.1020    raeburn  8805: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8806:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8807:     my ($homeserver,$response);
                   8808:     if ($dom =~ /^$match_domain$/) {
                   8809:         $homeserver = &domain($dom,'primary');
                   8810:     }
1.1172.2.43  raeburn  8811:     unless ($homeserver eq 'no_host') {
                   8812:         my $customdata;
                   8813:         if (ref($custominfo) eq 'HASH') {
                   8814:             $customdata = &freeze_escape($custominfo);
                   8815:         }
1.1020    raeburn  8816:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8817:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8818:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8819:                                     $customdata,$homeserver));
1.1020    raeburn  8820:     }
                   8821:     return $response;
                   8822: }
                   8823: 
1.777     albertel 8824: sub auto_validate_class_sec {
1.918     raeburn  8825:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8826:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8827:     my $ownerlist;
                   8828:     if (ref($owners) eq 'ARRAY') {
                   8829:         $ownerlist = join(',',@{$owners});
                   8830:     } else {
                   8831:         $ownerlist = $owners;
                   8832:     }
1.773     raeburn  8833:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8834:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8835:     return $response;
                   8836: }
                   8837: 
1.1172.2.94  raeburn  8838: sub auto_validate_instclasses {
                   8839:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8840:     my ($homeserver,%validations);
                   8841:     $homeserver = &homeserver($cnum,$cdom);
                   8842:     unless ($homeserver eq 'no_host') {
                   8843:         my $ownerlist;
                   8844:         if (ref($owners) eq 'ARRAY') {
                   8845:             $ownerlist = join(',',@{$owners});
                   8846:         } else {
                   8847:             $ownerlist = $owners;
                   8848:         }
                   8849:         if (ref($classesref) eq 'HASH') {
                   8850:             my $classes = &freeze_escape($classesref);
                   8851:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8852:                                 ':'.$cdom.':'.$classes,$homeserver);
                   8853:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8854:                 my @items = split(/&/,$response);
                   8855:                 foreach my $item (@items) {
                   8856:                     my ($key,$value) = split('=',$item);
                   8857:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8858:                 }
                   8859:             }
                   8860:         }
                   8861:     }
                   8862:     return %validations;
                   8863: }
                   8864: 
1.1172.2.38  raeburn  8865: sub auto_crsreq_update {
                   8866:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8867:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8868:     my ($homeserver,%crsreqresponse);
                   8869:     if ($cdom =~ /^$match_domain$/) {
                   8870:         $homeserver = &domain($cdom,'primary');
                   8871:     }
                   8872:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8873:         my $info;
                   8874:         if (ref($inbound) eq 'HASH') {
                   8875:             $info = &freeze_escape($inbound);
                   8876:         }
                   8877:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8878:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8879:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8880:                             &escape($title).':'.&escape($code).':'.
                   8881:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8882:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8883:             my @items = split(/&/,$response);
                   8884:             foreach my $item (@items) {
                   8885:                 my ($key,$value) = split('=',$item);
                   8886:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8887:             }
                   8888:         }
                   8889:     }
                   8890:     return \%crsreqresponse;
                   8891: }
                   8892: 
1.1172.2.78  raeburn  8893: sub auto_export_grades {
                   8894:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8895:     my ($homeserver,%exportresponse);
                   8896:     if ($cdom =~ /^$match_domain$/) {
                   8897:         $homeserver = &domain($cdom,'primary');
                   8898:     }
                   8899:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8900:         my $info;
                   8901:         if (ref($inforef) eq 'HASH') {
                   8902:             $info = &freeze_escape($inforef);
                   8903:         }
                   8904:         if (ref($gradesref) eq 'HASH') {
                   8905:             my $grades = &freeze_escape($gradesref);
                   8906:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8907:                                 $info.':'.$grades,$homeserver);
                   8908:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8909:                 my @items = split(/&/,$response);
                   8910:                 foreach my $item (@items) {
                   8911:                     my ($key,$value) = split('=',$item);
                   8912:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8913:                 }
                   8914:             }
                   8915:         }
                   8916:     }
                   8917:     return \%exportresponse;
                   8918: }
                   8919: 
1.1172.2.68  raeburn  8920: sub check_instcode_cloning {
                   8921:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8922:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8923:         return;
                   8924:     }
                   8925:     my $canclone;
                   8926:     if (@{$code_order} > 0) {
                   8927:         my $instcoderegexp ='^';
                   8928:         my @clonecodes = split(/\&/,$cloner);
                   8929:         foreach my $item (@{$code_order}) {
                   8930:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8931:                 foreach my $pair (@clonecodes) {
                   8932:                     my ($key,$val) = split(/\=/,$pair,2);
                   8933:                     $val = &unescape($val);
                   8934:                     if ($key eq $item) {
                   8935:                         $instcoderegexp .= '('.$val.')';
                   8936:                         last;
                   8937:                     }
                   8938:                 }
                   8939:             } else {
                   8940:                 $instcoderegexp .= $codedefaults->{$item};
                   8941:             }
                   8942:         }
                   8943:         $instcoderegexp .= '$';
                   8944:         my (@from,@to);
                   8945:         eval {
                   8946:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8947:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8948:         };
                   8949:         if ((@from > 0) && (@to > 0)) {
                   8950:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8951:             if (!@diffs) {
                   8952:                 $canclone = 1;
                   8953:             }
                   8954:         }
                   8955:     }
                   8956:     return $canclone;
                   8957: }
                   8958: 
                   8959: sub default_instcode_cloning {
                   8960:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8961:     my (%codedefaults,@code_order,$canclone);
                   8962:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8963:         %codedefaults = %{$codedefaultsref};
                   8964:         @code_order = @{$codeorderref};
                   8965:     } elsif ($clonedom) {
                   8966:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8967:     }
                   8968:     if (($domdefclone) && (@code_order)) {
                   8969:         my @clonecodes = split(/\+/,$domdefclone);
                   8970:         my $instcoderegexp ='^';
                   8971:         foreach my $item (@code_order) {
                   8972:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8973:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8974:             } else {
                   8975:                 $instcoderegexp .= $codedefaults{$item};
                   8976:             }
                   8977:         }
                   8978:         $instcoderegexp .= '$';
                   8979:         my (@from,@to);
                   8980:         eval {
                   8981:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8982:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8983:         };
                   8984:         if ((@from > 0) && (@to > 0)) {
                   8985:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8986:             if (!@diffs) {
                   8987:                 $canclone = 1;
                   8988:             }
                   8989:         }
                   8990:     }
                   8991:     return $canclone;
                   8992: }
                   8993: 
1.679     raeburn  8994: # ------------------------------------------------------- Course Group routines
                   8995: 
                   8996: sub get_coursegroups {
1.809     raeburn  8997:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8998:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8999: }
                   9000: 
1.679     raeburn  9001: sub modify_coursegroup {
                   9002:     my ($cdom,$cnum,$groupsettings) = @_;
                   9003:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9004: }
                   9005: 
1.809     raeburn  9006: sub toggle_coursegroup_status {
                   9007:     my ($cdom,$cnum,$group,$action) = @_;
                   9008:     my ($from_namespace,$to_namespace);
                   9009:     if ($action eq 'delete') {
                   9010:         $from_namespace = 'coursegroups';
                   9011:         $to_namespace = 'deleted_groups';
                   9012:     } else {
                   9013:         $from_namespace = 'deleted_groups';
                   9014:         $to_namespace = 'coursegroups';
                   9015:     }
                   9016:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9017:     if (my $tmp = &error(%curr_group)) {
                   9018:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9019:         return ('read error',$tmp);
                   9020:     } else {
                   9021:         my %savedsettings = %curr_group; 
1.809     raeburn  9022:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9023:         my $deloutcome;
                   9024:         if ($result eq 'ok') {
1.809     raeburn  9025:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9026:         } else {
                   9027:             return ('write error',$result);
                   9028:         }
                   9029:         if ($deloutcome eq 'ok') {
                   9030:             return 'ok';
                   9031:         } else {
                   9032:             return ('delete error',$deloutcome);
                   9033:         }
                   9034:     }
                   9035: }
                   9036: 
1.679     raeburn  9037: sub modify_group_roles {
1.957     raeburn  9038:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9039:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9040:     my $role = 'gr/'.&escape($userprivs);
                   9041:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9042:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9043:     if ($result eq 'ok') {
                   9044:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9045:     }
1.679     raeburn  9046:     return $result;
                   9047: }
                   9048: 
                   9049: sub modify_coursegroup_membership {
                   9050:     my ($cdom,$cnum,$membership) = @_;
                   9051:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9052:     return $result;
                   9053: }
                   9054: 
1.682     raeburn  9055: sub get_active_groups {
                   9056:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9057:     my $now = time;
                   9058:     my %groups = ();
                   9059:     foreach my $key (keys(%env)) {
1.811     albertel 9060:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9061:             my ($start,$end) = split(/\./,$env{$key});
                   9062:             if (($end!=0) && ($end<$now)) { next; }
                   9063:             if (($start!=0) && ($start>$now)) { next; }
                   9064:             if ($1 eq $cdom && $2 eq $cnum) {
                   9065:                 $groups{$3} = $env{$key} ;
                   9066:             }
                   9067:         }
                   9068:     }
                   9069:     return %groups;
                   9070: }
                   9071: 
1.683     raeburn  9072: sub get_group_membership {
                   9073:     my ($cdom,$cnum,$group) = @_;
                   9074:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9075: }
                   9076: 
                   9077: sub get_users_groups {
                   9078:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9079:     my @usersgroups;
1.683     raeburn  9080:     my $cachetime=1800;
                   9081: 
                   9082:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9083:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9084:     if (defined($cached)) {
1.734     albertel 9085:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9086:     } else {  
                   9087:         $grouplist = '';
1.816     raeburn  9088:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9089:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9090:         my $access_end = $env{'course.'.$courseid.
                   9091:                               '.default_enrollment_end_date'};
                   9092:         my $now = time;
                   9093:         foreach my $key (keys(%roleshash)) {
                   9094:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9095:                 my $group = $1;
                   9096:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9097:                     my $start = $2;
                   9098:                     my $end = $1;
                   9099:                     if ($start == -1) { next; } # deleted from group
                   9100:                     if (($start!=0) && ($start>$now)) { next; }
                   9101:                     if (($end!=0) && ($end<$now)) {
                   9102:                         if ($access_end && $access_end < $now) {
                   9103:                             if ($access_end - $end < 86400) {
                   9104:                                 push(@usersgroups,$group);
1.733     raeburn  9105:                             }
                   9106:                         }
1.817     raeburn  9107:                         next;
1.733     raeburn  9108:                     }
1.817     raeburn  9109:                     push(@usersgroups,$group);
1.683     raeburn  9110:                 }
                   9111:             }
                   9112:         }
1.817     raeburn  9113:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9114:         $grouplist = join(':',@usersgroups);
                   9115:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9116:     }
1.733     raeburn  9117:     return @usersgroups;
1.683     raeburn  9118: }
                   9119: 
                   9120: sub devalidate_getgroups_cache {
                   9121:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9122:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9123: 
1.683     raeburn  9124:     my $hashid="$udom:$uname:$courseid";
                   9125:     &devalidate_cache_new('getgroups',$hashid);
                   9126: }
                   9127: 
1.12      www      9128: # ------------------------------------------------------------------ Plain Text
                   9129: 
                   9130: sub plaintext {
1.988     raeburn  9131:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9132:     if ($short =~ m{^cr/}) {
1.758     albertel 9133: 	return (split('/',$short))[-1];
                   9134:     }
1.742     raeburn  9135:     if (!defined($cid)) {
                   9136:         $cid = $env{'request.course.id'};
                   9137:     }
                   9138:     my %rolenames = (
1.1008    raeburn  9139:                       Course    => 'std',
                   9140:                       Community => 'alt1',
1.742     raeburn  9141:                     );
1.1037    raeburn  9142:     if ($cid ne '') {
                   9143:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9144:             unless ($forcedefault) {
                   9145:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9146:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9147:                 return &Apache::lonlocal::mt($roletext);
                   9148:             }
                   9149:         }
                   9150:     }
                   9151:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9152:         (defined($rolenames{$type})) && 
                   9153:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9154:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9155:     } elsif ($cid ne '') {
                   9156:         my $crstype = $env{'course.'.$cid.'.type'};
                   9157:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9158:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9159:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9160:         }
1.742     raeburn  9161:     }
1.1037    raeburn  9162:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9163: }
                   9164: 
                   9165: # ----------------------------------------------------------------- Assign Role
                   9166: 
                   9167: sub assignrole {
1.957     raeburn  9168:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9169:         $context)=@_;
1.21      www      9170:     my $mrole;
                   9171:     if ($role =~ /^cr\//) {
1.393     www      9172:         my $cwosec=$url;
1.811     albertel 9173:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9174: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9175:            my $refused = 1;
                   9176:            if ($context eq 'requestcourses') {
                   9177:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9178:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9179:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9180:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9181:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9182:                            if ($crsenv{'internal.courseowner'} eq
                   9183:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9184:                                $refused = '';
                   9185:                            }
                   9186:                        }
                   9187:                    }
                   9188:                }
                   9189:            }
                   9190:            if ($refused) {
                   9191:                &logthis('Refused custom assignrole: '.
                   9192:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9193:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9194:                return 'refused';
                   9195:            }
1.104     www      9196:         }
1.21      www      9197:         $mrole='cr';
1.678     raeburn  9198:     } elsif ($role =~ /^gr\//) {
                   9199:         my $cwogrp=$url;
1.811     albertel 9200:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9201:         unless (&allowed('mdg',$cwogrp)) {
                   9202:             &logthis('Refused group assignrole: '.
                   9203:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9204:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9205:             return 'refused';
                   9206:         }
                   9207:         $mrole='gr';
1.21      www      9208:     } else {
1.82      www      9209:         my $cwosec=$url;
1.811     albertel 9210:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9211:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9212:             my $refused;
                   9213:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9214:                 if (!(&allowed('c'.$role,$url))) {
                   9215:                     $refused = 1;
                   9216:                 }
                   9217:             } else {
                   9218:                 $refused = 1;
                   9219:             }
1.947     raeburn  9220:             if ($refused) {
1.1045    raeburn  9221:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9222:                 if (!$selfenroll && $context eq 'course') {
                   9223:                     my %crsenv;
                   9224:                     if ($role eq 'cc' || $role eq 'co') {
                   9225:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9226:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9227:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9228:                                 if ($crsenv{'internal.courseowner'} eq 
                   9229:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9230:                                     $refused = '';
                   9231:                                 }
                   9232:                             }
                   9233:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9234:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9235:                                 if ($crsenv{'internal.courseowner'} eq 
                   9236:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9237:                                     $refused = '';
                   9238:                                 }
                   9239:                             }
                   9240:                         }
                   9241:                     }
                   9242:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9243:                     $refused = '';
1.1017    raeburn  9244:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9245:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9246:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9247:                         my $wrongcc;
                   9248:                         if ($cnum =~ /^$match_community$/) {
                   9249:                             $wrongcc = 1 if ($role eq 'cc');
                   9250:                         } else {
                   9251:                             $wrongcc = 1 if ($role eq 'co');
                   9252:                         }
                   9253:                         unless ($wrongcc) {
                   9254:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9255:                             if ($crsenv{'internal.courseowner'} eq 
                   9256:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9257:                                 $refused = '';
                   9258:                             }
1.1017    raeburn  9259:                         }
                   9260:                     }
1.1172.2.9  raeburn  9261:                 } elsif ($context eq 'requestauthor') {
                   9262:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9263:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9264:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9265:                             $refused = '';
                   9266:                         } else {
                   9267:                             my %domdefaults = &get_domain_defaults($udom);
                   9268:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9269:                                 my $checkbystatus;
                   9270:                                 if ($env{'user.adv'}) {
                   9271:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9272:                                     if ($disposition eq 'automatic') {
                   9273:                                         $refused = '';
                   9274:                                     } elsif ($disposition eq '') {
                   9275:                                         $checkbystatus = 1;
                   9276:                                     }
                   9277:                                 } else {
                   9278:                                     $checkbystatus = 1;
                   9279:                                 }
                   9280:                                 if ($checkbystatus) {
                   9281:                                     if ($env{'environment.inststatus'}) {
                   9282:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9283:                                         foreach my $type (@inststatuses) {
                   9284:                                             if (($type ne '') &&
                   9285:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9286:                                                 $refused = '';
                   9287:                                             }
                   9288:                                         }
                   9289:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9290:                                         $refused = '';
                   9291:                                     }
                   9292:                                 }
                   9293:                             }
                   9294:                         }
                   9295:                     }
1.1017    raeburn  9296:                 }
                   9297:                 if ($refused) {
1.947     raeburn  9298:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9299:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9300: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9301:                     return 'refused';
                   9302:                 }
1.932     raeburn  9303:             }
1.1131    raeburn  9304:         } elsif ($role eq 'au') {
                   9305:             if ($url ne '/'.$udom.'/') {
                   9306:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9307:                          ' to assign author role for '.$uname.':'.$udom.
                   9308:                          ' in domain: '.$url.' refused (wrong domain).');
                   9309:                 return 'refused';
                   9310:             }
1.104     www      9311:         }
1.21      www      9312:         $mrole=$role;
                   9313:     }
1.620     albertel 9314:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9315:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9316:     if ($end) { $command.='_'.$end; }
1.21      www      9317:     if ($start) {
                   9318: 	if ($end) { 
1.81      www      9319:            $command.='_'.$start; 
1.21      www      9320:         } else {
1.81      www      9321:            $command.='_0_'.$start;
1.21      www      9322:         }
                   9323:     }
1.739     raeburn  9324:     my $origstart = $start;
                   9325:     my $origend = $end;
1.957     raeburn  9326:     my $delflag;
1.357     www      9327: # actually delete
                   9328:     if ($deleteflag) {
1.373     www      9329: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9330: # modify command to delete the role
1.620     albertel 9331:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9332:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9333: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9334: # set start and finish to negative values for userrolelog
                   9335:            $start=-1;
                   9336:            $end=-1;
1.957     raeburn  9337:            $delflag = 1;
1.357     www      9338:         }
                   9339:     }
                   9340: # send command
1.349     www      9341:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9342: # log new user role if status is ok
1.349     www      9343:     if ($answer eq 'ok') {
1.663     raeburn  9344: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9345:         if (($role eq 'cc') || ($role eq 'in') ||
                   9346:             ($role eq 'ep') || ($role eq 'ad') ||
                   9347:             ($role eq 'ta') || ($role eq 'st') ||
                   9348:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9349:             ($role eq 'co')) {
1.1172.2.13  raeburn  9350: # for course roles, perform group memberships changes triggered by role change.
                   9351:             unless ($role =~ /^gr/) {
                   9352:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9353:                                                  $origstart,$selfenroll,$context);
                   9354:             }
1.1172.2.9  raeburn  9355:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9356:                            $selfenroll,$context);
                   9357:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9358:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9359:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9360:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9361:                            $context);
                   9362:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9363:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9364:                              $context);
                   9365:         }
1.1053    raeburn  9366:         if ($role eq 'cc') {
                   9367:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9368:         }
1.349     www      9369:     }
                   9370:     return $answer;
1.169     harris41 9371: }
                   9372: 
1.1053    raeburn  9373: sub autoupdate_coowners {
                   9374:     my ($url,$end,$start,$uname,$udom) = @_;
                   9375:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9376:     if (($cdom ne '') && ($cnum ne '')) {
                   9377:         my $now = time;
                   9378:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9379:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9380:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9381:             my $instcode = $coursehash{'internal.coursecode'};
                   9382:             if ($instcode ne '') {
1.1056    raeburn  9383:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9384:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9385:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9386:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9387:                         if ($result eq 'valid') {
                   9388:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9389:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9390:                                     push(@newcoowners,$coowner);
                   9391:                                 }
                   9392:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9393:                                     push(@newcoowners,$uname.':'.$udom);
                   9394:                                 }
                   9395:                                 @newcoowners = sort(@newcoowners);
                   9396:                             } else {
                   9397:                                 push(@newcoowners,$uname.':'.$udom);
                   9398:                             }
                   9399:                         } else {
                   9400:                             if ($coursehash{'internal.co-owners'}) {
                   9401:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9402:                                     unless ($coowner eq $uname.':'.$udom) {
                   9403:                                         push(@newcoowners,$coowner);
                   9404:                                     }
                   9405:                                 }
                   9406:                                 unless (@newcoowners > 0) {
                   9407:                                     $delcoowners = 1;
                   9408:                                     $coowners = '';
                   9409:                                 }
                   9410:                             }
                   9411:                         }
                   9412:                         if (@newcoowners || $delcoowners) {
                   9413:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9414:                                             $delcoowners,@newcoowners);
                   9415:                         }
                   9416:                     }
                   9417:                 }
                   9418:             }
                   9419:         }
                   9420:     }
                   9421: }
                   9422: 
                   9423: sub store_coowners {
                   9424:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9425:     my $cid = $cdom.'_'.$cnum;
                   9426:     my ($coowners,$delresult,$putresult);
                   9427:     if (@newcoowners) {
                   9428:         $coowners = join(',',@newcoowners);
                   9429:         my %coownershash = (
                   9430:                             'internal.co-owners' => $coowners,
                   9431:                            );
                   9432:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9433:         if ($putresult eq 'ok') {
                   9434:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9435:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9436:             }
                   9437:         }
                   9438:     }
                   9439:     if ($delcoowners) {
                   9440:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9441:         if ($delresult eq 'ok') {
                   9442:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9443:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9444:             }
                   9445:         }
                   9446:     }
                   9447:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9448:         my %crsinfo =
                   9449:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9450:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9451:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9452:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9453:         }
                   9454:     }
                   9455: }
                   9456: 
1.169     harris41 9457: # -------------------------------------------------- Modify user authentication
1.197     www      9458: # Overrides without validation
                   9459: 
1.169     harris41 9460: sub modifyuserauth {
                   9461:     my ($udom,$uname,$umode,$upass)=@_;
                   9462:     my $uhome=&homeserver($uname,$udom);
1.197     www      9463:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9464:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9465:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9466:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9467:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9468: 		     &escape($upass),$uhome);
1.620     albertel 9469:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9470:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9471:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9472:     &log($udom,,$uname,$uhome,
1.620     albertel 9473:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9474:                                      $env{'user.name'}.', '.$umode.
1.197     www      9475:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9476:     unless ($reply eq 'ok') {
1.197     www      9477:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9478: 	return 'error: '.$reply;
                   9479:     }   
1.170     harris41 9480:     return 'ok';
1.80      www      9481: }
                   9482: 
1.81      www      9483: # --------------------------------------------------------------- Modify a user
1.80      www      9484: 
1.81      www      9485: sub modifyuser {
1.206     matthew  9486:     my ($udom,    $uname, $uid,
                   9487:         $umode,   $upass, $first,
                   9488:         $middle,  $last,  $gene,
1.1058    raeburn  9489:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9490:     $udom= &LONCAPA::clean_domain($udom);
                   9491:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9492:     my $showcandelete = 'none';
                   9493:     if (ref($candelete) eq 'ARRAY') {
                   9494:         if (@{$candelete} > 0) {
                   9495:             $showcandelete = join(', ',@{$candelete});
                   9496:         }
                   9497:     }
1.81      www      9498:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9499:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9500: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9501:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9502:                                      ' desiredhome not specified'). 
1.620     albertel 9503:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9504:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9505:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9506:     my $newuser;
                   9507:     if ($uhome eq 'no_host') {
                   9508:         $newuser = 1;
                   9509:     }
1.80      www      9510: # ----------------------------------------------------------------- Create User
1.406     albertel 9511:     if (($uhome eq 'no_host') && 
                   9512: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9513:         my $unhome='';
1.844     albertel 9514:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9515:             $unhome = $desiredhome;
1.620     albertel 9516: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9517: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9518:         } else { # load balancing routine for determining $unhome
1.81      www      9519:             my $loadm=10000000;
1.841     albertel 9520: 	    my %servers = &get_servers($udom,'library');
                   9521: 	    foreach my $tryserver (keys(%servers)) {
                   9522: 		my $answer=reply('load',$tryserver);
                   9523: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9524: 		    $loadm=$answer;
                   9525: 		    $unhome=$tryserver;
                   9526: 		}
1.80      www      9527: 	    }
                   9528:         }
                   9529:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9530: 	    return 'error: unable to find a home server for '.$uname.
                   9531:                    ' in domain '.$udom;
1.80      www      9532:         }
                   9533:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9534:                          &escape($upass),$unhome);
                   9535: 	unless ($reply eq 'ok') {
                   9536:             return 'error: '.$reply;
                   9537:         }   
1.230     stredwic 9538:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9539:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9540: 	    return 'error: unable verify users home machine.';
1.80      www      9541:         }
1.209     matthew  9542:     }   # End of creation of new user
1.80      www      9543: # ---------------------------------------------------------------------- Add ID
                   9544:     if ($uid) {
                   9545:        $uid=~tr/A-Z/a-z/;
                   9546:        my %uidhash=&idrget($udom,$uname);
1.196     www      9547:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9548:          && (!$forceid)) {
1.80      www      9549: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9550: 	      return 'error: user id "'.$uid.'" does not match '.
                   9551:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9552:           }
                   9553:        } else {
                   9554: 	  &idput($udom,($uname => $uid));
                   9555:        }
                   9556:     }
                   9557: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9558:     my @tmp=&get('environment',
1.899     raeburn  9559: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9560:                     'permanentemail','inststatus'],
1.134     albertel 9561: 		   $udom,$uname);
1.1075    raeburn  9562:     my (%names,%oldnames);
1.313     matthew  9563:     if ($tmp[0] =~ m/^error:.*/) { 
                   9564:         %names=(); 
                   9565:     } else {
                   9566:         %names = @tmp;
1.1075    raeburn  9567:         %oldnames = %names;
1.313     matthew  9568:     }
1.388     www      9569: #
1.1058    raeburn  9570: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9571: # of users did not contain them), do not overwrite existing values
                   9572: # unless field is in $candelete array ref.  
                   9573: #
                   9574: 
                   9575:     my @fields = ('firstname','middlename','lastname','generation',
                   9576:                   'permanentemail','id');
                   9577:     my %newvalues;
                   9578:     if (ref($candelete) eq 'ARRAY') {
                   9579:         foreach my $field (@fields) {
                   9580:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9581:                 if ($field eq 'firstname') {
                   9582:                     $names{$field} = $first;
                   9583:                 } elsif ($field eq 'middlename') {
                   9584:                     $names{$field} = $middle;
                   9585:                 } elsif ($field eq 'lastname') {
                   9586:                     $names{$field} = $last;
                   9587:                 } elsif ($field eq 'generation') { 
                   9588:                     $names{$field} = $gene;
                   9589:                 } elsif ($field eq 'permanentemail') {
                   9590:                     $names{$field} = $email;
                   9591:                 } elsif ($field eq 'id') {
                   9592:                     $names{$field}  = $uid;
                   9593:                 }
                   9594:             }
                   9595:         }
                   9596:     }
1.388     www      9597:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9598:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9599:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9600:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9601:     if ($email) {
                   9602:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9603:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9604:     }
1.899     raeburn  9605:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9606:     if (defined($inststatus)) {
                   9607:         $names{'inststatus'} = '';
                   9608:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9609:         if (ref($usertypes) eq 'HASH') {
                   9610:             my @okstatuses; 
                   9611:             foreach my $item (split(/:/,$inststatus)) {
                   9612:                 if (defined($usertypes->{$item})) {
                   9613:                     push(@okstatuses,$item);  
                   9614:                 }
                   9615:             }
                   9616:             if (@okstatuses) {
                   9617:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9618:             }
                   9619:         }
                   9620:     }
1.1075    raeburn  9621:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9622:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9623:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9624:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9625:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9626:     } else {
                   9627:         $logmsg .= ' during self creation';
                   9628:     }
1.1075    raeburn  9629:     my $changed;
                   9630:     if ($newuser) {
                   9631:         $changed = 1;
                   9632:     } else {
                   9633:         foreach my $field (@fields) {
                   9634:             if ($names{$field} ne $oldnames{$field}) {
                   9635:                 $changed = 1;
                   9636:                 last;
                   9637:             }
                   9638:         }
                   9639:     }
                   9640:     unless ($changed) {
                   9641:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9642:         &logthis($logmsg);
                   9643:         return 'ok';
                   9644:     }
                   9645:     my $reply = &put('environment', \%names, $udom,$uname);
                   9646:     if ($reply ne 'ok') { 
                   9647:         return 'error: '.$reply;
                   9648:     }
1.1087    raeburn  9649:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9650:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9651:     }
1.1075    raeburn  9652:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9653:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9654:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9655:     &logthis($logmsg);
1.134     albertel 9656:     return 'ok';
1.80      www      9657: }
                   9658: 
1.81      www      9659: # -------------------------------------------------------------- Modify student
1.80      www      9660: 
1.81      www      9661: sub modifystudent {
                   9662:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9663:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9664:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9665:     if (!$cid) {
1.620     albertel 9666: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9667: 	    return 'not_in_class';
                   9668: 	}
1.80      www      9669:     }
                   9670: # --------------------------------------------------------------- Make the user
1.81      www      9671:     my $reply=&modifyuser
1.209     matthew  9672: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9673:          $desiredhome,$email,$inststatus);
1.80      www      9674:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9675:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9676:     # student's environment
1.297     matthew  9677:     $uid = undef if (!$forceid);
1.455     albertel 9678:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9679: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9680:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9681:     return $reply;
                   9682: }
                   9683: 
                   9684: sub modify_student_enrollment {
1.1172.2.23  raeburn  9685:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9686:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9687:     my ($cdom,$cnum,$chome);
                   9688:     if (!$cid) {
1.620     albertel 9689: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9690: 	    return 'not_in_class';
                   9691: 	}
1.620     albertel 9692: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9693: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9694:     } else {
                   9695: 	($cdom,$cnum)=split(/_/,$cid);
                   9696:     }
1.620     albertel 9697:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9698:     if (!$chome) {
1.457     raeburn  9699: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9700:     }
1.455     albertel 9701:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9702:     # Make sure the user exists
1.81      www      9703:     my $uhome=&homeserver($uname,$udom);
                   9704:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9705: 	return 'error: no such user';
                   9706:     }
1.297     matthew  9707:     # Get student data if we were not given enough information
                   9708:     if (!defined($first)  || $first  eq '' || 
                   9709:         !defined($last)   || $last   eq '' || 
                   9710:         !defined($uid)    || $uid    eq '' || 
                   9711:         !defined($middle) || $middle eq '' || 
                   9712:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9713:         # They did not supply us with enough data to enroll the student, so
                   9714:         # we need to pick up more information.
1.297     matthew  9715:         my %tmp = &get('environment',
1.294     matthew  9716:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9717:                        ,$udom,$uname);
                   9718: 
1.800     albertel 9719:         #foreach my $key (keys(%tmp)) {
                   9720:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9721:         #}
1.294     matthew  9722:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9723:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9724:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9725:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9726:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9727:     }
1.556     albertel 9728:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9729:     my $user = "$uname:$udom";
                   9730:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9731:     my $reply=cput('classlist',
1.1148    raeburn  9732: 		   {$user => 
1.1172.2.76  raeburn  9733: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9734: 		   $cdom,$cnum);
1.1148    raeburn  9735:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9736:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9737:     } else { 
1.81      www      9738: 	return 'error: '.$reply;
                   9739:     }
1.297     matthew  9740:     # Add student role to user
1.83      www      9741:     my $uurl='/'.$cid;
1.81      www      9742:     $uurl=~s/\_/\//g;
                   9743:     if ($usec) {
                   9744: 	$uurl.='/'.$usec;
                   9745:     }
1.1148    raeburn  9746:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9747:                              $selfenroll,$context);
                   9748:     if ($result ne 'ok') {
                   9749:         if ($old_entry{$user} ne '') {
                   9750:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9751:         } else {
                   9752:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9753:         }
                   9754:     }
                   9755:     return $result; 
1.21      www      9756: }
                   9757: 
1.556     albertel 9758: sub format_name {
                   9759:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9760:     my $name;
                   9761:     if ($first ne 'lastname') {
                   9762: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9763:     } else {
                   9764: 	if ($lastname=~/\S/) {
                   9765: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9766: 	    $name=~s/\s+,/,/;
                   9767: 	} else {
                   9768: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9769: 	}
                   9770:     }
                   9771:     $name=~s/^\s+//;
                   9772:     $name=~s/\s+$//;
                   9773:     $name=~s/\s+/ /g;
                   9774:     return $name;
                   9775: }
                   9776: 
1.84      www      9777: # ------------------------------------------------- Write to course preferences
                   9778: 
                   9779: sub writecoursepref {
                   9780:     my ($courseid,%prefs)=@_;
                   9781:     $courseid=~s/^\///;
                   9782:     $courseid=~s/\_/\//g;
                   9783:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9784:     my $chome=homeserver($cnum,$cdomain);
                   9785:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9786: 	return 'error: no such course';
                   9787:     }
                   9788:     my $cstring='';
1.800     albertel 9789:     foreach my $pref (keys(%prefs)) {
                   9790: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9791:     }
1.84      www      9792:     $cstring=~s/\&$//;
                   9793:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9794: }
                   9795: 
                   9796: # ---------------------------------------------------------- Make/modify course
                   9797: 
                   9798: sub createcourse {
1.741     raeburn  9799:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9800:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9801:     $url=&declutter($url);
                   9802:     my $cid='';
1.1028    raeburn  9803:     if ($context eq 'requestcourses') {
                   9804:         my $can_create = 0;
                   9805:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9806:         if ($udom eq $ownerdom) {
                   9807:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9808:                                   $context)) {
                   9809:                 $can_create = 1;
                   9810:             }
                   9811:         } else {
                   9812:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9813:                                            $category);
                   9814:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9815:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9816:                 if (@curr > 0) {
                   9817:                     my @options = qw(approval validate autolimit);
                   9818:                     my $optregex = join('|',@options);
                   9819:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9820:                         $can_create = 1;
                   9821:                     }
                   9822:                 }
                   9823:             }
                   9824:         }
                   9825:         if ($can_create) {
                   9826:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9827:                 unless (&allowed('ccc',$udom)) {
                   9828:                     return 'refused'; 
                   9829:                 }
1.1017    raeburn  9830:             }
                   9831:         } else {
                   9832:             return 'refused';
                   9833:         }
1.1028    raeburn  9834:     } elsif (!&allowed('ccc',$udom)) {
                   9835:         return 'refused';
1.84      www      9836:     }
1.1011    raeburn  9837: # --------------------------------------------------------------- Get Unique ID
                   9838:     my $uname;
                   9839:     if ($cnum =~ /^$match_courseid$/) {
                   9840:         my $chome=&homeserver($cnum,$udom,'true');
                   9841:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9842:             $uname = $cnum;
                   9843:         } else {
1.1038    raeburn  9844:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9845:         }
                   9846:     } else {
1.1038    raeburn  9847:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9848:     }
                   9849:     return $uname if ($uname =~ /^error/);
                   9850: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9851:     if (!defined($course_server)) {
                   9852:         if (defined(&domain($udom,'primary'))) {
                   9853:             $course_server = &domain($udom,'primary');
                   9854:         } else {
                   9855:             $course_server = $env{'user.home'}; 
                   9856:         }
                   9857:     }
                   9858:     my %host_servers =
                   9859:         &Apache::lonnet::get_servers($udom,'library');
                   9860:     unless ($host_servers{$course_server}) {
                   9861:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9862:     }
1.84      www      9863: # ------------------------------------------------------------- Make the course
                   9864:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9865:                       $course_server);
1.84      www      9866:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9867:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9868:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9869: 	return 'error: no such course';
                   9870:     }
1.271     www      9871: # ----------------------------------------------------------------- Course made
1.516     raeburn  9872: # log existence
1.1029    raeburn  9873:     my $now = time;
1.918     raeburn  9874:     my $newcourse = {
                   9875:                     $udom.'_'.$uname => {
1.921     raeburn  9876:                                      description => $description,
                   9877:                                      inst_code   => $inst_code,
                   9878:                                      owner       => $course_owner,
                   9879:                                      type        => $crstype,
1.1029    raeburn  9880:                                      creator     => $env{'user.name'}.':'.
                   9881:                                                     $env{'user.domain'},
                   9882:                                      created     => $now,
                   9883:                                      context     => $context,
1.918     raeburn  9884:                                                 },
                   9885:                     };
1.921     raeburn  9886:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9887: # set toplevel url
1.271     www      9888:     my $topurl=$url;
                   9889:     unless ($nonstandard) {
                   9890: # ------------------------------------------ For standard courses, make top url
                   9891:         my $mapurl=&clutter($url);
1.278     www      9892:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9893:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9894: <map>
                   9895: <resource id="1" type="start"></resource>
                   9896: <resource id="2" src="$mapurl"></resource>
                   9897: <resource id="3" type="finish"></resource>
                   9898: <link index="1" from="1" to="2"></link>
                   9899: <link index="2" from="2" to="3"></link>
                   9900: </map>
                   9901: ENDINITMAP
                   9902:         $topurl=&declutter(
1.638     albertel 9903:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9904:                           );
                   9905:     }
                   9906: # ----------------------------------------------------------- Write preferences
1.84      www      9907:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9908:                      ('description'              => $description,
                   9909:                       'url'                      => $topurl,
                   9910:                       'internal.creator'         => $env{'user.name'}.':'.
                   9911:                                                     $env{'user.domain'},
                   9912:                       'internal.created'         => $now,
                   9913:                       'internal.creationcontext' => $context)
                   9914:                     );
1.84      www      9915:     return '/'.$udom.'/'.$uname;
                   9916: }
                   9917: 
1.1011    raeburn  9918: # ------------------------------------------------------------------- Create ID
                   9919: sub generate_coursenum {
1.1038    raeburn  9920:     my ($udom,$crstype) = @_;
1.1011    raeburn  9921:     my $domdesc = &domain($udom);
                   9922:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9923:     my $first;
                   9924:     if ($crstype eq 'Community') {
                   9925:         $first = '0';
                   9926:     } else {
                   9927:         $first = int(1+rand(9)); 
                   9928:     } 
                   9929:     my $uname=$first.
1.1011    raeburn  9930:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9931:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9932:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9933: # ----------------------------------------------- Make sure that does not exist
                   9934:     my $uhome=&homeserver($uname,$udom,'true');
                   9935:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9936:         if ($crstype eq 'Community') {
                   9937:             $first = '0';
                   9938:         } else {
                   9939:             $first = int(1+rand(9));
                   9940:         }
                   9941:         $uname=$first.
1.1011    raeburn  9942:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9943:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9944:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9945:         $uhome=&homeserver($uname,$udom,'true');
                   9946:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9947:             return 'error: unable to generate unique course-ID';
                   9948:         }
                   9949:     }
                   9950:     return $uname;
                   9951: }
                   9952: 
1.813     albertel 9953: sub is_course {
1.1167    droeschl 9954:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9955:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  9956:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   9957:     my $uhome=&homeserver($cnum,$cdom);
                   9958:     my $iscourse;
                   9959:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   9960:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   9961:     } else {
                   9962:         my $hashid = $cdom.':'.$cnum;
                   9963:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   9964:         unless (defined($cached)) {
                   9965:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   9966:                                         $cnum,undef,undef,'.');
                   9967:             $iscourse = 0;
                   9968:             if (exists($courses{$cdom.'_'.$cnum})) {
                   9969:                 $iscourse = 1;
                   9970:             }
                   9971:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   9972:         }
                   9973:     }
                   9974:     return unless($iscourse);
1.1167    droeschl 9975:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9976: }
                   9977: 
1.1015    raeburn  9978: sub store_userdata {
                   9979:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9980:     my $result;
1.1016    raeburn  9981:     if ($datakey ne '') {
1.1013    raeburn  9982:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9983:             if ($udom eq '' || $uname eq '') {
                   9984:                 $udom = $env{'user.domain'};
                   9985:                 $uname = $env{'user.name'};
                   9986:             }
                   9987:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9988:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9989:                 $result = 'error: no_host';
                   9990:             } else {
                   9991:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9992:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9993: 
                   9994:                 my $namevalue='';
                   9995:                 foreach my $key (keys(%{$storehash})) {
                   9996:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9997:                 }
                   9998:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9999:                 unless ($namespace eq 'courserequests') {
                   10000:                     $datakey = &escape($datakey);
                   10001:                 }
1.1105    raeburn  10002:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10003:                                   $namevalue,$uhome);
1.1013    raeburn  10004:             }
                   10005:         } else {
                   10006:             $result = 'error: data to store was not a hash reference'; 
                   10007:         }
                   10008:     } else {
                   10009:         $result= 'error: invalid requestkey'; 
                   10010:     }
                   10011:     return $result;
                   10012: }
                   10013: 
1.21      www      10014: # ---------------------------------------------------------- Assign Custom Role
                   10015: 
                   10016: sub assigncustomrole {
1.957     raeburn  10017:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10018:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10019:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10020: }
                   10021: 
                   10022: # ----------------------------------------------------------------- Revoke Role
                   10023: 
                   10024: sub revokerole {
1.957     raeburn  10025:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10026:     my $now=time;
1.965     raeburn  10027:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10028: }
                   10029: 
                   10030: # ---------------------------------------------------------- Revoke Custom Role
                   10031: 
                   10032: sub revokecustomrole {
1.957     raeburn  10033:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10034:     my $now=time;
1.357     www      10035:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10036:            $deleteflag,$selfenroll,$context);
1.17      www      10037: }
                   10038: 
1.533     banghart 10039: # ------------------------------------------------------------ Disk usage
1.535     albertel 10040: sub diskusage {
1.955     raeburn  10041:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10042:     $directorypath =~ s/\/$//;
                   10043:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10044:                        .&escape($getpropath).':'.&escape($uname).':'
                   10045:                        .&escape($udom),homeserver($uname,$udom));
                   10046:     if ($listing eq 'unknown_cmd') {
                   10047:         if ($getpropath) {
                   10048:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10049:         }
                   10050:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10051:     }
1.514     albertel 10052:     return $listing;
1.512     banghart 10053: }
                   10054: 
1.566     banghart 10055: sub is_locked {
1.1096    raeburn  10056:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10057:     my @check;
                   10058:     my $is_locked;
1.1093    raeburn  10059:     push (@check,$file_name);
1.613     albertel 10060:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10061: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10062:     my ($tmp)=keys(%locked);
                   10063:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10064:     
1.566     banghart 10065:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10066:         $is_locked = 'false';
                   10067:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10068:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10069:                $is_locked = 'true';
1.1096    raeburn  10070:                if (ref($which) eq 'ARRAY') {
                   10071:                    push(@{$which},$entry);
                   10072:                } else {
                   10073:                    last;
                   10074:                }
1.745     raeburn  10075:            }
                   10076:        }
1.566     banghart 10077:     } else {
                   10078:         $is_locked = 'false';
                   10079:     }
1.1093    raeburn  10080:     return $is_locked;
1.566     banghart 10081: }
                   10082: 
1.759     albertel 10083: sub declutter_portfile {
                   10084:     my ($file) = @_;
1.833     albertel 10085:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10086:     return $file;
                   10087: }
                   10088: 
1.559     banghart 10089: # ------------------------------------------------------------- Mark as Read Only
                   10090: 
                   10091: sub mark_as_readonly {
                   10092:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10093:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10094:     my ($tmp)=keys(%current_permissions);
                   10095:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10096:     foreach my $file (@{$files}) {
1.759     albertel 10097: 	$file = &declutter_portfile($file);
1.561     banghart 10098:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10099:     }
1.613     albertel 10100:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10101:     return;
                   10102: }
                   10103: 
1.572     banghart 10104: # ------------------------------------------------------------Save Selected Files
                   10105: 
                   10106: sub save_selected_files {
                   10107:     my ($user, $path, @files) = @_;
                   10108:     my $filename = $user."savedfiles";
1.573     banghart 10109:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10110:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10111:     foreach my $file (@files) {
1.620     albertel 10112:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10113:     }
                   10114:     foreach my $file (@other_files) {
1.574     banghart 10115:         print (OUT $file."\n");
1.572     banghart 10116:     }
1.574     banghart 10117:     close (OUT);
1.572     banghart 10118:     return 'ok';
                   10119: }
                   10120: 
1.574     banghart 10121: sub clear_selected_files {
                   10122:     my ($user) = @_;
                   10123:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10124:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10125:     print (OUT undef);
                   10126:     close (OUT);
                   10127:     return ("ok");    
                   10128: }
                   10129: 
1.572     banghart 10130: sub files_in_path {
                   10131:     my ($user, $path) = @_;
                   10132:     my $filename = $user."savedfiles";
                   10133:     my %return_files;
1.1172.2.96  raeburn  10134:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10135:     while (my $line_in = <IN>) {
1.574     banghart 10136:         chomp ($line_in);
                   10137:         my @paths_and_file = split (m!/!, $line_in);
                   10138:         my $file_part = pop (@paths_and_file);
                   10139:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10140:         $path_part.='/';
                   10141:         my $path_and_file = $path_part.$file_part;
                   10142:         if ($path_part eq $path) {
                   10143:             $return_files{$file_part}= 'selected';
                   10144:         }
                   10145:     }
1.574     banghart 10146:     close (IN);
                   10147:     return (\%return_files);
1.572     banghart 10148: }
                   10149: 
                   10150: # called in portfolio select mode, to show files selected NOT in current directory
                   10151: sub files_not_in_path {
                   10152:     my ($user, $path) = @_;
                   10153:     my $filename = $user."savedfiles";
                   10154:     my @return_files;
                   10155:     my $path_part;
1.1172.2.96  raeburn  10156:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10157:     while (my $line = <IN>) {
1.572     banghart 10158:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10159:         my @paths_and_file = split(m|/|, $line);
                   10160:         my $file_part = pop(@paths_and_file);
                   10161:         chomp($file_part);
                   10162:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10163:         $path_part .= '/';
                   10164:         my $path_and_file = $path_part.$file_part;
                   10165:         if ($path_part ne $path) {
1.800     albertel 10166:             push(@return_files, ($path_and_file));
1.572     banghart 10167:         }
                   10168:     }
1.800     albertel 10169:     close(OUT);
1.574     banghart 10170:     return (@return_files);
1.572     banghart 10171: }
                   10172: 
1.745     raeburn  10173: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10174: 
1.745     raeburn  10175: sub get_portfile_permissions {
                   10176:     my ($domain,$user) = @_;
1.613     albertel 10177:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10178:     my ($tmp)=keys(%current_permissions);
                   10179:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10180:     return \%current_permissions;
                   10181: }
                   10182: 
                   10183: #---------------------------------------------Get portfolio file access controls
                   10184: 
1.749     raeburn  10185: sub get_access_controls {
1.745     raeburn  10186:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10187:     my %access;
                   10188:     my $real_file = $file;
                   10189:     $file =~ s/\.meta$//;
1.745     raeburn  10190:     if (defined($file)) {
1.749     raeburn  10191:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10192:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10193:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10194:             }
                   10195:         }
1.745     raeburn  10196:     } else {
1.749     raeburn  10197:         foreach my $key (keys(%{$current_permissions})) {
                   10198:             if ($key =~ /\0accesscontrol$/) {
                   10199:                 if (defined($group)) {
                   10200:                     if ($key !~ m-^\Q$group\E/-) {
                   10201:                         next;
                   10202:                     }
                   10203:                 }
                   10204:                 my ($fullpath) = split(/\0/,$key);
                   10205:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10206:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10207:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10208:                     }
                   10209:                 }
                   10210:             }
                   10211:         }
                   10212:     }
                   10213:     return %access;
                   10214: }
                   10215: 
                   10216: sub modify_access_controls {
                   10217:     my ($file_name,$changes,$domain,$user)=@_;
                   10218:     my ($outcome,$deloutcome);
                   10219:     my %store_permissions;
                   10220:     my %new_values;
                   10221:     my %new_control;
                   10222:     my %translation;
                   10223:     my @deletions = ();
                   10224:     my $now = time;
                   10225:     if (exists($$changes{'activate'})) {
                   10226:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10227:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10228:             my $numnew = scalar(@newitems);
                   10229:             for (my $i=0; $i<$numnew; $i++) {
                   10230:                 my $newkey = $newitems[$i];
                   10231:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10232:                 if ($newkey =~ /^\d+:/) { 
                   10233:                     $newkey =~ s/^(\d+)/$newid/;
                   10234:                     $translation{$1} = $newid;
                   10235:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10236:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10237:                     $translation{$1} = $newid;
                   10238:                 }
1.749     raeburn  10239:                 $new_values{$file_name."\0".$newkey} = 
                   10240:                                           $$changes{'activate'}{$newitems[$i]};
                   10241:                 $new_control{$newkey} = $now;
                   10242:             }
                   10243:         }
                   10244:     }
                   10245:     my %todelete;
                   10246:     my %changed_items;
                   10247:     foreach my $action ('delete','update') {
                   10248:         if (exists($$changes{$action})) {
                   10249:             if (ref($$changes{$action}) eq 'HASH') {
                   10250:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10251:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10252:                     if ($action eq 'delete') { 
                   10253:                         $todelete{$itemnum} = 1;
                   10254:                     } else {
                   10255:                         $changed_items{$itemnum} = $key;
                   10256:                     }
                   10257:                 }
1.745     raeburn  10258:             }
                   10259:         }
1.749     raeburn  10260:     }
                   10261:     # get lock on access controls for file.
                   10262:     my $lockhash = {
                   10263:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10264:                                                        ':'.$env{'user.domain'},
                   10265:                    }; 
                   10266:     my $tries = 0;
                   10267:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10268:    
1.1172.2.79  raeburn  10269:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10270:         $tries ++;
1.1172.2.79  raeburn  10271:         sleep(0.1);
1.749     raeburn  10272:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10273:     }
                   10274:     if ($gotlock eq 'ok') {
                   10275:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10276:         my ($tmp)=keys(%curr_permissions);
                   10277:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10278:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10279:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10280:             if (ref($curr_controls) eq 'HASH') {
                   10281:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10282:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10283:                     if (defined($todelete{$itemnum})) {
                   10284:                         push(@deletions,$file_name."\0".$control_item);
                   10285:                     } else {
                   10286:                         if (defined($changed_items{$itemnum})) {
                   10287:                             $new_control{$changed_items{$itemnum}} = $now;
                   10288:                             push(@deletions,$file_name."\0".$control_item);
                   10289:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10290:                         } else {
                   10291:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10292:                         }
                   10293:                     }
1.745     raeburn  10294:                 }
                   10295:             }
                   10296:         }
1.970     raeburn  10297:         my ($group);
                   10298:         if (&is_course($domain,$user)) {
                   10299:             ($group,my $file) = split(/\//,$file_name,2);
                   10300:         }
1.749     raeburn  10301:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10302:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10303:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10304:         #  remove lock
                   10305:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10306:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10307:         my $sqlresult =
1.970     raeburn  10308:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10309:                                     $group);
1.749     raeburn  10310:     } else {
                   10311:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10312:     }
1.749     raeburn  10313:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10314: }
                   10315: 
1.827     raeburn  10316: sub make_public_indefinitely {
                   10317:     my ($requrl) = @_;
                   10318:     my $now = time;
                   10319:     my $action = 'activate';
                   10320:     my $aclnum = 0;
                   10321:     if (&is_portfolio_url($requrl)) {
                   10322:         my (undef,$udom,$unum,$file_name,$group) =
                   10323:             &parse_portfolio_url($requrl);
                   10324:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10325:         my %access_controls = &get_access_controls($current_perms,
                   10326:                                                    $group,$file_name);
                   10327:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10328:             my ($num,$scope,$end,$start) = 
                   10329:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10330:             if ($scope eq 'public') {
                   10331:                 if ($start <= $now && $end == 0) {
                   10332:                     $action = 'none';
                   10333:                 } else {
                   10334:                     $action = 'update';
                   10335:                     $aclnum = $num;
                   10336:                 }
                   10337:                 last;
                   10338:             }
                   10339:         }
                   10340:         if ($action eq 'none') {
                   10341:              return 'ok';
                   10342:         } else {
                   10343:             my %changes;
                   10344:             my $newend = 0;
                   10345:             my $newstart = $now;
                   10346:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10347:             $changes{$action}{$newkey} = {
                   10348:                 type => 'public',
                   10349:                 time => {
                   10350:                     start => $newstart,
                   10351:                     end   => $newend,
                   10352:                 },
                   10353:             };
                   10354:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10355:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10356:             return $outcome;
                   10357:         }
                   10358:     } else {
                   10359:         return 'invalid';
                   10360:     }
                   10361: }
                   10362: 
1.745     raeburn  10363: #------------------------------------------------------Get Marked as Read Only
                   10364: 
                   10365: sub get_marked_as_readonly {
                   10366:     my ($domain,$user,$what,$group) = @_;
                   10367:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10368:     my @readonly_files;
1.629     banghart 10369:     my $cmp1=$what;
                   10370:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10371:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10372:         if (defined($group)) {
                   10373:             if ($file_name !~ m-^\Q$group\E/-) {
                   10374:                 next;
                   10375:             }
                   10376:         }
1.561     banghart 10377:         if (ref($value) eq "ARRAY"){
                   10378:             foreach my $stored_what (@{$value}) {
1.629     banghart 10379:                 my $cmp2=$stored_what;
1.759     albertel 10380:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10381:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10382:                 }
1.629     banghart 10383:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10384:                     push(@readonly_files, $file_name);
1.745     raeburn  10385:                     last;
1.563     banghart 10386:                 } elsif (!defined($what)) {
                   10387:                     push(@readonly_files, $file_name);
1.745     raeburn  10388:                     last;
1.561     banghart 10389:                 }
                   10390:             }
1.745     raeburn  10391:         }
1.561     banghart 10392:     }
                   10393:     return @readonly_files;
                   10394: }
1.577     banghart 10395: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10396: 
1.577     banghart 10397: sub get_marked_as_readonly_hash {
1.745     raeburn  10398:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10399:     my %readonly_files;
1.745     raeburn  10400:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10401:         if (defined($group)) {
                   10402:             if ($file_name !~ m-^\Q$group\E/-) {
                   10403:                 next;
                   10404:             }
                   10405:         }
1.577     banghart 10406:         if (ref($value) eq "ARRAY"){
                   10407:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10408:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10409:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10410:                         if ($lock_descriptor eq 'graded') {
                   10411:                             $readonly_files{$file_name} = 'graded';
                   10412:                         } elsif ($lock_descriptor eq 'handback') {
                   10413:                             $readonly_files{$file_name} = 'handback';
                   10414:                         } else {
                   10415:                             if (!exists($readonly_files{$file_name})) {
                   10416:                                 $readonly_files{$file_name} = 'locked';
                   10417:                             }
                   10418:                         }
1.745     raeburn  10419:                     }
1.750     banghart 10420:                 } 
1.577     banghart 10421:             }
                   10422:         } 
                   10423:     }
                   10424:     return %readonly_files;
                   10425: }
1.559     banghart 10426: # ------------------------------------------------------------ Unmark as Read Only
                   10427: 
                   10428: sub unmark_as_readonly {
1.629     banghart 10429:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10430:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10431:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10432:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10433:     my $symb_crs = $what;
                   10434:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10435:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10436:     my ($tmp)=keys(%current_permissions);
                   10437:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10438:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10439:     foreach my $file (@readonly_files) {
1.759     albertel 10440: 	my $clean_file = &declutter_portfile($file);
                   10441: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10442: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10443:         my @new_locks;
                   10444:         my @del_keys;
                   10445:         if (ref($current_locks) eq "ARRAY"){
                   10446:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10447:                 my $compare=$locker;
1.749     raeburn  10448:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10449:                     $compare=join('',@{$locker});
1.746     raeburn  10450:                     if ($compare ne $symb_crs) {
                   10451:                         push(@new_locks, $locker);
                   10452:                     }
1.563     banghart 10453:                 }
                   10454:             }
1.650     albertel 10455:             if (scalar(@new_locks) > 0) {
1.563     banghart 10456:                 $current_permissions{$file} = \@new_locks;
                   10457:             } else {
                   10458:                 push(@del_keys, $file);
1.613     albertel 10459:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10460:                 delete($current_permissions{$file});
1.563     banghart 10461:             }
                   10462:         }
1.561     banghart 10463:     }
1.613     albertel 10464:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10465:     return;
                   10466: }
1.512     banghart 10467: 
1.17      www      10468: # ------------------------------------------------------------ Directory lister
                   10469: 
                   10470: sub dirlist {
1.955     raeburn  10471:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10472:     $uri=~s/^\///;
                   10473:     $uri=~s/\/$//;
1.253     stredwic 10474:     my ($udom, $uname);
1.955     raeburn  10475:     if ($getuserdir) {
1.253     stredwic 10476:         $udom = $userdomain;
                   10477:         $uname = $username;
1.955     raeburn  10478:     } else {
                   10479:         (undef,$udom,$uname)=split(/\//,$uri);
                   10480:         if(defined($userdomain)) {
                   10481:             $udom = $userdomain;
                   10482:         }
                   10483:         if(defined($username)) {
                   10484:             $uname = $username;
                   10485:         }
1.253     stredwic 10486:     }
1.955     raeburn  10487:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10488: 
1.955     raeburn  10489:     $dirRoot = $perlvar{'lonDocRoot'};
                   10490:     if (defined($getpropath)) {
                   10491:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10492:         $dirRoot =~ s/\/$//;
1.955     raeburn  10493:     } elsif (defined($getuserdir)) {
                   10494:         my $subdir=$uname.'__';
                   10495:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10496:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10497:                    ."/$udom/$subdir/$uname";
                   10498:     } elsif (defined($alternateRoot)) {
                   10499:         $dirRoot = $alternateRoot;
1.751     banghart 10500:     }
1.253     stredwic 10501: 
                   10502:     if($udom) {
                   10503:         if($uname) {
1.1135    raeburn  10504:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10505:             if ($uhome eq 'no_host') {
                   10506:                 return ([],'no_host');
                   10507:             }
1.955     raeburn  10508:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10509:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10510:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10511:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10512:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10513:             } else {
                   10514:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10515:             }
1.605     matthew  10516:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10517:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10518:                 @listing_results = split(/:/,$listing);
                   10519:             } else {
                   10520:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10521:             }
1.1135    raeburn  10522:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10523:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10524:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10525:                 return ([],$listing);
                   10526:             } else {
                   10527:                 return (\@listing_results);
1.1135    raeburn  10528:             }
1.955     raeburn  10529:         } elsif(!$alternateRoot) {
1.1136    raeburn  10530:             my (%allusers,%listerror);
1.841     albertel 10531: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10532:  	    foreach my $tryserver (keys(%servers)) {
                   10533:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10534:                                   &escape($udom),$tryserver);
                   10535:                 if ($listing eq 'unknown_cmd') {
                   10536: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10537: 				      $udom, $tryserver);
                   10538:                 } else {
                   10539:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10540:                 }
1.841     albertel 10541: 		if ($listing eq 'unknown_cmd') {
                   10542: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10543: 				      $udom, $tryserver);
                   10544: 		    @listing_results = split(/:/,$listing);
                   10545: 		} else {
                   10546: 		    @listing_results =
                   10547: 			map { &unescape($_); } split(/:/,$listing);
                   10548: 		}
1.1136    raeburn  10549:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10550:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10551:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10552:                     $listerror{$tryserver} = $listing;
                   10553:                 } else {
1.841     albertel 10554: 		    foreach my $line (@listing_results) {
                   10555: 			my ($entry) = split(/&/,$line,2);
                   10556: 			$allusers{$entry} = 1;
                   10557: 		    }
                   10558: 		}
1.253     stredwic 10559:             }
1.1136    raeburn  10560:             my @alluserslist=();
1.800     albertel 10561:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10562:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10563:             }
1.1172.2.80  raeburn  10564:             if (!%listerror) {
                   10565:                 # no errors
                   10566:                 return (\@alluserslist);
                   10567:             } elsif (scalar(keys(%servers)) == 1) {
                   10568:                 # one library server, one error
                   10569:                 my ($key) = keys(%listerror);
                   10570:                 return (\@alluserslist, $listerror{$key});
                   10571:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10572:                 # con_lost indicates that we might miss data from at least one
                   10573:                 # library server
                   10574:                 return (\@alluserslist, 'con_lost');
                   10575:             } else {
                   10576:                 # multiple library servers and no con_lost -> data should be
                   10577:                 # complete.
                   10578:                 return (\@alluserslist);
                   10579:             }
                   10580: 
1.253     stredwic 10581:         } else {
1.1136    raeburn  10582:             return ([],'missing username');
1.253     stredwic 10583:         }
1.955     raeburn  10584:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10585:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10586:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10587:         return (\@all_domains);
1.955     raeburn  10588:     } else {
1.1136    raeburn  10589:         return ([],'missing domain');
1.275     stredwic 10590:     }
                   10591: }
                   10592: 
                   10593: # --------------------------------------------- GetFileTimestamp
                   10594: # This function utilizes dirlist and returns the date stamp for
                   10595: # when it was last modified.  It will also return an error of -1
                   10596: # if an error occurs
                   10597: 
                   10598: sub GetFileTimestamp {
1.955     raeburn  10599:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10600:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10601:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10602:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10603:                                     undef,$getuserdir);
                   10604:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10605:         return -1;
                   10606:     }
                   10607:     if (ref($fileref) eq 'ARRAY') {
                   10608:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10609:         # @stats contains first the filename, then the stat output
                   10610:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10611:     } else {
                   10612:         return -1;
1.253     stredwic 10613:     }
1.26      www      10614: }
                   10615: 
1.712     albertel 10616: sub stat_file {
                   10617:     my ($uri) = @_;
1.787     albertel 10618:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10619: 
1.955     raeburn  10620:     my ($udom,$uname,$file);
1.712     albertel 10621:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10622: 	($udom,$uname,$file) =
1.811     albertel 10623: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10624: 	$file = 'userfiles/'.$file;
                   10625:     }
                   10626:     if ($uri =~ m-^/res/-) {
                   10627: 	($udom,$uname) = 
1.807     albertel 10628: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10629: 	$file = $uri;
                   10630:     }
                   10631: 
                   10632:     if (!$udom || !$uname || !$file) {
                   10633: 	# unable to handle the uri
                   10634: 	return ();
                   10635:     }
1.956     raeburn  10636:     my $getpropath;
                   10637:     if ($file =~ /^userfiles\//) {
                   10638:         $getpropath = 1;
                   10639:     }
1.1136    raeburn  10640:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10641:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10642:         return ();
                   10643:     } else {
                   10644:         if (ref($listref) eq 'ARRAY') {
                   10645:             my @stats = split('&',$listref->[0]);
                   10646: 	    shift(@stats); #filename is first
                   10647: 	    return @stats;
                   10648:         }
1.712     albertel 10649:     }
                   10650:     return ();
                   10651: }
                   10652: 
1.26      www      10653: # -------------------------------------------------------- Value of a Condition
                   10654: 
1.713     albertel 10655: # gets the value of a specific preevaluated condition
                   10656: #    stored in the string  $env{user.state.<cid>}
                   10657: # or looks up a condition reference in the bighash and if if hasn't
                   10658: # already been evaluated recurses into docondval to get the value of
                   10659: # the condition, then memoizing it to 
                   10660: #   $env{user.state.<cid>.<condition>}
1.40      www      10661: sub directcondval {
                   10662:     my $number=shift;
1.620     albertel 10663:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10664: 	&Apache::lonuserstate::evalstate();
                   10665:     }
1.713     albertel 10666:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10667: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10668:     } elsif ($number =~ /^_/) {
                   10669: 	my $sub_condition;
                   10670: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10671: 		&GDBM_READER(),0640)) {
                   10672: 	    $sub_condition=$bighash{'conditions'.$number};
                   10673: 	    untie(%bighash);
                   10674: 	}
                   10675: 	my $value = &docondval($sub_condition);
1.949     raeburn  10676: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10677: 	return $value;
                   10678:     }
1.620     albertel 10679:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10680:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10681:     } else {
                   10682:        return 2;
                   10683:     }
                   10684: }
                   10685: 
1.713     albertel 10686: # get the collection of conditions for this resource
1.26      www      10687: sub condval {
                   10688:     my $condidx=shift;
1.54      www      10689:     my $allpathcond='';
1.713     albertel 10690:     foreach my $cond (split(/\|/,$condidx)) {
                   10691: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10692: 	    $allpathcond.=
                   10693: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10694: 	}
1.191     harris41 10695:     }
1.54      www      10696:     $allpathcond=~s/\|$//;
1.713     albertel 10697:     return &docondval($allpathcond);
                   10698: }
                   10699: 
                   10700: #evaluates an expression of conditions
                   10701: sub docondval {
                   10702:     my ($allpathcond) = @_;
                   10703:     my $result=0;
                   10704:     if ($env{'request.course.id'}
                   10705: 	&& defined($allpathcond)) {
                   10706: 	my $operand='|';
                   10707: 	my @stack;
                   10708: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10709: 	    if ($chunk eq '(') {
                   10710: 		push @stack,($operand,$result);
                   10711: 	    } elsif ($chunk eq ')') {
                   10712: 		my $before=pop @stack;
                   10713: 		if (pop @stack eq '&') {
                   10714: 		    $result=$result>$before?$before:$result;
                   10715: 		} else {
                   10716: 		    $result=$result>$before?$result:$before;
                   10717: 		}
                   10718: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10719: 		$operand=$chunk;
                   10720: 	    } else {
                   10721: 		my $new=directcondval($chunk);
                   10722: 		if ($operand eq '&') {
                   10723: 		    $result=$result>$new?$new:$result;
                   10724: 		} else {
                   10725: 		    $result=$result>$new?$result:$new;
                   10726: 		}
                   10727: 	    }
                   10728: 	}
1.26      www      10729:     }
                   10730:     return $result;
1.421     albertel 10731: }
                   10732: 
                   10733: # ---------------------------------------------------- Devalidate courseresdata
                   10734: 
                   10735: sub devalidatecourseresdata {
                   10736:     my ($coursenum,$coursedomain)=@_;
                   10737:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10738:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10739: }
                   10740: 
1.763     www      10741: 
1.200     www      10742: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10743: #
                   10744: #  Parameters:
                   10745: #      $coursenum    - Number of the course.
                   10746: #      $coursedomain - Domain at which the course was created.
                   10747: #  Returns:
                   10748: #     A hash of the course parameters along (I think) with timestamps
                   10749: #     and version info.
1.877     foxr     10750: 
1.624     albertel 10751: sub get_courseresdata {
                   10752:     my ($coursenum,$coursedomain)=@_;
1.200     www      10753:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10754:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10755:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10756:     my %dumpreply;
1.417     albertel 10757:     unless (defined($cached)) {
1.624     albertel 10758: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10759: 	$result=\%dumpreply;
1.251     albertel 10760: 	my ($tmp) = keys(%dumpreply);
                   10761: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10762: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10763: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10764: 	    return $tmp;
1.416     albertel 10765: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10766: 	    $result=undef;
1.599     albertel 10767: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10768: 	}
                   10769:     }
1.624     albertel 10770:     return $result;
                   10771: }
                   10772: 
1.633     albertel 10773: sub devalidateuserresdata {
                   10774:     my ($uname,$udom)=@_;
                   10775:     my $hashid="$udom:$uname";
                   10776:     &devalidate_cache_new('userres',$hashid);
                   10777: }
                   10778: 
1.624     albertel 10779: sub get_userresdata {
                   10780:     my ($uname,$udom)=@_;
                   10781:     #most student don\'t have any data set, check if there is some data
                   10782:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10783: 
                   10784:     my $hashid="$udom:$uname";
                   10785:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10786:     if (!defined($cached)) {
                   10787: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10788: 	$result=\%resourcedata;
                   10789: 	&do_cache_new('userres',$hashid,$result,600);
                   10790:     }
                   10791:     my ($tmp)=keys(%$result);
                   10792:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10793: 	return $result;
                   10794:     }
                   10795:     #error 2 occurs when the .db doesn't exist
                   10796:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10797:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10798: 	    &logthis("<font color=\"blue\">WARNING:".
                   10799: 		     " Trying to get resource data for ".
                   10800: 		     $uname." at ".$udom.": ".
                   10801: 		     $tmp."</font>");
                   10802:         }
1.624     albertel 10803:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10804: 	#&EXT_cache_set($udom,$uname);
                   10805: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10806: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10807:     }
                   10808:     return $tmp;
                   10809: }
1.879     foxr     10810: #----------------------------------------------- resdata - return resource data
                   10811: #  Purpose:
                   10812: #    Return resource data for either users or for a course.
                   10813: #  Parameters:
                   10814: #     $name      - Course/user name.
                   10815: #     $domain    - Name of the domain the user/course is registered on.
                   10816: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10817: #     @which     - Array of names of resources desired.
                   10818: #  Returns:
                   10819: #     The value of the first reasource in @which that is found in the
                   10820: #     resource hash.
                   10821: #  Exceptional Conditions:
                   10822: #     If the $type passed in is not valid (not the string 'course' or 
                   10823: #     'user', an undefined  reference is returned.
                   10824: #     If none of the resources are found, an undef is returned
1.624     albertel 10825: sub resdata {
                   10826:     my ($name,$domain,$type,@which)=@_;
                   10827:     my $result;
                   10828:     if ($type eq 'course') {
                   10829: 	$result=&get_courseresdata($name,$domain);
                   10830:     } elsif ($type eq 'user') {
                   10831: 	$result=&get_userresdata($name,$domain);
                   10832:     }
                   10833:     if (!ref($result)) { return $result; }    
1.251     albertel 10834:     foreach my $item (@which) {
1.927     albertel 10835: 	if (defined($result->{$item->[0]})) {
                   10836: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10837: 	}
1.250     albertel 10838:     }
1.291     albertel 10839:     return undef;
1.200     www      10840: }
                   10841: 
1.1172.2.31  raeburn  10842: sub get_numsuppfiles {
                   10843:     my ($cnum,$cdom,$ignorecache)=@_;
                   10844:     my $hashid=$cnum.':'.$cdom;
                   10845:     my ($suppcount,$cached);
                   10846:     unless ($ignorecache) {
                   10847:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10848:     }
                   10849:     unless (defined($cached)) {
                   10850:         my $chome=&homeserver($cnum,$cdom);
                   10851:         unless ($chome eq 'no_host') {
                   10852:             ($suppcount,my $errors) = (0,0);
                   10853:             my $suppmap = 'supplemental.sequence';
                   10854:             ($suppcount,$errors) =
                   10855:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10856:         }
                   10857:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10858:     }
                   10859:     return $suppcount;
                   10860: }
                   10861: 
1.379     matthew  10862: #
                   10863: # EXT resource caching routines
                   10864: #
                   10865: 
                   10866: sub clear_EXT_cache_status {
1.383     albertel 10867:     &delenv('cache.EXT.');
1.379     matthew  10868: }
                   10869: 
                   10870: sub EXT_cache_status {
                   10871:     my ($target_domain,$target_user) = @_;
1.383     albertel 10872:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10873:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10874:         # We know already the user has no data
                   10875:         return 1;
                   10876:     } else {
                   10877:         return 0;
                   10878:     }
                   10879: }
                   10880: 
                   10881: sub EXT_cache_set {
                   10882:     my ($target_domain,$target_user) = @_;
1.383     albertel 10883:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10884:     #&appenv({$cachename => time});
1.379     matthew  10885: }
                   10886: 
1.28      www      10887: # --------------------------------------------------------- Value of a Variable
1.58      www      10888: sub EXT {
1.715     albertel 10889: 
1.1172.2.28  raeburn  10890:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10891:     unless ($varname) { return ''; }
1.218     albertel 10892:     #get real user name/domain, courseid and symb
                   10893:     my $courseid;
1.359     albertel 10894:     my $publicuser;
1.427     www      10895:     if ($symbparm) {
                   10896: 	$symbparm=&get_symb_from_alias($symbparm);
                   10897:     }
1.218     albertel 10898:     if (!($uname && $udom)) {
1.790     albertel 10899:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10900:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10901:     } else {
1.620     albertel 10902: 	$courseid=$env{'request.course.id'};
1.218     albertel 10903:     }
1.48      www      10904:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10905:     my $rest;
1.320     albertel 10906:     if (defined($therest[0])) {
1.48      www      10907:        $rest=join('.',@therest);
                   10908:     } else {
                   10909:        $rest='';
                   10910:     }
1.320     albertel 10911: 
1.57      www      10912:     my $qualifierrest=$qualifier;
                   10913:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10914:     my $spacequalifierrest=$space;
                   10915:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10916:     if ($realm eq 'user') {
1.48      www      10917: # --------------------------------------------------------------- user.resource
                   10918: 	if ($space eq 'resource') {
1.651     albertel 10919: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10920: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10921: 		 &&
1.744     albertel 10922: 		 ($symbparm eq &symbread()) ) {	
                   10923: 		# if we are in the middle of processing the resource the
                   10924: 		# get the value we are planning on committing
                   10925:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10926:                     return $Apache::lonhomework::results{$qualifierrest};
                   10927:                 } else {
                   10928:                     return $Apache::lonhomework::history{$qualifierrest};
                   10929:                 }
1.335     albertel 10930: 	    } else {
1.359     albertel 10931: 		my %restored;
1.620     albertel 10932: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10933: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10934: 		} else {
                   10935: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10936: 		}
1.335     albertel 10937: 		return $restored{$qualifierrest};
                   10938: 	    }
1.48      www      10939: # ----------------------------------------------------------------- user.access
                   10940:         } elsif ($space eq 'access') {
1.218     albertel 10941: 	    # FIXME - not supporting calls for a specific user
1.48      www      10942:             return &allowed($qualifier,$rest);
                   10943: # ------------------------------------------ user.preferences, user.environment
                   10944:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10945: 	    if (($uname eq $env{'user.name'}) &&
                   10946: 		($udom eq $env{'user.domain'})) {
                   10947: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10948: 	    } else {
1.359     albertel 10949: 		my %returnhash;
                   10950: 		if (!$publicuser) {
                   10951: 		    %returnhash=&userenvironment($udom,$uname,
                   10952: 						 $qualifierrest);
                   10953: 		}
1.218     albertel 10954: 		return $returnhash{$qualifierrest};
                   10955: 	    }
1.48      www      10956: # ----------------------------------------------------------------- user.course
                   10957:         } elsif ($space eq 'course') {
1.218     albertel 10958: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10959:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10960: # ------------------------------------------------------------------- user.role
                   10961:         } elsif ($space eq 'role') {
1.218     albertel 10962: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10963:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10964:             if ($qualifier eq 'value') {
                   10965: 		return $role;
                   10966:             } elsif ($qualifier eq 'extent') {
                   10967:                 return $where;
                   10968:             }
                   10969: # ----------------------------------------------------------------- user.domain
                   10970:         } elsif ($space eq 'domain') {
1.218     albertel 10971:             return $udom;
1.48      www      10972: # ------------------------------------------------------------------- user.name
                   10973:         } elsif ($space eq 'name') {
1.218     albertel 10974:             return $uname;
1.48      www      10975: # ---------------------------------------------------- Any other user namespace
1.29      www      10976:         } else {
1.359     albertel 10977: 	    my %reply;
                   10978: 	    if (!$publicuser) {
                   10979: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10980: 	    }
                   10981: 	    return $reply{$qualifierrest};
1.48      www      10982:         }
1.236     www      10983:     } elsif ($realm eq 'query') {
                   10984: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10985:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10986: 						[$spacequalifierrest]);
1.620     albertel 10987: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10988:    } elsif ($realm eq 'request') {
1.48      www      10989: # ------------------------------------------------------------- request.browser
                   10990:         if ($space eq 'browser') {
1.1145    bisitz   10991:             return $env{'browser.'.$qualifier};
1.57      www      10992: # ------------------------------------------------------------ request.filename
                   10993:         } else {
1.620     albertel 10994:             return $env{'request.'.$spacequalifierrest};
1.29      www      10995:         }
1.28      www      10996:     } elsif ($realm eq 'course') {
1.48      www      10997: # ---------------------------------------------------------- course.description
1.620     albertel 10998:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10999:     } elsif ($realm eq 'resource') {
1.165     www      11000: 
1.620     albertel 11001: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11002: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11003: 	}
1.693     albertel 11004: 
1.1172.2.30  raeburn  11005:         if ($qualifier eq '') {
                   11006: 	    if ($space eq 'title') {
                   11007: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11008: 	        return &gettitle($symbparm);
                   11009: 	    }
1.693     albertel 11010: 	
1.1172.2.30  raeburn  11011: 	    if ($space eq 'map') {
                   11012: 	        my ($map) = &decode_symb($symbparm);
                   11013: 	        return &symbread($map);
                   11014: 	    }
                   11015:             if ($space eq 'maptitle') {
                   11016:                 my ($map) = &decode_symb($symbparm);
                   11017:                 return &gettitle($map);
                   11018:             }
                   11019: 	    if ($space eq 'filename') {
                   11020: 	        if ($symbparm) {
                   11021: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11022: 	        }
                   11023: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11024: 	    }
1.1172.2.30  raeburn  11025: 
                   11026:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11027:                 if ($space eq 'visibleparts') {
                   11028:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11029:                     my $item;
                   11030:                     if (ref($navmap)) {
                   11031:                         my $res = $navmap->getBySymb($symbparm);
                   11032:                         my $parts = $res->parts();
                   11033:                         if (ref($parts) eq 'ARRAY') {
                   11034:                             $item = join(',',@{$parts});
                   11035:                         }
                   11036:                         undef($navmap);
                   11037:                     }
                   11038:                     return $item;
                   11039:                 }
                   11040:             }
                   11041:         }
1.693     albertel 11042: 
                   11043: 	my ($section, $group, @groups);
1.593     albertel 11044: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11045:         if (($courseid eq '') && ($cid)) {
                   11046:             $courseid = $cid;
                   11047:         }
                   11048: 	if (($symbparm && $courseid) && 
                   11049: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11050: 
1.218     albertel 11051: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11052: 
1.60      www      11053: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11054: 	    my $symbp=$symbparm;
1.735     albertel 11055: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11056: 
                   11057: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11058: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11059: 
1.620     albertel 11060: 	    if (($env{'user.name'} eq $uname) &&
                   11061: 		($env{'user.domain'} eq $udom)) {
                   11062: 		$section=$env{'request.course.sec'};
1.733     raeburn  11063:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11064:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11065: 	    } else {
1.539     albertel 11066: 		if (! defined($usection)) {
1.551     albertel 11067: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11068: 		} else {
                   11069: 		    $section = $usection;
                   11070: 		}
1.733     raeburn  11071:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11072: 	    }
                   11073: 
                   11074: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11075: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11076: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11077: 
1.593     albertel 11078: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11079: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11080: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11081: 
1.60      www      11082: # ----------------------------------------------------------- first, check user
1.624     albertel 11083: 
                   11084: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11085: 				       ([$courselevelr,'resource'],
                   11086: 					[$courselevelm,'map'     ],
                   11087: 					[$courselevel, 'course'  ]));
1.931     albertel 11088: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11089: 
1.594     albertel 11090: # ------------------------------------------------ second, check some of course
1.684     raeburn  11091:             my $coursereply;
1.691     raeburn  11092:             if (@groups > 0) {
                   11093:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11094:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11095:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11096:             }
1.96      www      11097: 
1.684     raeburn  11098: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11099: 				  $env{'course.'.$courseid.'.domain'},
                   11100: 				  'course',
                   11101: 				  ([$seclevelr,   'resource'],
                   11102: 				   [$seclevelm,   'map'     ],
                   11103: 				   [$seclevel,    'course'  ],
                   11104: 				   [$courselevelr,'resource']));
                   11105: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11106: 
1.60      www      11107: # ------------------------------------------------------ third, check map parms
1.218     albertel 11108: 	    my %parmhash=();
                   11109: 	    my $thisparm='';
                   11110: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11111: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11112: 		    &GDBM_READER(),0640)) {
1.218     albertel 11113: 		$thisparm=$parmhash{$symbparm};
                   11114: 		untie(%parmhash);
                   11115: 	    }
1.927     albertel 11116: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11117: 	}
1.594     albertel 11118: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11119: 
1.218     albertel 11120: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11121: 	my $filename;
                   11122: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11123: 	if ($symbparm) {
1.409     www      11124: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11125: 	} else {
1.620     albertel 11126: 	    $filename=$env{'request.filename'};
1.282     albertel 11127: 	}
                   11128: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11129: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11130: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11131: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11132: 
1.927     albertel 11133: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11134: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11135: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11136: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11137: 				     $env{'course.'.$courseid.'.domain'},
                   11138: 				     'course',
1.927     albertel 11139: 				     ([$courselevelm,'map'   ],
                   11140: 				      [$courselevel, 'course']));
                   11141: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11142: 	}
1.145     www      11143: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11144: 	unless ($space eq '0') {
1.336     albertel 11145: 	    my @parts=split(/_/,$space);
                   11146: 	    my $id=pop(@parts);
                   11147: 	    my $part=join('_',@parts);
                   11148: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11149: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11150: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11151: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11152: 	}
1.395     albertel 11153: 	if ($recurse) { return undef; }
                   11154: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11155: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11156: # ---------------------------------------------------- Any other user namespace
                   11157:     } elsif ($realm eq 'environment') {
                   11158: # ----------------------------------------------------------------- environment
1.620     albertel 11159: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11160: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11161: 	} else {
1.770     albertel 11162: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11163: 		return '';
                   11164: 	    }
1.219     albertel 11165: 	    my %returnhash=&userenvironment($udom,$uname,
                   11166: 					    $spacequalifierrest);
                   11167: 	    return $returnhash{$spacequalifierrest};
                   11168: 	}
1.28      www      11169:     } elsif ($realm eq 'system') {
1.48      www      11170: # ----------------------------------------------------------------- system.time
                   11171: 	if ($space eq 'time') {
                   11172: 	    return time;
                   11173:         }
1.696     albertel 11174:     } elsif ($realm eq 'server') {
                   11175: # ----------------------------------------------------------------- system.time
                   11176: 	if ($space eq 'name') {
                   11177: 	    return $ENV{'SERVER_NAME'};
                   11178:         }
1.28      www      11179:     }
1.48      www      11180:     return '';
1.61      www      11181: }
                   11182: 
1.927     albertel 11183: sub get_reply {
                   11184:     my ($reply_value) = @_;
1.940     raeburn  11185:     if (ref($reply_value) eq 'ARRAY') {
                   11186:         if (wantarray) {
                   11187: 	    return @$reply_value;
                   11188:         }
                   11189:         return $reply_value->[0];
                   11190:     } else {
                   11191:         return $reply_value;
1.927     albertel 11192:     }
                   11193: }
                   11194: 
1.691     raeburn  11195: sub check_group_parms {
                   11196:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11197:     my @groupitems = ();
                   11198:     my $resultitem;
1.927     albertel 11199:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11200:     foreach my $group (@{$groups}) {
                   11201:         foreach my $level (@levels) {
1.927     albertel 11202:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11203:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11204:         }
                   11205:     }
                   11206:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11207:                             $env{'course.'.$courseid.'.domain'},
                   11208:                                      'course',@groupitems);
                   11209:     return $coursereply;
                   11210: }
                   11211: 
                   11212: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11213:     my ($courseid,@groups) = @_;
                   11214:     @groups = sort(@groups);
1.691     raeburn  11215:     return @groups;
                   11216: }
                   11217: 
1.395     albertel 11218: sub packages_tab_default {
                   11219:     my ($uri,$varname)=@_;
                   11220:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11221: 
                   11222:     my (@extension,@specifics,$do_default);
                   11223:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11224: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11225: 	if ($pack_type eq 'default') {
                   11226: 	    $do_default=1;
                   11227: 	} elsif ($pack_type eq 'extension') {
                   11228: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11229: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11230: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11231: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11232: 	}
                   11233:     }
                   11234:     # first look for a package that matches the requested part id
                   11235:     foreach my $package (@specifics) {
                   11236: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11237: 	next if ($pack_part ne $part);
                   11238: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11239: 	    return $packagetab{"$pack_type&$name&default"};
                   11240: 	}
                   11241:     }
                   11242:     # look for any possible matching non extension_ package
                   11243:     foreach my $package (@specifics) {
                   11244: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11245: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11246: 	    return $packagetab{"$pack_type&$name&default"};
                   11247: 	}
1.585     albertel 11248: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11249: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11250: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11251: 	}
                   11252:     }
1.738     albertel 11253:     # look for any posible extension_ match
                   11254:     foreach my $package (@extension) {
                   11255: 	my ($package,$pack_type)=@{$package};
                   11256: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11257: 	    return $packagetab{"$pack_type&$name&default"};
                   11258: 	}
                   11259: 	if (defined($packagetab{$package."&$name&default"})) {
                   11260: 	    return $packagetab{$package."&$name&default"};
                   11261: 	}
                   11262:     }
                   11263:     # look for a global default setting
                   11264:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11265: 	return $packagetab{"default&$name&default"};
                   11266:     }
1.395     albertel 11267:     return undef;
                   11268: }
                   11269: 
1.334     albertel 11270: sub add_prefix_and_part {
                   11271:     my ($prefix,$part)=@_;
                   11272:     my $keyroot;
                   11273:     if (defined($prefix) && $prefix !~ /^__/) {
                   11274: 	# prefix that has a part already
                   11275: 	$keyroot=$prefix;
                   11276:     } elsif (defined($prefix)) {
                   11277: 	# prefix that is missing a part
                   11278: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11279:     } else {
                   11280: 	# no prefix at all
                   11281: 	if (defined($part)) { $keyroot='_'.$part; }
                   11282:     }
                   11283:     return $keyroot;
                   11284: }
                   11285: 
1.71      www      11286: # ---------------------------------------------------------------- Get metadata
                   11287: 
1.599     albertel 11288: my %metaentry;
1.1070    www      11289: my %importedpartids;
1.1172.2.99  raeburn  11290: my %importedrespids;
1.71      www      11291: sub metadata {
1.176     www      11292:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11293:     $uri=&declutter($uri);
1.288     albertel 11294:     # if it is a non metadata possible uri return quickly
1.529     albertel 11295:     if (($uri eq '') || 
                   11296: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11297: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11298:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11299: 	return undef;
                   11300:     }
1.1172.2.49  raeburn  11301:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11302: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11303: 	return undef;
1.288     albertel 11304:     }
1.73      www      11305:     my $filename=$uri;
                   11306:     $uri=~s/\.meta$//;
1.172     www      11307: #
                   11308: # Is the metadata already cached?
1.177     www      11309: # Look at timestamp of caching
1.172     www      11310: # Everything is cached by the main uri, libraries are never directly cached
                   11311: #
1.428     albertel 11312:     if (!defined($liburi)) {
1.599     albertel 11313: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11314: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11315:     }
                   11316:     {
1.1069    www      11317: # Imported parts would go here
1.1172.2.99  raeburn  11318:         my @origfiletagids=();
1.1069    www      11319:         my $importedparts=0;
1.1172.2.99  raeburn  11320: 
                   11321: # Imported responseids would go here
                   11322:         my $importedresponses=0;
1.172     www      11323: #
                   11324: # Is this a recursive call for a library?
                   11325: #
1.599     albertel 11326: #	if (! exists($metacache{$uri})) {
                   11327: #	    $metacache{$uri}={};
                   11328: #	}
1.924     albertel 11329: 	my $cachetime = 60*60;
1.171     www      11330:         if ($liburi) {
                   11331: 	    $liburi=&declutter($liburi);
                   11332:             $filename=$liburi;
1.401     bowersj2 11333:         } else {
1.599     albertel 11334: 	    &devalidate_cache_new('meta',$uri);
                   11335: 	    undef(%metaentry);
1.401     bowersj2 11336: 	}
1.140     www      11337:         my %metathesekeys=();
1.73      www      11338:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11339: 	my $metastring;
1.1140    www      11340: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11341: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11342: 	    $metastring = 
1.929     albertel 11343: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11344: 					  ('grade_target' => 'meta'));
                   11345: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11346: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11347:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11348: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11349: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11350: 	    $metastring=&getfile($file);
1.489     albertel 11351: 	}
1.208     albertel 11352:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11353:         my $token;
1.140     www      11354:         undef %metathesekeys;
1.71      www      11355:         while ($token=$parser->get_token) {
1.339     albertel 11356: 	    if ($token->[0] eq 'S') {
                   11357: 		if (defined($token->[2]->{'package'})) {
1.172     www      11358: #
                   11359: # This is a package - get package info
                   11360: #
1.339     albertel 11361: 		    my $package=$token->[2]->{'package'};
                   11362: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11363: 		    if (defined($token->[2]->{'id'})) { 
                   11364: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11365: 		    }
1.599     albertel 11366: 		    if ($metaentry{':packages'}) {
                   11367: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11368: 		    } else {
1.599     albertel 11369: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11370: 		    }
1.736     albertel 11371: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11372: 			my $part=$keyroot;
                   11373: 			$part=~s/^\_//;
1.736     albertel 11374: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11375: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11376: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11377: 			    # ignore package.tab specified default values
                   11378:                             # here &package_tab_default() will fetch those
                   11379: 			    if ($subp eq 'default') { next; }
1.736     albertel 11380: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11381: 			    my $unikey;
                   11382: 			    if ($pack =~ /_0$/) {
                   11383: 				$unikey='parameter_0_'.$name;
                   11384: 				$part=0;
                   11385: 			    } else {
                   11386: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11387: 			    }
1.339     albertel 11388: 			    if ($subp eq 'display') {
                   11389: 				$value.=' [Part: '.$part.']';
                   11390: 			    }
1.599     albertel 11391: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11392: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11393: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11394: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11395: 			    }
1.599     albertel 11396: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11397: 				$metaentry{':'.$unikey}=
                   11398: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11399: 			    }
1.339     albertel 11400: 			}
                   11401: 		    }
                   11402: 		} else {
1.172     www      11403: #
                   11404: # This is not a package - some other kind of start tag
1.339     albertel 11405: #
                   11406: 		    my $entry=$token->[1];
1.1068    www      11407: 		    my $unikey='';
1.175     www      11408: 
1.339     albertel 11409: 		    if ($entry eq 'import') {
1.175     www      11410: #
                   11411: # Importing a library here
1.339     albertel 11412: #
1.1067    www      11413:                         my $location=$parser->get_text('/import');
                   11414:                         my $dir=$filename;
                   11415:                         $dir=~s|[^/]*$||;
                   11416:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11417: 
                   11418:                         my $importid=$token->[2]->{'id'};
1.1068    www      11419:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11420: #
                   11421: # Check metadata for imported file to
                   11422: # see if it contained response items
                   11423: #
                   11424:                         my %currmetaentry = %metaentry;
                   11425:                         my $libresponseorder = &metadata($location,'responseorder');
                   11426:                         my $origfile;
                   11427:                         if ($libresponseorder ne '') {
                   11428:                             if ($#origfiletagids<0) {
                   11429:                                 undef(%importedrespids);
                   11430:                                 undef(%importedpartids);
                   11431:                             }
                   11432:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11433:                             if (@{$importedrespids{$importid}} > 0) {
                   11434:                                 $importedresponses = 1;
                   11435: # We need to get the original file and the imported file to get the response order correct
                   11436: # Load and inspect original file
                   11437:                                 if ($#origfiletagids<0) {
                   11438:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11439:                                     $origfile=&getfile($origfilelocation);
                   11440:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11441:                                 }
                   11442:                             }
                   11443:                         }
                   11444: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11445: # hash populated for imported library file
                   11446:                         %metaentry = %currmetaentry;
                   11447:                         undef(%currmetaentry);
1.1068    www      11448:                         if ($importmode eq 'problem') {
1.1069    www      11449: # Import as problem/response
1.1068    www      11450:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11451:                         } elsif ($importmode eq 'part') {
                   11452: # Import as part(s)
1.1069    www      11453:                            $importedparts=1;
                   11454: # We need to get the original file and the imported file to get the part order correct
                   11455: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11456: # Load and inspect original file if we didn't do that already
                   11457:                            if ($#origfiletagids<0) {
                   11458:                                undef(%importedrespids);
                   11459:                                undef(%importedpartids);
                   11460:                                if ($origfile eq '') {
                   11461:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11462:                                    $origfile=&getfile($origfilelocation);
                   11463:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11464:                                }
1.1070    www      11465:                            }
                   11466: 
1.1069    www      11467: # Load and inspect imported file
                   11468:                            my $impfile=&getfile($location);
                   11469:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11470:                            if ($#impfilepartids>=0) {
                   11471: # This problem had parts
1.1070    www      11472:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11473:                            } else {
                   11474: # Importing by turning a single problem into a problem part
                   11475: # It gets the import-tags ID as part-ID
                   11476:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11477:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11478:                            }
1.1068    www      11479:                         } else {
                   11480: # Normal import
                   11481:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11482:                            if (defined($token->[2]->{'id'})) {
                   11483:                               $unikey.='_'.$token->[2]->{'id'};
                   11484:                            }
1.1067    www      11485:                         }
                   11486: 
1.339     albertel 11487: 			if ($depthcount<20) {
1.736     albertel 11488: 			    my $metadata = 
                   11489: 				&metadata($uri,'keys', $location,$unikey,
                   11490: 					  $depthcount+1);
                   11491: 			    foreach my $meta (split(',',$metadata)) {
                   11492: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11493: 				$metathesekeys{$meta}=1;
1.339     albertel 11494: 			    }
1.1068    www      11495: 			
                   11496:                         }
1.1067    www      11497: 		    } else {
                   11498: #
                   11499: # Not importing, some other kind of non-package, non-library start tag
                   11500: # 
                   11501:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11502:                         if (defined($token->[2]->{'id'})) {
                   11503:                             $unikey.='_'.$token->[2]->{'id'};
                   11504:                         }
1.339     albertel 11505: 			if (defined($token->[2]->{'name'})) { 
                   11506: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11507: 			}
                   11508: 			$metathesekeys{$unikey}=1;
1.736     albertel 11509: 			foreach my $param (@{$token->[3]}) {
                   11510: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11511: 				$token->[2]->{$param};
1.339     albertel 11512: 			}
                   11513: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11514: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11515: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11516: 		 # only ws inside the tag, and not in default, so use default
                   11517: 		 # as value
1.599     albertel 11518: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11519: 			} elsif ( $internaltext =~ /\S/ ) {
                   11520: 		  # something interesting inside the tag
                   11521: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11522: 			} else {
1.908     albertel 11523: 		  # no interesting values, don't set a default
1.339     albertel 11524: 			}
1.172     www      11525: # end of not-a-package not-a-library import
1.339     albertel 11526: 		    }
1.172     www      11527: # end of not-a-package start tag
1.339     albertel 11528: 		}
1.172     www      11529: # the next is the end of "start tag"
1.339     albertel 11530: 	    }
                   11531: 	}
1.483     albertel 11532: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11533: 	$extension = lc($extension);
                   11534: 	if ($extension eq 'htm') { $extension='html'; }
                   11535: 
1.737     albertel 11536: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11537: 	    #no specific packages #how's our extension
                   11538: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11539: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11540: 					 \%metathesekeys);
                   11541: 	}
1.883     albertel 11542: 
                   11543: 	if (!exists($metaentry{':packages'})
                   11544: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11545: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11546: 		#no specific packages well let's get default then
                   11547: 		if ($key!~/^default&/) { next; }
1.488     albertel 11548: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11549: 					     \%metathesekeys);
                   11550: 	    }
                   11551: 	}
1.338     www      11552: # are there custom rights to evaluate
1.599     albertel 11553: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11554: 
1.338     www      11555:     #
                   11556:     # Importing a rights file here
1.339     albertel 11557:     #
                   11558: 	    unless ($depthcount) {
1.599     albertel 11559: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11560: 		my $dir=$filename;
                   11561: 		$dir=~s|[^/]*$||;
                   11562: 		$location=&filelocation($dir,$location);
1.736     albertel 11563: 		my $rights_metadata =
                   11564: 		    &metadata($uri,'keys',$location,'_rights',
                   11565: 			      $depthcount+1);
                   11566: 		foreach my $rights (split(',',$rights_metadata)) {
                   11567: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11568: 		    $metathesekeys{$rights}=1;
1.339     albertel 11569: 		}
                   11570: 	    }
                   11571: 	}
1.737     albertel 11572: 	# uniqifiy package listing
                   11573: 	my %seen;
                   11574: 	my @uniq_packages =
                   11575: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11576: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11577: 
1.1172.2.99  raeburn  11578:         if (($importedresponses) || ($importedparts)) {
                   11579:             if ($importedparts) {
1.1070    www      11580: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  11581:                 $metaentry{':partorder'}='';
                   11582:                 $metathesekeys{'partorder'}=1;
                   11583:             }
                   11584:             if ($importedresponses) {
                   11585: # We had imported responses and need to rebuild responseorder
                   11586:                 $metaentry{':responseorder'}='';
                   11587:                 $metathesekeys{'responseorder'}=1;
                   11588:             }
                   11589:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11590:                 my $origid = $origfiletagids[$index+1];
                   11591:                 if ($origfiletagids[$index] eq 'part') {
                   11592: # Original part, part of the problem
                   11593:                     if ($importedparts) {
                   11594:                         $metaentry{':partorder'}.=','.$origid;
                   11595:                     }
                   11596:                 } elsif ($origfiletagids[$index] eq 'import') {
                   11597:                     if ($importedparts) {
                   11598: # We have imported parts at this position
                   11599:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11600:                     }
                   11601:                     if ($importedresponses) {
                   11602: # We have imported responses at this position
                   11603:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11604:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11605:                         }
                   11606:                     }
                   11607:                 } else {
                   11608: # Original response item, part of the problem
                   11609:                     if ($importedresponses) {
                   11610:                         $metaentry{':responseorder'}.=','.$origid;
                   11611:                     }
                   11612:                 }
                   11613:             }
                   11614:             if ($importedparts) {
                   11615:                 $metaentry{':partorder'}=~s/^\,//;
                   11616:             }
                   11617:             if ($importedresponses) {
                   11618:                 $metaentry{':responseorder'}=~s/^\,//;
                   11619:             }
1.1070    www      11620:         }
                   11621: 
1.737     albertel 11622: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11623: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11624: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11625: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11626: # this is the end of "was not already recently cached
1.71      www      11627:     }
1.599     albertel 11628:     return $metaentry{':'.$what};
1.261     albertel 11629: }
                   11630: 
1.488     albertel 11631: sub metadata_create_package_def {
1.483     albertel 11632:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11633:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11634:     if ($subp eq 'default') { next; }
                   11635:     
1.599     albertel 11636:     if (defined($metaentry{':packages'})) {
                   11637: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11638:     } else {
1.599     albertel 11639: 	$metaentry{':packages'}=$package;
1.483     albertel 11640:     }
                   11641:     my $value=$packagetab{$key};
                   11642:     my $unikey;
                   11643:     $unikey='parameter_0_'.$name;
1.599     albertel 11644:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11645:     $$metathesekeys{$unikey}=1;
1.599     albertel 11646:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11647: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11648:     }
1.599     albertel 11649:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11650: 	$metaentry{':'.$unikey}=
                   11651: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11652:     }
                   11653: }
                   11654: 
1.261     albertel 11655: sub metadata_generate_part0 {
                   11656:     my ($metadata,$metacache,$uri) = @_;
                   11657:     my %allnames;
1.737     albertel 11658:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11659: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11660: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11661: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11662: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11663: 	    $allnames{$name}=$part;
                   11664: 	  }
                   11665: 	}
                   11666:     }
                   11667:     foreach my $name (keys(%allnames)) {
                   11668:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11669:       my $key=":parameter_0_$name";
1.261     albertel 11670:       $$metacache{"$key.part"}='0';
                   11671:       $$metacache{"$key.name"}=$name;
1.428     albertel 11672:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11673: 					   $allnames{$name}.'_'.$name.
                   11674: 					   '.type'};
1.428     albertel 11675:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11676: 			     '.display'};
1.644     www      11677:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11678:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11679:       $$metacache{"$key.display"}=$olddis;
                   11680:     }
1.71      www      11681: }
                   11682: 
1.764     albertel 11683: # ------------------------------------------------------ Devalidate title cache
                   11684: 
                   11685: sub devalidate_title_cache {
                   11686:     my ($url)=@_;
                   11687:     if (!$env{'request.course.id'}) { return; }
                   11688:     my $symb=&symbread($url);
                   11689:     if (!$symb) { return; }
                   11690:     my $key=$env{'request.course.id'}."\0".$symb;
                   11691:     &devalidate_cache_new('title',$key);
                   11692: }
                   11693: 
1.1014    droeschl 11694: # ------------------------------------------------- Get the title of a course
                   11695: 
                   11696: sub current_course_title {
                   11697:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11698: }
1.301     www      11699: # ------------------------------------------------- Get the title of a resource
                   11700: 
                   11701: sub gettitle {
                   11702:     my $urlsymb=shift;
                   11703:     my $symb=&symbread($urlsymb);
1.534     albertel 11704:     if ($symb) {
1.620     albertel 11705: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11706: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11707: 	if (defined($cached)) { 
                   11708: 	    return $result;
                   11709: 	}
1.534     albertel 11710: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11711: 	my $title='';
1.907     albertel 11712: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11713: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11714: 	} else {
                   11715: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11716: 		    &GDBM_READER(),0640)) {
                   11717: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11718: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11719: 		untie(%bighash);
                   11720: 	    }
1.534     albertel 11721: 	}
                   11722: 	$title=~s/\&colon\;/\:/gs;
                   11723: 	if ($title) {
1.1159    www      11724: # Remember both $symb and $title for dynamic metadata
                   11725:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11726:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11727: # Cache this title and then return it
1.599     albertel 11728: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11729: 	}
                   11730: 	$urlsymb=$url;
                   11731:     }
                   11732:     my $title=&metadata($urlsymb,'title');
                   11733:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11734:     return $title;
1.301     www      11735: }
1.613     albertel 11736: 
1.614     albertel 11737: sub get_slot {
                   11738:     my ($which,$cnum,$cdom)=@_;
                   11739:     if (!$cnum || !$cdom) {
1.790     albertel 11740: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11741: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11742: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11743:     }
1.703     albertel 11744:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11745:     my %slotinfo;
                   11746:     if (exists($remembered{$key})) {
                   11747: 	$slotinfo{$which} = $remembered{$key};
                   11748:     } else {
                   11749: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11750: 	&Apache::lonhomework::showhash(%slotinfo);
                   11751: 	my ($tmp)=keys(%slotinfo);
                   11752: 	if ($tmp=~/^error:/) { return (); }
                   11753: 	$remembered{$key} = $slotinfo{$which};
                   11754:     }
1.616     albertel 11755:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11756: 	return %{$slotinfo{$which}};
                   11757:     }
                   11758:     return $slotinfo{$which};
1.614     albertel 11759: }
1.1150    raeburn  11760: 
                   11761: sub get_reservable_slots {
                   11762:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11763:     my $now = time;
                   11764:     my $reservable_info;
                   11765:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11766:     if (exists($remembered{$key})) {
                   11767:         $reservable_info = $remembered{$key};
                   11768:     } else {
                   11769:         my %resv;
                   11770:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11771:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11772:         $reservable_info = \%resv;
                   11773:         $remembered{$key} = $reservable_info;
                   11774:     }
                   11775:     return $reservable_info;
                   11776: }
                   11777: 
                   11778: sub get_course_slots {
                   11779:     my ($cnum,$cdom) = @_;
                   11780:     my $hashid=$cnum.':'.$cdom;
                   11781:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11782:     if (defined($cached)) {
                   11783:         if (ref($result) eq 'HASH') {
                   11784:             return %{$result};
                   11785:         }
                   11786:     } else {
                   11787:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11788:         my ($tmp) = keys(%slots);
                   11789:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11790:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11791:             return %slots;
                   11792:         }
                   11793:     }
                   11794:     return;
                   11795: }
                   11796: 
                   11797: sub devalidate_slots_cache {
                   11798:     my ($cnum,$cdom)=@_;
                   11799:     my $hashid=$cnum.':'.$cdom;
                   11800:     &devalidate_cache_new('allslots',$hashid);
                   11801: }
                   11802: 
1.1172.2.8  raeburn  11803: sub get_coursechange {
                   11804:     my ($cdom,$cnum) = @_;
                   11805:     if ($cdom eq '' || $cnum eq '') {
                   11806:         return unless ($env{'request.course.id'});
                   11807:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11808:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11809:     }
                   11810:     my $hashid=$cdom.'_'.$cnum;
                   11811:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11812:     if ((defined($cached)) && ($change ne '')) {
                   11813:         return $change;
                   11814:     } else {
                   11815:         my %crshash;
                   11816:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11817:         if ($crshash{'internal.contentchange'} eq '') {
                   11818:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11819:             if ($change eq '') {
                   11820:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11821:                 $change = $crshash{'internal.created'};
                   11822:             }
                   11823:         } else {
                   11824:             $change = $crshash{'internal.contentchange'};
                   11825:         }
                   11826:         my $cachetime = 600;
                   11827:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11828:     }
                   11829:     return $change;
                   11830: }
                   11831: 
                   11832: sub devalidate_coursechange_cache {
                   11833:     my ($cnum,$cdom)=@_;
                   11834:     my $hashid=$cnum.':'.$cdom;
                   11835:     &devalidate_cache_new('crschange',$hashid);
                   11836: }
                   11837: 
1.31      www      11838: # ------------------------------------------------- Update symbolic store links
                   11839: 
                   11840: sub symblist {
                   11841:     my ($mapname,%newhash)=@_;
1.438     www      11842:     $mapname=&deversion(&declutter($mapname));
1.31      www      11843:     my %hash;
1.620     albertel 11844:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11845:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11846:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11847: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11848: 		next if ($url eq 'last_known'
                   11849: 			 && $env{'form.no_update_last_known'});
                   11850: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11851: 						    $newhash{$url}->[1],
                   11852: 						    $newhash{$url}->[0]);
1.191     harris41 11853:             }
1.31      www      11854:             if (untie(%hash)) {
                   11855: 		return 'ok';
                   11856:             }
                   11857:         }
                   11858:     }
                   11859:     return 'error';
1.212     www      11860: }
                   11861: 
                   11862: # --------------------------------------------------------------- Verify a symb
                   11863: 
                   11864: sub symbverify {
1.1172.2.11  raeburn  11865:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11866:     my $thisfn=$thisurl;
1.439     www      11867:     $thisfn=&declutter($thisfn);
1.215     www      11868: # direct jump to resource in page or to a sequence - will construct own symbs
                   11869:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11870: # check URL part
1.409     www      11871:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11872: 
1.431     www      11873:     unless ($url eq $thisfn) { return 0; }
1.213     www      11874: 
1.216     www      11875:     $symb=&symbclean($symb);
1.510     www      11876:     $thisurl=&deversion($thisurl);
1.439     www      11877:     $thisfn=&deversion($thisfn);
1.213     www      11878: 
                   11879:     my %bighash;
                   11880:     my $okay=0;
1.431     www      11881: 
1.620     albertel 11882:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11883:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11884:         my $noclutter;
1.1032    raeburn  11885:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11886:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11887:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11888:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11889:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11890:                 $noclutter = 1;
                   11891:             }
                   11892:         }
                   11893:         my $ids;
                   11894:         if ($noclutter) {
                   11895:             $ids=$bighash{'ids_'.$thisurl};
                   11896:         } else {
                   11897:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11898:         }
1.1102    raeburn  11899:         unless ($ids) {
1.1172.2.13  raeburn  11900:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11901:             $ids=$bighash{$idkey};
1.216     www      11902:         }
                   11903:         if ($ids) {
                   11904: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11905:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11906:                 $symb =~ s/\?.+$//;
                   11907:             }
1.800     albertel 11908: 	    foreach my $id (split(/\,/,$ids)) {
                   11909: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11910:                if (
                   11911:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11912:    eq $symb) {
1.1172.2.11  raeburn  11913:                    if (ref($encstate)) {
                   11914:                        $$encstate = $bighash{'encrypted_'.$id};
                   11915:                    }
1.1172.2.13  raeburn  11916:                    if (($env{'request.role.adv'}) ||
                   11917:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11918:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11919:                        $okay=1;
                   11920:                        last;
                   11921:                    }
                   11922:                }
                   11923:            }
1.216     www      11924:         }
1.213     www      11925: 	untie(%bighash);
                   11926:     }
                   11927:     return $okay;
1.31      www      11928: }
                   11929: 
1.210     www      11930: # --------------------------------------------------------------- Clean-up symb
                   11931: 
                   11932: sub symbclean {
                   11933:     my $symb=shift;
1.568     albertel 11934:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11935: # remove version from map
                   11936:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11937: 
1.210     www      11938: # remove version from URL
                   11939:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11940: 
1.507     www      11941: # remove wrapper
                   11942: 
1.510     www      11943:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11944:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11945:     return $symb;
1.409     www      11946: }
                   11947: 
                   11948: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11949: 
                   11950: sub encode_symb {
                   11951:     my ($map,$resid,$url)=@_;
                   11952:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11953: }
1.409     www      11954: 
                   11955: sub decode_symb {
1.568     albertel 11956:     my $symb=shift;
                   11957:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11958:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11959:     return (&fixversion($map),$resid,&fixversion($url));
                   11960: }
                   11961: 
                   11962: sub fixversion {
                   11963:     my $fn=shift;
1.609     banghart 11964:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11965:     my %bighash;
                   11966:     my $uri=&clutter($fn);
1.620     albertel 11967:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11968: # is this cached?
1.599     albertel 11969:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11970:     if (defined($cached)) { return $result; }
                   11971: # unfortunately not cached, or expired
1.620     albertel 11972:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11973: 	    &GDBM_READER(),0640)) {
                   11974:  	if ($bighash{'version_'.$uri}) {
                   11975:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11976:  	    unless (($version eq 'mostrecent') || 
                   11977: 		    ($version==&getversion($uri))) {
1.440     www      11978:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11979:  	    }
                   11980:  	}
                   11981:  	untie %bighash;
1.413     www      11982:     }
1.599     albertel 11983:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11984: }
                   11985: 
                   11986: sub deversion {
                   11987:     my $url=shift;
                   11988:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11989:     return $url;
1.210     www      11990: }
                   11991: 
1.31      www      11992: # ------------------------------------------------------ Return symb list entry
                   11993: 
                   11994: sub symbread {
1.1172.2.66  raeburn  11995:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11996:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11997:     if (defined($env{$cache_str})) {
                   11998:         if ($ignorecachednull) {
                   11999:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12000:         } else {
                   12001:             return $env{$cache_str};
                   12002:         }
                   12003:     }
1.242     www      12004: # no filename provided? try from environment
1.1172.2.54  raeburn  12005:     unless ($thisfn) {
1.620     albertel 12006:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  12007:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12008:         }
                   12009:         $thisfn=$env{'request.filename'};
1.44      www      12010:     }
1.569     albertel 12011:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12012: # is that filename actually a symb? Verify, clean, and return
                   12013:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12014: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12015: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12016: 	}
1.242     www      12017:     }
1.44      www      12018:     $thisfn=declutter($thisfn);
1.31      www      12019:     my %hash;
1.37      www      12020:     my %bighash;
                   12021:     my $syval='';
1.620     albertel 12022:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12023:         my $targetfn = $thisfn;
1.609     banghart 12024:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12025:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12026:         }
1.687     albertel 12027: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12028: 	    $targetfn=$1;
                   12029: 	}
1.620     albertel 12030:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12031:                       &GDBM_READER(),0640)) {
1.481     raeburn  12032: 	    $syval=$hash{$targetfn};
1.37      www      12033:             untie(%hash);
                   12034:         }
                   12035: # ---------------------------------------------------------- There was an entry
                   12036:         if ($syval) {
1.601     albertel 12037: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12038: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12039: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12040: 		    #return $env{$cache_str}='';
1.601     albertel 12041: 		#}    
                   12042: 		#$syval.=$1;
                   12043: 	    #}
1.37      www      12044:         } else {
                   12045: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12046:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12047:                             &GDBM_READER(),0640)) {
1.37      www      12048: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12049:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12050:               unless ($ids) { 
                   12051:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12052:               }
                   12053:               unless ($ids) {
                   12054: # alias?
                   12055: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12056:               }
1.37      www      12057:               if ($ids) {
                   12058: # ------------------------------------------------------------------- Has ID(s)
                   12059:                  my @possibilities=split(/\,/,$ids);
1.39      www      12060:                  if ($#possibilities==0) {
                   12061: # ----------------------------------------------- There is only one possibility
1.37      www      12062: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12063: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12064: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12065:                      if (ref($possibles) eq 'HASH') {
                   12066:                          $possibles->{$syval} = 1;
                   12067:                      }
                   12068:                      if ($checkforblock) {
                   12069:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12070:                          if (@blockers) {
                   12071:                              $syval = '';
                   12072:                              return;
                   12073:                          }
                   12074:                      }
                   12075:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12076: # ------------------------------------------ There is more than one possibility
                   12077:                      my $realpossible=0;
1.800     albertel 12078:                      foreach my $id (@possibilities) {
                   12079: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12080:                          my $canaccess;
                   12081:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12082:                              $canaccess = 1;
                   12083:                          } else {
                   12084:                              $canaccess = &allowed('bre',$file);
                   12085:                          }
                   12086:                          if ($canaccess) {
                   12087:          		     my ($mapid,$resid)=split(/\./,$id);
                   12088:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12089:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12090:                                                              $resid,$thisfn);
                   12091:                                  if (ref($possibles) eq 'HASH') {
                   12092:                                      $possibles->{$syval} = 1;
                   12093:                                  }
                   12094:                                  if ($checkforblock) {
                   12095:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12096:                                      unless (@blockers > 0) {
                   12097:                                          $syval = $poss_syval;
                   12098:                                          $realpossible++;
                   12099:                                      }
                   12100:                                  } else {
                   12101:                                      $syval = $poss_syval;
                   12102:                                      $realpossible++;
                   12103:                                  }
                   12104:                              }
1.39      www      12105: 			 }
1.191     harris41 12106:                      }
1.39      www      12107: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12108:                  } else {
                   12109:                      $syval='';
1.37      www      12110:                  }
                   12111: 	      }
1.1172.2.66  raeburn  12112:               untie(%bighash);
1.481     raeburn  12113:            }
1.31      www      12114:         }
1.62      www      12115:         if ($syval) {
1.620     albertel 12116: 	    return $env{$cache_str}=$syval;
1.62      www      12117:         }
1.31      www      12118:     }
1.949     raeburn  12119:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12120:     return $env{$cache_str}='';
1.31      www      12121: }
                   12122: 
                   12123: # ---------------------------------------------------------- Return random seed
                   12124: 
1.32      www      12125: sub numval {
                   12126:     my $txt=shift;
                   12127:     $txt=~tr/A-J/0-9/;
                   12128:     $txt=~tr/a-j/0-9/;
                   12129:     $txt=~tr/K-T/0-9/;
                   12130:     $txt=~tr/k-t/0-9/;
                   12131:     $txt=~tr/U-Z/0-5/;
                   12132:     $txt=~tr/u-z/0-5/;
                   12133:     $txt=~s/\D//g;
1.564     albertel 12134:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12135:     return int($txt);
1.368     albertel 12136: }
                   12137: 
1.484     albertel 12138: sub numval2 {
                   12139:     my $txt=shift;
                   12140:     $txt=~tr/A-J/0-9/;
                   12141:     $txt=~tr/a-j/0-9/;
                   12142:     $txt=~tr/K-T/0-9/;
                   12143:     $txt=~tr/k-t/0-9/;
                   12144:     $txt=~tr/U-Z/0-5/;
                   12145:     $txt=~tr/u-z/0-5/;
                   12146:     $txt=~s/\D//g;
                   12147:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12148:     my $total;
                   12149:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12150:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12151:     return int($total);
                   12152: }
                   12153: 
1.575     albertel 12154: sub numval3 {
                   12155:     use integer;
                   12156:     my $txt=shift;
                   12157:     $txt=~tr/A-J/0-9/;
                   12158:     $txt=~tr/a-j/0-9/;
                   12159:     $txt=~tr/K-T/0-9/;
                   12160:     $txt=~tr/k-t/0-9/;
                   12161:     $txt=~tr/U-Z/0-5/;
                   12162:     $txt=~tr/u-z/0-5/;
                   12163:     $txt=~s/\D//g;
                   12164:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12165:     my $total;
                   12166:     foreach my $val (@txts) { $total+=$val; }
                   12167:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12168:     return $total;
                   12169: }
                   12170: 
1.675     albertel 12171: sub digest {
                   12172:     my ($data)=@_;
                   12173:     my $digest=&Digest::MD5::md5($data);
                   12174:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12175:     my ($e,$f);
                   12176:     {
                   12177:         use integer;
                   12178:         $e=($a+$b);
                   12179:         $f=($c+$d);
                   12180:         if ($_64bit) {
                   12181:             $e=(($e<<32)>>32);
                   12182:             $f=(($f<<32)>>32);
                   12183:         }
                   12184:     }
                   12185:     if (wantarray) {
                   12186: 	return ($e,$f);
                   12187:     } else {
                   12188: 	my $g;
                   12189: 	{
                   12190: 	    use integer;
                   12191: 	    $g=($e+$f);
                   12192: 	    if ($_64bit) {
                   12193: 		$g=(($g<<32)>>32);
                   12194: 	    }
                   12195: 	}
                   12196: 	return $g;
                   12197:     }
                   12198: }
                   12199: 
1.368     albertel 12200: sub latest_rnd_algorithm_id {
1.675     albertel 12201:     return '64bit5';
1.366     albertel 12202: }
1.32      www      12203: 
1.503     albertel 12204: sub get_rand_alg {
                   12205:     my ($courseid)=@_;
1.790     albertel 12206:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12207:     if ($courseid) {
1.620     albertel 12208: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12209:     }
                   12210:     return &latest_rnd_algorithm_id();
                   12211: }
                   12212: 
1.562     albertel 12213: sub validCODE {
                   12214:     my ($CODE)=@_;
                   12215:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12216:     return 0;
                   12217: }
                   12218: 
1.491     albertel 12219: sub getCODE {
1.620     albertel 12220:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12221:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12222: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12223: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12224: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12225:     }
                   12226:     return undef;
                   12227: }
1.1133    foxr     12228: #
                   12229: #  Determines the random seed for a specific context:
                   12230: #
                   12231: # parameters:
                   12232: #   symb      - in course context the symb for the seed.
                   12233: #   course_id - The course id of the form domain_coursenum.
                   12234: #   domain    - Domain for the user.
                   12235: #   course    - Course for the user.
                   12236: #   cenv      - environment of the course.
                   12237: #
                   12238: # NOTE:
                   12239: #   All parameters are picked out of the environment if missing
                   12240: #   or not defined.
                   12241: #   If a symb cannot be determined the current time is used instead.
                   12242: #
                   12243: #  For a given well defined symb, courside, domain, username,
                   12244: #  and course environment, the seed is reproducible.
                   12245: #
1.31      www      12246: sub rndseed {
1.1133    foxr     12247:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12248:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12249:     if (!defined($symb)) {
1.366     albertel 12250: 	unless ($symb=$wsymb) { return time; }
                   12251:     }
1.1146    foxr     12252:     if (!defined $courseid) { 
                   12253: 	$courseid=$wcourseid; 
                   12254:     }
                   12255:     if (!defined $domain) { $domain=$wdomain; }
                   12256:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12257: 
                   12258:     my $which;
                   12259:     if (defined($cenv->{'rndseed'})) {
                   12260: 	$which = $cenv->{'rndseed'};
                   12261:     } else {
                   12262: 	$which =&get_rand_alg($courseid);
                   12263:     }
1.491     albertel 12264:     if (defined(&getCODE())) {
1.675     albertel 12265: 	if ($which eq '64bit5') {
                   12266: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12267: 	} elsif ($which eq '64bit4') {
1.575     albertel 12268: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12269: 	} else {
                   12270: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12271: 	}
1.675     albertel 12272:     } elsif ($which eq '64bit5') {
                   12273: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12274:     } elsif ($which eq '64bit4') {
                   12275: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12276:     } elsif ($which eq '64bit3') {
                   12277: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12278:     } elsif ($which eq '64bit2') {
                   12279: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12280:     } elsif ($which eq '64bit') {
                   12281: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12282:     }
                   12283:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12284: }
                   12285: 
                   12286: sub rndseed_32bit {
                   12287:     my ($symb,$courseid,$domain,$username)=@_;
                   12288:     {
                   12289: 	use integer;
                   12290: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12291: 	my $symbseed=numval($symb) << 22;
                   12292: 	my $namechck=unpack("%32C*",$username) << 17;
                   12293: 	my $nameseed=numval($username) << 12;
                   12294: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12295: 	my $courseseed=unpack("%32C*",$courseid);
                   12296: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12297: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12298: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12299: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12300: 	return $num;
                   12301:     }
                   12302: }
                   12303: 
                   12304: sub rndseed_64bit {
                   12305:     my ($symb,$courseid,$domain,$username)=@_;
                   12306:     {
                   12307: 	use integer;
                   12308: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12309: 	my $symbseed=numval($symb) << 10;
                   12310: 	my $namechck=unpack("%32S*",$username);
                   12311: 	
                   12312: 	my $nameseed=numval($username) << 21;
                   12313: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12314: 	my $courseseed=unpack("%32S*",$courseid);
                   12315: 	
                   12316: 	my $num1=$symbchck+$symbseed+$namechck;
                   12317: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12318: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12319: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12320: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12321: 	return "$num1,$num2";
1.155     albertel 12322:     }
1.366     albertel 12323: }
                   12324: 
1.443     albertel 12325: sub rndseed_64bit2 {
                   12326:     my ($symb,$courseid,$domain,$username)=@_;
                   12327:     {
                   12328: 	use integer;
                   12329: 	# strings need to be an even # of cahracters long, it it is odd the
                   12330:         # last characters gets thrown away
                   12331: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12332: 	my $symbseed=numval($symb) << 10;
                   12333: 	my $namechck=unpack("%32S*",$username.' ');
                   12334: 	
                   12335: 	my $nameseed=numval($username) << 21;
1.501     albertel 12336: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12337: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12338: 	
                   12339: 	my $num1=$symbchck+$symbseed+$namechck;
                   12340: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12341: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12342: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12343: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12344: 	return "$num1,$num2";
                   12345:     }
                   12346: }
                   12347: 
                   12348: sub rndseed_64bit3 {
                   12349:     my ($symb,$courseid,$domain,$username)=@_;
                   12350:     {
                   12351: 	use integer;
                   12352: 	# strings need to be an even # of cahracters long, it it is odd the
                   12353:         # last characters gets thrown away
                   12354: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12355: 	my $symbseed=numval2($symb) << 10;
                   12356: 	my $namechck=unpack("%32S*",$username.' ');
                   12357: 	
                   12358: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12359: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12360: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12361: 	
                   12362: 	my $num1=$symbchck+$symbseed+$namechck;
                   12363: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12364: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12365: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12366: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12367: 	
1.503     albertel 12368: 	return "$num1:$num2";
1.443     albertel 12369:     }
                   12370: }
                   12371: 
1.575     albertel 12372: sub rndseed_64bit4 {
                   12373:     my ($symb,$courseid,$domain,$username)=@_;
                   12374:     {
                   12375: 	use integer;
                   12376: 	# strings need to be an even # of cahracters long, it it is odd the
                   12377:         # last characters gets thrown away
                   12378: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12379: 	my $symbseed=numval3($symb) << 10;
                   12380: 	my $namechck=unpack("%32S*",$username.' ');
                   12381: 	
                   12382: 	my $nameseed=numval3($username) << 21;
                   12383: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12384: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12385: 	
                   12386: 	my $num1=$symbchck+$symbseed+$namechck;
                   12387: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12388: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12389: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12390: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12391: 	
1.575     albertel 12392: 	return "$num1:$num2";
                   12393:     }
                   12394: }
                   12395: 
1.675     albertel 12396: sub rndseed_64bit5 {
                   12397:     my ($symb,$courseid,$domain,$username)=@_;
                   12398:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12399:     return "$num1:$num2";
                   12400: }
                   12401: 
1.366     albertel 12402: sub rndseed_CODE_64bit {
                   12403:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12404:     {
1.366     albertel 12405: 	use integer;
1.443     albertel 12406: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12407: 	my $symbseed=numval2($symb);
1.491     albertel 12408: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12409: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12410: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12411: 	my $num1=$symbseed+$CODEchck;
                   12412: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12413: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12414: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12415: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12416: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12417: 	return "$num1:$num2";
1.366     albertel 12418:     }
                   12419: }
                   12420: 
1.575     albertel 12421: sub rndseed_CODE_64bit4 {
                   12422:     my ($symb,$courseid,$domain,$username)=@_;
                   12423:     {
                   12424: 	use integer;
                   12425: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12426: 	my $symbseed=numval3($symb);
                   12427: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12428: 	my $CODEseed=numval3(&getCODE());
                   12429: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12430: 	my $num1=$symbseed+$CODEchck;
                   12431: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12432: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12433: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12434: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12435: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12436: 	return "$num1:$num2";
                   12437:     }
                   12438: }
                   12439: 
1.675     albertel 12440: sub rndseed_CODE_64bit5 {
                   12441:     my ($symb,$courseid,$domain,$username)=@_;
                   12442:     my $code = &getCODE();
                   12443:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12444:     return "$num1:$num2";
                   12445: }
                   12446: 
1.366     albertel 12447: sub setup_random_from_rndseed {
                   12448:     my ($rndseed)=@_;
1.503     albertel 12449:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12450: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12451:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12452:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12453:         } else {
                   12454:             &Math::Random::random_set_seed($num1,$num2);
                   12455:         }
1.366     albertel 12456:     } else {
                   12457: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12458:     }
1.36      albertel 12459: }
                   12460: 
1.474     albertel 12461: sub latest_receipt_algorithm_id {
1.835     albertel 12462:     return 'receipt3';
1.474     albertel 12463: }
                   12464: 
1.480     www      12465: sub recunique {
                   12466:     my $fucourseid=shift;
                   12467:     my $unique;
1.835     albertel 12468:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12469: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12470: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12471:     } else {
                   12472: 	$unique=$perlvar{'lonReceipt'};
                   12473:     }
                   12474:     return unpack("%32C*",$unique);
                   12475: }
                   12476: 
                   12477: sub recprefix {
                   12478:     my $fucourseid=shift;
                   12479:     my $prefix;
1.835     albertel 12480:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12481: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12482: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12483:     } else {
                   12484: 	$prefix=$perlvar{'lonHostID'};
                   12485:     }
                   12486:     return unpack("%32C*",$prefix);
                   12487: }
                   12488: 
1.76      www      12489: sub ireceipt {
1.474     albertel 12490:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12491: 
                   12492:     my $return =&recprefix($fucourseid).'-';
                   12493: 
                   12494:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12495: 	$env{'request.state'} eq 'construct') {
                   12496: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12497: 	return $return;
                   12498:     }
                   12499: 
1.76      www      12500:     my $cuname=unpack("%32C*",$funame);
                   12501:     my $cudom=unpack("%32C*",$fudom);
                   12502:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12503:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12504:     my $cunique=&recunique($fucourseid);
1.474     albertel 12505:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12506:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12507: 
1.790     albertel 12508: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12509: 			       
                   12510: 	$return.= ($cunique%$cuname+
                   12511: 		   $cunique%$cudom+
                   12512: 		   $cusymb%$cuname+
                   12513: 		   $cusymb%$cudom+
                   12514: 		   $cucourseid%$cuname+
                   12515: 		   $cucourseid%$cudom+
                   12516: 		   $cpart%$cuname+
                   12517: 		   $cpart%$cudom);
                   12518:     } else {
                   12519: 	$return.= ($cunique%$cuname+
                   12520: 		   $cunique%$cudom+
                   12521: 		   $cusymb%$cuname+
                   12522: 		   $cusymb%$cudom+
                   12523: 		   $cucourseid%$cuname+
                   12524: 		   $cucourseid%$cudom);
                   12525:     }
                   12526:     return $return;
1.76      www      12527: }
                   12528: 
                   12529: sub receipt {
1.474     albertel 12530:     my ($part)=@_;
1.790     albertel 12531:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12532:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12533: }
1.260     ng       12534: 
1.790     albertel 12535: sub whichuser {
                   12536:     my ($passedsymb)=@_;
                   12537:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12538:     if (defined($env{'form.grade_symb'})) {
                   12539: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12540: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12541: 	if (!$allowed &&
                   12542: 	    exists($env{'request.course.sec'}) &&
                   12543: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12544: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12545: 			      '/'.$env{'request.course.sec'});
                   12546: 	}
                   12547: 	if ($allowed) {
                   12548: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12549: 	    $courseid=$tmp_courseid;
                   12550: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12551: 	    ($name)=&get_env_multiple('form.grade_username');
                   12552: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12553: 	}
                   12554:     }
                   12555:     if (!$passedsymb) {
                   12556: 	$symb=&symbread();
                   12557:     } else {
                   12558: 	$symb=$passedsymb;
                   12559:     }
                   12560:     $courseid=$env{'request.course.id'};
                   12561:     $domain=$env{'user.domain'};
                   12562:     $name=$env{'user.name'};
                   12563:     if ($name eq 'public' && $domain eq 'public') {
                   12564: 	if (!defined($env{'form.username'})) {
                   12565: 	    $env{'form.username'}.=time.rand(10000000);
                   12566: 	}
                   12567: 	$name.=$env{'form.username'};
                   12568:     }
                   12569:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12570: 
                   12571: }
                   12572: 
1.36      albertel 12573: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12574: # returns either the contents of the file or 
                   12575: # -1 if the file doesn't exist
1.481     raeburn  12576: #
                   12577: # if the target is a file that was uploaded via DOCS, 
                   12578: # a check will be made to see if a current copy exists on the local server,
                   12579: # if it does this will be served, otherwise a copy will be retrieved from
                   12580: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12581: # the local server.   
1.472     albertel 12582: 
1.36      albertel 12583: sub getfile {
1.538     albertel 12584:     my ($file) = @_;
1.609     banghart 12585:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12586:     &repcopy($file);
                   12587:     return &readfile($file);
                   12588: }
                   12589: 
                   12590: sub repcopy_userfile {
                   12591:     my ($file)=@_;
1.1142    raeburn  12592:     my $londocroot = $perlvar{'lonDocRoot'};
                   12593:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12594:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12595:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12596: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12597:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12598:     if (-e "$file") {
1.828     www      12599: # we already have a local copy, check it out
1.538     albertel 12600: 	my @fileinfo = stat($file);
1.828     www      12601: 	my $rtncode;
                   12602: 	my $info;
1.538     albertel 12603: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12604: 	if ($lwpresp ne 'ok') {
1.828     www      12605: # there is no such file anymore, even though we had a local copy
1.482     albertel 12606: 	    if ($rtncode eq '404') {
1.538     albertel 12607: 		unlink($file);
1.482     albertel 12608: 	    }
                   12609: 	    return -1;
                   12610: 	}
                   12611: 	if ($info < $fileinfo[9]) {
1.828     www      12612: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12613: 	    return 'ok';
1.828     www      12614: 	} else {
                   12615: # the file is outdated, get rid of it
                   12616: 	    unlink($file);
1.482     albertel 12617: 	}
1.828     www      12618:     }
                   12619: # one way or the other, at this point, we don't have the file
                   12620: # construct the correct path for the file
                   12621:     my @parts = ($cdom,$cnum); 
                   12622:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12623: 	push @parts, split(/\//,$1);
                   12624:     }
                   12625:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12626:     foreach my $part (@parts) {
                   12627: 	$path .= '/'.$part;
                   12628: 	if (!-e $path) {
                   12629: 	    mkdir($path,0770);
1.482     albertel 12630: 	}
                   12631:     }
1.828     www      12632: # now the path exists for sure
                   12633: # get a user agent
                   12634:     my $ua=new LWP::UserAgent;
                   12635:     my $transferfile=$file.'.in.transfer';
                   12636: # FIXME: this should flock
                   12637:     if (-e $transferfile) { return 'ok'; }
                   12638:     my $request;
                   12639:     $uri=~s/^\///;
1.980     raeburn  12640:     my $homeserver = &homeserver($cnum,$cdom);
                   12641:     my $protocol = $protocol{$homeserver};
                   12642:     $protocol = 'http' if ($protocol ne 'https');
                   12643:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12644:     my $response=$ua->request($request,$transferfile);
                   12645: # did it work?
                   12646:     if ($response->is_error()) {
                   12647: 	unlink($transferfile);
                   12648: 	&logthis("Userfile repcopy failed for $uri");
                   12649: 	return -1;
                   12650:     }
                   12651: # worked, rename the transfer file
                   12652:     rename($transferfile,$file);
1.607     raeburn  12653:     return 'ok';
1.481     raeburn  12654: }
                   12655: 
1.517     albertel 12656: sub tokenwrapper {
                   12657:     my $uri=shift;
1.980     raeburn  12658:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12659:     $uri=~s|^/||;
1.620     albertel 12660:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12661:     my $token=$1;
1.552     albertel 12662:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12663:     if ($udom && $uname && $file) {
                   12664: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12665:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12666:         my $homeserver = &homeserver($uname,$udom);
                   12667:         my $protocol = $protocol{$homeserver};
                   12668:         $protocol = 'http' if ($protocol ne 'https');
                   12669:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12670:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12671:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12672:     } else {
                   12673:         return '/adm/notfound.html';
                   12674:     }
                   12675: }
                   12676: 
1.828     www      12677: # call with reqtype HEAD: get last modification time
                   12678: # call with reqtype GET: get the file contents
                   12679: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12680: #
1.481     raeburn  12681: sub getuploaded {
                   12682:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12683:     $uri=~s/^\///;
1.980     raeburn  12684:     my $homeserver = &homeserver($cnum,$cdom);
                   12685:     my $protocol = $protocol{$homeserver};
                   12686:     $protocol = 'http' if ($protocol ne 'https');
                   12687:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12688:     my $ua=new LWP::UserAgent;
                   12689:     my $request=new HTTP::Request($reqtype,$uri);
                   12690:     my $response=$ua->request($request);
                   12691:     $$rtncode = $response->code;
1.482     albertel 12692:     if (! $response->is_success()) {
                   12693: 	return 'failed';
                   12694:     }      
                   12695:     if ($reqtype eq 'HEAD') {
1.486     www      12696: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12697:     } elsif ($reqtype eq 'GET') {
                   12698: 	$$info = $response->content;
1.472     albertel 12699:     }
1.482     albertel 12700:     return 'ok';
1.36      albertel 12701: }
                   12702: 
1.481     raeburn  12703: sub readfile {
                   12704:     my $file = shift;
                   12705:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12706:     my $fh;
1.1172.2.96  raeburn  12707:     open($fh,"<",$file);
1.481     raeburn  12708:     my $a='';
1.800     albertel 12709:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12710:     return $a;
                   12711: }
                   12712: 
1.36      albertel 12713: sub filelocation {
1.590     banghart 12714:     my ($dir,$file) = @_;
                   12715:     my $location;
                   12716:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12717: 
                   12718:     if ($file =~ m-^/adm/-) {
                   12719: 	$file=~s-^/adm/wrapper/-/-;
                   12720: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12721:     }
1.882     albertel 12722: 
1.1139    www      12723:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12724:         $location = $file;
1.609     banghart 12725:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12726:         my ($udom,$uname,$filename)=
1.811     albertel 12727:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12728:         my $home=&homeserver($uname,$udom);
                   12729:         my $is_me=0;
                   12730:         my @ids=&current_machine_ids();
                   12731:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12732:         if ($is_me) {
1.1117    foxr     12733:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12734:         } else {
                   12735:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12736:   	      $udom.'/'.$uname.'/'.$filename;
                   12737:         }
1.882     albertel 12738:     } elsif ($file =~ m-^/adm/-) {
                   12739: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12740:     } else {
                   12741:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12742:         $file=~s:^/(res|priv)/:/:;
                   12743:         my $space=$1;
1.590     banghart 12744:         if ( !( $file =~ m:^/:) ) {
                   12745:             $location = $dir. '/'.$file;
                   12746:         } else {
1.1142    raeburn  12747:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12748:         }
1.59      albertel 12749:     }
1.590     banghart 12750:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12751:     while ($location=~m{/\.\./}) {
                   12752: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12753: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12754: 	} else {
                   12755: 	    $location=~ s{/\.\./}{/}g;
                   12756: 	}
                   12757:     } #remove dir/..
1.590     banghart 12758:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12759:     return $location;
1.46      www      12760: }
1.36      albertel 12761: 
1.46      www      12762: sub hreflocation {
                   12763:     my ($dir,$file)=@_;
1.980     raeburn  12764:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12765: 	$file=filelocation($dir,$file);
1.700     albertel 12766:     } elsif ($file=~m-^/adm/-) {
                   12767: 	$file=~s-^/adm/wrapper/-/-;
                   12768: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12769:     }
                   12770:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12771: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12772:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12773: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12774: 	        {/uploaded/$1/$2/}x;
1.46      www      12775:     }
1.913     albertel 12776:     if ($file=~ m{^/userfiles/}) {
                   12777: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12778:     }
1.462     albertel 12779:     return $file;
1.465     albertel 12780: }
                   12781: 
1.1139    www      12782: 
                   12783: 
                   12784: 
                   12785: 
1.465     albertel 12786: sub current_machine_domains {
1.853     albertel 12787:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12788: }
                   12789: 
                   12790: sub machine_domains {
                   12791:     my ($hostname) = @_;
1.465     albertel 12792:     my @domains;
1.838     albertel 12793:     my %hostname = &all_hostnames();
1.465     albertel 12794:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12795: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12796: 	if ($hostname eq $name) {
1.844     albertel 12797: 	    push(@domains,&host_domain($id));
1.465     albertel 12798: 	}
                   12799:     }
                   12800:     return @domains;
                   12801: }
                   12802: 
                   12803: sub current_machine_ids {
1.853     albertel 12804:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12805: }
                   12806: 
                   12807: sub machine_ids {
                   12808:     my ($hostname) = @_;
                   12809:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12810:     my @ids;
1.888     albertel 12811:     my %name_to_host = &all_names();
1.889     albertel 12812:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12813: 	return @{ $name_to_host{$hostname} };
                   12814:     }
                   12815:     return;
1.31      www      12816: }
                   12817: 
1.824     raeburn  12818: sub additional_machine_domains {
                   12819:     my @domains;
1.1172.2.96  raeburn  12820:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  12821:     while( my $line = <$fh>) {
                   12822:         $line =~ s/\s//g;
                   12823:         push(@domains,$line);
                   12824:     }
                   12825:     return @domains;
                   12826: }
                   12827: 
                   12828: sub default_login_domain {
                   12829:     my $domain = $perlvar{'lonDefDomain'};
                   12830:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12831:     foreach my $posdom (&current_machine_domains(),
                   12832:                         &additional_machine_domains()) {
                   12833:         if (lc($posdom) eq lc($testdomain)) {
                   12834:             $domain=$posdom;
                   12835:             last;
                   12836:         }
                   12837:     }
                   12838:     return $domain;
                   12839: }
                   12840: 
1.1172.2.106  raeburn  12841: sub shared_institution {
                   12842:     my ($dom) = @_;
                   12843:     my $same_intdom;
                   12844:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   12845:     if ($hostintdom ne '') {
                   12846:         my %iphost = &get_iphost();
                   12847:         my $primary_id = &domain($dom,'primary');
                   12848:         my $primary_ip = &get_host_ip($primary_id);
                   12849:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   12850:             foreach my $id (@{$iphost{$primary_ip}}) {
                   12851:                 my $intdom = &internet_dom($id);
                   12852:                 if ($intdom eq $hostintdom) {
                   12853:                     $same_intdom = 1;
                   12854:                     last;
                   12855:                 }
                   12856:             }
                   12857:         }
                   12858:     }
                   12859:     return $same_intdom;
                   12860: }
                   12861: 
1.31      www      12862: # ------------------------------------------------------------- Declutters URLs
                   12863: 
                   12864: sub declutter {
                   12865:     my $thisfn=shift;
1.569     albertel 12866:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12867:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12868:         $thisfn=~s{^/home/httpd/html}{};
                   12869:     }
1.31      www      12870:     $thisfn=~s/^\///;
1.697     albertel 12871:     $thisfn=~s|^adm/wrapper/||;
                   12872:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12873:     $thisfn=~s/^res\///;
1.1172    bisitz   12874:     $thisfn=~s/^priv\///;
1.1032    raeburn  12875:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12876:         $thisfn=~s/\?.+$//;
                   12877:     }
1.268     www      12878:     return $thisfn;
                   12879: }
                   12880: 
                   12881: # ------------------------------------------------------------- Clutter up URLs
                   12882: 
                   12883: sub clutter {
                   12884:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12885:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12886: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12887:        $thisfn='/res'.$thisfn; 
                   12888:     }
1.1031    raeburn  12889:     if ($thisfn !~m|^/adm|) {
                   12890: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12891: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12892: 	} else {
                   12893: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12894: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12895: 	    if ($embstyle eq 'ssi'
                   12896: 		|| ($embstyle eq 'hdn')
                   12897: 		|| ($embstyle eq 'rat')
                   12898: 		|| ($embstyle eq 'prv')
                   12899: 		|| ($embstyle eq 'ign')) {
                   12900: 		#do nothing with these
                   12901: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12902: 		|| ($embstyle eq 'emb')
                   12903: 		|| ($embstyle eq 'wrp')) {
                   12904: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12905: 	    } elsif ($embstyle eq 'unk'
                   12906: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12907: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12908: 	    } else {
1.718     www      12909: #		&logthis("Got a blank emb style");
1.695     albertel 12910: 	    }
1.694     albertel 12911: 	}
                   12912:     }
1.31      www      12913:     return $thisfn;
1.12      www      12914: }
                   12915: 
1.787     albertel 12916: sub clutter_with_no_wrapper {
                   12917:     my $uri = &clutter(shift);
                   12918:     if ($uri =~ m-^/adm/-) {
                   12919: 	$uri =~ s-^/adm/wrapper/-/-;
                   12920: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12921:     }
                   12922:     return $uri;
                   12923: }
                   12924: 
1.557     albertel 12925: sub freeze_escape {
                   12926:     my ($value)=@_;
                   12927:     if (ref($value)) {
                   12928: 	$value=&nfreeze($value);
                   12929: 	return '__FROZEN__'.&escape($value);
                   12930:     }
                   12931:     return &escape($value);
                   12932: }
                   12933: 
1.11      www      12934: 
1.557     albertel 12935: sub thaw_unescape {
                   12936:     my ($value)=@_;
                   12937:     if ($value =~ /^__FROZEN__/) {
                   12938: 	substr($value,0,10,undef);
                   12939: 	$value=&unescape($value);
                   12940: 	return &thaw($value);
                   12941:     }
                   12942:     return &unescape($value);
                   12943: }
                   12944: 
1.436     albertel 12945: sub correct_line_ends {
                   12946:     my ($result)=@_;
                   12947:     $$result =~s/\r\n/\n/mg;
                   12948:     $$result =~s/\r/\n/mg;
1.415     albertel 12949: }
1.1       albertel 12950: # ================================================================ Main Program
                   12951: 
1.184     www      12952: sub goodbye {
1.204     albertel 12953:    &logthis("Starting Shut down");
1.443     albertel 12954: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12955:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12956: #converted
1.599     albertel 12957: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12958:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12959: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12960: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12961: #1.1 only
1.870     albertel 12962: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12963: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12964: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12965: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12966:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12967:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12968:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12969:    &flushcourselogs();
                   12970:    &logthis("Shutting down");
                   12971: }
                   12972: 
1.852     albertel 12973: sub get_dns {
1.1172.2.17  raeburn  12974:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12975:     if (!$ignore_cache) {
                   12976: 	my ($content,$cached)=
                   12977: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12978: 	if ($cached) {
1.1172.2.17  raeburn  12979: 	    &$func($content,$hashref);
1.869     albertel 12980: 	    return;
                   12981: 	}
                   12982:     }
                   12983: 
                   12984:     my %alldns;
1.1172.2.96  raeburn  12985:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   12986:         foreach my $dns (<$config>) {
                   12987: 	    next if ($dns !~ /^\^(\S*)/x);
                   12988:             my $line = $1;
                   12989:             my ($host,$protocol) = split(/:/,$line);
                   12990:             if ($protocol ne 'https') {
                   12991:                 $protocol = 'http';
                   12992:             }
                   12993: 	    $alldns{$host} = $protocol;
1.979     raeburn  12994:         }
1.1172.2.96  raeburn  12995:         close($config);
1.869     albertel 12996:     }
                   12997:     while (%alldns) {
1.1172.2.52  raeburn  12998: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12999: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13000:         $ua->timeout(30);
1.979     raeburn  13001: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13002: 	my $response=$ua->request($request);
1.979     raeburn  13003:         delete($alldns{$dns});
1.852     albertel 13004: 	next if ($response->is_error());
                   13005: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13006:         unless ($nocache) {
1.1172.2.23  raeburn  13007: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13008:         }
                   13009: 	&$func(\@content,$hashref);
1.869     albertel 13010: 	return;
1.852     albertel 13011:     }
1.871     albertel 13012:     my $which = (split('/',$url))[3];
                   13013:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13014:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13015:         my @content = <$config>;
                   13016:         &$func(\@content,$hashref);
                   13017:     }
1.1172.2.17  raeburn  13018:     return;
                   13019: }
                   13020: 
                   13021: # ------------------------------------------------------Get DNS checksums file
                   13022: sub parse_dns_checksums_tab {
                   13023:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13024:     my $lonhost = $perlvar{'lonHostID'};
                   13025:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13026:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13027:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13028:     my $webconfdir = '/etc/httpd/conf';
                   13029:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13030:         $webconfdir = '/etc/apache2';
                   13031:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13032:         if ($1 >= 10) {
                   13033:             $webconfdir = '/etc/apache2';
                   13034:         }
                   13035:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13036:         if ($1 >= 10.0) {
                   13037:             $webconfdir = '/etc/apache2';
                   13038:         }
                   13039:     }
1.1172.2.17  raeburn  13040:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13041:     my (%chksum,%revnum);
                   13042:     if (ref($lines) eq 'ARRAY') {
                   13043:         chomp(@{$lines});
1.1172.2.34  raeburn  13044:         my $version = shift(@{$lines});
                   13045:         if ($version eq $release) {
1.1172.2.17  raeburn  13046:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13047:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13048:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13049:                     if ($webconfdir eq '/etc/apache2') {
                   13050:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13051:                     }
                   13052:                 }
1.1172.2.34  raeburn  13053:                 $chksum{$file} = $shasum;
                   13054:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13055:             }
                   13056:             if (ref($hashref) eq 'HASH') {
                   13057:                 %{$hashref} = (
                   13058:                                 sums     => \%chksum,
                   13059:                                 versions => \%revnum,
                   13060:                               );
                   13061:             }
                   13062:         }
                   13063:     }
1.869     albertel 13064:     return;
1.852     albertel 13065: }
1.1172.2.17  raeburn  13066: 
                   13067: sub fetch_dns_checksums {
                   13068:     my %checksums;
1.1172.2.34  raeburn  13069:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13070:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13071:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13072:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13073:              \%checksums);
                   13074:     return \%checksums;
                   13075: }
                   13076: 
1.327     albertel 13077: # ------------------------------------------------------------ Read domain file
                   13078: {
1.852     albertel 13079:     my $loaded;
1.846     albertel 13080:     my %domain;
                   13081: 
1.852     albertel 13082:     sub parse_domain_tab {
                   13083: 	my ($lines) = @_;
                   13084: 	foreach my $line (@$lines) {
                   13085: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13086: 
1.846     albertel 13087: 	    chomp($line);
1.852     albertel 13088: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13089: 	    my %this_domain;
                   13090: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13091: 			       'lang_def', 'city', 'longi', 'lati',
                   13092: 			       'primary') {
                   13093: 		$this_domain{$field} = shift(@elements);
                   13094: 	    }
                   13095: 	    $domain{$name} = \%this_domain;
1.852     albertel 13096: 	}
                   13097:     }
1.864     albertel 13098: 
                   13099:     sub reset_domain_info {
                   13100: 	undef($loaded);
                   13101: 	undef(%domain);
                   13102:     }
                   13103: 
1.852     albertel 13104:     sub load_domain_tab {
1.1172.2.70  raeburn  13105: 	my ($ignore_cache,$nocache) = @_;
                   13106: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13107: 	my $fh;
1.1172.2.96  raeburn  13108: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13109: 	    my @lines = <$fh>;
                   13110: 	    &parse_domain_tab(\@lines);
1.448     albertel 13111: 	}
1.852     albertel 13112: 	close($fh);
                   13113: 	$loaded = 1;
1.327     albertel 13114:     }
1.846     albertel 13115: 
                   13116:     sub domain {
1.852     albertel 13117: 	&load_domain_tab() if (!$loaded);
                   13118: 
1.846     albertel 13119: 	my ($name,$what) = @_;
                   13120: 	return if ( !exists($domain{$name}) );
                   13121: 
                   13122: 	if (!$what) {
                   13123: 	    return $domain{$name}{'description'};
                   13124: 	}
                   13125: 	return $domain{$name}{$what};
                   13126:     }
1.974     raeburn  13127: 
                   13128:     sub domain_info {
                   13129:         &load_domain_tab() if (!$loaded);
                   13130:         return %domain;
                   13131:     }
                   13132: 
1.327     albertel 13133: }
                   13134: 
                   13135: 
1.1       albertel 13136: # ------------------------------------------------------------- Read hosts file
                   13137: {
1.838     albertel 13138:     my %hostname;
1.844     albertel 13139:     my %hostdom;
1.845     albertel 13140:     my %libserv;
1.852     albertel 13141:     my $loaded;
1.888     albertel 13142:     my %name_to_host;
1.1074    raeburn  13143:     my %internetdom;
1.1107    raeburn  13144:     my %LC_dns_serv;
1.852     albertel 13145: 
                   13146:     sub parse_hosts_tab {
                   13147: 	my ($file) = @_;
                   13148: 	foreach my $configline (@$file) {
                   13149: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13150:             chomp($configline);
                   13151: 	    if ($configline =~ /^\^/) {
                   13152:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13153:                     $LC_dns_serv{$1} = 1;
                   13154:                 }
                   13155:                 next;
                   13156:             }
1.1074    raeburn  13157: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13158: 	    $name=~s/\s//g;
                   13159: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13160:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13161:                     my $curr = $hostname{$id};
                   13162:                     my $skip;
                   13163:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13164:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13165:                             $skip = 1;
                   13166:                         } else {
                   13167:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13168:                         }
                   13169:                     }
                   13170:                     unless ($skip) {
                   13171:                         push(@{$name_to_host{$name}},$id);
                   13172:                     }
                   13173:                 } else {
                   13174:                     push(@{$name_to_host{$name}},$id);
                   13175:                 }
1.852     albertel 13176: 		$hostname{$id}=$name;
                   13177: 		$hostdom{$id}=$domain;
                   13178: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13179:                 if (defined($protocol)) {
                   13180:                     if ($protocol eq 'https') {
                   13181:                         $protocol{$id} = $protocol;
                   13182:                     } else {
                   13183:                         $protocol{$id} = 'http'; 
                   13184:                     }
1.968     raeburn  13185:                 } else {
1.969     raeburn  13186:                     $protocol{$id} = 'http';
1.968     raeburn  13187:                 }
1.1074    raeburn  13188:                 if (defined($intdom)) {
                   13189:                     $internetdom{$id} = $intdom;
                   13190:                 }
1.852     albertel 13191: 	    }
                   13192: 	}
                   13193:     }
1.864     albertel 13194:     
                   13195:     sub reset_hosts_info {
1.897     albertel 13196: 	&purge_remembered();
1.864     albertel 13197: 	&reset_domain_info();
                   13198: 	&reset_hosts_ip_info();
1.892     albertel 13199: 	undef(%name_to_host);
1.864     albertel 13200: 	undef(%hostname);
                   13201: 	undef(%hostdom);
                   13202: 	undef(%libserv);
                   13203: 	undef($loaded);
                   13204:     }
1.1       albertel 13205: 
1.852     albertel 13206:     sub load_hosts_tab {
1.1172.2.70  raeburn  13207: 	my ($ignore_cache,$nocache) = @_;
                   13208: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13209: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13210: 	my @config = <$config>;
                   13211: 	&parse_hosts_tab(\@config);
                   13212: 	close($config);
                   13213: 	$loaded=1;
1.1       albertel 13214:     }
1.852     albertel 13215: 
1.838     albertel 13216:     sub hostname {
1.852     albertel 13217: 	&load_hosts_tab() if (!$loaded);
                   13218: 
1.838     albertel 13219: 	my ($lonid) = @_;
                   13220: 	return $hostname{$lonid};
                   13221:     }
1.845     albertel 13222: 
1.838     albertel 13223:     sub all_hostnames {
1.852     albertel 13224: 	&load_hosts_tab() if (!$loaded);
                   13225: 
1.838     albertel 13226: 	return %hostname;
                   13227:     }
1.845     albertel 13228: 
1.888     albertel 13229:     sub all_names {
1.1172.2.70  raeburn  13230:         my ($ignore_cache,$nocache) = @_;
                   13231: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13232: 
                   13233: 	return %name_to_host;
                   13234:     }
                   13235: 
1.974     raeburn  13236:     sub all_host_domain {
                   13237:         &load_hosts_tab() if (!$loaded);
                   13238:         return %hostdom;
                   13239:     }
                   13240: 
1.845     albertel 13241:     sub is_library {
1.852     albertel 13242: 	&load_hosts_tab() if (!$loaded);
                   13243: 
1.845     albertel 13244: 	return exists($libserv{$_[0]});
                   13245:     }
                   13246: 
                   13247:     sub all_library {
1.852     albertel 13248: 	&load_hosts_tab() if (!$loaded);
                   13249: 
1.845     albertel 13250: 	return %libserv;
                   13251:     }
                   13252: 
1.1062    droeschl 13253:     sub unique_library {
                   13254: 	#2x reverse removes all hostnames that appear more than once
                   13255:         my %unique = reverse &all_library();
                   13256:         return reverse %unique;
                   13257:     }
                   13258: 
1.841     albertel 13259:     sub get_servers {
1.852     albertel 13260: 	&load_hosts_tab() if (!$loaded);
                   13261: 
1.841     albertel 13262: 	my ($domain,$type) = @_;
                   13263: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13264: 	                                          : %hostname;
                   13265: 	my %result;
1.842     albertel 13266: 	if (ref($domain) eq 'ARRAY') {
                   13267: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13268: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13269: 		    $result{$host} = $hostname;
                   13270: 		}
                   13271: 	    }
                   13272: 	} else {
                   13273: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13274: 		if ($hostdom{$host} eq $domain) {
                   13275: 		    $result{$host} = $hostname;
                   13276: 		}
1.841     albertel 13277: 	    }
                   13278: 	}
                   13279: 	return %result;
                   13280:     }
1.845     albertel 13281: 
1.1062    droeschl 13282:     sub get_unique_servers {
                   13283:         my %unique = reverse &get_servers(@_);
                   13284: 	return reverse %unique;
                   13285:     }
                   13286: 
1.844     albertel 13287:     sub host_domain {
1.852     albertel 13288: 	&load_hosts_tab() if (!$loaded);
                   13289: 
1.844     albertel 13290: 	my ($lonid) = @_;
                   13291: 	return $hostdom{$lonid};
                   13292:     }
                   13293: 
1.841     albertel 13294:     sub all_domains {
1.852     albertel 13295: 	&load_hosts_tab() if (!$loaded);
                   13296: 
1.841     albertel 13297: 	my %seen;
                   13298: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13299: 	return @uniq;
                   13300:     }
1.1074    raeburn  13301: 
                   13302:     sub internet_dom {
                   13303:         &load_hosts_tab() if (!$loaded);
                   13304: 
                   13305:         my ($lonid) = @_;
                   13306:         return $internetdom{$lonid};
                   13307:     }
1.1107    raeburn  13308: 
                   13309:     sub is_LC_dns {
                   13310:         &load_hosts_tab() if (!$loaded);
                   13311: 
                   13312:         my ($hostname) = @_;
                   13313:         return exists($LC_dns_serv{$hostname});
                   13314:     }
                   13315: 
1.1       albertel 13316: }
                   13317: 
1.847     albertel 13318: { 
                   13319:     my %iphost;
1.856     albertel 13320:     my %name_to_ip;
                   13321:     my %lonid_to_ip;
1.869     albertel 13322: 
1.847     albertel 13323:     sub get_hosts_from_ip {
                   13324: 	my ($ip) = @_;
                   13325: 	my %iphosts = &get_iphost();
                   13326: 	if (ref($iphosts{$ip})) {
                   13327: 	    return @{$iphosts{$ip}};
                   13328: 	}
                   13329: 	return;
1.839     albertel 13330:     }
1.864     albertel 13331:     
                   13332:     sub reset_hosts_ip_info {
                   13333: 	undef(%iphost);
                   13334: 	undef(%name_to_ip);
                   13335: 	undef(%lonid_to_ip);
                   13336:     }
1.856     albertel 13337: 
                   13338:     sub get_host_ip {
                   13339: 	my ($lonid) = @_;
                   13340: 	if (exists($lonid_to_ip{$lonid})) {
                   13341: 	    return $lonid_to_ip{$lonid};
                   13342: 	}
                   13343: 	my $name=&hostname($lonid);
                   13344:    	my $ip = gethostbyname($name);
                   13345: 	return if (!$ip || length($ip) ne 4);
                   13346: 	$ip=inet_ntoa($ip);
                   13347: 	$name_to_ip{$name}   = $ip;
                   13348: 	$lonid_to_ip{$lonid} = $ip;
                   13349: 	return $ip;
                   13350:     }
1.847     albertel 13351:     
                   13352:     sub get_iphost {
1.1172.2.70  raeburn  13353: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13354: 
1.869     albertel 13355: 	if (!$ignore_cache) {
                   13356: 	    if (%iphost) {
                   13357: 		return %iphost;
                   13358: 	    }
                   13359: 	    my ($ip_info,$cached)=
                   13360: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13361: 	    if ($cached) {
                   13362: 		%iphost      = %{$ip_info->[0]};
                   13363: 		%name_to_ip  = %{$ip_info->[1]};
                   13364: 		%lonid_to_ip = %{$ip_info->[2]};
                   13365: 		return %iphost;
                   13366: 	    }
                   13367: 	}
1.894     albertel 13368: 
                   13369: 	# get yesterday's info for fallback
                   13370: 	my %old_name_to_ip;
                   13371: 	my ($ip_info,$cached)=
                   13372: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13373: 	if ($cached) {
                   13374: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13375: 	}
                   13376: 
1.1172.2.70  raeburn  13377: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13378: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13379: 	    my $ip;
                   13380: 	    if (!exists($name_to_ip{$name})) {
                   13381: 		$ip = gethostbyname($name);
                   13382: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13383: 		    if (defined($old_name_to_ip{$name})) {
                   13384: 			$ip = $old_name_to_ip{$name};
                   13385: 			&logthis("Can't find $name defaulting to old $ip");
                   13386: 		    } else {
                   13387: 			&logthis("Name $name no IP found");
                   13388: 			next;
                   13389: 		    }
                   13390: 		} else {
                   13391: 		    $ip=inet_ntoa($ip);
1.847     albertel 13392: 		}
                   13393: 		$name_to_ip{$name} = $ip;
                   13394: 	    } else {
                   13395: 		$ip = $name_to_ip{$name};
1.653     albertel 13396: 	    }
1.888     albertel 13397: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13398: 		$lonid_to_ip{$id} = $ip;
                   13399: 	    }
                   13400: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13401: 	}
1.1172.2.70  raeburn  13402:         unless ($nocache) {
                   13403: 	    &do_cache_new('iphost','iphost',
                   13404: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13405: 		          48*60*60);
                   13406:         }
1.869     albertel 13407: 
1.847     albertel 13408: 	return %iphost;
1.598     albertel 13409:     }
                   13410: 
1.992     raeburn  13411:     #
                   13412:     #  Given a DNS returns the loncapa host name for that DNS 
                   13413:     # 
                   13414:     sub host_from_dns {
                   13415:         my ($dns) = @_;
                   13416:         my @hosts;
                   13417:         my $ip;
                   13418: 
1.993     raeburn  13419:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13420:             $ip = $name_to_ip{$dns};
                   13421:         }
                   13422:         if (!$ip) {
                   13423:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13424:             if (length($ip) == 4) { 
                   13425: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13426:             }
                   13427:         }
                   13428:         if ($ip) {
                   13429: 	    @hosts = get_hosts_from_ip($ip);
                   13430: 	    return $hosts[0];
                   13431:         }
                   13432:         return undef;
1.986     foxr     13433:     }
1.992     raeburn  13434: 
1.1074    raeburn  13435:     sub get_internet_names {
                   13436:         my ($lonid) = @_;
                   13437:         return if ($lonid eq '');
                   13438:         my ($idnref,$cached)=
                   13439:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13440:         if ($cached) {
                   13441:             return $idnref;
                   13442:         }
                   13443:         my $ip = &get_host_ip($lonid);
                   13444:         my @hosts = &get_hosts_from_ip($ip);
                   13445:         my %iphost = &get_iphost();
                   13446:         my (@idns,%seen);
                   13447:         foreach my $id (@hosts) {
                   13448:             my $dom = &host_domain($id);
                   13449:             my $prim_id = &domain($dom,'primary');
                   13450:             my $prim_ip = &get_host_ip($prim_id);
                   13451:             next if ($seen{$prim_ip});
                   13452:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13453:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13454:                     my $intdom = &internet_dom($id);
                   13455:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13456:                         push(@idns,$intdom);
                   13457:                     }
                   13458:                 }
                   13459:             }
                   13460:             $seen{$prim_ip} = 1;
                   13461:         }
1.1172.2.23  raeburn  13462:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13463:     }
                   13464: 
1.986     foxr     13465: }
                   13466: 
1.1079    raeburn  13467: sub all_loncaparevs {
1.1172.2.39  raeburn  13468:     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  13469: }
                   13470: 
1.1172.2.27  raeburn  13471: # ------------------------------------------------------- Read loncaparev table
                   13472: {
                   13473:     sub load_loncaparevs {
                   13474:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13475:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13476:                 while (my $configline=<$config>) {
                   13477:                     chomp($configline);
                   13478:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13479:                     $loncaparevs{$hostid}=$loncaparev;
                   13480:                 }
                   13481:                 close($config);
                   13482:             }
                   13483:         }
                   13484:     }
                   13485: }
                   13486: 
                   13487: # ----------------------------------------------------- Read serverhostID table
                   13488: {
                   13489:     sub load_serverhomeIDs {
                   13490:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13491:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13492:                 while (my $configline=<$config>) {
                   13493:                     chomp($configline);
                   13494:                     my ($name,$id)=split(/:/,$configline);
                   13495:                     $serverhomeIDs{$name}=$id;
                   13496:                 }
                   13497:                 close($config);
                   13498:             }
                   13499:         }
                   13500:     }
                   13501: }
                   13502: 
                   13503: 
1.862     albertel 13504: BEGIN {
                   13505: 
                   13506: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13507:     unless ($readit) {
                   13508: {
                   13509:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13510:     %perlvar = (%perlvar,%{$configvars});
                   13511: }
                   13512: 
                   13513: 
1.1       albertel 13514: # ------------------------------------------------------ Read spare server file
                   13515: {
1.1172.2.96  raeburn  13516:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13517: 
                   13518:     while (my $configline=<$config>) {
                   13519:        chomp($configline);
1.284     matthew  13520:        if ($configline) {
1.784     albertel 13521: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13522: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13523: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13524:        }
                   13525:     }
1.448     albertel 13526:     close($config);
1.1       albertel 13527: }
1.11      www      13528: # ------------------------------------------------------------ Read permissions
                   13529: {
1.1172.2.96  raeburn  13530:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13531: 
                   13532:     while (my $configline=<$config>) {
1.448     albertel 13533: 	chomp($configline);
                   13534: 	if ($configline) {
                   13535: 	    my ($role,$perm)=split(/ /,$configline);
                   13536: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13537: 	}
1.11      www      13538:     }
1.448     albertel 13539:     close($config);
1.11      www      13540: }
                   13541: 
                   13542: # -------------------------------------------- Read plain texts for permissions
                   13543: {
1.1172.2.96  raeburn  13544:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13545: 
                   13546:     while (my $configline=<$config>) {
1.448     albertel 13547: 	chomp($configline);
                   13548: 	if ($configline) {
1.742     raeburn  13549: 	    my ($short,@plain)=split(/:/,$configline);
                   13550:             %{$prp{$short}} = ();
                   13551: 	    if (@plain > 0) {
                   13552:                 $prp{$short}{'std'} = $plain[0];
                   13553:                 for (my $i=1; $i<@plain; $i++) {
                   13554:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13555:                 }
                   13556:             }
1.448     albertel 13557: 	}
1.135     www      13558:     }
1.448     albertel 13559:     close($config);
1.135     www      13560: }
                   13561: 
                   13562: # ---------------------------------------------------------- Read package table
                   13563: {
1.1172.2.96  raeburn  13564:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13565: 
                   13566:     while (my $configline=<$config>) {
1.483     albertel 13567: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13568: 	chomp($configline);
                   13569: 	my ($short,$plain)=split(/:/,$configline);
                   13570: 	my ($pack,$name)=split(/\&/,$short);
                   13571: 	if ($plain ne '') {
                   13572: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13573: 	    $packagetab{$short}=$plain; 
                   13574: 	}
1.11      www      13575:     }
1.448     albertel 13576:     close($config);
1.329     matthew  13577: }
                   13578: 
1.1172.2.27  raeburn  13579: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13580: 
1.1172.2.27  raeburn  13581: &load_loncaparevs();
                   13582: 
                   13583: # ------------------------------------------------------- Read serverhostID table
                   13584: 
                   13585: &load_serverhomeIDs();
1.1074    raeburn  13586: 
1.1172.2.27  raeburn  13587: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13588: {
                   13589:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13590:     if (-e $file) {
                   13591:         my $parser = HTML::LCParser->new($file);
                   13592:         while (my $token = $parser->get_token()) {
                   13593:             if ($token->[0] eq 'S') {
                   13594:                 my $item = $token->[1];
                   13595:                 my $name = $token->[2]{'name'};
                   13596:                 my $value = $token->[2]{'value'};
                   13597:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13598:                     my $release = $parser->get_text();
                   13599:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13600:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13601:                 }
                   13602:             }
                   13603:         }
                   13604:     }
1.1073    raeburn  13605: }
                   13606: 
1.1138    raeburn  13607: # ---------------------------------------------------------- Read managers table
                   13608: {
                   13609:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  13610:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13611:             while (my $configline=<$config>) {
                   13612:                 chomp($configline);
                   13613:                 next if ($configline =~ /^\#/);
                   13614:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13615:                     $managerstab{$configline} = 1;
                   13616:                 }
                   13617:             }
                   13618:             close($config);
                   13619:         }
                   13620:     }
                   13621: }
                   13622: 
1.329     matthew  13623: # ------------- set up temporary directory
                   13624: {
1.1117    foxr     13625:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13626: 
1.11      www      13627: }
                   13628: 
1.1172.2.104  raeburn  13629: # ------------- set default texengine (domain default overrides this)
                   13630: {
                   13631:     $deftex = LONCAPA::texengine();
                   13632: }
                   13633: 
1.794     albertel 13634: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13635: 				'compress_threshold'=> 20_000,
                   13636:  			        });
1.185     www      13637: 
1.281     www      13638: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13639: $dumpcount=0;
1.958     www      13640: $locknum=0;
1.22      www      13641: 
1.163     harris41 13642: &logtouch();
1.672     albertel 13643: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13644: $readit=1;
1.564     albertel 13645:     {
                   13646: 	use integer;
                   13647: 	my $test=(2**32)+1;
1.568     albertel 13648: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13649: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13650:     }
1.195     www      13651: }
1.1       albertel 13652: }
1.179     www      13653: 
1.1       albertel 13654: 1;
1.191     harris41 13655: __END__
                   13656: 
1.243     albertel 13657: =pod
                   13658: 
1.191     harris41 13659: =head1 NAME
                   13660: 
1.243     albertel 13661: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13662: 
                   13663: =head1 SYNOPSIS
                   13664: 
1.243     albertel 13665: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13666: 
                   13667:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13668: 
1.243     albertel 13669: Common parameters:
                   13670: 
                   13671: =over 4
                   13672: 
                   13673: =item *
                   13674: 
                   13675: $uname : an internal username (if $cname expecting a course Id specifically)
                   13676: 
                   13677: =item *
                   13678: 
                   13679: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13680: 
                   13681: =item *
                   13682: 
                   13683: $symb : a resource instance identifier
                   13684: 
                   13685: =item *
                   13686: 
                   13687: $namespace : the name of a .db file that contains the data needed or
                   13688: being set.
                   13689: 
                   13690: =back
                   13691: 
1.394     bowersj2 13692: =head1 OVERVIEW
1.191     harris41 13693: 
1.394     bowersj2 13694: lonnet provides subroutines which interact with the
                   13695: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13696: about classes, users, and resources.
1.243     albertel 13697: 
                   13698: For many of these objects you can also use this to store data about
                   13699: them or modify them in various ways.
1.191     harris41 13700: 
1.394     bowersj2 13701: =head2 Symbs
1.191     harris41 13702: 
1.394     bowersj2 13703: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13704: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13705: map, the resource number of the resource in the map, and the URL of
                   13706: the resource itself. The latter is somewhat redundant, but might help
                   13707: if maps change.
                   13708: 
                   13709: An example is
                   13710: 
                   13711:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13712: 
                   13713: The respective map entry is
                   13714: 
                   13715:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13716:   title="Problem 2">
                   13717:  </resource>
                   13718: 
                   13719: Symbs are used by the random number generator, as well as to store and
                   13720: restore data specific to a certain instance of for example a problem.
                   13721: 
                   13722: =head2 Storing And Retrieving Data
                   13723: 
                   13724: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13725: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13726: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13727: is is the non-critical message twin of cstore. These functions are for
                   13728: handlers to store a perl hash to a user's permanent data space in an
                   13729: easy manner, and to retrieve it again on another call. It is expected
                   13730: that a handler would use this once at the beginning to retrieve data,
                   13731: and then again once at the end to send only the new data back.
                   13732: 
                   13733: The data is stored in the user's data directory on the user's
                   13734: homeserver under the ID of the course.
                   13735: 
                   13736: The hash that is returned by restore will have all of the previous
                   13737: value for all of the elements of the hash.
                   13738: 
                   13739: Example:
                   13740: 
                   13741:  #creating a hash
                   13742:  my %hash;
                   13743:  $hash{'foo'}='bar';
                   13744: 
                   13745:  #storing it
                   13746:  &Apache::lonnet::cstore(\%hash);
                   13747: 
                   13748:  #changing a value
                   13749:  $hash{'foo'}='notbar';
                   13750: 
                   13751:  #adding a new value
                   13752:  $hash{'bar'}='foo';
                   13753:  &Apache::lonnet::cstore(\%hash);
                   13754: 
                   13755:  #retrieving the hash
                   13756:  my %history=&Apache::lonnet::restore();
                   13757: 
                   13758:  #print the hash
                   13759:  foreach my $key (sort(keys(%history))) {
                   13760:    print("\%history{$key} = $history{$key}");
                   13761:  }
                   13762: 
                   13763: Will print out:
1.191     harris41 13764: 
1.394     bowersj2 13765:  %history{1:foo} = bar
                   13766:  %history{1:keys} = foo:timestamp
                   13767:  %history{1:timestamp} = 990455579
                   13768:  %history{2:bar} = foo
                   13769:  %history{2:foo} = notbar
                   13770:  %history{2:keys} = foo:bar:timestamp
                   13771:  %history{2:timestamp} = 990455580
                   13772:  %history{bar} = foo
                   13773:  %history{foo} = notbar
                   13774:  %history{timestamp} = 990455580
                   13775:  %history{version} = 2
                   13776: 
                   13777: Note that the special hash entries C<keys>, C<version> and
                   13778: C<timestamp> were added to the hash. C<version> will be equal to the
                   13779: total number of versions of the data that have been stored. The
                   13780: C<timestamp> attribute will be the UNIX time the hash was
                   13781: stored. C<keys> is available in every historical section to list which
                   13782: keys were added or changed at a specific historical revision of a
                   13783: hash.
                   13784: 
                   13785: B<Warning>: do not store the hash that restore returns directly. This
                   13786: will cause a mess since it will restore the historical keys as if the
                   13787: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13788: 
1.394     bowersj2 13789: Calling convention:
1.191     harris41 13790: 
1.1172.2.27  raeburn  13791:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13792:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13793: 
1.394     bowersj2 13794: For more detailed information, see lonnet specific documentation.
1.191     harris41 13795: 
1.394     bowersj2 13796: =head1 RETURN MESSAGES
1.191     harris41 13797: 
1.394     bowersj2 13798: =over 4
1.191     harris41 13799: 
1.394     bowersj2 13800: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13801: 
1.394     bowersj2 13802: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13803: when the connection is brought back up
1.191     harris41 13804: 
1.394     bowersj2 13805: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13806: for later delivery
1.191     harris41 13807: 
1.967     bisitz   13808: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13809: 
1.394     bowersj2 13810: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13811: that was requested
1.191     harris41 13812: 
1.243     albertel 13813: =back
1.191     harris41 13814: 
1.243     albertel 13815: =head1 PUBLIC SUBROUTINES
1.191     harris41 13816: 
1.243     albertel 13817: =head2 Session Environment Functions
1.191     harris41 13818: 
1.243     albertel 13819: =over 4
1.191     harris41 13820: 
1.394     bowersj2 13821: =item * 
                   13822: X<appenv()>
1.949     raeburn  13823: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13824: the user envirnoment file, and will be restored for each access this
1.620     albertel 13825: user makes during this session, also modifies the %env for the current
1.949     raeburn  13826: process. Optional rolesarrayref - if defined contains a reference to an array
                   13827: of roles which are exempt from the restriction on modifying user.role entries 
                   13828: in the user's environment.db and in %env.    
1.191     harris41 13829: 
                   13830: =item *
1.394     bowersj2 13831: X<delenv()>
1.987     raeburn  13832: B<delenv($delthis,$regexp)>: removes all items from the session
                   13833: environment file that begin with $delthis. If the 
                   13834: optional second arg - $regexp - is true, $delthis is treated as a 
                   13835: regular expression, otherwise \Q$delthis\E is used. 
                   13836: The values are also deleted from the current processes %env.
1.191     harris41 13837: 
1.795     albertel 13838: =item * get_env_multiple($name) 
                   13839: 
                   13840: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13841: values may be defined and end up as an array ref.
                   13842: 
                   13843: returns an array of values
                   13844: 
1.243     albertel 13845: =back
                   13846: 
                   13847: =head2 User Information
1.191     harris41 13848: 
1.243     albertel 13849: =over 4
1.191     harris41 13850: 
                   13851: =item *
1.394     bowersj2 13852: X<queryauthenticate()>
                   13853: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13854: authentication scheme
                   13855: 
                   13856: =item *
1.394     bowersj2 13857: X<authenticate()>
1.1073    raeburn  13858: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13859: authenticate user from domain's lib servers (first use the current
                   13860: one). C<$upass> should be the users password.
1.1073    raeburn  13861: $checkdefauth is optional (value is 1 if a check should be made to
                   13862:    authenticate user using default authentication method, and allow
                   13863:    account creation if username does not have account in the domain).
                   13864: $clientcancheckhost is optional (value is 1 if checking whether the
                   13865:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13866: 
                   13867: =item *
1.394     bowersj2 13868: X<homeserver()>
                   13869: B<homeserver($uname,$udom)>: find the server which has
                   13870: the user's directory and files (there must be only one), this caches
                   13871: the answer, and also caches if there is a borken connection.
1.191     harris41 13872: 
                   13873: =item *
1.394     bowersj2 13874: X<idget()>
                   13875: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13876: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13877: username, and only 1 username per ID in a specific domain) (returns
                   13878: hash: id=>name,id=>name)
1.191     harris41 13879: 
                   13880: =item *
1.394     bowersj2 13881: X<idrget()>
                   13882: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13883: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13884: 
                   13885: =item *
1.394     bowersj2 13886: X<idput()>
                   13887: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13888: 
                   13889: =item *
1.394     bowersj2 13890: X<rolesinit()>
1.1169    droeschl 13891: B<rolesinit($udom,$username)>: get user privileges.
                   13892: returns user role, first access and timer interval hashes
1.243     albertel 13893: 
                   13894: =item *
1.1171    droeschl 13895: X<privileged()>
                   13896: B<privileged($username,$domain)>: returns a true if user has a
                   13897: privileged and active role (i.e. su or dc), false otherwise.
                   13898: 
                   13899: =item *
1.551     albertel 13900: X<getsection()>
                   13901: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13902: course $cname, return section name/number or '' for "not in course"
                   13903: and '-1' for "no section"
                   13904: 
                   13905: =item *
1.394     bowersj2 13906: X<userenvironment()>
                   13907: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13908: passed in @what from the requested user's environment, returns a hash
                   13909: 
1.858     raeburn  13910: =item * 
                   13911: X<userlog_query()>
1.859     albertel 13912: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13913: activity.log file. %filters defines filters applied when parsing the
                   13914: log file. These can be start or end timestamps, or the type of action
                   13915: - log to look for Login or Logout events, check for Checkin or
                   13916: Checkout, role for role selection. The response is in the form
                   13917: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13918: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13919: 
1.243     albertel 13920: =back
                   13921: 
                   13922: =head2 User Roles
                   13923: 
                   13924: =over 4
                   13925: 
                   13926: =item *
                   13927: 
1.1172.2.65  raeburn  13928: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13929: returns codes for allowed actions.
                   13930: 
                   13931: The first argument is required, all others are optional.
                   13932: 
                   13933: $priv is the privilege being checked.
                   13934: $uri contains additional information about what is being checked for access (e.g.,
                   13935: URL, course ID etc.).
                   13936: $symb is the unique resource instance identifier in a course; if needed,
                   13937: but not provided, it will be retrieved via a call to &symbread().
                   13938: $role is the role for which a priv is being checked (only used if priv is evb).
                   13939: $clientip is the user's IP address (only used when checking for access to portfolio
                   13940: files).
                   13941: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13942: prevents recursive calls to &allowed.
                   13943: 
1.243     albertel 13944:  F: full access
                   13945:  U,I,K: authentication modes (cxx only)
                   13946:  '': forbidden
                   13947:  1: user needs to choose course
                   13948:  2: browse allowed
1.766     albertel 13949:  A: passphrase authentication needed
1.1172.2.65  raeburn  13950:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13951: 
                   13952: =item *
                   13953: 
1.1172.2.13  raeburn  13954: constructaccess($url,$setpriv) : check for access to construction space URL
                   13955: 
                   13956: See if the owner domain and name in the URL match those in the
                   13957: expected environment.  If so, return three element list
                   13958: ($ownername,$ownerdomain,$ownerhome).
                   13959: 
                   13960: Otherwise return the null string.
                   13961: 
                   13962: If second argument 'setpriv' is true, it assigns the privileges,
                   13963: and returns the same three element list, unless the owner has
                   13964: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13965: in which case the null string is returned.
                   13966: 
                   13967: =item *
                   13968: 
1.1172.2.84  raeburn  13969: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13970: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13971: for system, domain, and course level. $uname and $udom are optional (current
                   13972: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13973: 
                   13974: =item *
                   13975: 
1.988     raeburn  13976: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13977: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13978: $type is Course (default) or Community.
1.988     raeburn  13979: If $forcedefault evaluates to true, text returned will be default 
                   13980: text for $type. Otherwise, if this is a course, the text returned 
                   13981: will be a custom name for the role (if defined in the course's 
                   13982: environment).  If no custom name is defined the default is returned.
                   13983:    
1.832     raeburn  13984: =item *
                   13985: 
1.1172.2.23  raeburn  13986: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13987: All arguments are optional. Returns a hash of a roles, either for
                   13988: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13989: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13990: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13991: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13992: For each key, value is set to colon-separated start and end times for
                   13993: the role.  If no username and domain are specified, will default to
1.934     raeburn  13994: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13995: of role statuses (active, future or previous), roles 
                   13996: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13997: to restrict the list of roles reported. If no array ref is 
                   13998: provided for types, will default to return only active roles.
1.834     albertel 13999: 
1.1172.2.13  raeburn  14000: =item *
                   14001: 
                   14002: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14003: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14004: 
                   14005: Additional optional arguments are: $type (if role checking is to be restricted
                   14006: to certain user status types -- previous (expired roles), active (currently
                   14007: available roles) or future (roles available in the future), and
                   14008: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14009: have active Domain Coordinator role in course's domain or in additional
                   14010: domains (specified in 'Domains to check for privileged users' in course
                   14011: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14012: 
                   14013: =item *
                   14014: 
                   14015: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14016: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14017: $possdomains and $possroles are optional array refs -- to domains to check and
                   14018: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14019: users' roles.db to check for a dc or su role in any domain. This can be
                   14020: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14021: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14022: this then allows &privileged_by_domain() to be used, which caches the identity
                   14023: of privileged users, eliminating the need for repeated calls to &dump().
                   14024: 
                   14025: =item *
                   14026: 
                   14027: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14028: where the outer hash keys are domains specified in the $possdomains array ref,
                   14029: next inner hash keys are privileged roles specified in the $roles array ref,
                   14030: and the innermost hash contains key = value pairs for username:domain = end:start
                   14031: for active or future "privileged" users with that role in that domain. To avoid
                   14032: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14033: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14034: 
1.243     albertel 14035: =back
                   14036: 
                   14037: =head2 User Modification
                   14038: 
                   14039: =over 4
                   14040: 
                   14041: =item *
                   14042: 
1.957     raeburn  14043: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14044: user for the level given by URL.  Optional start and end dates (leave empty
                   14045: string or zero for "no date")
1.191     harris41 14046: 
                   14047: =item *
                   14048: 
1.243     albertel 14049: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14050: change a users, password, possible return values are: ok,
                   14051: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14052: refused
1.191     harris41 14053: 
                   14054: =item *
                   14055: 
1.243     albertel 14056: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14057: 
                   14058: =item *
                   14059: 
1.1058    raeburn  14060: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14061:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14062: 
                   14063: will update user information (firstname,middlename,lastname,generation,
                   14064: permanentemail), and if forceid is true, student/employee ID also.
                   14065: A user's institutional affiliation(s) can also be updated.
                   14066: User information fields will not be overwritten with empty entries 
                   14067: unless the field is included in the $candelete array reference.
                   14068: This array is included when a single user is modified via "Manage Users",
                   14069: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14070: 
                   14071: =item *
                   14072: 
1.286     matthew  14073: modifystudent
                   14074: 
1.957     raeburn  14075: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14076: The course id is resolved based on the current user's environment.  
                   14077: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14078: associated with a course.
                   14079: 
1.297     matthew  14080: This call is essentially a wrapper for lonnet::modifyuser and
                   14081: lonnet::modify_student_enrollment
1.286     matthew  14082: 
                   14083: Inputs: 
                   14084: 
                   14085: =over 4
                   14086: 
1.957     raeburn  14087: =item B<$udom> Student's loncapa domain
1.286     matthew  14088: 
1.957     raeburn  14089: =item B<$uname> Student's loncapa login name
1.286     matthew  14090: 
1.964     bisitz   14091: =item B<$uid> Student/Employee ID
1.286     matthew  14092: 
1.957     raeburn  14093: =item B<$umode> Student's authentication mode
1.286     matthew  14094: 
1.957     raeburn  14095: =item B<$upass> Student's password
1.286     matthew  14096: 
1.957     raeburn  14097: =item B<$first> Student's first name
1.286     matthew  14098: 
1.957     raeburn  14099: =item B<$middle> Student's middle name
1.286     matthew  14100: 
1.957     raeburn  14101: =item B<$last> Student's last name
1.286     matthew  14102: 
1.957     raeburn  14103: =item B<$gene> Student's generation
1.286     matthew  14104: 
1.957     raeburn  14105: =item B<$usec> Student's section in course
1.286     matthew  14106: 
                   14107: =item B<$end> Unix time of the roles expiration
                   14108: 
                   14109: =item B<$start> Unix time of the roles start date
                   14110: 
                   14111: =item B<$forceid> If defined, allow $uid to be changed
                   14112: 
                   14113: =item B<$desiredhome> server to use as home server for student
                   14114: 
1.957     raeburn  14115: =item B<$email> Student's permanent e-mail address
                   14116: 
                   14117: =item B<$type> Type of enrollment (auto or manual)
                   14118: 
1.963     raeburn  14119: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14120: 
                   14121: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14122: 
1.963     raeburn  14123: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14124: 
1.963     raeburn  14125: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14126: 
1.1172.2.19  raeburn  14127: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14128: 
                   14129: =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  14130: 
1.286     matthew  14131: =back
1.297     matthew  14132: 
                   14133: =item *
                   14134: 
                   14135: modify_student_enrollment
                   14136: 
1.1172.2.31  raeburn  14137: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14138: 'role.request.course' must be defined for this function to proceed.
                   14139: 
                   14140: Inputs:
                   14141: 
                   14142: =over 4
                   14143: 
1.1172.2.31  raeburn  14144: =item $udom, student's domain
1.297     matthew  14145: 
1.1172.2.31  raeburn  14146: =item $uname, student's name
1.297     matthew  14147: 
1.1172.2.31  raeburn  14148: =item $uid, student's user id
1.297     matthew  14149: 
1.1172.2.31  raeburn  14150: =item $first, student's first name
1.297     matthew  14151: 
                   14152: =item $middle
                   14153: 
                   14154: =item $last
                   14155: 
                   14156: =item $gene
                   14157: 
                   14158: =item $usec
                   14159: 
                   14160: =item $end
                   14161: 
                   14162: =item $start
                   14163: 
1.957     raeburn  14164: =item $type
                   14165: 
                   14166: =item $locktype
                   14167: 
                   14168: =item $cid
                   14169: 
                   14170: =item $selfenroll
                   14171: 
                   14172: =item $context
                   14173: 
1.1172.2.19  raeburn  14174: =item $credits, number of credits student will earn from this class
                   14175: 
1.1172.2.76  raeburn  14176: =item $instsec, institutional course section code for student
                   14177: 
1.297     matthew  14178: =back
                   14179: 
1.191     harris41 14180: 
                   14181: =item *
                   14182: 
1.243     albertel 14183: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14184: custom role; give a custom role to a user for the level given by URL.  Specify
                   14185: name and domain of role author, and role name
1.191     harris41 14186: 
                   14187: =item *
                   14188: 
1.243     albertel 14189: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14190: 
                   14191: =item *
                   14192: 
1.243     albertel 14193: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14194: 
                   14195: =back
                   14196: 
                   14197: =head2 Course Infomation
                   14198: 
                   14199: =over 4
1.191     harris41 14200: 
                   14201: =item *
                   14202: 
1.1118    foxr     14203: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14204: specified course id, including all environment settings for the
                   14205: course, the description of the course will be in the hash under the
                   14206: key 'description'
1.191     harris41 14207: 
1.1118    foxr     14208: $options is an optional parameter that if supplied is a hash reference that controls
                   14209: what how this function works.  It has the following key/values:
                   14210: 
                   14211: =over 4
                   14212: 
                   14213: =item freshen_cache
                   14214: 
                   14215: If defined, and the environment cache for the course is valid, it is 
                   14216: returned in the returned hash.
                   14217: 
                   14218: =item one_time
                   14219: 
                   14220: If defined, the last cache time is set to _now_
                   14221: 
                   14222: =item user
                   14223: 
                   14224: If defined, the supplied username is used instead of the current user.
                   14225: 
                   14226: 
                   14227: =back
                   14228: 
1.191     harris41 14229: =item *
                   14230: 
1.624     albertel 14231: resdata($name,$domain,$type,@which) : request for current parameter
                   14232: setting for a specific $type, where $type is either 'course' or 'user',
                   14233: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14234: answers for 10 minutes.
1.243     albertel 14235: 
1.877     foxr     14236: =item *
                   14237: 
                   14238: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14239: data base, returning a hash that is keyed by the resource name and has
                   14240: values that are the resource value.  I believe that the timestamps and
                   14241: versions are also returned.
                   14242: 
1.1172.2.31  raeburn  14243: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14244: supplemental content area. This routine caches the number of files for
                   14245: 10 minutes.
                   14246: 
1.243     albertel 14247: =back
                   14248: 
                   14249: =head2 Course Modification
                   14250: 
                   14251: =over 4
1.191     harris41 14252: 
                   14253: =item *
                   14254: 
1.243     albertel 14255: writecoursepref($courseid,%prefs) : write preferences (environment
                   14256: database) for a course
1.191     harris41 14257: 
                   14258: =item *
                   14259: 
1.1011    raeburn  14260: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14261: 
                   14262: =item *
                   14263: 
1.1038    raeburn  14264: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14265: 
1.1167    droeschl 14266: =item *
                   14267: 
                   14268: is_course($courseid), is_course($cdom, $cnum)
                   14269: 
                   14270: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14271: two component version $cdom, $cnum. It checks if the specified course exists.
                   14272: 
                   14273: Returns:
                   14274:     undef if the course doesn't exist, otherwise
                   14275:     in scalar context the combined courseid.
                   14276:     in list context the two components of the course identifier, domain and 
                   14277:     courseid.    
                   14278: 
1.243     albertel 14279: =back
                   14280: 
                   14281: =head2 Resource Subroutines
                   14282: 
                   14283: =over 4
1.191     harris41 14284: 
                   14285: =item *
                   14286: 
1.243     albertel 14287: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14288: 
                   14289: =item *
                   14290: 
1.243     albertel 14291: repcopy($filename) : subscribes to the requested file, and attempts to
                   14292: replicate from the owning library server, Might return
1.607     raeburn  14293: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14294: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14295: resource. Expects the local filesystem pathname
                   14296: (/home/httpd/html/res/....)
                   14297: 
                   14298: =back
                   14299: 
                   14300: =head2 Resource Information
                   14301: 
                   14302: =over 4
1.191     harris41 14303: 
                   14304: =item *
                   14305: 
1.1172.2.28  raeburn  14306: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14307: and returns the value of a variety of different possible values,
                   14308: $varname should be a request string, and the other parameters can be
                   14309: used to specify who and what one is asking about. Ordinarily, $cid 
                   14310: does not need to be specified, as it is retrived from 
                   14311: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14312: within lonuserstate::loadmap() when initializing a course, before
                   14313: $env{'request.course.id'} has been set, so it needs to be provided
                   14314: in that one case.
1.243     albertel 14315: 
                   14316: Possible values for $varname are environment.lastname (or other item
                   14317: from the envirnment hash), user.name (or someother aspect about the
                   14318: user), resource.0.maxtries (or some other part and parameter of a
                   14319: resource)
1.204     albertel 14320: 
                   14321: =item *
                   14322: 
1.243     albertel 14323: directcondval($number) : get current value of a condition; reads from a state
                   14324: string
1.204     albertel 14325: 
                   14326: =item *
                   14327: 
1.243     albertel 14328: condval($condidx) : value of condition index based on state
1.204     albertel 14329: 
                   14330: =item *
                   14331: 
1.243     albertel 14332: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14333: resource's metadata, $what should be either a specific key, or either
                   14334: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14335: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14336: 
                   14337: this function automatically caches all requests
1.191     harris41 14338: 
                   14339: =item *
                   14340: 
1.243     albertel 14341: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14342: network of library servers; returns file handle of where SQL and regex results
                   14343: will be stored for query
1.191     harris41 14344: 
                   14345: =item *
                   14346: 
1.1172.2.66  raeburn  14347: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14348: return symbolic list entry (all arguments optional).
                   14349: 
                   14350: Args: filename is the filename (including path) for the file for which a symb
                   14351: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14352: to check access status if more than one resource was found in the bighash
                   14353: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14354: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14355: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14356: cause possible symbs to be checked to determine if they are subject to content
                   14357: blocking, if so they will not be included as possible symbs; possibles is a
                   14358: ref to a hash, which, as a side effect, will be populated with all possible
                   14359: symbs (content blocking not tested).
                   14360: 
1.243     albertel 14361: returns the data handle
1.191     harris41 14362: 
                   14363: =item *
                   14364: 
1.1172.2.17  raeburn  14365: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14366: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14367: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14368: on failure, user must be in a course, as it assumes the existence of
                   14369: the course initial hash, and uses $env('request.course.id'}.  The third
                   14370: arg is an optional reference to a scalar.  If this arg is passed in the
                   14371: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14372: encrypted; otherwise it will be null.
1.243     albertel 14373: 
1.191     harris41 14374: =item *
                   14375: 
1.243     albertel 14376: symbclean($symb) : removes versions numbers from a symb, returns the
                   14377: cleaned symb
1.191     harris41 14378: 
                   14379: =item *
                   14380: 
1.243     albertel 14381: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14382: course map, user must be in a course for it to work.
1.191     harris41 14383: 
                   14384: =item *
                   14385: 
1.243     albertel 14386: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14387: 
                   14388: =item *
                   14389: 
1.243     albertel 14390: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14391: a random seed, all arguments are optional, if they aren't sent it uses the
                   14392: environment to derive them. Note: if symb isn't sent and it can't get one
                   14393: from &symbread it will use the current time as its return value
1.191     harris41 14394: 
                   14395: =item *
                   14396: 
1.243     albertel 14397: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14398: unfakeable, receipt
1.191     harris41 14399: 
                   14400: =item *
                   14401: 
1.620     albertel 14402: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14403: 
                   14404: =item *
                   14405: 
1.243     albertel 14406: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14407: 
                   14408: =item *
                   14409: 
1.243     albertel 14410: 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 14411: 
                   14412: =item *
                   14413: 
1.243     albertel 14414: 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 14415: 
                   14416: =item *
                   14417: 
1.243     albertel 14418: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14419: 
                   14420: =item *
                   14421: 
1.243     albertel 14422: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14423: forcing spreadsheet to reevaluate the resource scores next time.
                   14424: 
1.1172.2.13  raeburn  14425: =item *
                   14426: 
                   14427: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14428: when viewing in course context.
                   14429: 
                   14430:  input: six args -- filename (decluttered), course number, course domain,
                   14431:                     url, symb (if registered) and group (if this is a
                   14432:                     group item -- e.g., bulletin board, group page etc.).
                   14433: 
                   14434:  output: array of five scalars --
                   14435:          $cfile -- url for file editing if editable on current server
                   14436:          $home -- homeserver of resource (i.e., for author if published,
                   14437:                                           or course if uploaded.).
                   14438:          $switchserver --  1 if server switch will be needed.
                   14439:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14440:          $forceview -- 1 if icon/link should be to go to view mode
                   14441: 
                   14442: =item *
                   14443: 
                   14444: is_course_upload($file,$cnum,$cdom)
                   14445: 
                   14446: Used in course context to determine if current file was uploaded to
                   14447: the course (i.e., would be found in /userfiles/docs on the course's
                   14448: homeserver.
                   14449: 
                   14450:   input: 3 args -- filename (decluttered), course number and course domain.
                   14451:   output: boolean -- 1 if file was uploaded.
                   14452: 
1.243     albertel 14453: =back
                   14454: 
                   14455: =head2 Storing/Retreiving Data
                   14456: 
                   14457: =over 4
1.191     harris41 14458: 
                   14459: =item *
                   14460: 
1.1172.2.64  raeburn  14461: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14462: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14463: the remaining args aren't required and if they aren't passed or are '' they will
                   14464: be derived from the env (with the exception of $laststore, which is an
                   14465: optional arg used when a user's submission is stored in grading).
                   14466: $laststore is $version=$timestamp, where $version is the most recent version
                   14467: number retrieved for the corresponding $symb in the $namespace db file, and
                   14468: $timestamp is the timestamp for that transaction (UNIX time).
                   14469: $laststore is currently only passed when cstore() is called by
                   14470: structuretags::finalize_storage().
1.191     harris41 14471: 
                   14472: =item *
                   14473: 
1.1172.2.64  raeburn  14474: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14475: but uses critical subroutine
1.191     harris41 14476: 
                   14477: =item *
                   14478: 
1.243     albertel 14479: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14480: all args are optional
1.191     harris41 14481: 
                   14482: =item *
                   14483: 
1.717     albertel 14484: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14485: dumps the complete (or key matching regexp) namespace into a hash
                   14486: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14487: normally &store()ed into
                   14488: 
                   14489: $range should be either an integer '100' (give me the first 100
                   14490:                                            matching records)
                   14491:               or be  two integers sperated by a - with no spaces
                   14492:                  '30-50' (give me the 30th through the 50th matching
                   14493:                           records)
                   14494: 
                   14495: 
                   14496: =item *
                   14497: 
1.1172.2.59  raeburn  14498: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14499: replaces a &store() version of data with a replacement set of data
                   14500: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14501: reference. If $tolog is true, the transaction is logged in the courselog
                   14502: with an action=PUTSTORE.
1.717     albertel 14503: 
                   14504: =item *
                   14505: 
1.243     albertel 14506: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14507: works very similar to store/cstore, but all data is stored in a
                   14508: temporary location and can be reset using tmpreset, $storehash should
                   14509: be a hash reference, returns nothing on success
1.191     harris41 14510: 
                   14511: =item *
                   14512: 
1.243     albertel 14513: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14514: similar to restore, but all data is stored in a temporary location and
                   14515: can be reset using tmpreset. Returns a hash of values on success,
                   14516: error string otherwise.
1.191     harris41 14517: 
                   14518: =item *
                   14519: 
1.243     albertel 14520: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14521: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14522: 
                   14523: =item *
                   14524: 
1.243     albertel 14525: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14526: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14527: 
                   14528: =item *
                   14529: 
1.243     albertel 14530: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14531: namesp ($udom and $uname are optional)
1.191     harris41 14532: 
                   14533: =item *
                   14534: 
1.702     albertel 14535: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14536: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14537: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14538: 
1.702     albertel 14539: $range should be either an integer '100' (give me the first 100
                   14540:                                            matching records)
                   14541:               or be  two integers sperated by a - with no spaces
                   14542:                  '30-50' (give me the 30th through the 50th matching
                   14543:                           records)
1.449     matthew  14544: =item *
                   14545: 
                   14546: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14547: $store can be a scalar, an array reference, or if the amount to be 
                   14548: incremented is > 1, a hash reference.
                   14549: 
                   14550: ($udom and $uname are optional)
1.191     harris41 14551: 
                   14552: =item *
                   14553: 
1.243     albertel 14554: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14555: ($udom and $uname are optional)
1.191     harris41 14556: 
                   14557: =item *
                   14558: 
1.243     albertel 14559: cput($namespace,$storehash,$udom,$uname) : critical put
                   14560: ($udom and $uname are optional)
1.191     harris41 14561: 
                   14562: =item *
                   14563: 
1.748     albertel 14564: newput($namespace,$storehash,$udom,$uname) :
                   14565: 
                   14566: Attempts to store the items in the $storehash, but only if they don't
                   14567: currently exist, if this succeeds you can be certain that you have 
                   14568: successfully created a new key value pair in the $namespace db.
                   14569: 
                   14570: 
                   14571: Args:
                   14572:  $namespace: name of database to store values to
                   14573:  $storehash: hashref to store to the db
                   14574:  $udom: (optional) domain of user containing the db
                   14575:  $uname: (optional) name of user caontaining the db
                   14576: 
                   14577: Returns:
                   14578:  'ok' -> succeeded in storing all keys of $storehash
                   14579:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14580:                         least <key> already existed in the db (other
                   14581:                         requested keys may also already exist)
1.967     bisitz   14582:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14583:  'con_lost' -> unable to contact request server
                   14584:  'refused' -> action was not allowed by remote machine
                   14585: 
                   14586: 
                   14587: =item *
                   14588: 
1.243     albertel 14589: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14590: reference filled in from namesp (encrypts the return communication)
                   14591: ($udom and $uname are optional)
1.191     harris41 14592: 
                   14593: =item *
                   14594: 
1.243     albertel 14595: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14596: critical subroutine
                   14597: 
1.806     raeburn  14598: =item *
                   14599: 
1.860     raeburn  14600: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14601: array reference filled in from namespace found in domain level on either
                   14602: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14603: 
                   14604: =item *
                   14605: 
1.860     raeburn  14606: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14607: domain level either on specified domain server ($uhome) or primary domain 
                   14608: server ($udom and $uhome are optional)
1.806     raeburn  14609: 
1.943     raeburn  14610: =item * 
                   14611: 
1.1172.2.35  raeburn  14612: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14613: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14614: the target domain.
                   14615: 
                   14616: May also include additional key => value pairs for the following groups:
                   14617: 
                   14618: =over
                   14619: 
                   14620: =item
                   14621: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14622: 
                   14623: =over
                   14624: 
                   14625: =item defaultquota, authorquota
                   14626: 
                   14627: =back
                   14628: 
                   14629: =item
                   14630: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14631: portfolio for users).
                   14632: 
                   14633: =over
                   14634: 
                   14635: =item
                   14636: aboutme, blog, webdav, portfolio
                   14637: 
                   14638: =back
                   14639: 
                   14640: =item
                   14641: requestcourses: ability to request courses, and how requests are processed.
                   14642: 
                   14643: =over
                   14644: 
                   14645: =item
1.1172.2.37  raeburn  14646: official, unofficial, community, textbook
1.1172.2.35  raeburn  14647: 
                   14648: =back
                   14649: 
                   14650: =item
                   14651: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14652: 
                   14653: =over
                   14654: 
                   14655: =item
1.1172.2.44  raeburn  14656: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  14657: 
                   14658: =back
                   14659: 
                   14660: =item
                   14661: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14662: for course's uploaded content.
                   14663: 
                   14664: =over
                   14665: 
                   14666: =item
1.1172.2.68  raeburn  14667: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   14668: communityquota, textbookquota
1.1172.2.35  raeburn  14669: 
                   14670: =back
                   14671: 
                   14672: =item
                   14673: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14674: on your servers.
                   14675: 
                   14676: =over
                   14677: 
                   14678: =item
                   14679: remotesessions, hostedsessions
                   14680: 
                   14681: =back
                   14682: 
                   14683: =back
                   14684: 
                   14685: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14686: utility to create a configuration.db file on a domain's primary library server
                   14687: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14688: -- corresponding values are authentication type (internal, krb4, krb5,
                   14689: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   14690: will be available. Values are retrieved from cache (if current), unless the
                   14691: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14692: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14693: 
                   14694: Typical usage:
1.943     raeburn  14695: 
1.1172.2.35  raeburn  14696: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14697: 
1.243     albertel 14698: =back
                   14699: 
                   14700: =head2 Network Status Functions
                   14701: 
                   14702: =over 4
1.191     harris41 14703: 
                   14704: =item *
                   14705: 
1.1137    raeburn  14706: dirlist() : return directory list based on URI (first arg).
                   14707: 
                   14708: Inputs: 1 required, 5 optional.
                   14709: 
                   14710: =over
                   14711: 
                   14712: =item 
                   14713: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14714: 
                   14715: =item
                   14716: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14717: 
                   14718: =item
                   14719: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14720: 
                   14721: =item
                   14722: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14723: 
                   14724: =item
                   14725: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14726: 
                   14727: =item 
                   14728: $alternateRoot - path to prepend in place of path from $uri.
                   14729: 
                   14730: =back
                   14731: 
                   14732: Returns: Array of up to two items.
                   14733: 
                   14734: =over
                   14735: 
                   14736: a reference to an array of files/subdirectories
                   14737: 
                   14738: =over
                   14739: 
                   14740: Each element in the array of files/subdirectories is a & separated list of
                   14741: item name and the result of running stat on the item.  If dirlist was requested
                   14742: for a file instead of a directory, the item name will be ''. For a directory 
                   14743: listing, if the item is a metadata file, the element will end &N&M 
                   14744: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14745: default copyright set (1).  
                   14746: 
                   14747: =back
                   14748: 
                   14749: a scalar containing error condition (if encountered).
                   14750: 
                   14751: =over
                   14752: 
                   14753: =item 
                   14754: no_host (no homeserver identified for $username:$domain).
                   14755: 
                   14756: =item 
                   14757: no_such_host (server contacted for listing not identified as valid host).
                   14758: 
                   14759: =item 
                   14760: con_lost (connection to remote server failed).
                   14761: 
                   14762: =item 
                   14763: refused (invalid $username:$domain received on lond side).
                   14764: 
                   14765: =item 
                   14766: no_such_dir (directory at specified path on lond side does not exist). 
                   14767: 
                   14768: =item 
                   14769: empty (directory at specified path on lond side is empty).
                   14770: 
                   14771: =over
                   14772: 
                   14773: This is currently not encountered because the &ls3, &ls2, 
                   14774: &ls (_handler) routines on the lond side do not filter out
                   14775: . and .. from a directory listing. 
                   14776: 
                   14777: =back
                   14778: 
                   14779: =back
                   14780: 
                   14781: =back
1.191     harris41 14782: 
                   14783: =item *
                   14784: 
1.243     albertel 14785: spareserver() : find server with least workload from spare.tab
                   14786: 
1.986     foxr     14787: 
                   14788: =item *
                   14789: 
                   14790: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14791: if there is no corresponding loncapa host.
                   14792: 
1.243     albertel 14793: =back
                   14794: 
1.986     foxr     14795: 
1.243     albertel 14796: =head2 Apache Request
                   14797: 
                   14798: =over 4
1.191     harris41 14799: 
                   14800: =item *
                   14801: 
1.243     albertel 14802: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14803: localhost, posts hash
                   14804: 
                   14805: =back
                   14806: 
                   14807: =head2 Data to String to Data
                   14808: 
                   14809: =over 4
1.191     harris41 14810: 
                   14811: =item *
                   14812: 
1.243     albertel 14813: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14814: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14815: 
                   14816: =item *
                   14817: 
1.243     albertel 14818: hashref2str($hashref) : convert a hashref into a string complete with
                   14819: escaping and '=' and '&' separators, supports elements that are
                   14820: arrayrefs and hashrefs
1.191     harris41 14821: 
                   14822: =item *
                   14823: 
1.243     albertel 14824: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14825: with escaping and '&' separators, supports elements that are arrayrefs
                   14826: and hashrefs
1.191     harris41 14827: 
                   14828: =item *
                   14829: 
1.243     albertel 14830: str2hash($string) : convert string to hash using unescaping and
                   14831: splitting on '=' and '&', supports elements that are arrayrefs and
                   14832: hashrefs
1.191     harris41 14833: 
                   14834: =item *
                   14835: 
1.243     albertel 14836: str2array($string) : convert string to hash using unescaping and
                   14837: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14838: 
                   14839: =back
                   14840: 
                   14841: =head2 Logging Routines
                   14842: 
                   14843: 
                   14844: These routines allow one to make log messages in the lonnet.log and
                   14845: lonnet.perm logfiles.
1.191     harris41 14846: 
1.1119    foxr     14847: =over 4
                   14848: 
1.191     harris41 14849: =item *
                   14850: 
1.243     albertel 14851: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14852: 
                   14853: =item *
                   14854: 
1.243     albertel 14855: logthis() : append message to the normal lonnet.log file, it gets
                   14856: preiodically rolled over and deleted.
1.191     harris41 14857: 
                   14858: =item *
                   14859: 
1.243     albertel 14860: logperm() : append a permanent message to lonnet.perm.log, this log
                   14861: file never gets deleted by any automated portion of the system, only
                   14862: messages of critical importance should go in here.
                   14863: 
1.1119    foxr     14864: 
1.243     albertel 14865: =back
                   14866: 
                   14867: =head2 General File Helper Routines
                   14868: 
                   14869: =over 4
1.191     harris41 14870: 
                   14871: =item *
                   14872: 
1.481     raeburn  14873: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14874: (a) files in /uploaded
                   14875:   (i) If a local copy of the file exists - 
                   14876:       compares modification date of local copy with last-modified date for 
                   14877:       definitive version stored on home server for course. If local copy is 
                   14878:       stale, requests a new version from the home server and stores it. 
                   14879:       If the original has been removed from the home server, then local copy 
                   14880:       is unlinked.
                   14881:   (ii) If local copy does not exist -
                   14882:       requests the file from the home server and stores it. 
                   14883:   
                   14884:   If $caller is 'uploadrep':  
                   14885:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14886:     for request for files originally uploaded via DOCS. 
                   14887:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14888:   
                   14889:   Otherwise:
                   14890:      This indicates a call from the content generation phase of the request.
                   14891:      -  returns the entire contents of the file or -1.
                   14892:      
                   14893: (b) files in /res
                   14894:    - returns the entire contents of a file or -1; 
                   14895:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14896: 
1.712     albertel 14897: 
                   14898: =item *
                   14899: 
                   14900: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14901:                   reference
                   14902: 
                   14903: returns either a stat() list of data about the file or an empty list
                   14904: if the file doesn't exist or couldn't find out about it (connection
                   14905: problems or user unknown)
                   14906: 
1.191     harris41 14907: =item *
                   14908: 
1.243     albertel 14909: filelocation($dir,$file) : returns file system location of a file
                   14910: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14911: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14912: and a file of ../bob will become /a/bob)
1.191     harris41 14913: 
                   14914: =item *
                   14915: 
                   14916: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14917: filelocation except for hrefs
                   14918: 
                   14919: =item *
                   14920: 
1.1172.2.49  raeburn  14921: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14922: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14923: 
1.243     albertel 14924: =back
                   14925: 
1.608     albertel 14926: =head2 Usererfile file routines (/uploaded*)
                   14927: 
                   14928: =over 4
                   14929: 
                   14930: =item *
                   14931: 
                   14932: userfileupload(): main rotine for putting a file in a user or course's
                   14933:                   filespace, arguments are,
                   14934: 
1.620     albertel 14935:  formname - required - this is the name of the element in $env where the
1.608     albertel 14936:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14937:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14938:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14939:  context - if coursedoc, store the file in the course of the active role
                   14940:              of the current user; 
                   14941:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14942:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14943:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14944:          if undefined, it will be placed in "unknown"
                   14945: 
                   14946:  (This routine calls clean_filename() to remove any dangerous
                   14947:  characters from the filename, and then calls finuserfileupload() to
                   14948:  complete the transaction)
                   14949: 
                   14950:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14951:  and /adm/notfound.html if unsuccessful
                   14952: 
                   14953: =item *
                   14954: 
                   14955: clean_filename(): routine for cleaing a filename up for storage in
                   14956:                  userfile space, argument is:
                   14957: 
                   14958:  filename - proposed filename
                   14959: 
                   14960: returns: the new clean filename
                   14961: 
                   14962: =item *
                   14963: 
1.1090    raeburn  14964: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14965: userspace, probably shouldn't be called directly
                   14966: 
                   14967:   docuname: username or courseid of destination for the file
                   14968:   docudom: domain of user/course of destination for the file
                   14969:   formname: same as for userfileupload()
1.1090    raeburn  14970:   fname: filename (including subdirectories) for the file
                   14971:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14972:   allfiles: reference to hash used to store objects found by parser
                   14973:   codebase: reference to hash used for codebases of java objects found by parser
                   14974:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14975:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14976:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14977:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14978:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14979:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14980:   mimetype: reference to scalar to accommodate mime type determined
                   14981:             from File::MMagic if $parser = parse.
1.608     albertel 14982: 
                   14983:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14984:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14985:  was 'overwrite').
                   14986:  
1.608     albertel 14987: 
                   14988: =item *
                   14989: 
                   14990: renameuserfile(): renames an existing userfile to a new name
                   14991: 
                   14992:   Args:
                   14993:    docuname: username or courseid of destination for the file
                   14994:    docudom: domain of user/course of destination for the file
                   14995:    old: current file name (including any subdirs under userfiles)
                   14996:    new: desired file name (including any subdirs under userfiles)
                   14997: 
                   14998: =item *
                   14999: 
                   15000: mkdiruserfile(): creates a directory is a userfiles dir
                   15001: 
                   15002:   Args:
                   15003:    docuname: username or courseid of destination for the file
                   15004:    docudom: domain of user/course of destination for the file
                   15005:    dir: dir to create (including any subdirs under userfiles)
                   15006: 
                   15007: =item *
                   15008: 
                   15009: removeuserfile(): removes a file that exists in userfiles
                   15010: 
                   15011:   Args:
                   15012:    docuname: username or courseid of destination for the file
                   15013:    docudom: domain of user/course of destination for the file
                   15014:    fname: filname to delete (including any subdirs under userfiles)
                   15015: 
                   15016: =item *
                   15017: 
                   15018: removeuploadedurl(): convience function for removeuserfile()
                   15019: 
                   15020:   Args:
                   15021:    url:  a full /uploaded/... url to delete
                   15022: 
1.747     albertel 15023: =item * 
                   15024: 
                   15025: get_portfile_permissions():
                   15026:   Args:
                   15027:     domain: domain of user or course contain the portfolio files
                   15028:     user: name of user or num of course contain the portfolio files
                   15029:   Returns:
                   15030:     hashref of a dump of the proper file_permissions.db
                   15031:    
                   15032: 
                   15033: =item * 
                   15034: 
                   15035: get_access_controls():
                   15036: 
                   15037: Args:
                   15038:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15039:   group: (optional) the group you want the files associated with
                   15040:   file: (optional) the file you want access info on
                   15041: 
                   15042: Returns:
1.749     raeburn  15043:     a hash (keys are file names) of hashes containing
                   15044:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15045:         values are XML containing access control settings (see below) 
1.747     albertel 15046: 
                   15047: Internal notes:
                   15048: 
1.749     raeburn  15049:  access controls are stored in file_permissions.db as key=value pairs.
                   15050:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15051:         where scope -> public,guest,course,group,domains or users.
                   15052:               end -> UNIX time for end of access (0 -> no end date)
                   15053:               start -> UNIX time for start of access
                   15054: 
                   15055:     value -> XML description of access control
                   15056:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15057:             <start></start>
                   15058:             <end></end>
                   15059: 
                   15060:             <password></password>  for scope type = guest
                   15061: 
                   15062:             <domain></domain>     for scope type = course or group
                   15063:             <number></number>
                   15064:             <roles id="">
                   15065:              <role></role>
                   15066:              <access></access>
                   15067:              <section></section>
                   15068:              <group></group>
                   15069:             </roles>
                   15070: 
                   15071:             <dom></dom>         for scope type = domains
                   15072: 
                   15073:             <users>             for scope type = users
                   15074:              <user>
                   15075:               <uname></uname>
                   15076:               <udom></udom>
                   15077:              </user>
                   15078:             </users>
                   15079:            </scope> 
                   15080:               
                   15081:  Access data is also aggregated for each file in an additional key=value pair:
                   15082:  key -> path to file/file_name\0accesscontrol 
                   15083:  value -> reference to hash
                   15084:           hash contains key = value pairs
                   15085:           where key = uniqueID:scope_end_start
                   15086:                 value = UNIX time record was last updated
                   15087: 
                   15088:           Used to improve speed of look-ups of access controls for each file.  
                   15089:  
                   15090:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15091: 
1.1172.2.13  raeburn  15092: =item *
                   15093: 
1.749     raeburn  15094: modify_access_controls():
                   15095: 
                   15096: Modifies access controls for a portfolio file
                   15097: Args
                   15098: 1. file name
                   15099: 2. reference to hash of required changes,
                   15100: 3. domain
                   15101: 4. username
                   15102:   where domain,username are the domain of the portfolio owner 
                   15103:   (either a user or a course) 
                   15104: 
                   15105: Returns:
                   15106: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15107: 2. result of deletions ('ok' or 'error', with error message).
                   15108: 3. reference to hash of any new or updated access controls.
                   15109: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15110:    key = integer (inbound ID)
1.1172.2.13  raeburn  15111:    value = uniqueID
                   15112: 
                   15113: =item *
                   15114: 
                   15115: get_timebased_id():
                   15116: 
                   15117: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15118: course via the Course Editor (e.g., folders, composite pages,
                   15119: group bulletin boards).
                   15120: 
                   15121: Args: (first three required; six others optional)
                   15122: 
                   15123: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15124:    docssequence, or name of group
                   15125: 
                   15126: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15127:    e.g., num, boardids
                   15128: 
                   15129: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15130:    file will be named nohist_namespace.db
                   15131: 
                   15132: 4. cdom: domain of course; default is current course domain from %env
                   15133: 
                   15134: 5. cnum: course number; default is current course number from %env
                   15135: 
                   15136: 6. idtype: set to concat if an additional digit is to be appended to the
                   15137:    unix timestamp to form the suffix, if the plain timestamp is already
                   15138:    in use.  Default is to not do this, but simply increment the unix
                   15139:    timestamp by 1 until a unique key is obtained.
                   15140: 
                   15141: 7. who: holder of locking key; defaults to user:domain for user.
                   15142: 
                   15143: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15144:    retrying); default is 3.
                   15145: 
                   15146: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15147: 
                   15148: Returns:
                   15149: 
                   15150: 1. suffix obtained (numeric)
                   15151: 
                   15152: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15153: 
                   15154: 3. error: contains (localized) error message if an error occurred.
                   15155: 
1.747     albertel 15156: 
1.608     albertel 15157: =back
                   15158: 
1.243     albertel 15159: =head2 HTTP Helper Routines
                   15160: 
                   15161: =over 4
                   15162: 
1.191     harris41 15163: =item *
                   15164: 
                   15165: escape() : unpack non-word characters into CGI-compatible hex codes
                   15166: 
                   15167: =item *
                   15168: 
                   15169: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15170: 
1.243     albertel 15171: =back
                   15172: 
                   15173: =head1 PRIVATE SUBROUTINES
                   15174: 
                   15175: =head2 Underlying communication routines (Shouldn't call)
                   15176: 
                   15177: =over 4
                   15178: 
                   15179: =item *
                   15180: 
                   15181: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15182: 
                   15183: =item *
                   15184: 
                   15185: reply() : uses subreply to send a message to remote machine, logs all failures
                   15186: 
                   15187: =item *
                   15188: 
                   15189: critical() : passes a critical message to another server; if cannot
                   15190: get through then place message in connection buffer directory and
                   15191: returns con_delayed, if incapable of saving message, returns
                   15192: con_failed
                   15193: 
                   15194: =item *
                   15195: 
                   15196: reconlonc() : tries to reconnect lonc client processes.
                   15197: 
                   15198: =back
                   15199: 
                   15200: =head2 Resource Access Logging
                   15201: 
                   15202: =over 4
                   15203: 
                   15204: =item *
                   15205: 
                   15206: flushcourselogs() : flush (save) buffer logs and access logs
                   15207: 
                   15208: =item *
                   15209: 
                   15210: courselog($what) : save message for course in hash
                   15211: 
                   15212: =item *
                   15213: 
                   15214: courseacclog($what) : save message for course using &courselog().  Perform
                   15215: special processing for specific resource types (problems, exams, quizzes, etc).
                   15216: 
1.191     harris41 15217: =item *
                   15218: 
                   15219: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15220: as a PerlChildExitHandler
1.243     albertel 15221: 
                   15222: =back
                   15223: 
                   15224: =head2 Other
                   15225: 
                   15226: =over 4
                   15227: 
                   15228: =item *
                   15229: 
                   15230: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15231: 
                   15232: =back
                   15233: 
                   15234: =cut
1.877     foxr     15235: 

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