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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1466  ! raeburn     4: # $Id: lonnet.pm,v 1.1465 2021/09/21 22:54:27 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.486     www        74: use HTTP::Date;
1.977     amueller   75: use Image::Magick;
1.1389    raeburn    76: use CGI::Cookie;
1.1182    foxr       77: 
1.1173    foxr       78: use Encode;
                     79: 
1.1405    raeburn    80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1416    raeburn    82:             %managerstab $passwdmin);
1.871     albertel   83: 
                     84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        87:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        88: 
1.1       albertel   89: use IO::Socket;
1.31      www        90: use GDBM_File;
1.208     albertel   91: use HTML::LCParser;
1.88      www        92: use Fcntl qw(:flock);
1.870     albertel   93: use Storable qw(thaw nfreeze);
1.1289    damieng    94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   95: use Cache::Memcached;
1.676     albertel   96: use Digest::MD5;
1.790     albertel   97: use Math::Random;
1.1024    raeburn    98: use File::MMagic;
1.1434    raeburn    99: use Net::CIDR;
1.1456    raeburn   100: use Sys::Hostname::FQDN();
1.807     albertel  101: use LONCAPA qw(:DEFAULT :match);
1.740     www       102: use LONCAPA::Configuration;
1.1160    www       103: use LONCAPA::lonmetadata;
1.1167    droeschl  104: use LONCAPA::Lond;
1.1345    raeburn   105: use LONCAPA::LWPReq;
1.1406    raeburn   106: use LONCAPA::transliterate;
1.1117    foxr      107: 
1.1090    raeburn   108: use File::Copy;
1.676     albertel  109: 
1.195     www       110: my $readit;
1.1288    damieng   111: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  112: 
1.619     albertel  113: require Exporter;
                    114: 
                    115: our @ISA = qw (Exporter);
                    116: our @EXPORT = qw(%env);
                    117: 
1.449     matthew   118: 
1.1187    raeburn   119: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       120: {
                    121:     my $logid;
1.1187    raeburn   122:     sub write_log {
1.1188    raeburn   123: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   124:         if ($context eq 'course') {
                    125:             if (($cnum eq '') || ($cdom eq '')) {
                    126:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    127:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    128:             }
1.957     raeburn   129:         }
1.1184    raeburn   130: 	$logid ++;
1.957     raeburn   131:         my $now = time();
                    132: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1434    raeburn   133:         my $ip = &get_requestor_ip();
1.1184    raeburn   134:         my $logentry = { 
                    135:                           $id => {
                    136:                                    'exe_uname' => $env{'user.name'},
                    137:                                    'exe_udom'  => $env{'user.domain'},
                    138:                                    'exe_time'  => $now,
1.1434    raeburn   139:                                    'exe_ip'    => $ip,
1.1184    raeburn   140:                                    'delflag'   => $delflag,
                    141:                                    'logentry'  => $storehash,
                    142:                                    'uname'     => $uname,
                    143:                                    'udom'      => $udom,
                    144:                                   }
                    145:                        };
                    146: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       147:     }
                    148: }
1.1       albertel  149: 
1.163     harris41  150: sub logtouch {
                    151:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  152:     unless (-e "$execdir/logs/lonnet.log") {	
1.1359    raeburn   153: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  154: 	close $fh;
                    155:     }
                    156:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    157:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    158: }
                    159: 
1.1       albertel  160: sub logthis {
                    161:     my $message=shift;
                    162:     my $execdir=$perlvar{'lonDaemons'};
                    163:     my $now=time;
                    164:     my $local=localtime($now);
1.1359    raeburn   165:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      166: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    167: 	print $fh $logstring;
1.448     albertel  168: 	close($fh);
                    169:     }
1.1       albertel  170:     return 1;
                    171: }
                    172: 
                    173: sub logperm {
                    174:     my $message=shift;
                    175:     my $execdir=$perlvar{'lonDaemons'};
                    176:     my $now=time;
                    177:     my $local=localtime($now);
1.1359    raeburn   178:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  179: 	print $fh "$now:$message:$local\n";
                    180: 	close($fh);
                    181:     }
1.1       albertel  182:     return 1;
                    183: }
                    184: 
1.850     albertel  185: sub create_connection {
1.853     albertel  186:     my ($hostname,$lonid) = @_;
1.851     albertel  187:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  188: 				     Type    => SOCK_STREAM,
                    189: 				     Timeout => 10);
                    190:     return 0 if (!$client);
1.1399    raeburn   191:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
1.850     albertel  192:     my $result = <$client>;
                    193:     chomp($result);
                    194:     return 1 if ($result eq 'done');
                    195:     return 0;
                    196: }
                    197: 
1.983     raeburn   198: sub get_server_timezone {
                    199:     my ($cnum,$cdom) = @_;
                    200:     my $home=&homeserver($cnum,$cdom);
                    201:     if ($home ne 'no_host') {
                    202:         my $cachetime = 24*3600;
                    203:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    204:         if (defined($cached)) {
                    205:             return $timezone;
                    206:         } else {
                    207:             my $timezone = &reply('servertimezone',$home);
                    208:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    209:         }
                    210:     }
                    211: }
1.850     albertel  212: 
1.1106    raeburn   213: sub get_server_distarch {
                    214:     my ($lonhost,$ignore_cache) = @_;
                    215:     if (defined($lonhost)) {
                    216:         if (!defined(&hostname($lonhost))) {
                    217:             return;
                    218:         }
                    219:         my $cachetime = 12*3600;
                    220:         if (!$ignore_cache) {
                    221:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    222:             if (defined($cached)) {
                    223:                 return $distarch;
                    224:             }
                    225:         }
                    226:         my $rep = &reply('serverdistarch',$lonhost);
                    227:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    228:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    229:                 $rep eq '') {
                    230:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    231:         }
                    232:     }
                    233:     return;
                    234: }
                    235: 
1.1315    raeburn   236: sub get_servercerts_info {
1.1383    raeburn   237:     my ($lonhost,$hostname,$context) = @_;
                    238:     return if ($lonhost eq '');
                    239:     if ($hostname eq '') {
                    240:         $hostname = &hostname($lonhost);
                    241:     }
                    242:     return if ($hostname eq '');
1.1315    raeburn   243:     my ($rep,$uselocal);
1.1388    raeburn   244:     if ($context eq 'install') {
1.1387    raeburn   245:         $uselocal = 1;
                    246:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
1.1315    raeburn   247:         $uselocal = 1;
                    248:     }
1.1387    raeburn   249:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315    raeburn   250:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   251:         if ($distro eq '') {
                    252:             $uselocal = 0;
                    253:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   254:             if ($1 < 6) {
                    255:                 $uselocal = 0;
                    256:             }
1.1346    raeburn   257:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    258:             if ($1 < 12) {
                    259:                 $uselocal = 0;
                    260:             }
1.1315    raeburn   261:         }
                    262:     }
                    263:     if ($uselocal) {
1.1383    raeburn   264:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315    raeburn   265:     } else {
                    266:         $rep=&reply('servercerts',$lonhost);
                    267:     }
                    268:     my ($result,%returnhash);
                    269:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    270:         ($rep eq 'unknown_cmd')) {
                    271:         $result = $rep;
                    272:     } else {
                    273:         $result = 'ok';
                    274:         my @pairs=split(/\&/,$rep);
                    275:         foreach my $item (@pairs) {
                    276:             my ($key,$value)=split(/=/,$item,2);
                    277:             my $what = &unescape($key);
                    278:             $returnhash{$what}=&thaw_unescape($value);
                    279:         }
                    280:     }
                    281:     return ($result,\%returnhash);
                    282: }
                    283: 
1.993     raeburn   284: sub get_server_loncaparev {
1.1073    raeburn   285:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   286:     if (defined($lonhost)) {
                    287:         if (!defined(&hostname($lonhost))) {
                    288:             undef($lonhost);
                    289:         }
                    290:     }
                    291:     if (!defined($lonhost)) {
                    292:         if (defined(&domain($dom,'primary'))) {
                    293:             $lonhost=&domain($dom,'primary');
                    294:             if ($lonhost eq 'no_host') {
                    295:                 undef($lonhost);
                    296:             }
                    297:         }
                    298:     }
                    299:     if (defined($lonhost)) {
1.1073    raeburn   300:         my $cachetime = 12*3600;
                    301:         if (!$ignore_cache) {
                    302:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    303:             if (defined($cached)) {
                    304:                 return $loncaparev;
                    305:             }
                    306:         }
                    307:         my ($answer,$loncaparev);
                    308:         my @ids=&current_machine_ids();
                    309:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    310:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   311:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   312:                 $loncaparev = $1;
                    313:             }
                    314:         } else {
                    315:             $answer = &reply('serverloncaparev',$lonhost);
                    316:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    317:                 if ($caller eq 'loncron') {
1.1397    raeburn   318:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   319:                     my $protocol = $protocol{$lonhost};
                    320:                     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn   321:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   322:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   323:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   324:                     unless ($response->is_error()) {
                    325:                         my $content = $response->content;
1.1081    raeburn   326:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   327:                             $loncaparev = $1;
                    328:                         }
                    329:                     }
                    330:                 } else {
                    331:                     $loncaparev = $loncaparevs{$lonhost};
                    332:                 }
1.1081    raeburn   333:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   334:                 $loncaparev = $1;
                    335:             }
1.993     raeburn   336:         }
1.1073    raeburn   337:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   338:     }
                    339: }
                    340: 
1.1074    raeburn   341: sub get_server_homeID {
                    342:     my ($hostname,$ignore_cache,$caller) = @_;
                    343:     unless ($ignore_cache) {
                    344:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    345:         if (defined($cached)) {
                    346:             return $serverhomeID;
                    347:         }
                    348:     }
                    349:     my $cachetime = 12*3600;
                    350:     my $serverhomeID;
                    351:     if ($caller eq 'loncron') { 
                    352:         my @machine_ids = &machine_ids($hostname);
                    353:         foreach my $id (@machine_ids) {
                    354:             my $response = &reply('serverhomeID',$id);
                    355:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    356:                 $serverhomeID = $response;
                    357:                 last;
                    358:             }
                    359:         }
                    360:         if ($serverhomeID eq '') {
                    361:             $serverhomeID = $machine_ids[-1];
                    362:         }
                    363:     } else {
                    364:         $serverhomeID = $serverhomeIDs{$hostname};
                    365:     }
                    366:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    367: }
                    368: 
1.1121    raeburn   369: sub get_remote_globals {
                    370:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   371:     my ($result,%returnhash,%whatneeded);
                    372:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   373:         foreach my $what (sort(keys(%{$whathash}))) {
                    374:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   375:             my ($response,$cached);
1.1121    raeburn   376:             unless ($ignore_cache) {
1.1125    raeburn   377:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   378:             }
                    379:             if (defined($cached)) {
1.1125    raeburn   380:                 $returnhash{$what} = $response;
1.1121    raeburn   381:             } else {
1.1125    raeburn   382:                 $whatneeded{$what} = 1;
1.1121    raeburn   383:             }
                    384:         }
1.1125    raeburn   385:         if (keys(%whatneeded) == 0) {
                    386:             $result = 'ok';
                    387:         } else {
1.1121    raeburn   388:             my $requested = &freeze_escape(\%whatneeded);
                    389:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   390:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    391:                 ($rep eq 'unknown_cmd')) {
                    392:                 $result = $rep;
                    393:             } else {
                    394:                 $result = 'ok';
1.1121    raeburn   395:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   396:                 foreach my $item (@pairs) {
                    397:                     my ($key,$value)=split(/=/,$item,2);
                    398:                     my $what = &unescape($key);
                    399:                     my $hashid = $lonhost.'-'.$what;
                    400:                     $returnhash{$what}=&thaw_unescape($value);
                    401:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   402:                 }
                    403:             }
                    404:         }
                    405:     }
1.1125    raeburn   406:     return ($result,\%returnhash);
1.1121    raeburn   407: }
                    408: 
1.1124    raeburn   409: sub remote_devalidate_cache {
1.1241    raeburn   410:     my ($lonhost,$cachekeys) = @_;
                    411:     my $items;
                    412:     return unless (ref($cachekeys) eq 'ARRAY');
                    413:     my $cachestr = join('&',@{$cachekeys});
                    414:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   415:     return $response;
                    416: }
                    417: 
1.1       albertel  418: # -------------------------------------------------- Non-critical communication
                    419: sub subreply {
                    420:     my ($cmd,$server)=@_;
1.838     albertel  421:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      422:     #
                    423:     #  With loncnew process trimming, there's a timing hole between lonc server
                    424:     #  process exit and the master server picking up the listen on the AF_UNIX
                    425:     #  socket.  In that time interval, a lock file will exist:
                    426: 
                    427:     my $lockfile=$peerfile.".lock";
                    428:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   429: 	sleep(0.1);
1.549     foxr      430:     }
                    431:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      432:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      433:     #
1.550     foxr      434:     #   We'll give the connection a few tries before abandoning it.  If
                    435:     #   connection is not possible, we'll con_lost back to the client.
                    436:     #   
                    437:     my $client;
                    438:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    439: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    440: 				      Type    => SOCK_STREAM,
                    441: 				      Timeout => 10);
1.869     albertel  442: 	if ($client) {
1.550     foxr      443: 	    last;		# Connected!
1.850     albertel  444: 	} else {
1.853     albertel  445: 	    &create_connection(&hostname($server),$server);
1.550     foxr      446: 	}
1.1289    damieng   447:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      448:     }
                    449:     my $answer;
                    450:     if ($client) {
1.704     albertel  451: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      452: 	$answer=<$client>;
                    453: 	if (!$answer) { $answer="con_lost"; }
                    454: 	chomp($answer);
                    455:     } else {
                    456: 	$answer = 'con_lost';	# Failed connection.
                    457:     }
1.1       albertel  458:     return $answer;
                    459: }
                    460: 
                    461: sub reply {
                    462:     my ($cmd,$server)=@_;
1.838     albertel  463:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  464:     my $answer=subreply($cmd,$server);
1.65      www       465:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396    raeburn   466:         my $logged = $cmd;
                    467:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    468:             my $subcmd = $1;
                    469:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    470:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462    raeburn   471:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
                    472:                 ($subcmd eq 'put')) {
1.1396    raeburn   473:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    474:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    475:                     splice(@rest,2,1,'Hidden');
                    476:                 } elsif ($subcmd eq 'passwd') {
                    477:                     splice(@rest,2,2,('Hidden','Hidden'));
                    478:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462    raeburn   479:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1396    raeburn   480:                     splice(@rest,3,1,'Hidden');
                    481:                 }
                    482:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    483:             }
                    484:         }
                    485:         &logthis("<font color=\"blue\">WARNING:".
                    486:                  " $logged to $server returned $answer</font>");
1.12      www       487:     }
1.1       albertel  488:     return $answer;
                    489: }
                    490: 
                    491: # ----------------------------------------------------------- Send USR1 to lonc
                    492: 
                    493: sub reconlonc {
1.891     albertel  494:     my ($lonid) = @_;
                    495:     if ($lonid) {
1.1295    raeburn   496:         my $hostname = &hostname($lonid);
1.891     albertel  497: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    498: 	if ($hostname && -e $peerfile) {
                    499: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    500: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    501: 					     Type    => SOCK_STREAM,
                    502: 					     Timeout => 10);
                    503: 	    if ($client) {
                    504: 		print $client ("reset_retries\n");
                    505: 		my $answer=<$client>;
                    506: 		#reset just this one.
                    507: 	    }
                    508: 	}
                    509: 	return;
                    510:     }
                    511: 
1.836     www       512:     &logthis("Trying to reconnect lonc");
1.1       albertel  513:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   514:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  515: 	my $loncpid=<$fh>;
                    516:         chomp($loncpid);
                    517:         if (kill 0 => $loncpid) {
                    518: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    519:             kill USR1 => $loncpid;
                    520:             sleep 1;
1.1295    raeburn   521:         } else {
1.12      www       522: 	    &logthis(
1.672     albertel  523:                "<font color=\"blue\">WARNING:".
1.12      www       524:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  525:         }
                    526:     } else {
1.836     www       527: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  528:     }
                    529: }
                    530: 
                    531: # ------------------------------------------------------ Critical communication
1.12      www       532: 
1.1       albertel  533: sub critical {
                    534:     my ($cmd,$server)=@_;
1.838     albertel  535:     unless (&hostname($server)) {
1.672     albertel  536:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       537:                " Critical message to unknown server ($server)</font>");
                    538:         return 'no_such_host';
                    539:     }
1.1       albertel  540:     my $answer=reply($cmd,$server);
                    541:     if ($answer eq 'con_lost') {
1.1295    raeburn   542: 	&reconlonc($server);
1.589     albertel  543: 	my $answer=reply($cmd,$server);
1.1       albertel  544:         if ($answer eq 'con_lost') {
                    545:             my $now=time;
                    546:             my $middlename=$cmd;
1.5       www       547:             $middlename=substr($middlename,0,16);
1.1       albertel  548:             $middlename=~s/\W//g;
                    549:             my $dfilename=
1.305     www       550:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    551:             $dumpcount++;
1.1       albertel  552:             {
1.448     albertel  553: 		my $dfh;
1.1359    raeburn   554: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  555: 		    print $dfh "$cmd\n"; 
                    556: 		    close($dfh);
                    557: 		}
1.1       albertel  558:             }
1.1288    damieng   559:             sleep 1;
1.1       albertel  560:             my $wcmd='';
                    561:             {
1.448     albertel  562: 		my $dfh;
1.1359    raeburn   563: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  564: 		    $wcmd=<$dfh>; 
                    565: 		    close($dfh);
                    566: 		}
1.1       albertel  567:             }
                    568:             chomp($wcmd);
1.7       www       569:             if ($wcmd eq $cmd) {
1.672     albertel  570: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       571:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  572:                 &logperm("D:$server:$cmd");
                    573: 	        return 'con_delayed';
                    574:             } else {
1.672     albertel  575:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       576:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  577:                 &logperm("F:$server:$cmd");
                    578:                 return 'con_failed';
                    579:             }
                    580:         }
                    581:     }
                    582:     return $answer;
1.405     albertel  583: }
                    584: 
1.755     albertel  585: # ------------------------------------------- check if return value is an error
                    586: 
                    587: sub error {
                    588:     my ($result) = @_;
1.756     albertel  589:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  590: 	if ($2 == 2) { return undef; }
                    591: 	return $1;
                    592:     }
                    593:     return undef;
                    594: }
                    595: 
1.783     albertel  596: sub convert_and_load_session_env {
                    597:     my ($lonidsdir,$handle)=@_;
                    598:     my @profile;
                    599:     {
1.917     albertel  600: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    601: 	if (!$opened) {
1.915     albertel  602: 	    return 0;
                    603: 	}
1.783     albertel  604: 	flock($idf,LOCK_SH);
                    605: 	@profile=<$idf>;
                    606: 	close($idf);
                    607:     }
                    608:     my %temp_env;
                    609:     foreach my $line (@profile) {
1.786     albertel  610: 	if ($line !~ m/=/) {
                    611: 	    return 0;
                    612: 	}
1.783     albertel  613: 	chomp($line);
                    614: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    615: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    616:     }
                    617:     unlink("$lonidsdir/$handle.id");
                    618:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    619: 	    0640)) {
                    620: 	%disk_env = %temp_env;
                    621: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    622: 	untie(%disk_env);
                    623:     }
1.786     albertel  624:     return 1;
1.783     albertel  625: }
                    626: 
1.374     www       627: # ------------------------------------------- Transfer profile into environment
1.780     albertel  628: my $env_loaded;
                    629: sub transfer_profile_to_env {
1.788     albertel  630:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    631:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       632: 
1.720     albertel  633:     if (!defined($lonidsdir)) {
                    634: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    635:     }
                    636:     if (!defined($handle)) {
                    637:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    638:     }
                    639: 
1.786     albertel  640:     my $convert;
                    641:     {
1.917     albertel  642:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    643: 	if (!$opened) {
1.915     albertel  644: 	    return;
                    645: 	}
1.786     albertel  646: 	flock($idf,LOCK_SH);
                    647: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    648: 		&GDBM_READER(),0640)) {
                    649: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    650: 	    untie(%disk_env);
                    651: 	} else {
                    652: 	    $convert = 1;
                    653: 	}
                    654:     }
                    655:     if ($convert) {
                    656: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    657: 	    &logthis("Failed to load session, or convert session.");
                    658: 	}
1.374     www       659:     }
1.783     albertel  660: 
1.786     albertel  661:     my %remove;
1.783     albertel  662:     while ( my $envname = each(%env) ) {
1.433     matthew   663:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    664:             if ($time < time-300) {
1.783     albertel  665:                 $remove{$key}++;
1.433     matthew   666:             }
                    667:         }
                    668:     }
1.783     albertel  669: 
1.619     albertel  670:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  671:     $env_loaded=1;
1.783     albertel  672:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   673:         &delenv($expired_key);
1.374     www       674:     }
1.1       albertel  675: }
                    676: 
1.916     albertel  677: # ---------------------------------------------------- Check for valid session 
                    678: sub check_for_valid_session {
1.1355    raeburn   679:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  680:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   681:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    682:     if ($name eq 'lonDAV') {
                    683:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    684:     } else {
                    685:         $lonidsdir=$r->dir_config('lonIDsDir');
                    686:         if ($name eq '') {
                    687:             $name = 'lonID';
                    688:         }
                    689:     }
                    690:     if ($name eq 'lonID') {
                    691:         $secure = 'lonSID';
1.1337    raeburn   692:         $linkname = 'lonLinkID';
                    693:         $pubname = 'lonPubID';
1.1378    raeburn   694:         if (exists($cookies{$secure})) {
                    695:             $lonid=$cookies{$secure};
                    696:         } elsif (exists($cookies{$name})) {
                    697:             $lonid=$cookies{$name};
1.1400    raeburn   698:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337    raeburn   699:             $lonid=$cookies{$linkname};
1.1378    raeburn   700:         } elsif (exists($cookies{$pubname})) {
                    701:             $lonid=$cookies{$pubname};
1.1337    raeburn   702:         }
1.1378    raeburn   703:     } else {
                    704:         $lonid=$cookies{$name};
1.1337    raeburn   705:     }
1.916     albertel  706:     return undef if (!$lonid);
                    707: 
                    708:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   709:     if (-l "$lonidsdir/$handle.id") {
                    710:         my $link = readlink("$lonidsdir/$handle.id");
                    711:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    712:             $handle = $1;
                    713:         }
1.1155    raeburn   714:     }
1.1355    raeburn   715:     if (!-e "$lonidsdir/$handle.id") {
                    716:         if ((ref($domref)) && ($name eq 'lonID') && 
                    717:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    718:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    719:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    720:                 $$domref = $possudom;
                    721:             }
                    722:         }
                    723:         return undef;
                    724:     }
1.916     albertel  725: 
1.917     albertel  726:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    727:     return undef if (!$opened);
1.916     albertel  728: 
                    729:     flock($idf,LOCK_SH);
                    730:     my %disk_env;
                    731:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    732: 	    &GDBM_READER(),0640)) {
                    733: 	return undef;	
                    734:     }
                    735: 
                    736:     if (!defined($disk_env{'user.name'})
                    737: 	|| !defined($disk_env{'user.domain'})) {
1.1394    raeburn   738:         untie(%disk_env);
1.916     albertel  739: 	return undef;
                    740:     }
1.1245    raeburn   741: 
                    742:     if (ref($userhashref) eq 'HASH') {
                    743:         $userhashref->{'name'} = $disk_env{'user.name'};
                    744:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1448    raeburn   745:         if ($disk_env{'request.role'}) {
                    746:             $userhashref->{'role'} = $disk_env{'request.role'};
                    747:         }
1.1361    raeburn   748:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   749:         if ($userhashref->{'lti'}) {
                    750:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    751:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    752:         }
1.1212    raeburn   753:     }
1.1394    raeburn   754:     untie(%disk_env);
1.1245    raeburn   755: 
1.916     albertel  756:     return $handle;
                    757: }
                    758: 
1.830     albertel  759: sub timed_flock {
                    760:     my ($file,$lock_type) = @_;
                    761:     my $failed=0;
                    762:     eval {
                    763: 	local $SIG{__DIE__}='DEFAULT';
                    764: 	local $SIG{ALRM}=sub {
                    765: 	    $failed=1;
                    766: 	    die("failed lock");
                    767: 	};
                    768: 	alarm(13);
                    769: 	flock($file,$lock_type);
                    770: 	alarm(0);
                    771:     };
                    772:     if ($failed) {
                    773: 	return undef;
                    774:     } else {
                    775: 	return 1;
                    776:     }
                    777: }
                    778: 
1.1392    raeburn   779: sub get_sessionfile_vars {
                    780:     my ($handle,$lonidsdir,$storearr) = @_;
                    781:     my %returnhash;
                    782:     unless (ref($storearr) eq 'ARRAY') {
                    783:         return %returnhash;
                    784:     }
                    785:     if (-l "$lonidsdir/$handle.id") {
                    786:         my $link = readlink("$lonidsdir/$handle.id");
                    787:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    788:             $handle = $1;
                    789:         }
                    790:     }
                    791:     if ((-e "$lonidsdir/$handle.id") &&
                    792:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    793:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    794:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    795:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    796:                 flock($idf,LOCK_SH);
                    797:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    798:                         &GDBM_READER(),0640)) {
                    799:                     foreach my $item (@{$storearr}) {
                    800:                         $returnhash{$item} = $disk_env{$item};
                    801:                     }
                    802:                     untie(%disk_env);
                    803:                 }
                    804:             }
                    805:         }
                    806:     }
                    807:     return %returnhash;
                    808: }
                    809: 
1.5       www       810: # ---------------------------------------------------------- Append Environment
                    811: 
                    812: sub appenv {
1.949     raeburn   813:     my ($newenv,$roles) = @_;
                    814:     if (ref($newenv) eq 'HASH') {
                    815:         foreach my $key (keys(%{$newenv})) {
                    816:             my $refused = 0;
                    817: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    818:                 $refused = 1;
                    819:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   820:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   821:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    822:                         $refused = 0;
                    823:                     }
                    824:                 }
                    825:             }
                    826:             if ($refused) {
                    827:                 &logthis("<font color=\"blue\">WARNING: ".
                    828:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    829:                          .'</font>');
                    830: 	        delete($newenv->{$key});
                    831:             } else {
                    832:                 $env{$key}=$newenv->{$key};
                    833:             }
                    834:         }
1.1376    raeburn   835:         my $lonids = $perlvar{'lonIDsDir'};
                    836:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    837:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    838:             if ($opened
                    839: 	        && &timed_flock($env_file,LOCK_EX)
                    840: 	        &&
                    841: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    842: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    843: 	        while (my ($key,$value) = each(%{$newenv})) {
                    844: 	            $disk_env{$key} = $value;
                    845: 	        }
                    846: 	        untie(%disk_env);
                    847:             }
1.35      www       848:         }
1.191     harris41  849:     }
1.56      www       850:     return 'ok';
                    851: }
                    852: # ----------------------------------------------------- Delete from Environment
                    853: 
                    854: sub delenv {
1.1104    raeburn   855:     my ($delthis,$regexp,$roles) = @_;
                    856:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    857:         my $refused = 1;
                    858:         if (ref($roles) eq 'ARRAY') {
                    859:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    860:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    861:                 $refused = 0;
                    862:             }
                    863:         }
                    864:         if ($refused) {
                    865:             &logthis("<font color=\"blue\">WARNING: ".
                    866:                      "Attempt to delete from environment ".$delthis);
                    867:             return 'error';
                    868:         }
1.56      www       869:     }
1.917     albertel  870:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    871:     if ($opened
1.915     albertel  872: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  873: 	&&
                    874: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    875: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  876: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   877: 	    if ($regexp) {
                    878:                 if ($key=~/^$delthis/) {
                    879:                     delete($env{$key});
                    880:                     delete($disk_env{$key});
                    881:                 } 
                    882:             } else {
                    883:                 if ($key=~/^\Q$delthis\E/) {
                    884: 		    delete($env{$key});
                    885: 		    delete($disk_env{$key});
                    886: 	        }
                    887:             }
1.448     albertel  888: 	}
1.783     albertel  889: 	untie(%disk_env);
1.5       www       890:     }
                    891:     return 'ok';
1.369     albertel  892: }
                    893: 
1.790     albertel  894: sub get_env_multiple {
                    895:     my ($name) = @_;
                    896:     my @values;
                    897:     if (defined($env{$name})) {
                    898:         # exists is it an array
                    899:         if (ref($env{$name})) {
                    900:             @values=@{ $env{$name} };
                    901:         } else {
                    902:             $values[0]=$env{$name};
                    903:         }
                    904:     }
                    905:     return(@values);
                    906: }
                    907: 
1.958     www       908: # ------------------------------------------------------------------- Locking
                    909: 
                    910: sub set_lock {
                    911:     my ($text)=@_;
                    912:     $locknum++;
                    913:     my $id=$$.'-'.$locknum;
                    914:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    915:              'session.lock.'.$id => $text});
                    916:     return $id;
                    917: }
                    918: 
                    919: sub get_locks {
                    920:     my $num=0;
                    921:     my %texts=();
                    922:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    923:        if ($lock=~/\w/) {
                    924:           $num++;
                    925:           $texts{$lock}=$env{'session.lock.'.$lock};
                    926:        }
                    927:    }
                    928:    return ($num,%texts);
                    929: }
                    930: 
                    931: sub remove_lock {
                    932:     my ($id)=@_;
                    933:     my $newlocks='';
                    934:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    935:        if (($lock=~/\w/) && ($lock ne $id)) {
                    936:           $newlocks.=','.$lock;
                    937:        }
                    938:     }
                    939:     &appenv({'session.locks' => $newlocks});
                    940:     &delenv('session.lock.'.$id);
                    941: }
                    942: 
                    943: sub remove_all_locks {
                    944:     my $activelocks=$env{'session.locks'};
                    945:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    946:        if ($lock=~/\w/) {
                    947:           &remove_lock($lock);
                    948:        }
                    949:     }
                    950: }
                    951: 
                    952: 
1.369     albertel  953: # ------------------------------------------ Find out current server userload
                    954: sub userload {
                    955:     my $numusers=0;
                    956:     {
                    957: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    958: 	my $filename;
                    959: 	my $curtime=time;
                    960: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  961: 	    next if ($filename eq '.' || $filename eq '..');
                    962: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn   963:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  964: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  965: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  966: 	}
                    967: 	closedir(LONIDS);
                    968:     }
                    969:     my $userloadpercent=0;
                    970:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    971:     if ($maxuserload) {
1.371     albertel  972: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  973:     }
1.372     albertel  974:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  975:     return $userloadpercent;
1.283     www       976: }
                    977: 
1.1       albertel  978: # ------------------------------ Find server with least workload from spare.tab
1.11      www       979: 
1.1       albertel  980: sub spareserver {
1.1451    raeburn   981:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  982:     my $spare_server;
1.370     albertel  983:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  984:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    985:                                                      :  $userloadpercent;
1.1083    raeburn   986:     my ($uint_dom,$remotesessions);
                    987:     if (($udom ne '') && (&domain($udom) ne '')) {
                    988:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    989:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    990:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    991:         $remotesessions = $udomdefaults{'remotesessions'};
                    992:     }
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'} }) {
1.1279    raeburn   997:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    998:                                              $try_server));
1.1123    raeburn   999: 	        ($spare_server, $lowest_load) =
                   1000: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                   1001:             }
1.1083    raeburn  1002:         }
1.784     albertel 1003: 
1.1123    raeburn  1004:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                   1005: 
                   1006:         if (!$found_server) {
                   1007:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1008: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn  1009:                     next unless (&spare_can_host($udom,$uint_dom,
                   1010:                                                  $remotesessions,$try_server));
1.1123    raeburn  1011: 	            ($spare_server, $lowest_load) =
                   1012: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1013:                 }
                   1014: 	    }
                   1015:         }
1.784     albertel 1016:     }
                   1017: 
                   1018:     if (!$want_server_name) {
1.1001    raeburn  1019:         if (defined($spare_server)) {
                   1020:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1021:             if (defined($hostname)) {
1.1397    raeburn  1022:                 my $protocol = 'http';
                   1023:                 if ($protocol{$spare_server} eq 'https') {
                   1024:                     $protocol = $protocol{$spare_server};
                   1025:                 }
1.1451    raeburn  1026:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
                   1027:                 $hostname = $alias if ($alias ne '');
1.1001    raeburn  1028: 	        $spare_server = $protocol.'://'.$hostname;
                   1029:             }
                   1030:         }
1.784     albertel 1031:     }
                   1032:     return $spare_server;
                   1033: }
                   1034: 
                   1035: sub compare_server_load {
1.1253    raeburn  1036:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1037: 
                   1038:     if ($required) {
                   1039:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1040:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1041:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1042:         if (($major eq '' && $minor eq '') ||
                   1043:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1044:             return ($spare_server,$lowest_load);
                   1045:         }
                   1046:     }
1.784     albertel 1047: 
                   1048:     my $loadans     = &reply('load',    $try_server);
                   1049:     my $userloadans = &reply('userload',$try_server);
                   1050: 
                   1051:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1052: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1053:     }
                   1054: 
                   1055:     my $load;
                   1056:     if ($loadans =~ /\d/) {
                   1057: 	if ($userloadans =~ /\d/) {
                   1058: 	    #both are numbers, pick the bigger one
                   1059: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1060: 		                              : $userloadans;
1.411     albertel 1061: 	} else {
1.784     albertel 1062: 	    $load = $loadans;
1.411     albertel 1063: 	}
1.784     albertel 1064:     } else {
                   1065: 	$load = $userloadans;
                   1066:     }
                   1067: 
                   1068:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1069: 	$spare_server = $try_server;
                   1070: 	$lowest_load  = $load;
1.370     albertel 1071:     }
1.784     albertel 1072:     return ($spare_server,$lowest_load);
1.202     matthew  1073: }
1.914     albertel 1074: 
                   1075: # --------------------------- ask offload servers if user already has a session
                   1076: sub find_existing_session {
                   1077:     my ($udom,$uname) = @_;
1.1123    raeburn  1078:     my $spareshash = &this_host_spares($udom);
                   1079:     if (ref($spareshash) eq 'HASH') {
                   1080:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1081:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1082:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1083:             }
                   1084:         }
                   1085:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1086:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1087:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1088:             }
                   1089:         }
1.914     albertel 1090:     }
                   1091:     return;
                   1092: }
                   1093: 
1.1411    raeburn  1094: sub delusersession {
                   1095:     my ($lonid,$udom,$uname) = @_;
                   1096:     my $uprimary_id = &domain($udom,'primary');
                   1097:     my $uintdom = &internet_dom($uprimary_id);
                   1098:     my $intdom = &internet_dom($lonid);
                   1099:     my $serverhomedom = &host_domain($lonid);
                   1100:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1101:         return &reply(join(':','delusersession',
                   1102:                             map {&escape($_)} ($udom,$uname)),$lonid);
                   1103:     }
                   1104:     return;
                   1105: }
                   1106: 
1.1389    raeburn  1107: # check if user's browser sent load balancer cookie and server still has session
                   1108: # and is not overloaded.
                   1109: sub check_for_balancer_cookie {
                   1110:     my ($r,$update_mtime) = @_;
                   1111:     my ($otherserver,$cookie);
                   1112:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1113:     if (exists($cookies{'balanceID'})) {
                   1114:         my $balid = $cookies{'balanceID'};
                   1115:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1116:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1117:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1118:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1119:                 my ($possudom,$possuname) = ($1,$2);
                   1120:                 my $has_session = 0;
                   1121:                 if ((&domain($possudom) ne '') &&
                   1122:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1123:                     my $try_server;
                   1124:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1125:                     if ($opened) {
                   1126:                         flock($idf,LOCK_SH);
                   1127:                         while (my $line = <$idf>) {
                   1128:                             chomp($line);
                   1129:                             if (&hostname($line) ne '') {
                   1130:                                 $try_server = $line;
                   1131:                                 last;
                   1132:                             }
                   1133:                         }
                   1134:                         close($idf);
                   1135:                         if (($try_server) &&
                   1136:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1137:                             my $lowest_load = 30000;
                   1138:                             ($otherserver,$lowest_load) =
                   1139:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1140:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1141:                                 $has_session = 1;
                   1142:                             } else {
                   1143:                                 undef($otherserver);
                   1144:                             }
                   1145:                         }
                   1146:                     }
                   1147:                 }
                   1148:                 if ($has_session) {
                   1149:                     if ($update_mtime) {
                   1150:                         my $atime = my $mtime = time;
                   1151:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1152:                     }
                   1153:                 } else {
                   1154:                     unlink("$balancedir/$cookie.id");
                   1155:                 }
                   1156:             }
                   1157:         }
                   1158:     }
                   1159:     return ($otherserver,$cookie);
                   1160: }
                   1161: 
1.1431    raeburn  1162: sub updatebalcookie {
                   1163:     my ($cookie,$balancer,$lastentry)=@_;
                   1164:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1165:         my ($udom,$uname) = ($1,$2);
                   1166:         my $uprimary_id = &domain($udom,'primary');
                   1167:         my $uintdom = &internet_dom($uprimary_id);
                   1168:         my $intdom = &internet_dom($balancer);
                   1169:         my $serverhomedom = &host_domain($balancer);
                   1170:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1171:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1172:         }
                   1173:     }
                   1174:     return;
                   1175: }
                   1176: 
1.1389    raeburn  1177: sub delbalcookie {
                   1178:     my ($cookie,$balancer) =@_;
                   1179:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1180:         my ($udom,$uname) = ($1,$2);
                   1181:         my $uprimary_id = &domain($udom,'primary');
                   1182:         my $uintdom = &internet_dom($uprimary_id);
                   1183:         my $intdom = &internet_dom($balancer);
                   1184:         my $serverhomedom = &host_domain($balancer);
                   1185:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431    raeburn  1186:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389    raeburn  1187:         }
                   1188:     }
                   1189: }
                   1190: 
1.914     albertel 1191: # -------------------------------- ask if server already has a session for user
                   1192: sub has_user_session {
                   1193:     my ($lonid,$udom,$uname) = @_;
                   1194:     my $result = &reply(join(':','userhassession',
                   1195: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1196:     return 1 if ($result eq 'ok');
                   1197: 
                   1198:     return 0;
                   1199: }
                   1200: 
1.1076    raeburn  1201: # --------- determine least loaded server in a user's domain which allows login
                   1202: 
                   1203: sub choose_server {
1.1259    raeburn  1204:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1205:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1206:     my %servers = &get_servers($udom);
1.1076    raeburn  1207:     my $lowest_load = 30000;
1.1259    raeburn  1208:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1209:     if ($skiploadbal) {
                   1210:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1211:         unless (defined($cached)) {
                   1212:             my $cachetime = 60*60*24;
                   1213:             my %domconfig =
                   1214:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1215:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1216:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1217:                                            $cachetime);
                   1218:             }
                   1219:         }
                   1220:     }
1.1076    raeburn  1221:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1222:         if ($skiploadbal) {
                   1223:             if (ref($balancers) eq 'HASH') {
                   1224:                 next if (exists($balancers->{$lonhost}));
                   1225:             }
1.1389    raeburn  1226:         }
1.1115    raeburn  1227:         my $loginvia;
                   1228:         if ($checkloginvia) {
                   1229:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1230:             if ($loginvia) {
                   1231:                 my ($server,$path) = split(/:/,$loginvia);
                   1232:                 ($login_host, $lowest_load) =
1.1253    raeburn  1233:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1234:                 if ($login_host eq $server) {
                   1235:                     $portal_path = $path;
1.1151    raeburn  1236:                     $isredirect = 1;
1.1116    raeburn  1237:                 }
                   1238:             } else {
                   1239:                 ($login_host, $lowest_load) =
1.1253    raeburn  1240:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1241:                 if ($login_host eq $lonhost) {
                   1242:                     $portal_path = '';
1.1151    raeburn  1243:                     $isredirect = ''; 
1.1116    raeburn  1244:                 }
                   1245:             }
                   1246:         } else {
1.1076    raeburn  1247:             ($login_host, $lowest_load) =
1.1253    raeburn  1248:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1249:         }
                   1250:     }
                   1251:     if ($login_host ne '') {
1.1116    raeburn  1252:         $hostname = &hostname($login_host);
1.1076    raeburn  1253:     }
1.1331    raeburn  1254:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1255: }
                   1256: 
1.1420    raeburn  1257: sub get_course_sessions {
                   1258:     my ($cnum,$cdom,$lastactivity) = @_;
                   1259:     my %servers = &internet_dom_servers($cdom);
                   1260:     my %returnhash;
                   1261:     foreach my $server (sort(keys(%servers))) {
                   1262:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1263:         my @pairs=split(/\&/,$rep);
                   1264:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1265:             foreach my $item (@pairs) {
                   1266:                 my ($key,$value)=split(/=/,$item,2);
                   1267:                 $key = &unescape($key);
                   1268:                 next if ($key =~ /^error: 2 /);
                   1269:                 if (exists($returnhash{$key})) {
                   1270:                     next if ($value < $returnhash{$key});
                   1271:                 }
                   1272:                 $returnhash{$key}=$value;
                   1273:             }
                   1274:         }
                   1275:     }
                   1276:     return %returnhash;
                   1277: }
                   1278: 
1.202     matthew  1279: # --------------------------------------------- Try to change a user's password
                   1280: 
                   1281: sub changepass {
1.799     raeburn  1282:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1283:     $currentpass = &escape($currentpass);
                   1284:     $newpass     = &escape($newpass);
1.1030    raeburn  1285:     my $lonhost = $perlvar{'lonHostID'};
                   1286:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1287: 		       $server);
                   1288:     if (! $answer) {
                   1289: 	&logthis("No reply on password change request to $server ".
                   1290: 		 "by $uname in domain $udom.");
                   1291:     } elsif ($answer =~ "^ok") {
                   1292:         &logthis("$uname in $udom successfully changed their password ".
                   1293: 		 "on $server.");
                   1294:     } elsif ($answer =~ "^pwchange_failure") {
                   1295: 	&logthis("$uname in $udom was unable to change their password ".
                   1296: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1297: 		 "or pwchange");
                   1298:     } elsif ($answer =~ "^non_authorized") {
                   1299:         &logthis("$uname in $udom did not get their password correct when ".
                   1300: 		 "attempting to change it on $server.");
                   1301:     } elsif ($answer =~ "^auth_mode_error") {
                   1302:         &logthis("$uname in $udom attempted to change their password despite ".
                   1303: 		 "not being locally or internally authenticated on $server.");
                   1304:     } elsif ($answer =~ "^unknown_user") {
                   1305:         &logthis("$uname in $udom attempted to change their password ".
                   1306: 		 "on $server but were unable to because $server is not ".
                   1307: 		 "their home server.");
                   1308:     } elsif ($answer =~ "^refused") {
                   1309: 	&logthis("$server refused to change $uname in $udom password because ".
                   1310: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1311:     } elsif ($answer =~ "invalid_client") {
                   1312:         &logthis("$server refused to change $uname in $udom password because ".
                   1313:                  "it was a reset by e-mail originating from an invalid server.");
1.1408    raeburn  1314:     } elsif ($answer =~ "^prioruse") {
                   1315:        &logthis("$server refused to change $uname in $udom password because ".
                   1316:                 "the password had been used before");
1.202     matthew  1317:     }
                   1318:     return $answer;
1.1       albertel 1319: }
                   1320: 
1.169     harris41 1321: # ----------------------- Try to determine user's current authentication scheme
                   1322: 
                   1323: sub queryauthenticate {
                   1324:     my ($uname,$udom)=@_;
1.456     albertel 1325:     my $uhome=&homeserver($uname,$udom);
                   1326:     if (!$uhome) {
                   1327: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1328: 	return 'no_host';
                   1329:     }
                   1330:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1331:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1332: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1333:     }
1.456     albertel 1334:     return $answer;
1.169     harris41 1335: }
                   1336: 
1.1       albertel 1337: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1338: 
1.1       albertel 1339: sub authenticate {
1.1073    raeburn  1340:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1341:     $upass=&escape($upass);
                   1342:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1343:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1344:     my $newhome;
1.836     www      1345:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1346: # Maybe the machine was offline and only re-appeared again recently?
                   1347:         &reconlonc();
                   1348: # One more
1.952     raeburn  1349: 	$uhome=&homeserver($uname,$udom,1);
                   1350:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1351:             if (defined(&domain($udom,'primary'))) {
                   1352:                 $newhome=&domain($udom,'primary');
                   1353:             }
                   1354:             if ($newhome ne '') {
                   1355:                 $uhome = $newhome;
                   1356:             }
                   1357:         }
1.836     www      1358: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1359: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1360: 	    return 'no_host';
                   1361:         }
1.1       albertel 1362:     }
1.1073    raeburn  1363:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1364:     if ($answer eq 'authorized') {
1.952     raeburn  1365:         if ($newhome) {
                   1366:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1367:             return 'no_account_on_host'; 
                   1368:         } else {
                   1369:             &logthis("User $uname at $udom authorized by $uhome");
                   1370:             return $uhome;
                   1371:         }
1.471     albertel 1372:     }
                   1373:     if ($answer eq 'non_authorized') {
                   1374: 	&logthis("User $uname at $udom rejected by $uhome");
                   1375: 	return 'no_host'; 
1.9       www      1376:     }
1.471     albertel 1377:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1378:     return 'no_host';
                   1379: }
                   1380: 
1.1073    raeburn  1381: sub can_host_session {
1.1074    raeburn  1382:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1383:     my $canhost = 1;
1.1074    raeburn  1384:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1385:     if (ref($remotesessions) eq 'HASH') {
                   1386:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1387:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1388:                 $canhost = 0;
                   1389:             } else {
                   1390:                 $canhost = 1;
                   1391:             }
                   1392:         }
                   1393:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1394:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1395:                 $canhost = 1;
                   1396:             } else {
                   1397:                 $canhost = 0;
                   1398:             }
                   1399:         }
                   1400:         if ($canhost) {
                   1401:             if ($remotesessions->{'version'} ne '') {
                   1402:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1403:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1404:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1405:                         my $major = $1;
                   1406:                         my $minor = $2;
                   1407:                         if (($major < $reqmajor ) ||
                   1408:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1409:                             $canhost = 0;
                   1410:                         }
                   1411:                     } else {
                   1412:                         $canhost = 0;
                   1413:                     }
                   1414:                 }
                   1415:             }
                   1416:         }
                   1417:     }
                   1418:     if ($canhost) {
                   1419:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1420:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1421:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1422:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1423:                 if (($uint_dom ne '') && 
                   1424:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1425:                     $canhost = 0;
                   1426:                 } else {
                   1427:                     $canhost = 1;
                   1428:                 }
                   1429:             }
                   1430:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1431:                 if (($uint_dom ne '') && 
                   1432:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1433:                     $canhost = 1;
                   1434:                 } else {
                   1435:                     $canhost = 0;
                   1436:                 }
                   1437:             }
                   1438:         }
                   1439:     }
                   1440:     return $canhost;
                   1441: }
                   1442: 
1.1083    raeburn  1443: sub spare_can_host {
                   1444:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1445:     my $canhost=1;
1.1279    raeburn  1446:     my $try_server_hostname = &hostname($try_server);
                   1447:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1448:     my $serverhomedom = &host_domain($serverhomeID);
                   1449:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1450:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1451:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1452:             $canhost = 0;
                   1453:         }
                   1454:     }
1.1439    raeburn  1455:     if ($canhost) {
                   1456:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1457:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1458:                 unless (&shared_institution($udom,$try_server)) {
                   1459:                     $canhost = 0;
                   1460:                 }
                   1461:             }
                   1462:         }
                   1463:     }
1.1279    raeburn  1464:     if (($canhost) && ($uint_dom)) {
                   1465:         my @intdoms;
                   1466:         my $internet_names = &get_internet_names($try_server);
                   1467:         if (ref($internet_names) eq 'ARRAY') {
                   1468:             @intdoms = @{$internet_names};
                   1469:         }
                   1470:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1471:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1472:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1473:                                          $remotesessions,
                   1474:                                          $defdomdefaults{'hostedsessions'});
                   1475:         }
1.1083    raeburn  1476:     }
                   1477:     return $canhost;
                   1478: }
                   1479: 
1.1123    raeburn  1480: sub this_host_spares {
                   1481:     my ($dom) = @_;
1.1126    raeburn  1482:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1483:     my @hosts = &current_machine_ids();
                   1484:     foreach my $lonhost (@hosts) {
                   1485:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1486:             $dom_in_use = $dom;
                   1487:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1488:             last;
                   1489:         }
                   1490:     }
1.1126    raeburn  1491:     if ($dom_in_use ne '') {
                   1492:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1493:     }
                   1494:     if (ref($result) ne 'HASH') {
                   1495:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1496:         $dom_in_use = &host_domain($lonhost_in_use);
                   1497:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1498:         if (ref($result) ne 'HASH') {
                   1499:             $result = \%spareid;
                   1500:         }
                   1501:     }
                   1502:     return $result;
                   1503: }
                   1504: 
                   1505: sub spares_for_offload  {
                   1506:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1507:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1508:     if (defined($cached)) {
                   1509:         return $result;
                   1510:     } else {
1.1126    raeburn  1511:         my $cachetime = 60*60*24;
                   1512:         my %domconfig =
                   1513:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1514:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1515:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1516:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1517:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1518:                 }
                   1519:             }
                   1520:         }
                   1521:     }
1.1126    raeburn  1522:     return;
1.1123    raeburn  1523: }
                   1524: 
1.1129    raeburn  1525: sub get_lonbalancer_config {
                   1526:     my ($servers) = @_;
                   1527:     my ($currbalancer,$currtargets);
                   1528:     if (ref($servers) eq 'HASH') {
                   1529:         foreach my $server (keys(%{$servers})) {
                   1530:             my %what = (
                   1531:                          spareid => 1,
                   1532:                          perlvar => 1,
                   1533:                        );
                   1534:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1535:             if ($result eq 'ok') {
                   1536:                 if (ref($returnhash) eq 'HASH') {
                   1537:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1538:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1539:                             $currbalancer = $server;
                   1540:                             $currtargets = {};
                   1541:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1542:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1543:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1544:                                 }
                   1545:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1546:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1547:                                 }
                   1548:                             }
                   1549:                             last;
                   1550:                         }
                   1551:                     }
                   1552:                 }
                   1553:             }
                   1554:         }
                   1555:     }
                   1556:     return ($currbalancer,$currtargets);
                   1557: }
                   1558: 
                   1559: sub check_loadbalancing {
1.1331    raeburn  1560:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1561:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1562:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1563:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1564:     my @hosts = &current_machine_ids();
1.1129    raeburn  1565:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1566:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1567:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1568:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1569:     my $domneedscache;
1.1129    raeburn  1570:     my $cachetime = 60*60*24;
                   1571: 
                   1572:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1573:         $dom_in_use = $udom;
                   1574:         $homeintdom = 1;
                   1575:     } else {
                   1576:         $dom_in_use = $serverhomedom;
                   1577:     }
                   1578:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1579:     unless (defined($cached)) {
                   1580:         my %domconfig =
                   1581:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1582:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1583:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1584:         } else {
                   1585:             $domneedscache = $dom_in_use;
1.1129    raeburn  1586:         }
                   1587:     }
                   1588:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1589:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1590:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1591:         if ($is_balancer) {
                   1592:             if (ref($currrules) eq 'HASH') {
                   1593:                 if ($homeintdom) {
                   1594:                     if ($uname ne '') {
                   1595:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1596:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1597:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1598:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1599:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1600:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1601:                             }
                   1602:                         }
                   1603:                         if ($rule_in_effect eq '') {
                   1604:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1605:                             if ($userenv{'inststatus'} ne '') {
                   1606:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1607:                                 my ($othertitle,$usertypes,$types) =
                   1608:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1609:                                 if (ref($types) eq 'ARRAY') {
                   1610:                                     foreach my $type (@{$types}) {
                   1611:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1612:                                             if (exists($currrules->{$type})) {
                   1613:                                                 $rule_in_effect = $currrules->{$type};
                   1614:                                             }
                   1615:                                         }
                   1616:                                     }
                   1617:                                 }
                   1618:                             } else {
                   1619:                                 if (exists($currrules->{'default'})) {
                   1620:                                     $rule_in_effect = $currrules->{'default'};
                   1621:                                 }
                   1622:                             }
                   1623:                         }
                   1624:                     } else {
                   1625:                         if (exists($currrules->{'default'})) {
                   1626:                             $rule_in_effect = $currrules->{'default'};
                   1627:                         }
                   1628:                     }
                   1629:                 } else {
                   1630:                     if ($currrules->{'_LC_external'} ne '') {
                   1631:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1632:                     }
                   1633:                 }
                   1634:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1635:                                                        $uname,$udom);
                   1636:             }
                   1637:         }
                   1638:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1639:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1640:         unless (defined($cached)) {
                   1641:             my %domconfig =
                   1642:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1643:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1644:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1645:             } else {
                   1646:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1647:             }
                   1648:         }
                   1649:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1650:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1651:                 &check_balancer_result($result,@hosts);
                   1652:             if ($is_balancer) {
1.1129    raeburn  1653:                 if (ref($currrules) eq 'HASH') {
                   1654:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1655:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1656:                     }
                   1657:                 }
                   1658:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1659:                                                        $uname,$udom);
                   1660:             }
                   1661:         } else {
                   1662:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1663:                 $is_balancer = 1;
                   1664:                 $offloadto = &this_host_spares($dom_in_use);
                   1665:             }
1.1307    raeburn  1666:             unless (defined($cached)) {
                   1667:                 $domneedscache = $serverhomedom;
                   1668:             }
1.1129    raeburn  1669:         }
                   1670:     } else {
                   1671:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1672:             $is_balancer = 1;
                   1673:             $offloadto = &this_host_spares($dom_in_use);
                   1674:         }
1.1307    raeburn  1675:         unless (defined($cached)) {
                   1676:             $domneedscache = $serverhomedom;
                   1677:         }
                   1678:     }
                   1679:     if ($domneedscache) {
                   1680:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1681:     }
1.1430    raeburn  1682:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176    raeburn  1683:         my $lowest_load = 30000;
                   1684:         if (ref($offloadto) eq 'HASH') {
                   1685:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1686:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1687:                     ($otherserver,$lowest_load) =
                   1688:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1689:                 }
1.1129    raeburn  1690:             }
1.1176    raeburn  1691:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1692: 
1.1176    raeburn  1693:             if (!$found_server) {
                   1694:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1695:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1696:                         ($otherserver,$lowest_load) =
                   1697:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1698:                     }
                   1699:                 }
                   1700:             }
                   1701:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1702:             if (@{$offloadto} == 1) {
                   1703:                 $otherserver = $offloadto->[0];
                   1704:             } elsif (@{$offloadto} > 1) {
                   1705:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1706:                     ($otherserver,$lowest_load) =
                   1707:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1708:                 }
                   1709:             }
                   1710:         }
1.1331    raeburn  1711:         unless ($caller eq 'login') {
                   1712:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1713:                 $is_balancer = 0;
                   1714:                 if ($uname ne '' && $udom ne '') {
                   1715:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1716:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1717:                                  'user.loadbalcheck.time' => time});
                   1718:                     }
1.1176    raeburn  1719:                 }
1.1129    raeburn  1720:             }
                   1721:         }
1.1430    raeburn  1722:     }
                   1723:     if (($is_balancer) && (!$homeintdom)) {
                   1724:         undef($setcookie);
1.1129    raeburn  1725:     }
1.1391    raeburn  1726:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1727: }
                   1728: 
1.1191    raeburn  1729: sub check_balancer_result {
                   1730:     my ($result,@hosts) = @_;
1.1391    raeburn  1731:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1732:     if (ref($result) eq 'HASH') {
                   1733:         if ($result->{'lonhost'} ne '') {
                   1734:             my $currbalancer = $result->{'lonhost'};
                   1735:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1736:                 $is_balancer = 1;
                   1737:                 $currtargets = $result->{'targets'};
                   1738:                 $currrules = $result->{'rules'};
                   1739:             }
1.1391    raeburn  1740:             $dom_balancers = $currbalancer;
1.1191    raeburn  1741:         } else {
1.1391    raeburn  1742:             if (keys(%{$result})) {
                   1743:                 foreach my $key (keys(%{$result})) {
                   1744:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1745:                         (ref($result->{$key}) eq 'HASH')) {
                   1746:                         $is_balancer = 1;
                   1747:                         $currrules = $result->{$key}{'rules'};
                   1748:                         $currtargets = $result->{$key}{'targets'};
                   1749:                         $setcookie = $result->{$key}{'cookie'};
                   1750:                         last;
                   1751:                     }
1.1191    raeburn  1752:                 }
1.1391    raeburn  1753:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1754:             }
                   1755:         }
                   1756:     }
1.1391    raeburn  1757:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1758: }
                   1759: 
1.1129    raeburn  1760: sub get_loadbalancer_targets {
                   1761:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1762:     my $offloadto;
1.1175    raeburn  1763:     if ($rule_in_effect eq 'none') {
                   1764:         return [$perlvar{'lonHostID'}];
                   1765:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1766:         $offloadto = $currtargets;
                   1767:     } else {
                   1768:         if ($rule_in_effect eq 'homeserver') {
                   1769:             my $homeserver = &homeserver($uname,$udom);
                   1770:             if ($homeserver ne 'no_host') {
                   1771:                 $offloadto = [$homeserver];
                   1772:             }
                   1773:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1774:             my %domconfig =
                   1775:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1776:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1777:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1778:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1779:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1780:                     }
                   1781:                 }
                   1782:             } else {
1.1178    raeburn  1783:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1784:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1785:                 if (&hostname($remotebalancer) ne '') {
                   1786:                     $offloadto = [$remotebalancer];
                   1787:                 }
                   1788:             }
                   1789:         } elsif (&hostname($rule_in_effect) ne '') {
                   1790:             $offloadto = [$rule_in_effect];
                   1791:         }
                   1792:     }
                   1793:     return $offloadto;
                   1794: }
                   1795: 
1.1127    raeburn  1796: sub internet_dom_servers {
                   1797:     my ($dom) = @_;
                   1798:     my (%uniqservers,%servers);
                   1799:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1800:     my @machinedoms = &machine_domains($primaryserver);
                   1801:     foreach my $mdom (@machinedoms) {
                   1802:         my %currservers = %servers;
                   1803:         my %server = &get_servers($mdom);
                   1804:         %servers = (%currservers,%server);
                   1805:     }
                   1806:     my %by_hostname;
                   1807:     foreach my $id (keys(%servers)) {
                   1808:         push(@{$by_hostname{$servers{$id}}},$id);
                   1809:     }
                   1810:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1811:         if (@{$by_hostname{$hostname}} > 1) {
                   1812:             my $match = 0;
                   1813:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1814:                 if (&host_domain($id) eq $dom) {
                   1815:                     $uniqservers{$id} = $hostname;
                   1816:                     $match = 1;
                   1817:                 }
                   1818:             }
                   1819:             unless ($match) {
                   1820:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1821:             }
                   1822:         } else {
                   1823:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1824:         }
                   1825:     }
                   1826:     return %uniqservers;
                   1827: }
                   1828: 
1.1347    raeburn  1829: sub trusted_domains {
                   1830:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1831:     my ($trusted,$untrusted);
1.1347    raeburn  1832:     if (&domain($calldom) eq '') {
1.1349    raeburn  1833:         return ($trusted,$untrusted);
1.1347    raeburn  1834:     }
1.1395    raeburn  1835:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1836:         return ($trusted,$untrusted);
1.1347    raeburn  1837:     }
                   1838:     my $callprimary = &domain($calldom,'primary');
                   1839:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1840:     if ($intcalldom eq '') {
1.1349    raeburn  1841:         return ($trusted,$untrusted);
1.1347    raeburn  1842:     }
                   1843: 
                   1844:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1845:     unless (defined($cached)) {
                   1846:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1847:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1848:         $trustconfig = $domconfig{'trust'};
                   1849:     }
                   1850:     if (ref($trustconfig)) {
                   1851:         my (%possexc,%possinc,@allexc,@allinc); 
                   1852:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1853:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1854:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1855:             }
                   1856:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1857:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1858:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1859:             }
                   1860:         }
                   1861:         if (keys(%possexc)) {
                   1862:             if (keys(%possinc)) {
                   1863:                 foreach my $key (sort(keys(%possexc))) {
                   1864:                     next if ($key eq $intcalldom);
                   1865:                     unless ($possinc{$key}) {
                   1866:                         push(@allexc,$key);
                   1867:                     }
                   1868:                 }
                   1869:             } else {
                   1870:                 @allexc = sort(keys(%possexc));
                   1871:             }
                   1872:         }
                   1873:         if (keys(%possinc)) {
                   1874:             $possinc{$intcalldom} = 1;
                   1875:             @allinc = sort(keys(%possinc));
                   1876:         }
                   1877:         if ((@allexc > 0) || (@allinc > 0)) {
                   1878:             my %doms_by_intdom;
                   1879:             my %allintdoms = &all_host_intdom();
                   1880:             my %alldoms = &all_host_domain();
                   1881:             foreach my $key (%allintdoms) {
                   1882:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1883:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1884:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1885:                     }
                   1886:                 } else {
                   1887:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1888:                 }
                   1889:             }
                   1890:             foreach my $exc (@allexc) {
                   1891:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1892:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1893:                 }
                   1894:             }
                   1895:             foreach my $inc (@allinc) {
                   1896:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1897:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1898:                 }
                   1899:             }
                   1900:         }
                   1901:     }
1.1349    raeburn  1902:     return ($trusted,$untrusted);
1.1347    raeburn  1903: }
                   1904: 
                   1905: sub will_trust {
                   1906:     my ($cmdtype,$domain,$possdom) = @_;
                   1907:     return 1 if ($domain eq $possdom);
                   1908:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1909:     my $willtrust; 
                   1910:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1911:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1912:             $willtrust = 1;
                   1913:         }
                   1914:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1915:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1916:             $willtrust = 1;
                   1917:         }
                   1918:     } else {
                   1919:         $willtrust = 1;
                   1920:     }
                   1921:     return $willtrust;
                   1922: }
                   1923: 
1.1       albertel 1924: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1925: 
1.599     albertel 1926: my %homecache;
1.1       albertel 1927: sub homeserver {
1.230     stredwic 1928:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1929:     my $index="$uname:$udom";
1.426     albertel 1930: 
1.599     albertel 1931:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1932: 
                   1933:     my %servers = &get_servers($udom,'library');
                   1934:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1935:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1936: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1937: 
                   1938: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1939: 	if ($answer eq 'found') {
                   1940: 	    delete($badServerCache{$tryserver}); 
                   1941: 	    return $homecache{$index}=$tryserver;
                   1942: 	} elsif ($answer eq 'no_host') {
                   1943: 	    $badServerCache{$tryserver}=1;
                   1944: 	}
1.1       albertel 1945:     }    
                   1946:     return 'no_host';
1.70      www      1947: }
                   1948: 
1.1300    raeburn  1949: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1950: 
                   1951: sub idget {
1.1300    raeburn  1952:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1953:     my %returnhash=();
1.1300    raeburn  1954:     my @ids=(); 
                   1955:     if (ref($idsref) eq 'ARRAY') {
                   1956:         @ids = @{$idsref};
                   1957:     } else {
                   1958:         return %returnhash; 
                   1959:     }
                   1960:     if ($namespace eq '') {
                   1961:         $namespace = 'ids';
                   1962:     }
1.70      www      1963:     
1.841     albertel 1964:     my %servers = &get_servers($udom,'library');
                   1965:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1966: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1967: 	if ($namespace eq 'ids') {
                   1968: 	    $idlist=~tr/A-Z/a-z/;
                   1969: 	}
                   1970: 	my $reply;
                   1971: 	if ($namespace eq 'ids') {
                   1972: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1973: 	} else {
                   1974: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1975: 	}
1.841     albertel 1976: 	my @answer=();
                   1977: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1978: 	    @answer=split(/\&/,$reply);
                   1979: 	}                    ;
                   1980: 	my $i;
                   1981: 	for ($i=0;$i<=$#ids;$i++) {
                   1982: 	    if ($answer[$i]) {
1.1299    raeburn  1983: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1984: 	    }
1.841     albertel 1985: 	}
1.1300    raeburn  1986:     }
1.70      www      1987:     return %returnhash;
                   1988: }
                   1989: 
                   1990: # ------------------------------------- Find the IDs behind a list of usernames
                   1991: 
                   1992: sub idrget {
                   1993:     my ($udom,@unames)=@_;
                   1994:     my %returnhash=();
1.800     albertel 1995:     foreach my $uname (@unames) {
                   1996:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1997:     }
1.70      www      1998:     return %returnhash;
                   1999: }
                   2000: 
1.1300    raeburn  2001: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      2002: 
                   2003: sub idput {
1.1300    raeburn  2004:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      2005:     my %servers=();
1.1300    raeburn  2006:     my %ids=();
                   2007:     my %byid = ();
                   2008:     if (ref($idsref) eq 'HASH') {
                   2009:         %ids=%{$idsref};
                   2010:     }
                   2011:     if ($namespace eq '') {
                   2012:         $namespace = 'ids'; 
                   2013:     }
1.800     albertel 2014:     foreach my $uname (keys(%ids)) {
                   2015: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  2016:         if ($uhom eq '') {
                   2017:             $uhom=&homeserver($uname,$udom);
                   2018:         }
1.70      www      2019:         if ($uhom ne 'no_host') {
1.800     albertel 2020:             my $esc_unam=&escape($uname);
1.1300    raeburn  2021:             if ($namespace eq 'ids') {
                   2022:                 my $id=&escape($ids{$uname});
                   2023:                 $id=~tr/A-Z/a-z/;
                   2024:                 my $esc_unam=&escape($uname);
                   2025:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      2026:             } else {
1.1300    raeburn  2027:                 my @currids = split(/,/,$ids{$uname});
                   2028:                 foreach my $id (@currids) {
                   2029:                     $byid{$uhom}{$id} .= $uname.',';
                   2030:                 }
                   2031:             }
                   2032:         }
                   2033:     }
                   2034:     if ($namespace eq 'clickers') {
                   2035:         foreach my $server (keys(%byid)) {
                   2036:             if (ref($byid{$server}) eq 'HASH') {
                   2037:                 foreach my $id (keys(%{$byid{$server}})) {
                   2038:                     $byid{$server} =~ s/,$//;
                   2039:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   2040:                 }
1.70      www      2041:             }
                   2042:         }
1.191     harris41 2043:     }
1.800     albertel 2044:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2045:         $servers{$server} =~ s/\&$//;
                   2046:         if ($namespace eq 'ids') {     
                   2047:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   2048:         } else {
                   2049:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   2050:         }
1.191     harris41 2051:     }
1.344     www      2052: }
                   2053: 
1.1300    raeburn  2054: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  2055: 
                   2056: sub iddel {
1.1300    raeburn  2057:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  2058:     my %result=();
1.1300    raeburn  2059:     my %ids=();
                   2060:     my %byid = ();
                   2061:     if (ref($idshashref) eq 'HASH') {
                   2062:         %ids=%{$idshashref};
                   2063:     } else {
1.1231    raeburn  2064:         return %result;
                   2065:     }
1.1300    raeburn  2066:     if ($namespace eq '') {
                   2067:         $namespace = 'ids';
                   2068:     }
1.1231    raeburn  2069:     my %servers=();
1.1300    raeburn  2070:     while (my ($id,$unamestr) = each(%ids)) {
                   2071:         if ($namespace eq 'ids') {
                   2072:             my $uhom = $uhome;
                   2073:             if ($uhom eq '') { 
                   2074:                 $uhom=&homeserver($unamestr,$udom);
                   2075:             }
                   2076:             if ($uhom ne 'no_host') {
                   2077:                 $servers{$uhom}.='&'.&escape($id);
                   2078:             }
                   2079:          } else {
                   2080:             my @curritems = split(/,/,$ids{$id});
                   2081:             foreach my $uname (@curritems) {
                   2082:                 my $uhom = $uhome;
                   2083:                 if ($uhom eq '') {
                   2084:                     $uhom=&homeserver($uname,$udom);
                   2085:                 }
                   2086:                 if ($uhom ne 'no_host') { 
                   2087:                     $byid{$uhom}{$id} .= $uname.',';
                   2088:                 }
                   2089:             }
1.1231    raeburn  2090:         }
1.1300    raeburn  2091:     }
                   2092:     if ($namespace eq 'clickers') {
                   2093:         foreach my $server (keys(%byid)) {
                   2094:             if (ref($byid{$server}) eq 'HASH') {
                   2095:                 foreach my $id (keys(%{$byid{$server}})) {
                   2096:                     $byid{$server}{$id} =~ s/,$//;
                   2097:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2098:                 }
1.1231    raeburn  2099:             }
                   2100:         }
                   2101:     }
                   2102:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2103:         $servers{$server} =~ s/\&$//;
                   2104:         if ($namespace eq 'ids') {
                   2105:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2106:         } elsif ($namespace eq 'clickers') {
                   2107:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2108:         }
1.1231    raeburn  2109:     }
                   2110:     return %result;
                   2111: }
                   2112: 
1.1300    raeburn  2113: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2114: 
                   2115: sub updateclickers {
                   2116:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2117:     my %clickers;
                   2118:     if (ref($idshashref) eq 'HASH') {
                   2119:         %clickers=%{$idshashref};
                   2120:     } else {
                   2121:         return;
                   2122:     }
                   2123:     my $items='';
                   2124:     foreach my $item (keys(%clickers)) {
                   2125:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2126:     }
                   2127:     $items=~s/\&$//;
                   2128:     my $request = "updateclickers:$udom:$action:$items";
                   2129:     if ($critical) {
                   2130:         return &critical($request,$uhome);
                   2131:     } else {
                   2132:         return &reply($request,$uhome);
                   2133:     }
                   2134: }
                   2135: 
1.1023    raeburn  2136: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2137: sub dump_dom {
1.1165    droeschl 2138:     my ($namespace, $udom, $regexp) = @_;
                   2139: 
                   2140:     $udom ||= $env{'user.domain'};
                   2141: 
                   2142:     return () unless $udom;
                   2143: 
                   2144:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2145: }
                   2146: 
1.1023    raeburn  2147: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2148: 
                   2149: sub get_dom {
1.1462    raeburn  2150:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1267    raeburn  2151:     return if ($udom eq 'public');
1.806     raeburn  2152:     my $items='';
                   2153:     foreach my $item (@$storearr) {
                   2154:         $items.=&escape($item).'&';
                   2155:     }
                   2156:     $items=~s/\&$//;
1.860     raeburn  2157:     if (!$udom) {
                   2158:         $udom=$env{'user.domain'};
1.1267    raeburn  2159:         return if ($udom eq 'public');
1.860     raeburn  2160:         if (defined(&domain($udom,'primary'))) {
                   2161:             $uhome=&domain($udom,'primary');
                   2162:         } else {
1.874     albertel 2163:             undef($uhome);
1.860     raeburn  2164:         }
                   2165:     } else {
                   2166:         if (!$uhome) {
                   2167:             if (defined(&domain($udom,'primary'))) {
                   2168:                 $uhome=&domain($udom,'primary');
                   2169:             }
                   2170:         }
                   2171:     }
                   2172:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2173:         my $rep;
1.1442    raeburn  2174:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   2175:             # domain information is hosted on this machine
1.1462    raeburn  2176:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1344    raeburn  2177:         } else {
1.1462    raeburn  2178:             if ($encrypt) {
1.1442    raeburn  2179:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2180:             } else {
                   2181:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2182:             }
1.1344    raeburn  2183:         }
1.866     raeburn  2184:         my %returnhash;
1.875     albertel 2185:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2186:             return %returnhash;
                   2187:         }
1.806     raeburn  2188:         my @pairs=split(/\&/,$rep);
                   2189:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2190:             return @pairs;
                   2191:         }
                   2192:         my $i=0;
                   2193:         foreach my $item (@$storearr) {
                   2194:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2195:             $i++;
                   2196:         }
                   2197:         return %returnhash;
                   2198:     } else {
1.880     banghart 2199:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2200:     }
                   2201: }
                   2202: 
                   2203: # -------------------------------------------- put items in domain db files 
                   2204: 
                   2205: sub put_dom {
1.1462    raeburn  2206:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  2207:     if (!$udom) {
                   2208:         $udom=$env{'user.domain'};
                   2209:         if (defined(&domain($udom,'primary'))) {
                   2210:             $uhome=&domain($udom,'primary');
                   2211:         } else {
1.874     albertel 2212:             undef($uhome);
1.860     raeburn  2213:         }
                   2214:     } else {
                   2215:         if (!$uhome) {
                   2216:             if (defined(&domain($udom,'primary'))) {
                   2217:                 $uhome=&domain($udom,'primary');
                   2218:             }
                   2219:         }
                   2220:     } 
                   2221:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2222:         my $items='';
                   2223:         foreach my $item (keys(%$storehash)) {
                   2224:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2225:         }
                   2226:         $items=~s/\&$//;
1.1462    raeburn  2227:         if ($encrypt) {
1.1344    raeburn  2228:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2229:         } else {
                   2230:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2231:         }
1.806     raeburn  2232:     } else {
1.860     raeburn  2233:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2234:     }
                   2235: }
                   2236: 
1.1023    raeburn  2237: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2238: sub newput_dom {
1.1023    raeburn  2239:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2240:     my $result;
                   2241:     if (!$udom) {
                   2242:         $udom=$env{'user.domain'};
                   2243:     }
1.1023    raeburn  2244:     if ($udom) {
                   2245:         my $uname = &get_domainconfiguser($udom);
                   2246:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2247:     }
                   2248:     return $result;
                   2249: }
                   2250: 
1.1023    raeburn  2251: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2252: sub del_dom {
1.1023    raeburn  2253:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2254:     if (ref($storearr) eq 'ARRAY') {
                   2255:         if (!$udom) {
                   2256:             $udom=$env{'user.domain'};
                   2257:         }
1.1023    raeburn  2258:         if ($udom) {
                   2259:             my $uname = &get_domainconfiguser($udom); 
                   2260:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2261:         }
                   2262:     }
                   2263: }
                   2264: 
1.1023    raeburn  2265: # ----------------------------------construct domainconfig user for a domain 
                   2266: sub get_domainconfiguser {
                   2267:     my ($udom) = @_;
                   2268:     return $udom.'-domainconfig';
                   2269: }
                   2270: 
1.837     raeburn  2271: sub retrieve_inst_usertypes {
                   2272:     my ($udom) = @_;
                   2273:     my (%returnhash,@order);
1.989     raeburn  2274:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2275:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2276:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2277:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2278:     } else {
                   2279:         if (defined(&domain($udom,'primary'))) {
                   2280:             my $uhome=&domain($udom,'primary');
                   2281:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2282:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2283:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2284:                 return (\%returnhash,\@order);
                   2285:             }
                   2286:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2287:             my @pairs=split(/\&/,$hashitems);
                   2288:             foreach my $item (@pairs) {
                   2289:                 my ($key,$value)=split(/=/,$item,2);
                   2290:                 $key = &unescape($key);
                   2291:                 next if ($key =~ /^error: 2 /);
                   2292:                 $returnhash{$key}=&thaw_unescape($value);
                   2293:             }
                   2294:             my @esc_order = split(/\&/,$orderitems);
                   2295:             foreach my $item (@esc_order) {
                   2296:                 push(@order,&unescape($item));
                   2297:             }
                   2298:         } else {
1.1256    raeburn  2299:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2300:         }
1.1256    raeburn  2301:         return (\%returnhash,\@order);
1.837     raeburn  2302:     }
                   2303: }
                   2304: 
1.868     raeburn  2305: sub is_domainimage {
                   2306:     my ($url) = @_;
1.1306    raeburn  2307:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2308:         if (&domain($1) ne '') {
                   2309:             return '1';
                   2310:         }
                   2311:     }
                   2312:     return;
                   2313: }
                   2314: 
1.899     raeburn  2315: sub inst_directory_query {
                   2316:     my ($srch) = @_;
                   2317:     my $udom = $srch->{'srchdomain'};
                   2318:     my %results;
                   2319:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2320:     my $outcome;
1.899     raeburn  2321:     if ($homeserver ne '') {
1.1357    raeburn  2322:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2323:             if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2324:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357    raeburn  2325:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2326:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2327:                     (($major == 2) && ($minor < 12))) {
                   2328:                     return;
                   2329:                 }
                   2330:             }
                   2331:         }
1.904     albertel 2332: 	my $queryid=&reply("querysend:instdirsearch:".
                   2333: 			   &escape($srch->{'srchby'}).':'.
                   2334: 			   &escape($srch->{'srchterm'}).':'.
                   2335: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2336: 	my $host=&hostname($homeserver);
                   2337: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2338: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2339: 	    return;
                   2340: 	}
                   2341: 	my $response = &get_query_reply($queryid);
                   2342: 	my $maxtries = 5;
                   2343: 	my $tries = 1;
                   2344: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2345: 	    $response = &get_query_reply($queryid);
                   2346: 	    $tries ++;
                   2347: 	}
                   2348: 
                   2349:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2350:             if ($response eq 'unavailable') {
                   2351:                 $outcome = $response;
                   2352:             } else {
                   2353:                 $outcome = 'ok';
                   2354:                 my @matches = split(/\n/,$response);
                   2355:                 foreach my $match (@matches) {
                   2356:                     my ($key,$value) = split(/=/,$match);
                   2357:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2358:                 }
1.899     raeburn  2359:             }
                   2360:         }
                   2361:     }
1.909     raeburn  2362:     return ($outcome,%results);
1.899     raeburn  2363: }
                   2364: 
                   2365: sub usersearch {
                   2366:     my ($srch) = @_;
                   2367:     my $dom = $srch->{'srchdomain'};
                   2368:     my %results;
                   2369:     my %libserv = &all_library();
                   2370:     my $query = 'usersearch';
                   2371:     foreach my $tryserver (keys(%libserv)) {
                   2372:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2373:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2374:                 if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2375:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357    raeburn  2376:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2377:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2378:                              (($major == 2) && ($minor < 12)));
                   2379:                 }
                   2380:             }
1.899     raeburn  2381:             my $host=&hostname($tryserver);
                   2382:             my $queryid=
1.911     raeburn  2383:                 &reply("querysend:".&escape($query).':'.
                   2384:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2385:                        &escape($srch->{'srchtype'}).':'.
                   2386:                        &escape($srch->{'srchterm'}),$tryserver);
                   2387:             if ($queryid !~/^\Q$host\E\_/) {
                   2388:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2389:                 next;
1.899     raeburn  2390:             }
                   2391:             my $reply = &get_query_reply($queryid);
                   2392:             my $maxtries = 1;
                   2393:             my $tries = 1;
                   2394:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2395:                 $reply = &get_query_reply($queryid);
                   2396:                 $tries ++;
                   2397:             }
                   2398:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2399:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2400:             } else {
1.911     raeburn  2401:                 my @matches;
                   2402:                 if ($reply =~ /\n/) {
                   2403:                     @matches = split(/\n/,$reply);
                   2404:                 } else {
                   2405:                     @matches = split(/\&/,$reply);
                   2406:                 }
1.899     raeburn  2407:                 foreach my $match (@matches) {
                   2408:                     my ($uname,$udom,%userhash);
1.911     raeburn  2409:                     foreach my $entry (split(/:/,$match)) {
                   2410:                         my ($key,$value) =
                   2411:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2412:                         $userhash{$key} = $value;
                   2413:                         if ($key eq 'username') {
                   2414:                             $uname = $value;
                   2415:                         } elsif ($key eq 'domain') {
                   2416:                             $udom = $value;
1.911     raeburn  2417:                         }
1.899     raeburn  2418:                     }
                   2419:                     $results{$uname.':'.$udom} = \%userhash;
                   2420:                 }
                   2421:             }
                   2422:         }
                   2423:     }
                   2424:     return %results;
                   2425: }
                   2426: 
1.912     raeburn  2427: sub get_instuser {
                   2428:     my ($udom,$uname,$id) = @_;
                   2429:     my $homeserver = &domain($udom,'primary');
                   2430:     my ($outcome,%results);
                   2431:     if ($homeserver ne '') {
                   2432:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2433:                            &escape($id).':'.&escape($udom),$homeserver);
                   2434:         my $host=&hostname($homeserver);
                   2435:         if ($queryid !~/^\Q$host\E\_/) {
                   2436:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2437:             return;
                   2438:         }
                   2439:         my $response = &get_query_reply($queryid);
                   2440:         my $maxtries = 5;
                   2441:         my $tries = 1;
                   2442:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2443:             $response = &get_query_reply($queryid);
                   2444:             $tries ++;
                   2445:         }
                   2446:         if (!&error($response) && $response ne 'refused') {
                   2447:             if ($response eq 'unavailable') {
                   2448:                 $outcome = $response;
                   2449:             } else {
                   2450:                 $outcome = 'ok';
                   2451:                 my @matches = split(/\n/,$response);
                   2452:                 foreach my $match (@matches) {
                   2453:                     my ($key,$value) = split(/=/,$match);
                   2454:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2455:                 }
                   2456:             }
                   2457:         }
                   2458:     }
                   2459:     my %userinfo;
                   2460:     if (ref($results{$uname}) eq 'HASH') {
                   2461:         %userinfo = %{$results{$uname}};
                   2462:     } 
                   2463:     return ($outcome,%userinfo);
                   2464: }
                   2465: 
1.1290    raeburn  2466: sub get_multiple_instusers {
                   2467:     my ($udom,$users,$caller) = @_;
                   2468:     my ($outcome,$results);
                   2469:     if (ref($users) eq 'HASH') {
                   2470:         my $count = keys(%{$users}); 
                   2471:         my $requested = &freeze_escape($users);
                   2472:         my $homeserver = &domain($udom,'primary');
                   2473:         if ($homeserver ne '') {
                   2474:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2475:             my $host=&hostname($homeserver);
                   2476:             if ($queryid !~/^\Q$host\E\_/) {
                   2477:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2478:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2479:                 return ($outcome,$results);
                   2480:             }
                   2481:             my $response = &get_query_reply($queryid);
                   2482:             my $maxtries = 5;
                   2483:             if ($count > 100) {
                   2484:                 $maxtries = 1+int($count/20);
                   2485:             }
                   2486:             my $tries = 1;
                   2487:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2488:                 $response = &get_query_reply($queryid);
                   2489:                 $tries ++;
                   2490:             }
                   2491:             if ($response eq '') {
                   2492:                 $results = {};
                   2493:                 foreach my $key (keys(%{$users})) {
                   2494:                     my ($uname,$id);
                   2495:                     if ($caller eq 'id') {
                   2496:                         $id = $key;
                   2497:                     } else {
                   2498:                         $uname = $key;
                   2499:                     }
                   2500:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2501:                     $outcome = $resp;
1.1290    raeburn  2502:                     if ($resp eq 'ok') {
                   2503:                         %{$results} = (%{$results}, %info);
                   2504:                     } else {
                   2505:                         last;
                   2506:                     }
                   2507:                 }
                   2508:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2509:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2510:                     $outcome = $response;
                   2511:                 } else {
1.1291    raeburn  2512:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2513:                     if ($outcome eq 'ok') {
                   2514:                         $results = &thaw_unescape($userdata); 
                   2515:                     }
                   2516:                 }
                   2517:             }
                   2518:         }
                   2519:     }
                   2520:     return ($outcome,$results);
                   2521: }
                   2522: 
1.912     raeburn  2523: sub inst_rulecheck {
1.923     raeburn  2524:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2525:     my %returnhash;
                   2526:     if ($udom ne '') {
                   2527:         if (ref($rules) eq 'ARRAY') {
                   2528:             @{$rules} = map {&escape($_);} (@{$rules});
                   2529:             my $rulestr = join(':',@{$rules});
                   2530:             my $homeserver=&domain($udom,'primary');
                   2531:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2532:                 my $response;
                   2533:                 if ($item eq 'username') {                
                   2534:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2535:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2536:                                               $homeserver));
1.923     raeburn  2537:                 } elsif ($item eq 'id') {
                   2538:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2539:                                               ':'.&escape($id).':'.$rulestr,
                   2540:                                               $homeserver));
1.945     raeburn  2541:                 } elsif ($item eq 'selfcreate') {
                   2542:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2543:                                                &escape($udom).':'.&escape($uname).
                   2544:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2545:                 }
1.912     raeburn  2546:                 if ($response ne 'refused') {
                   2547:                     my @pairs=split(/\&/,$response);
                   2548:                     foreach my $item (@pairs) {
                   2549:                         my ($key,$value)=split(/=/,$item,2);
                   2550:                         $key = &unescape($key);
                   2551:                         next if ($key =~ /^error: 2 /);
                   2552:                         $returnhash{$key}=&thaw_unescape($value);
                   2553:                     }
                   2554:                 }
                   2555:             }
                   2556:         }
                   2557:     }
                   2558:     return %returnhash;
                   2559: }
                   2560: 
                   2561: sub inst_userrules {
1.923     raeburn  2562:     my ($udom,$check) = @_;
1.912     raeburn  2563:     my (%ruleshash,@ruleorder);
                   2564:     if ($udom ne '') {
                   2565:         my $homeserver=&domain($udom,'primary');
                   2566:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2567:             my $response;
                   2568:             if ($check eq 'id') {
                   2569:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2570:                                  $homeserver);
1.943     raeburn  2571:             } elsif ($check eq 'email') {
                   2572:                 $response=&reply('instemailrules:'.&escape($udom),
                   2573:                                  $homeserver);
1.923     raeburn  2574:             } else {
                   2575:                 $response=&reply('instuserrules:'.&escape($udom),
                   2576:                                  $homeserver);
                   2577:             }
1.912     raeburn  2578:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2579:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2580:                 ($response ne 'no_such_host')) {
                   2581:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2582:                 my @pairs=split(/\&/,$hashitems);
                   2583:                 foreach my $item (@pairs) {
                   2584:                     my ($key,$value)=split(/=/,$item,2);
                   2585:                     $key = &unescape($key);
                   2586:                     next if ($key =~ /^error: 2 /);
                   2587:                     $ruleshash{$key}=&thaw_unescape($value);
                   2588:                 }
                   2589:                 my @esc_order = split(/\&/,$orderitems);
                   2590:                 foreach my $item (@esc_order) {
                   2591:                     push(@ruleorder,&unescape($item));
                   2592:                 }
                   2593:             }
                   2594:         }
                   2595:     }
                   2596:     return (\%ruleshash,\@ruleorder);
                   2597: }
                   2598: 
1.976     raeburn  2599: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2600: 
                   2601: sub get_domain_defaults {
1.1240    raeburn  2602:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2603:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2604:     my $cachetime = 60*60*24;
1.1240    raeburn  2605:     unless ($ignore_cache) {
                   2606:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2607:         if (defined($cached)) {
                   2608:             if (ref($result) eq 'HASH') {
                   2609:                 return %{$result};
                   2610:             }
1.943     raeburn  2611:         }
                   2612:     }
                   2613:     my %domdefaults;
                   2614:     my %domconfig =
1.989     raeburn  2615:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2616:                                   'requestcourses','inststatus',
1.1183    raeburn  2617:                                   'coursedefaults','usersessions',
1.1258    raeburn  2618:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2619:                                   'coursecategories','ssl','autoenroll',
1.1434    raeburn  2620:                                   'trust','helpsettings','wafproxy'],$domain);
1.1305    raeburn  2621:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2622:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2623:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2624:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2625:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2626:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2627:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2628:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2629:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2630:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2631:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2632:     } else {
                   2633:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2634:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2635:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2636:     }
1.976     raeburn  2637:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2638:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2639:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2640:         } else {
                   2641:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2642:         }
1.1177    raeburn  2643:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2644:         foreach my $item (@usertools) {
                   2645:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2646:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2647:             }
                   2648:         }
1.1229    raeburn  2649:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2650:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2651:         }
1.976     raeburn  2652:     }
1.985     raeburn  2653:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2654:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2655:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2656:         }
                   2657:     }
1.1183    raeburn  2658:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2659:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2660:     }
1.989     raeburn  2661:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2662:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2663:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2664:         }
                   2665:     }
1.1047    raeburn  2666:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2667:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2668:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2669:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2670:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2671:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2672:         }
1.1254    raeburn  2673:         foreach my $type (@coursetypes) {
                   2674:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2675:                 unless ($type eq 'community') {
                   2676:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2677:                 }
                   2678:             }
                   2679:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2680:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2681:             }
1.1277    raeburn  2682:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2683:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2684:                     $domdefaults{$type.'postsubtimeout'} = 
                   2685:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2686:                 }
                   2687:             }
1.1230    raeburn  2688:         }
1.1286    raeburn  2689:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2690:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2691:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2692:                 if (@clonecodes) {
                   2693:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2694:                 }
                   2695:             }
                   2696:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2697:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2698:         }
1.1356    raeburn  2699:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2700:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2701:         } 
1.1047    raeburn  2702:     }
1.1073    raeburn  2703:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2704:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2705:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2706:         }
                   2707:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2708:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2709:         }
1.1279    raeburn  2710:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2711:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2712:         }
1.1440    raeburn  2713:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439    raeburn  2714:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2715:         }
1.1073    raeburn  2716:     }
1.1254    raeburn  2717:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2718:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2719:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2720:                             'approval','limit');
                   2721:             foreach my $type (@coursetypes) {
                   2722:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2723:                     my @mgrdc = ();
                   2724:                     foreach my $item (@settings) {
                   2725:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2726:                             push(@mgrdc,$item);
                   2727:                         }
                   2728:                     }
                   2729:                     if (@mgrdc) {
                   2730:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2731:                     }
                   2732:                 }
                   2733:             }
                   2734:         }
                   2735:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2736:             foreach my $type (@coursetypes) {
                   2737:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2738:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2739:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2740:                     }
                   2741:                 }
                   2742:             }
                   2743:         }
                   2744:     }
1.1258    raeburn  2745:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2746:         $domdefaults{'catauth'} = 'std';
                   2747:         $domdefaults{'catunauth'} = 'std';
1.1413    raeburn  2748:         if ($domconfig{'coursecategories'}{'auth'}) {
1.1258    raeburn  2749:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2750:         }
                   2751:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2752:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2753:         }
                   2754:     }
1.1315    raeburn  2755:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2756:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2757:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2758:         }
1.1338    raeburn  2759:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2760:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2761:         }
                   2762:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2763:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2764:         }
                   2765:     }
1.1320    raeburn  2766:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2767:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2768:         foreach my $prefix (@prefixes) {
                   2769:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2770:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2771:             }
                   2772:         }
                   2773:     }
1.1314    raeburn  2774:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2775:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2776:     }
1.1332    raeburn  2777:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2778:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2779:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2780:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2781:         }
                   2782:     }
1.1434    raeburn  2783:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449    raeburn  2784:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434    raeburn  2785:             if ($domconfig{'wafproxy'}{$item}) {
                   2786:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2787:             }
                   2788:         }
                   2789:     } 
1.1219    raeburn  2790:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2791:     return %domdefaults;
                   2792: }
                   2793: 
1.1412    raeburn  2794: sub get_dom_cats {
                   2795:     my ($dom) = @_;
                   2796:     return unless (&domain($dom));
                   2797:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2798:     unless (defined($cached)) {
                   2799:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2800:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2801:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2802:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2803:             } else {
                   2804:                 $cats = {};
                   2805:             }
                   2806:         } else {
                   2807:             $cats = {};
                   2808:         }
                   2809:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2810:     }
1.1413    raeburn  2811:     return $cats;
                   2812: }
                   2813: 
                   2814: sub get_dom_instcats {
                   2815:     my ($dom) = @_;
                   2816:     return unless (&domain($dom));
                   2817:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2818:     unless (defined($cached)) {
                   2819:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2820:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2821:         if ($totcodes > 0) {
                   2822:             my $caller = 'global';
                   2823:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2824:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2825:                 $instcats = {
                   2826:                                 codes => \%codes,
                   2827:                                 codetitles => \@codetitles,
                   2828:                                 cat_titles => \%cat_titles,
                   2829:                                 cat_order => \%cat_order,
                   2830:                             };
                   2831:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2832:             }
                   2833:         }
                   2834:     }
                   2835:     return $instcats;
                   2836: }
                   2837: 
                   2838: sub retrieve_instcodes {
                   2839:     my ($coursecodes,$dom) = @_;
                   2840:     my $totcodes;
                   2841:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2842:     foreach my $course (keys(%courses)) {
                   2843:         if (ref($courses{$course}) eq 'HASH') {
                   2844:             if ($courses{$course}{'inst_code'} ne '') {
                   2845:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2846:                 $totcodes ++;
                   2847:             }
                   2848:         }
                   2849:     }
                   2850:     return $totcodes;
1.1412    raeburn  2851: }
                   2852: 
1.1311    raeburn  2853: sub course_portal_url {
1.1451    raeburn  2854:     my ($cnum,$cdom,$r) = @_;
1.1311    raeburn  2855:     my $chome = &homeserver($cnum,$cdom);
                   2856:     my $hostname = &hostname($chome);
                   2857:     my $protocol = $protocol{$chome};
                   2858:     $protocol = 'http' if ($protocol ne 'https');
                   2859:     my %domdefaults = &get_domain_defaults($cdom);
                   2860:     my $firsturl;
                   2861:     if ($domdefaults{'portal_def'}) {
                   2862:         $firsturl = $domdefaults{'portal_def'};
                   2863:     } else {
1.1451    raeburn  2864:         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2865:         $hostname = $alias if ($alias ne '');
1.1311    raeburn  2866:         $firsturl = $protocol.'://'.$hostname;
                   2867:     }
                   2868:     return $firsturl;
                   2869: }
                   2870: 
1.1407    raeburn  2871: # --------------------------------------------- Get domain config for passwords
                   2872: 
                   2873: sub get_passwdconf {
                   2874:     my ($dom) = @_;
                   2875:     my (%passwdconf,$gotconf,$lookup);
                   2876:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2877:     if (defined($cached)) {
                   2878:         if (ref($result) eq 'HASH') {
                   2879:             %passwdconf = %{$result};
                   2880:             $gotconf = 1;
                   2881:         }
                   2882:     }
                   2883:     unless ($gotconf) {
                   2884:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2885:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2886:             %passwdconf = %{$domconfig{'passwords'}};
                   2887:         }
                   2888:         my $cachetime = 24*60*60;
                   2889:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2890:     }
                   2891:     return %passwdconf;
                   2892: }
                   2893: 
1.344     www      2894: # --------------------------------------------------- Assign a key to a student
                   2895: 
                   2896: sub assign_access_key {
1.364     www      2897: #
                   2898: # a valid key looks like uname:udom#comments
                   2899: # comments are being appended
                   2900: #
1.498     www      2901:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2902:     $kdom=
1.620     albertel 2903:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2904:     $knum=
1.620     albertel 2905:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2906:     $cdom=
1.620     albertel 2907:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2908:     $cnum=
1.620     albertel 2909:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2910:     $udom=$env{'user.name'} unless (defined($udom));
                   2911:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2912:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2913:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2914:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2915:                                                   # assigned to this person
                   2916:                                                   # - this should not happen,
1.345     www      2917:                                                   # unless something went wrong
                   2918:                                                   # the first time around
                   2919: # ready to assign
1.364     www      2920:         $logentry=$1.'; '.$logentry;
1.496     www      2921:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2922:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2923: # key now belongs to user
1.346     www      2924: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2925:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2926:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2927:                 return 'ok';
                   2928:             } else {
                   2929:                 return 
                   2930:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2931: 	    }
                   2932:         } else {
                   2933:             return 'error: Could not assign key, try again later.';
                   2934:         }
1.364     www      2935:     } elsif (!$existing{$ckey}) {
1.345     www      2936: # the key does not exist
                   2937: 	return 'error: The key does not exist';
                   2938:     } else {
                   2939: # the key is somebody else's
                   2940: 	return 'error: The key is already in use';
                   2941:     }
1.344     www      2942: }
                   2943: 
1.364     www      2944: # ------------------------------------------ put an additional comment on a key
                   2945: 
                   2946: sub comment_access_key {
                   2947: #
                   2948: # a valid key looks like uname:udom#comments
                   2949: # comments are being appended
                   2950: #
                   2951:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2952:     $cdom=
1.620     albertel 2953:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2954:     $cnum=
1.620     albertel 2955:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2956:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2957:     if ($existing{$ckey}) {
                   2958:         $existing{$ckey}.='; '.$logentry;
                   2959: # ready to assign
1.367     www      2960:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2961:                                                  $cdom,$cnum) eq 'ok') {
                   2962: 	    return 'ok';
                   2963:         } else {
                   2964: 	    return 'error: Count not store comment.';
                   2965:         }
                   2966:     } else {
                   2967: # the key does not exist
                   2968: 	return 'error: The key does not exist';
                   2969:     }
                   2970: }
                   2971: 
1.344     www      2972: # ------------------------------------------------------ Generate a set of keys
                   2973: 
                   2974: sub generate_access_keys {
1.364     www      2975:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2976:     $cdom=
1.620     albertel 2977:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2978:     $cnum=
1.620     albertel 2979:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2980:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2981:     unless (($cdom) && ($cnum)) { return 0; }
                   2982:     if ($number>10000) { return 0; }
                   2983:     sleep(2); # make sure don't get same seed twice
                   2984:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2985:     my $total=0;
                   2986:     for (my $i=1;$i<=$number;$i++) {
                   2987:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2988:                   sprintf("%lx",int(100000*rand)).'-'.
                   2989:                   sprintf("%lx",int(100000*rand));
                   2990:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2991:        $newkey=~s/0/h/g; # and also 0 and O
                   2992:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2993:        if ($existing{$newkey}) {
                   2994:            $i--;
                   2995:        } else {
1.364     www      2996: 	  if (&put('accesskeys',
                   2997:               { $newkey => '# generated '.localtime().
1.620     albertel 2998:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2999:                            '; '.$logentry },
                   3000: 		   $cdom,$cnum) eq 'ok') {
1.344     www      3001:               $total++;
                   3002: 	  }
                   3003:        }
                   3004:     }
1.620     albertel 3005:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      3006:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   3007:     return $total;
                   3008: }
                   3009: 
                   3010: # ------------------------------------------------------- Validate an accesskey
                   3011: 
                   3012: sub validate_access_key {
                   3013:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   3014:     $cdom=
1.620     albertel 3015:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3016:     $cnum=
1.620     albertel 3017:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3018:     $udom=$env{'user.domain'} unless (defined($udom));
                   3019:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      3020:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 3021:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      3022: }
                   3023: 
                   3024: # ------------------------------------- Find the section of student in a course
1.652     albertel 3025: sub devalidate_getsection_cache {
                   3026:     my ($udom,$unam,$courseid)=@_;
                   3027:     my $hashid="$udom:$unam:$courseid";
                   3028:     &devalidate_cache_new('getsection',$hashid);
                   3029: }
1.298     matthew  3030: 
1.815     albertel 3031: sub courseid_to_courseurl {
                   3032:     my ($courseid) = @_;
                   3033:     #already url style courseid
                   3034:     return $courseid if ($courseid =~ m{^/});
                   3035: 
                   3036:     if (exists($env{'course.'.$courseid.'.num'})) {
                   3037: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   3038: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   3039: 	return "/$cdom/$cnum";
                   3040:     }
                   3041: 
                   3042:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   3043:     if (exists($courseinfo{'num'})) {
                   3044: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   3045:     }
                   3046: 
                   3047:     return undef;
                   3048: }
                   3049: 
1.298     matthew  3050: sub getsection {
                   3051:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3052:     my $cachetime=1800;
1.551     albertel 3053: 
                   3054:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3055:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3056:     if (defined($cached)) { return $result; }
                   3057: 
1.298     matthew  3058:     my %Pending; 
                   3059:     my %Expired;
                   3060:     #
                   3061:     # Each role can either have not started yet (pending), be active, 
                   3062:     #    or have expired.
                   3063:     #
                   3064:     # If there is an active role, we are done.
                   3065:     #
                   3066:     # If there is more than one role which has not started yet, 
                   3067:     #     choose the one which will start sooner
                   3068:     # If there is one role which has not started yet, return it.
                   3069:     #
                   3070:     # If there is more than one expired role, choose the one which ended last.
                   3071:     # If there is a role which has expired, return it.
                   3072:     #
1.815     albertel 3073:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3074:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3075:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3076:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3077:         my $section=$1;
                   3078:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3079:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3080:         my $now=time;
1.548     albertel 3081:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3082:             $Expired{$end}=$section;
                   3083:             next;
                   3084:         }
1.548     albertel 3085:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3086:             $Pending{$start}=$section;
                   3087:             next;
                   3088:         }
1.599     albertel 3089:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3090:     }
                   3091:     #
                   3092:     # Presumedly there will be few matching roles from the above
                   3093:     # loop and the sorting time will be negligible.
                   3094:     if (scalar(keys(%Pending))) {
                   3095:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3096:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3097:     } 
                   3098:     if (scalar(keys(%Expired))) {
                   3099:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3100:         my $time = pop(@sorted);
1.599     albertel 3101:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3102:     }
1.599     albertel 3103:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3104: }
1.70      www      3105: 
1.599     albertel 3106: sub save_cache {
                   3107:     &purge_remembered();
1.722     albertel 3108:     #&Apache::loncommon::validate_page();
1.620     albertel 3109:     undef(%env);
1.780     albertel 3110:     undef($env_loaded);
1.599     albertel 3111: }
1.452     albertel 3112: 
1.599     albertel 3113: my $to_remember=-1;
                   3114: my %remembered;
                   3115: my %accessed;
                   3116: my $kicks=0;
                   3117: my $hits=0;
1.849     albertel 3118: sub make_key {
                   3119:     my ($name,$id) = @_;
1.872     albertel 3120:     if (length($id) > 65 
                   3121: 	&& length(&escape($id)) > 200) {
                   3122: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3123:     }
1.849     albertel 3124:     return &escape($name.':'.$id);
                   3125: }
                   3126: 
1.599     albertel 3127: sub devalidate_cache_new {
                   3128:     my ($name,$id,$debug) = @_;
                   3129:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  3130:     my $remembered_id=$name.':'.$id;
1.849     albertel 3131:     $id=&make_key($name,$id);
1.599     albertel 3132:     $memcache->delete($id);
1.1319    damieng  3133:     delete($remembered{$remembered_id});
                   3134:     delete($accessed{$remembered_id});
1.599     albertel 3135: }
                   3136: 
                   3137: sub is_cached_new {
                   3138:     my ($name,$id,$debug) = @_;
1.1319    damieng  3139:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   3140:     if (exists($remembered{$remembered_id})) {
                   3141: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3142: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3143: 	$hits++;
1.1319    damieng  3144: 	return ($remembered{$remembered_id},1);
1.599     albertel 3145:     }
1.1319    damieng  3146:     $id=&make_key($name,$id);
1.599     albertel 3147:     my $value = $memcache->get($id);
                   3148:     if (!(defined($value))) {
                   3149: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3150: 	return (undef,undef);
1.416     albertel 3151:     }
1.599     albertel 3152:     if ($value eq '__undef__') {
                   3153: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3154: 	$value=undef;
                   3155:     }
1.1319    damieng  3156:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3157:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3158:     return ($value,1);
                   3159: }
                   3160: 
                   3161: sub do_cache_new {
                   3162:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  3163:     my $remembered_id=$name.':'.$id;
1.849     albertel 3164:     $id=&make_key($name,$id);
1.599     albertel 3165:     my $setvalue=$value;
                   3166:     if (!defined($setvalue)) {
                   3167: 	$setvalue='__undef__';
                   3168:     }
1.623     albertel 3169:     if (!defined($time) ) {
                   3170: 	$time=600;
                   3171:     }
1.599     albertel 3172:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3173:     my $result = $memcache->set($id,$setvalue,$time);
                   3174:     if (! $result) {
1.872     albertel 3175: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3176: 	$memcache->disconnect_all();
1.872     albertel 3177:     }
1.600     albertel 3178:     # need to make a copy of $value
1.1319    damieng  3179:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3180:     return $value;
                   3181: }
                   3182: 
                   3183: sub make_room {
1.1319    damieng  3184:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3185: 
1.1319    damieng  3186:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3187:                                     : $value;
1.599     albertel 3188:     if ($to_remember<0) { return; }
1.1319    damieng  3189:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3190:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3191:     my $to_kick;
                   3192:     my $max_time=0;
                   3193:     foreach my $other (keys(%accessed)) {
                   3194: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3195: 	    $to_kick=$other;
                   3196: 	    $max_time=&tv_interval($accessed{$other});
                   3197: 	}
                   3198:     }
                   3199:     delete($remembered{$to_kick});
                   3200:     delete($accessed{$to_kick});
                   3201:     $kicks++;
                   3202:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3203:     return;
                   3204: }
                   3205: 
1.599     albertel 3206: sub purge_remembered {
1.604     albertel 3207:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3208:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3209:     undef(%remembered);
                   3210:     undef(%accessed);
1.428     albertel 3211: }
1.70      www      3212: # ------------------------------------- Read an entry from a user's environment
                   3213: 
                   3214: sub userenvironment {
                   3215:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3216:     my $items;
                   3217:     foreach my $item (@what) {
                   3218:         $items.=&escape($item).'&';
                   3219:     }
                   3220:     $items=~s/\&$//;
1.70      www      3221:     my %returnhash=();
1.1009    raeburn  3222:     my $uhome = &homeserver($unam,$udom);
                   3223:     unless ($uhome eq 'no_host') {
                   3224:         my @answer=split(/\&/, 
                   3225:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3226:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3227:             return %returnhash;
                   3228:         }
1.1009    raeburn  3229:         my $i;
                   3230:         for ($i=0;$i<=$#what;$i++) {
                   3231: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3232:         }
1.70      www      3233:     }
                   3234:     return %returnhash;
1.1       albertel 3235: }
                   3236: 
1.617     albertel 3237: # ---------------------------------------------------------- Get a studentphoto
                   3238: sub studentphoto {
                   3239:     my ($udom,$unam,$ext) = @_;
                   3240:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3241:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3242:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3243:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3244:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3245:             } else {
                   3246:                 my ($result,$perm_reqd)=
1.707     albertel 3247: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3248:                 if ($result eq 'ok') {
                   3249:                     if (!($perm_reqd eq 'yes')) {
                   3250:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3251:                     }
                   3252:                 }
                   3253:             }
                   3254:         }
                   3255:     } else {
                   3256:         my ($result,$perm_reqd) = 
1.707     albertel 3257: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3258:         if ($result eq 'ok') {
                   3259:             if (!($perm_reqd eq 'yes')) {
                   3260:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3261:             }
                   3262:         }
                   3263:     }
                   3264:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3265: }
                   3266: 
                   3267: sub retrievestudentphoto {
                   3268:     my ($udom,$unam,$ext,$type) = @_;
                   3269:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3270:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3271:     if ($ret eq 'ok') {
                   3272:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3273:         if ($type eq 'thumbnail') {
                   3274:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3275:         }
                   3276:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3277:         return $tokenurl;
                   3278:     } else {
                   3279:         if ($type eq 'thumbnail') {
                   3280:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3281:         } else { 
                   3282:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3283:         }
1.617     albertel 3284:     }
                   3285: }
                   3286: 
1.263     www      3287: # -------------------------------------------------------------------- New chat
                   3288: 
                   3289: sub chatsend {
1.724     raeburn  3290:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3291:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3292:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3293:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3294:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3295: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3296: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3297: }
                   3298: 
                   3299: # ------------------------------------------ Find current version of a resource
                   3300: 
                   3301: sub getversion {
                   3302:     my $fname=&clutter(shift);
1.1189    raeburn  3303:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3304:     return &currentversion(&filelocation('',$fname));
                   3305: }
                   3306: 
                   3307: sub currentversion {
                   3308:     my $fname=shift;
                   3309:     my $author=$fname;
                   3310:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3311:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3312:     my $home=&homeserver($uname,$udom);
1.292     www      3313:     if ($home eq 'no_host') { 
                   3314:         return -1; 
                   3315:     }
1.1112    www      3316:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3317:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3318: 	return -1;
                   3319:     }
1.1112    www      3320:     return $answer;
1.263     www      3321: }
                   3322: 
1.1111    www      3323: #
                   3324: # Return special version number of resource if set by override, empty otherwise
                   3325: #
                   3326: sub usedversion {
                   3327:     my $fname=shift;
                   3328:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3329:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3330:     if ($urlversion) { return $urlversion; }
                   3331:     return '';
                   3332: }
                   3333: 
1.1       albertel 3334: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3335: 
1.1       albertel 3336: sub subscribe {
                   3337:     my $fname=shift;
1.761     raeburn  3338:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3339:     $fname=~s/[\n\r]//g;
1.1       albertel 3340:     my $author=$fname;
                   3341:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3342:     my ($udom,$uname)=split(/\//,$author);
                   3343:     my $home=homeserver($uname,$udom);
1.335     albertel 3344:     if ($home eq 'no_host') {
                   3345:         return 'not_found';
1.1       albertel 3346:     }
                   3347:     my $answer=reply("sub:$fname",$home);
1.64      www      3348:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3349: 	$answer.=' by '.$home;
                   3350:     }
1.1       albertel 3351:     return $answer;
                   3352: }
                   3353:     
1.8       www      3354: # -------------------------------------------------------------- Replicate file
                   3355: 
                   3356: sub repcopy {
                   3357:     my $filename=shift;
1.23      www      3358:     $filename=~s/\/+/\//g;
1.1142    raeburn  3359:     my $londocroot = $perlvar{'lonDocRoot'};
                   3360:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3361:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3362:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3363: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3364: 	return &repcopy_userfile($filename);
                   3365:     }
1.532     albertel 3366:     $filename=~s/[\n\r]//g;
1.8       www      3367:     my $transname="$filename.in.transfer";
1.828     www      3368: # FIXME: this should flock
1.607     raeburn  3369:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3370:     my $remoteurl=subscribe($filename);
1.64      www      3371:     if ($remoteurl =~ /^con_lost by/) {
                   3372: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3373:            return 'unavailable';
1.8       www      3374:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3375: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3376: 	   return 'not_found';
1.64      www      3377:     } elsif ($remoteurl =~ /^rejected by/) {
                   3378: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3379:            return 'forbidden';
1.20      www      3380:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3381:            return 'ok';
1.8       www      3382:     } else {
1.290     www      3383:         my $author=$filename;
                   3384:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3385:         my ($udom,$uname)=split(/\//,$author);
                   3386:         my $home=homeserver($uname,$udom);
                   3387:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3388:            my @parts=split(/\//,$filename);
                   3389:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3390:            if ($path ne "$londocroot/res") {
1.8       www      3391:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3392: 	       return 'bad_request';
1.8       www      3393:            }
                   3394:            my $count;
                   3395:            for ($count=5;$count<$#parts;$count++) {
                   3396:                $path.="/$parts[$count]";
                   3397:                if ((-e $path)!=1) {
                   3398: 		   mkdir($path,0777);
                   3399:                }
                   3400:            }
                   3401:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3402:            my $response;
                   3403:            if ($remoteurl =~ m{/raw/}) {
                   3404:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3405:            } else {
                   3406:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3407:            }
1.8       www      3408:            if ($response->is_error()) {
                   3409: 	       unlink($transname);
                   3410:                my $message=$response->status_line;
1.672     albertel 3411:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3412:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3413:                return 'unavailable';
1.8       www      3414:            } else {
1.16      www      3415: 	       if ($remoteurl!~/\.meta$/) {
                   3416:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3417:                   my $mresponse;
                   3418:                   if ($remoteurl =~ m{/raw/}) {
                   3419:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3420:                   } else {
                   3421:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3422:                   }
1.16      www      3423:                   if ($mresponse->is_error()) {
                   3424: 		      unlink($filename.'.meta');
                   3425:                       &logthis(
1.672     albertel 3426:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3427:                   }
                   3428: 	       }
1.8       www      3429:                rename($transname,$filename);
1.607     raeburn  3430:                return 'ok';
1.8       www      3431:            }
1.290     www      3432:        }
1.8       www      3433:     }
1.330     www      3434: }
                   3435: 
1.1422    raeburn  3436: # ------------------------------------------------- Unsubscribe from a resource
                   3437: 
                   3438: sub unsubscribe {
                   3439:     my ($fname) = @_;
                   3440:     my $answer;
                   3441:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3442:     $fname=~s/[\n\r]//g;
                   3443:     my $author=$fname;
                   3444:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3445:     my ($udom,$uname)=split(/\//,$author);
                   3446:     my $home=homeserver($uname,$udom);
                   3447:     if ($home eq 'no_host') {
                   3448:         $answer = 'no_host';
                   3449:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3450:         $answer = 'home';
                   3451:     } else {
                   3452:         my $defdom = $perlvar{'lonDefDomain'};
                   3453:         if (&will_trust('content',$defdom,$udom)) {
                   3454:             $answer = reply("unsub:$fname",$home);
                   3455:         } else {
                   3456:             $answer = 'untrusted';
                   3457:         }
                   3458:     }
                   3459:     return $answer;
                   3460: }
                   3461: 
1.330     www      3462: # ------------------------------------------------ Get server side include body
                   3463: sub ssi_body {
1.381     albertel 3464:     my ($filelink,%form)=@_;
1.606     matthew  3465:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3466:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3467:     }
1.953     www      3468:     my $output='';
                   3469:     my $response;
1.980     raeburn  3470:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3471:        ($output,$response)=&externalssi($filelink);
1.953     www      3472:     } else {
1.1004    droeschl 3473:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3474:        $filelink .= 'inhibitmenu=yes';
1.953     www      3475:        ($output,$response)=&ssi($filelink,%form);
                   3476:     }
1.778     albertel 3477:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3478:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3479:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3480:     if (wantarray) {
                   3481:         return ($output, $response);
                   3482:     } else {
                   3483:         return $output;
                   3484:     }
1.8       www      3485: }
                   3486: 
1.15      www      3487: # --------------------------------------------------------- Server Side Include
                   3488: 
1.782     albertel 3489: sub absolute_url {
1.1447    raeburn  3490:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3491:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3492:     if ($host_name eq '') {
                   3493: 	$host_name = $ENV{'SERVER_NAME'};
                   3494:     }
1.1447    raeburn  3495:     if ($unalias) {
                   3496:         my $alias = &get_proxy_alias();
                   3497:         if ($alias eq $host_name) {
                   3498:             my $lonhost = $perlvar{'lonHostID'};
                   3499:             my $hostname = &hostname($lonhost);
                   3500:             my $lcproto; 
                   3501:             if (($keep_proto) || ($hostname eq '')) {
                   3502:                 $lcproto = $protocol;
                   3503:             } else {
                   3504:                 $lcproto = $protocol{$lonhost};
                   3505:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3506:                 $lcproto .= '://';
                   3507:             }
                   3508:             unless ($hostname eq '') {
                   3509:                 return $lcproto.$hostname;
                   3510:             }
                   3511:         }
                   3512:     }
1.782     albertel 3513:     return $protocol.$host_name;
                   3514: }
                   3515: 
1.942     foxr     3516: #
                   3517: #   Server side include.
                   3518: # Parameters:
                   3519: #  fn     Possibly encrypted resource name/id.
                   3520: #  form   Hash that describes how the rendering should be done
                   3521: #         and other things.
1.944     foxr     3522: # Returns:
1.950     raeburn  3523: #   Scalar context: The content of the response.
                   3524: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3525: #     
1.15      www      3526: sub ssi {
                   3527: 
1.944     foxr     3528:     my ($fn,%form)=@_;
1.1447    raeburn  3529:     my ($host,$request,$response);
                   3530:     $host = &absolute_url('',1);
1.711     albertel 3531: 
                   3532:     $form{'no_update_last_known'}=1;
1.895     albertel 3533:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3534:     if (%form) {
1.1447    raeburn  3535:       $request=new HTTP::Request('POST',$host.$fn);
1.1272    droeschl 3536:       $request->content(join('&',map { 
                   3537:             my $name = escape($_);
                   3538:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3539:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3540:             : &escape($form{$_}) );    
                   3541:         } keys(%form)));
1.23      www      3542:     } else {
1.1447    raeburn  3543:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3544:     }
                   3545: 
1.15      www      3546:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3547:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3548:     my $islocal;
                   3549:     if (($env{'request.course.id'}) &&
                   3550:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3551:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3552:         ($form{'grade_symb'} ne '') &&
                   3553:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3554:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3555:         $islocal = 1;
                   3556:     }
1.1447    raeburn  3557:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
                   3558:                                              '','','',$islocal);
1.1182    foxr     3559: 
1.944     foxr     3560:     if (wantarray) {
1.1345    raeburn  3561: 	return ($response->content, $response);
1.944     foxr     3562:     } else {
1.1345    raeburn  3563: 	return $response->content;
1.942     foxr     3564:     }
1.324     www      3565: }
                   3566: 
                   3567: sub externalssi {
                   3568:     my ($url)=@_;
                   3569:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3570:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3571:     if (wantarray) {
                   3572:         return ($response->content, $response);
                   3573:     } else {
                   3574:         return $response->content;
                   3575:     }
1.15      www      3576: }
1.254     www      3577: 
1.1354    raeburn  3578: 
                   3579: # If the local copy of a replicated resource is outdated, trigger a  
                   3580: # connection from the homeserver to flush the delayed queue. If no update 
                   3581: # happens, remove local copies of outdated resource (and corresponding
                   3582: # metadata file).
                   3583: 
1.1352    raeburn  3584: sub remove_stale_resfile {
                   3585:     my ($url) = @_;
1.1354    raeburn  3586:     my $removed;
1.1352    raeburn  3587:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3588:         my $audom = $1;
                   3589:         my $auname = $2;
1.1353    raeburn  3590:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3591:             my $homeserver = &homeserver($auname,$audom);
                   3592:             unless (($homeserver eq 'no_host') ||
                   3593:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3594:                 my $fname = &filelocation('',$url);
                   3595:                 if (-e $fname) {
                   3596:                     my $hostname = &hostname($homeserver);
                   3597:                     if ($hostname) {
1.1397    raeburn  3598:                         my $protocol = $protocol{$homeserver};
                   3599:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3600:                         my $uri = &declutter($url);
                   3601:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3602:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3603:                         if ($response->is_success()) {
                   3604:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3605:                             my $locmodtime = (stat($fname))[9];
                   3606:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3607:                                 my $stale;
                   3608:                                 my $answer = &reply('pong',$homeserver);
                   3609:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3610:                                     sleep(0.2);
                   3611:                                     $locmodtime = (stat($fname))[9];
                   3612:                                     if ($locmodtime < $remmodtime) {
                   3613:                                         my $posstransfer = $fname.'.in.transfer';
                   3614:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3615:                                             $removed = 1;
                   3616:                                         } else {
                   3617:                                             $stale = 1;
                   3618:                                         }
                   3619:                                     } else {
                   3620:                                         $removed = 1;
                   3621:                                     }
                   3622:                                 } else {
                   3623:                                     $stale = 1;
                   3624:                                 }
                   3625:                                 if ($stale) {
1.1421    raeburn  3626:                                     if (unlink($fname)) {
                   3627:                                         if ($uri!~/\.meta$/) {
                   3628:                                             if (-e $fname.'.meta') {
                   3629:                                                 unlink($fname.'.meta');
                   3630:                                             }
                   3631:                                         }
1.1422    raeburn  3632:                                         my $unsubresult = &unsubscribe($fname);
                   3633:                                         unless ($unsubresult eq 'ok') {
                   3634:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3635:                                         }
1.1421    raeburn  3636:                                         $removed = 1;
1.1354    raeburn  3637:                                     }
1.1352    raeburn  3638:                                 }
                   3639:                             }
                   3640:                         }
                   3641:                     }
                   3642:                 }
                   3643:             }
                   3644:         }
                   3645:     }
1.1354    raeburn  3646:     return $removed;
1.1352    raeburn  3647: }
                   3648: 
1.492     albertel 3649: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3650: 
                   3651: sub allowuploaded {
                   3652:     my ($srcurl,$url)=@_;
                   3653:     $url=&clutter(&declutter($url));
                   3654:     my $dir=$url;
                   3655:     $dir=~s/\/[^\/]+$//;
                   3656:     my %httpref=();
                   3657:     my $httpurl=&hreflocation('',$url);
                   3658:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3659:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3660: }
1.477     raeburn  3661: 
1.1193    raeburn  3662: #
                   3663: # Determine if the current user should be able to edit a particular resource,
                   3664: # when viewing in course context.
                   3665: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3666: #     Functions.
                   3667: # (b) When displaying folder contents in course editor, used to determine if
                   3668: #     "Edit" link will be displayed alongside resource.
                   3669: #
1.1196    raeburn  3670: #  input: six args -- filename (decluttered), course number, course domain,
                   3671: #                   url, symb (if registered) and group (if this is a group
                   3672: #                   item -- e.g., bulletin board, group page etc.).
                   3673: #  output: array of five scalars -- 
1.1193    raeburn  3674: #          $cfile -- url for file editing if editable on current server
                   3675: #          $home -- homeserver of resource (i.e., for author if published,
                   3676: #                                           or course if uploaded.).
                   3677: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3678: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3679: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3680: #
                   3681: 
                   3682: sub can_edit_resource {
1.1194    raeburn  3683:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3684:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3685: #
                   3686: # For aboutme pages user can only edit his/her own.
                   3687: #
1.1199    raeburn  3688:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3689:         my ($sdom,$sname) = ($1,$2);
                   3690:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3691:             $home = $env{'user.home'};
                   3692:             $cfile = $resurl;
                   3693:             if ($env{'form.forceedit'}) {
                   3694:                 $forceview = 1;
                   3695:             } else {
                   3696:                 $forceedit = 1;
                   3697:             }
                   3698:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3699:         } else {
                   3700:             return;
                   3701:         }
                   3702:     }
                   3703: 
                   3704:     if ($env{'request.course.id'}) {
                   3705:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3706:         if ($group ne '') {
                   3707: # if this is a group homepage or group bulletin board, check group privs
                   3708:             my $allowed = 0;
1.1197    raeburn  3709:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3710:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3711:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3712:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3713:                     $allowed = 1;
                   3714:                 }
1.1197    raeburn  3715:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3716:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3717:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3718:                     $allowed = 1;
                   3719:                 }
                   3720:             }
                   3721:             if ($allowed) {
                   3722:                 $home=&homeserver($cnum,$cdom);
                   3723:                 if ($env{'form.forceedit'}) {
                   3724:                     $forceview = 1;
                   3725:                 } else {
                   3726:                     $forceedit = 1;
                   3727:                 }
                   3728:                 $cfile = $resurl;
                   3729:             } else {
                   3730:                 return;
                   3731:             }
                   3732:         } else {
1.1208    raeburn  3733:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3734:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3735:                     return;
                   3736:                 }
                   3737:             } elsif (!$crsedit) {
1.1194    raeburn  3738: #
                   3739: # No edit allowed where CC has switched to student role.
                   3740: #
                   3741:                 return;
                   3742:             }
                   3743:         }
                   3744:     }
                   3745: 
1.1193    raeburn  3746:     if ($file ne '') {
                   3747:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3748:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3749:                 $uploaded = 1;
                   3750:                 $incourse = 1;
1.1193    raeburn  3751:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3752:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3753:                     if ($env{'form.forceedit'}) {
                   3754:                         $forceview = 1;
                   3755:                     } else {
                   3756:                         $forceedit = 1;
                   3757:                     }
1.1194    raeburn  3758:                 }
                   3759:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3760:                 $incourse = 1;
                   3761:                 if ($env{'form.forceedit'}) {
                   3762:                     $forceview = 1;
                   3763:                 } else {
                   3764:                     $forceedit = 1;
                   3765:                 }
                   3766:                 $cfile = $resurl;
                   3767:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3768:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3769:                     $incourse = 1;
                   3770:                     if ($env{'form.forceedit'}) {
                   3771:                         $forceview = 1;
                   3772:                     } else {
                   3773:                         $forceedit = 1;
                   3774:                     }
                   3775:                     $cfile = $resurl;
1.1199    raeburn  3776:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3777:                     $incourse = 1;
                   3778:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3779:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3780:                     $incourse = 1;
1.1199    raeburn  3781:                     if ($env{'form.forceedit'}) {
                   3782:                         $forceview = 1;
                   3783:                     } else {
                   3784:                         $forceedit = 1;
                   3785:                     }
                   3786:                     $cfile = $resurl;
1.1419    raeburn  3787:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3788:                     my ($map,$id,$res) = &decode_symb($symb);
                   3789:                     if ($map =~ /\.page$/) {
                   3790:                         $incourse = 1;
                   3791:                         if ($env{'form.forceedit'}) {
                   3792:                             $forceview = 1;
                   3793:                             $cfile = $map;
                   3794:                         } else {
                   3795:                             $forceedit = 1;
                   3796:                             $cfile =  '/adm/wrapper'.$resurl;
                   3797:                         }
                   3798:                     }
1.1343    raeburn  3799:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3800:                     $incourse = 1;
                   3801:                     if ($env{'form.forceedit'}) {
                   3802:                         $forceview = 1;
                   3803:                     } else {
                   3804:                         $forceedit = 1;
                   3805:                     }
                   3806:                     $cfile = $resurl;
1.1208    raeburn  3807:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3808:                     $incourse = 1;
                   3809:                     if ($env{'form.forceedit'}) {
                   3810:                         $forceview = 1;
                   3811:                     } else {
                   3812:                         $forceedit = 1;
                   3813:                     }
                   3814:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3815:                 }
                   3816:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3817:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3818:                 if (&is_on_map($template)) { 
                   3819:                     $incourse = 1;
                   3820:                     $forceview = 1;
                   3821:                     $cfile = $template;
1.1193    raeburn  3822:                 }
1.1199    raeburn  3823:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418    raeburn  3824:                 $incourse = 1;
                   3825:                 if ($env{'form.forceedit'}) {
                   3826:                     $forceview = 1;
                   3827:                 } else {
                   3828:                     $forceedit = 1;
                   3829:                 }
                   3830:                 $cfile = $resurl;
1.1343    raeburn  3831:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3832:                 $incourse = 1;
                   3833:                 if ($env{'form.forceedit'}) {
                   3834:                     $forceview = 1;
                   3835:                 } else {
                   3836:                     $forceedit = 1;
                   3837:                 }
                   3838:                 $cfile = $resurl;
1.1199    raeburn  3839:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3840:                 $incourse = 1;
                   3841:                 $forceview = 1;
                   3842:                 if ($symb) {
                   3843:                     my ($map,$id,$res)=&decode_symb($symb);
                   3844:                     $env{'request.symb'} = $symb;
                   3845:                     $cfile = &clutter($res);
                   3846:                 } else {
                   3847:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3848:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3849:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3850:                         $cfile = '/adm/wrapper'.$escfile;
                   3851:                     } else {
                   3852:                         $escfile =~ s{^http://}{};
                   3853:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3854:                     }
1.1199    raeburn  3855:                 }
1.1234    raeburn  3856:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3857:                 if ($env{'form.forceedit'}) {
                   3858:                     $forceview = 1;
                   3859:                 } else {
                   3860:                     $forceedit = 1;
                   3861:                 }
                   3862:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3863:             }
                   3864:         }
1.1194    raeburn  3865:         if ($uploaded || $incourse) {
                   3866:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3867:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3868:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3869:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3870:             # Check that the user has permission to edit this resource
                   3871:             my $setpriv = 1;
                   3872:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3873:             if (defined($cfudom)) {
                   3874:                 $home=&homeserver($cfuname,$cfudom);
                   3875:                 $cfile=$file;
                   3876:             }
                   3877:         }
1.1194    raeburn  3878:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3879:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3880:             my @ids=&current_machine_ids();
                   3881:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3882:                 $switchserver=1;
                   3883:             }
                   3884:         }
                   3885:     }
1.1194    raeburn  3886:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3887: }
                   3888: 
                   3889: sub is_course_upload {
                   3890:     my ($file,$cnum,$cdom) = @_;
                   3891:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3892:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3893:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3894:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3895:         return 1;
                   3896:     }
                   3897:     return;
                   3898: }
                   3899: 
1.1194    raeburn  3900: sub in_course {
1.1195    raeburn  3901:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3902:     if ($hideprivileged) {
                   3903:         my $skipuser;
1.1219    raeburn  3904:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3905:         my @possdoms = ($cdom);  
                   3906:         if ($coursehash{'checkforpriv'}) { 
                   3907:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3908:         }
                   3909:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3910:             $skipuser = 1;
                   3911:             if ($coursehash{'nothideprivileged'}) {
                   3912:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3913:                     my $user;
                   3914:                     if ($item =~ /:/) {
                   3915:                         $user = $item;
                   3916:                     } else {
                   3917:                         $user = join(':',split(/[\@]/,$item));
                   3918:                     }
                   3919:                     if ($user eq $uname.':'.$udom) {
                   3920:                         undef($skipuser);
                   3921:                         last;
                   3922:                     }
                   3923:                 }
                   3924:             }
                   3925:             if ($skipuser) {
                   3926:                 return 0;
                   3927:             }
                   3928:         }
                   3929:     }
1.1194    raeburn  3930:     $type ||= 'any';
                   3931:     if (!defined($cdom) || !defined($cnum)) {
                   3932:         my $cid  = $env{'request.course.id'};
                   3933:         $cdom = $env{'course.'.$cid.'.domain'};
                   3934:         $cnum = $env{'course.'.$cid.'.num'};
                   3935:     }
                   3936:     my $typesref;
1.1195    raeburn  3937:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3938:         $typesref = ['active','previous','future'];
                   3939:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3940:         $typesref = [$type];
                   3941:     }
                   3942:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3943:                               $typesref,undef,[$cdom]);
                   3944:     my ($tmp) = keys(%roles);
                   3945:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3946:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3947:     if (@course_roles > 0) {
                   3948:         return 1;
                   3949:     }
                   3950:     return 0;
                   3951: }
                   3952: 
1.478     albertel 3953: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3954: # input: action, courseID, current domain, intended
1.637     raeburn  3955: #        path to file, source of file, instruction to parse file for objects,
                   3956: #        ref to hash for embedded objects,
                   3957: #        ref to hash for codebase of java objects.
1.1095    raeburn  3958: #        reference to scalar to accommodate mime type determined
                   3959: #          from File::MMagic if $parser = parse.
1.637     raeburn  3960: #
1.485     raeburn  3961: # output: url to file (if action was uploaddoc), 
                   3962: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3963: #
1.478     albertel 3964: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3965: # course.
1.477     raeburn  3966: #
1.478     albertel 3967: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3968: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3969: #          course's home server.
1.477     raeburn  3970: #
1.478     albertel 3971: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3972: #          be copied from $source (current location) to 
                   3973: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3974: #         and will then be copied to
                   3975: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3976: #         course's home server.
1.485     raeburn  3977: #
1.481     raeburn  3978: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3979: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3980: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3981: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3982: #         in course's home server.
1.637     raeburn  3983: #
1.477     raeburn  3984: 
                   3985: sub process_coursefile {
1.1095    raeburn  3986:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3987:         $mimetype)=@_;
1.477     raeburn  3988:     my $fetchresult;
1.638     albertel 3989:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3990:     if ($action eq 'propagate') {
1.638     albertel 3991:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3992: 			     $home);
1.481     raeburn  3993:     } else {
1.477     raeburn  3994:         my $fpath = '';
                   3995:         my $fname = $file;
1.478     albertel 3996:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3997:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3998:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3999:         if ($action eq 'copy') {
                   4000:             if ($source eq '') {
                   4001:                 $fetchresult = 'no source file';
                   4002:                 return $fetchresult;
                   4003:             } else {
                   4004:                 my $destination = $filepath.'/'.$fname;
                   4005:                 rename($source,$destination);
                   4006:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4007:                                  $home);
1.481     raeburn  4008:             }
                   4009:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  4010:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 4011:             print $fh $env{'form.'.$source};
1.481     raeburn  4012:             close($fh);
1.637     raeburn  4013:             if ($parser eq 'parse') {
1.1024    raeburn  4014:                 my $mm = new File::MMagic;
1.1095    raeburn  4015:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   4016:                 if ($type eq 'text/html') {
1.1024    raeburn  4017:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   4018:                     unless ($parse_result eq 'ok') {
                   4019:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   4020:                     }
1.637     raeburn  4021:                 }
1.1095    raeburn  4022:                 if (ref($mimetype)) {
                   4023:                     $$mimetype = $type;
                   4024:                 } 
1.637     raeburn  4025:             }
1.477     raeburn  4026:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4027:                                  $home);
1.481     raeburn  4028:             if ($fetchresult eq 'ok') {
                   4029:                 return '/uploaded/'.$fpath.'/'.$fname;
                   4030:             } else {
                   4031:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4032:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  4033:                 return '/adm/notfound.html';
                   4034:             }
1.477     raeburn  4035:         }
                   4036:     }
1.485     raeburn  4037:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  4038:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4039:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  4040:     }
                   4041:     return $fetchresult;
                   4042: }
                   4043: 
1.637     raeburn  4044: sub build_filepath {
                   4045:     my ($fpath) = @_;
                   4046:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   4047:     unless ($fpath eq '') {
                   4048:         my @parts=split('/',$fpath);
                   4049:         foreach my $part (@parts) {
                   4050:             $filepath.= '/'.$part;
                   4051:             if ((-e $filepath)!=1) {
                   4052:                 mkdir($filepath,0777);
                   4053:             }
                   4054:         }
                   4055:     }
                   4056:     return $filepath;
                   4057: }
                   4058: 
                   4059: sub store_edited_file {
1.638     albertel 4060:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4061:     my $file = $primary_url;
                   4062:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4063:     my $fpath = '';
                   4064:     my $fname = $file;
                   4065:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4066:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4067:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  4068:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4069:     print $fh $content;
                   4070:     close($fh);
1.638     albertel 4071:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4072:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4073: 			  $home);
1.637     raeburn  4074:     if ($$fetchresult eq 'ok') {
                   4075:         return '/uploaded/'.$fpath.'/'.$fname;
                   4076:     } else {
1.638     albertel 4077:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4078: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4079:         return '/adm/notfound.html';
                   4080:     }
                   4081: }
                   4082: 
1.531     albertel 4083: sub clean_filename {
1.831     albertel 4084:     my ($fname,$args)=@_;
1.315     www      4085: # Replace Windows backslashes by forward slashes
1.257     www      4086:     $fname=~s/\\/\//g;
1.831     albertel 4087:     if (!$args->{'keep_path'}) {
                   4088:         # Get rid of everything but the actual filename
                   4089: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4090:     }
1.315     www      4091: # Replace spaces by underscores
                   4092:     $fname=~s/\s+/\_/g;
1.1406    raeburn  4093: # Transliterate non-ascii text to ascii
                   4094:     my $lang = &Apache::lonlocal::current_language();
                   4095:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4096: # Replace all other weird characters by nothing
1.831     albertel 4097:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4098: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4099: # numbers
                   4100:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443    raeburn  4101: # Replace three or more adjacent underscores with one for consistency 
                   4102: # with loncfile::filename_check() so complete url can be extracted by
                   4103: # lonnet::decode_symb()
                   4104:     $fname=~s/_{3,}/_/g;
1.531     albertel 4105:     return $fname;
                   4106: }
1.1406    raeburn  4107: 
1.1051    raeburn  4108: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4109: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4110: # image with the same aspect ratio as the original, but with dimensions which do 
                   4111: # not exceed $resizewidth and $resizeheight.
                   4112:  
1.984     neumanie 4113: sub resizeImage {
1.1051    raeburn  4114:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4115:     my $ima = Image::Magick->new;
                   4116:     my $resized;
                   4117:     if (-e $img_path) {
                   4118:         $ima->Read($img_path);
                   4119:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4120:             my $width = $ima->Get('width');
                   4121:             my $height = $ima->Get('height');
                   4122:             if ($width > $resizewidth) {
                   4123: 	        my $factor = $width/$resizewidth;
                   4124:                 my $newheight = $height/$factor;
                   4125:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4126:                 $resized = 1;
                   4127:             }
                   4128:         }
                   4129:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4130:             my $width = $ima->Get('width');
                   4131:             my $height = $ima->Get('height');
                   4132:             if ($height > $resizeheight) {
                   4133:                 my $factor = $height/$resizeheight;
                   4134:                 my $newwidth = $width/$factor;
                   4135:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4136:                 $resized = 1;
                   4137:             }
                   4138:         }
                   4139:         if ($resized) {
                   4140:             $ima->Write($img_path);
                   4141:         }
                   4142:     }
                   4143:     return;
1.977     amueller 4144: }
                   4145: 
1.608     albertel 4146: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4147: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4148: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4149: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1401    raeburn  4150: #                                    canceloverwrite, scantron or ''.
1.1090    raeburn  4151: #                   if 'coursedoc': upload to the current course
                   4152: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4153: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4154: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4155: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  4156: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4157: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4158: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   4159: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4160: #        $allfiles - reference to hash for embedded objects
                   4161: #        $codebase - reference to hash for codebase of java objects
                   4162: #        $desuname - username for permanent storage of uploaded file
                   4163: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  4164: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4165: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4166: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4167: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4168: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4169: #                    from File::MMagic.
1.858     raeburn  4170: # 
1.686     albertel 4171: # output: url of file in userspace, or error: <message> 
                   4172: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4173: 
1.531     albertel 4174: sub userfileupload {
1.1090    raeburn  4175:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4176:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4177:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4178:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4179:     $fname=&clean_filename($fname);
1.1090    raeburn  4180:     # See if there is anything left
1.257     www      4181:     unless ($fname) { return 'error: no uploaded file'; }
1.1406    raeburn  4182:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4183:     if ($fname =~ /^\./) {
                   4184:         my ($s,$usec) = &gettimeofday();
                   4185:         while (length($usec) < 6) {
                   4186:             $usec = '0'.$usec;
                   4187:         }
                   4188:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4189:     }
1.1090    raeburn  4190:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4191:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4192:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4193:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4194:         my $now = time;
1.1090    raeburn  4195:         my $filepath;
1.1095    raeburn  4196:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4197:              $filepath = 'tmp/helprequests/'.$now;
                   4198:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4199:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4200:                          '_'.$env{'user.domain'}.'/pending';
                   4201:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4202:             my ($docuname,$docudom);
1.1350    raeburn  4203:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4204:                 $docudom = $destudom;
                   4205:             } else {
                   4206:                 $docudom = $env{'user.domain'};
                   4207:             }
1.1350    raeburn  4208:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  4209:                 $docuname = $destuname;
                   4210:             } else {
                   4211:                 $docuname = $env{'user.name'};
                   4212:             }
                   4213:             if (exists($env{'form.group'})) {
                   4214:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4215:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4216:             }
                   4217:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4218:             if ($context eq 'canceloverwrite') {
                   4219:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4220:                 if (-e  $tempfile) {
                   4221:                     my @info = stat($tempfile);
                   4222:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4223:                         unlink($tempfile);
                   4224:                     }
                   4225:                 }
                   4226:                 return;
1.523     raeburn  4227:             }
                   4228:         }
1.1090    raeburn  4229:         # Create the directory if not present
1.741     raeburn  4230:         my @parts=split(/\//,$filepath);
                   4231:         my $fullpath = $perlvar{'lonDaemons'};
                   4232:         for (my $i=0;$i<@parts;$i++) {
                   4233:             $fullpath .= '/'.$parts[$i];
                   4234:             if ((-e $fullpath)!=1) {
                   4235:                 mkdir($fullpath,0777);
                   4236:             }
                   4237:         }
1.1359    raeburn  4238:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4239:         print $fh $env{'form.'.$formname};
                   4240:         close($fh);
1.1090    raeburn  4241:         if ($context eq 'existingfile') {
                   4242:             my @info = stat($fullpath.'/'.$fname);
                   4243:             return ($fullpath.'/'.$fname,$info[9]);
                   4244:         } else {
                   4245:             return $fullpath.'/'.$fname;
                   4246:         }
1.523     raeburn  4247:     }
1.995     raeburn  4248:     if ($subdir eq 'scantron') {
                   4249:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4250:     } else {
1.995     raeburn  4251:         $fname="$subdir/$fname";
                   4252:     }
1.1090    raeburn  4253:     if ($context eq 'coursedoc') {
1.638     albertel 4254: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4255: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4256:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4257:             return &finishuserfileupload($docuname,$docudom,
                   4258: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4259: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4260:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4261:         } else {
1.1218    raeburn  4262:             if ($env{'form.folder'}) {
                   4263:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4264:             }
1.638     albertel 4265:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4266: 				       $fname,$formname,$parser,
1.1095    raeburn  4267: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4268:         }
1.719     banghart 4269:     } elsif (defined($destuname)) {
                   4270:         my $docuname=$destuname;
                   4271:         my $docudom=$destudom;
1.860     raeburn  4272: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4273: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4274:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4275:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4276:     } else {
1.638     albertel 4277:         my $docuname=$env{'user.name'};
                   4278:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4279:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4280:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4281:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4282:         }
1.860     raeburn  4283: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4284: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4285:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4286:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4287:     }
1.271     www      4288: }
                   4289: 
                   4290: sub finishuserfileupload {
1.860     raeburn  4291:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4292:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4293:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4294:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4295:   
1.860     raeburn  4296:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4297:     $file=$fname;
                   4298:     if ($fname=~m|/|) {
                   4299:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4300: 	$path.=$fnamepath.'/';
                   4301:     }
1.259     www      4302:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4303:     my $count;
                   4304:     for ($count=4;$count<=$#parts;$count++) {
                   4305:         $filepath.="/$parts[$count]";
                   4306:         if ((-e $filepath)!=1) {
                   4307: 	    mkdir($filepath,0777);
                   4308:         }
                   4309:     }
1.984     neumanie 4310: 
1.258     www      4311: # Save the file
                   4312:     {
1.1359    raeburn  4313: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4314: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4315: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4316: 	    return '/adm/notfound.html';
                   4317: 	}
1.1090    raeburn  4318:         if ($context eq 'overwrite') {
1.1117    foxr     4319:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4320:             my $target = $filepath.'/'.$file;
                   4321:             if (-e $source) {
                   4322:                 my @info = stat($source);
                   4323:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4324:                     unless (&File::Copy::move($source,$target)) {
                   4325:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4326:                         return "Moving from $source failed";
                   4327:                     }
                   4328:                 } else {
                   4329:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4330:                 }
                   4331:             } else {
                   4332:                 return "Temporary file: $source missing";
                   4333:             }
                   4334:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4335: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4336: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4337: 	    return '/adm/notfound.html';
                   4338: 	}
1.570     albertel 4339: 	close(FH);
1.1051    raeburn  4340:         if ($resizewidth && $resizeheight) {
                   4341:             my $mm = new File::MMagic;
                   4342:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4343:             if ($mime_type =~ m{^image/}) {
                   4344: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4345:             }  
1.977     amueller 4346: 	}
1.258     www      4347:     }
1.1152    raeburn  4348:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4349:         if (ref($mimetype)) {
                   4350:             if ($$mimetype eq '') {
                   4351:                 my $mm = new File::MMagic;
                   4352:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4353:                 $$mimetype = $type;
                   4354:             }
                   4355:         }
                   4356:     }
1.1401    raeburn  4357:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4358:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4359:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4360:                                                        $allfiles,$codebase);
                   4361:             unless ($parse_result eq 'ok') {
                   4362:                 &logthis('Failed to parse '.$filepath.$file.
                   4363: 	   	         ' for embedded media: '.$parse_result); 
                   4364:             }
1.637     raeburn  4365:         }
1.1401    raeburn  4366:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4367:         my $format = $env{'form.scantron_format'};
                   4368:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4369:     }
1.860     raeburn  4370:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4371:         my $input = $filepath.'/'.$file;
                   4372:         my $output = $filepath.'/'.'tn-'.$file;
                   4373:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4374:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4375:         system({$args[0]} @args);
1.860     raeburn  4376:         if (-e $filepath.'/'.'tn-'.$file) {
                   4377:             $fetchthumb  = 1; 
                   4378:         }
                   4379:     }
1.858     raeburn  4380:  
1.259     www      4381: # Notify homeserver to grep it
                   4382: #
1.984     neumanie 4383:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4384:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4385:     if ($fetchresult eq 'ok') {
1.860     raeburn  4386:         if ($fetchthumb) {
                   4387:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4388:             if ($thumbresult ne 'ok') {
                   4389:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4390:                          $docuhome.': '.$thumbresult);
                   4391:             }
                   4392:         }
1.259     www      4393: #
1.258     www      4394: # Return the URL to it
1.494     albertel 4395:         return '/uploaded/'.$path.$file;
1.263     www      4396:     } else {
1.494     albertel 4397:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4398: 		 ': '.$fetchresult);
1.263     www      4399:         return '/adm/notfound.html';
1.858     raeburn  4400:     }
1.493     albertel 4401: }
                   4402: 
1.637     raeburn  4403: sub extract_embedded_items {
1.961     raeburn  4404:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4405:     my @state = ();
1.1164    raeburn  4406:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4407:     my %javafiles = (
                   4408:                       codebase => '',
                   4409:                       code => '',
                   4410:                       archive => ''
                   4411:                     );
                   4412:     my %mediafiles = (
                   4413:                       src => '',
                   4414:                       movie => '',
                   4415:                      );
1.648     raeburn  4416:     my $p;
                   4417:     if ($content) {
                   4418:         $p = HTML::LCParser->new($content);
                   4419:     } else {
1.961     raeburn  4420:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4421:     }
1.641     albertel 4422:     while (my $t=$p->get_token()) {
1.640     albertel 4423: 	if ($t->[0] eq 'S') {
                   4424: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4425: 	    push(@state, $tagname);
1.648     raeburn  4426:             if (lc($tagname) eq 'allow') {
                   4427:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4428:             }
1.640     albertel 4429: 	    if (lc($tagname) eq 'img') {
                   4430: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4431: 	    }
1.886     albertel 4432: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4433:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4434:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4435:                 }
1.886     albertel 4436: 	    }
1.645     raeburn  4437:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4438:                 my $src;
1.645     raeburn  4439:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4440:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4441:                 } else {
1.1164    raeburn  4442:                     if ($attr->{'src'} ne '') {
                   4443:                         $src = $attr->{'src'};
                   4444:                         &add_filetype($allfiles,$src,'src');
                   4445:                     }
                   4446:                 }
                   4447:                 my $text = $p->get_trimmed_text();
                   4448:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4449:                     my @swfargs = split(/,/,$1);
                   4450:                     foreach my $item (@swfargs) {
                   4451:                         $item =~ s/["']//g;
                   4452:                         $item =~ s/^\s+//;
                   4453:                         $item =~ s/\s+$//;
                   4454:                     }
                   4455:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4456:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4457:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4458:                         } else {
                   4459:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4460:                         }
                   4461:                     }
1.645     raeburn  4462:                 }
                   4463:             }
                   4464:             if (lc($tagname) eq 'link') {
                   4465:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4466:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4467:                 }
                   4468:             }
1.640     albertel 4469: 	    if (lc($tagname) eq 'object' ||
                   4470: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4471: 		foreach my $item (keys(%javafiles)) {
                   4472: 		    $javafiles{$item} = '';
                   4473: 		}
1.1164    raeburn  4474:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4475:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4476:                 }
1.640     albertel 4477: 	    }
                   4478: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4479: 		my $name = lc($attr->{'name'});
                   4480: 		foreach my $item (keys(%javafiles)) {
                   4481: 		    if ($name eq $item) {
                   4482: 			$javafiles{$item} = $attr->{'value'};
                   4483: 			last;
                   4484: 		    }
                   4485: 		}
1.1164    raeburn  4486:                 my $pathfrom;
1.640     albertel 4487: 		foreach my $item (keys(%mediafiles)) {
                   4488: 		    if ($name eq $item) {
1.1164    raeburn  4489:                         $pathfrom = $attr->{'value'};
                   4490:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4491: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4492: 			last;
                   4493: 		    }
                   4494: 		}
1.1164    raeburn  4495:                 if ($name eq 'flashvars') {
                   4496:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4497:                 }
                   4498:                 if ($pathfrom ne '') {
                   4499:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4500:                                          $pathfrom);
                   4501:                 }
1.640     albertel 4502: 	    }
                   4503: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4504: 		foreach my $item (keys(%javafiles)) {
                   4505: 		    if ($attr->{$item}) {
                   4506: 			$javafiles{$item} = $attr->{$item};
                   4507: 			last;
                   4508: 		    }
                   4509: 		}
                   4510: 		foreach my $item (keys(%mediafiles)) {
                   4511: 		    if ($attr->{$item}) {
                   4512: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4513: 			last;
                   4514: 		    }
                   4515: 		}
1.1164    raeburn  4516:                 if (lc($tagname) eq 'embed') {
                   4517:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4518:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4519:                                              $attr->{'src'});
                   4520:                     }
                   4521:                 }
1.640     albertel 4522: 	    }
1.1243    raeburn  4523:             if (lc($tagname) eq 'iframe') {
                   4524:                 my $src = $attr->{'src'} ;
                   4525:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4526:                     &add_filetype($allfiles,$src,'src');
                   4527:                 } elsif ($src =~ m{^/}) {
                   4528:                     if ($env{'request.course.id'}) {
                   4529:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4530:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4531:                         my $url = &hreflocation('',$fullpath);
                   4532:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4533:                             my $relpath = $1;
                   4534:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4535:                                 &add_filetype($allfiles,$1,'src');
                   4536:                             }
                   4537:                         }
                   4538:                     }
                   4539:                 }
                   4540:             }
1.1164    raeburn  4541:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4542:                 pop(@state);
1.1164    raeburn  4543:             }
1.640     albertel 4544: 	} elsif ($t->[0] eq 'E') {
                   4545: 	    my ($tagname) = ($t->[1]);
                   4546: 	    if ($javafiles{'codebase'} ne '') {
                   4547: 		$javafiles{'codebase'} .= '/';
                   4548: 	    }  
                   4549: 	    if (lc($tagname) eq 'applet' ||
                   4550: 		lc($tagname) eq 'object' ||
                   4551: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4552: 		) {
                   4553: 		foreach my $item (keys(%javafiles)) {
                   4554: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4555: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4556: 			&add_filetype($allfiles,$file,$item);
                   4557: 		    }
                   4558: 		}
                   4559: 	    } 
                   4560: 	    pop @state;
                   4561: 	}
                   4562:     }
1.1164    raeburn  4563:     foreach my $id (sort(keys(%flashvars))) {
                   4564:         if ($shockwave{$id} ne '') {
                   4565:             my @pairs = split(/\&/,$flashvars{$id});
                   4566:             foreach my $pair (@pairs) {
                   4567:                 my ($key,$value) = split(/\=/,$pair);
                   4568:                 if ($key eq 'thumb') {
                   4569:                     &add_filetype($allfiles,$value,$key);
                   4570:                 } elsif ($key eq 'content') {
                   4571:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4572:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4573:                     if ($ext ne '') {
                   4574:                         &add_filetype($allfiles,$path.$value,$ext);
                   4575:                     }
                   4576:                 }
                   4577:             }
                   4578:         }
                   4579:     }
1.637     raeburn  4580:     return 'ok';
                   4581: }
                   4582: 
1.639     albertel 4583: sub add_filetype {
                   4584:     my ($allfiles,$file,$type)=@_;
                   4585:     if (exists($allfiles->{$file})) {
                   4586: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4587: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4588: 	}
                   4589:     } else {
                   4590: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4591:     }
                   4592: }
                   4593: 
1.1164    raeburn  4594: sub embedded_dependency {
                   4595:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4596:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4597:         if (($identifier ne '') &&
                   4598:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4599:             ($pathfrom ne '')) {
                   4600:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4601:             foreach my $dep (@{$related->{$identifier}}) {
                   4602:                 &add_filetype($allfiles,$path.$dep,'object');
                   4603:             }
                   4604:         }
                   4605:     }
                   4606:     return;
                   4607: }
                   4608: 
1.1401    raeburn  4609: sub bubblesheet_converter {
                   4610:     my ($cdom,$fullpath,$config,$format) = @_;
                   4611:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4612:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4613:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4614:         my (%csvcols,%csvoptions);
                   4615:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4616:             %csvcols = %{$config->{'fields'}};
                   4617:         }
                   4618:         if (ref($config->{'options'}) eq 'HASH') {
                   4619:             %csvoptions = %{$config->{'options'}};
                   4620:         }
1.1401    raeburn  4621:         my %csvbynum = reverse(%csvcols);
                   4622:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4623:         if (keys(%scantronconf)) {
                   4624:             my %bynum = (
                   4625:                           $scantronconf{CODEstart} => 'CODEstart',
                   4626:                           $scantronconf{IDstart}   => 'IDstart',
                   4627:                           $scantronconf{PaperID}   => 'PaperID',
                   4628:                           $scantronconf{FirstName} => 'FirstName',
                   4629:                           $scantronconf{LastName}  => 'LastName',
                   4630:                           $scantronconf{Qstart}    => 'Qstart',
                   4631:                         );
                   4632:             my @ordered;
                   4633:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4634:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4635:             }
                   4636:             my %mapstart = (
                   4637:                               CODEstart => 'CODE',
                   4638:                               IDstart   => 'ID',
                   4639:                               PaperID   => 'PaperID',
                   4640:                               FirstName => 'FirstName',
                   4641:                               LastName  => 'LastName',
                   4642:                               Qstart    => 'FirstQuestion',
                   4643:                            );
                   4644:             my %maplength = (
                   4645:                               CODEstart => 'CODElength',
                   4646:                               IDstart   => 'IDlength',
                   4647:                               PaperID   => 'PaperIDlength',
                   4648:                               FirstName => 'FirstNamelength',
                   4649:                               LastName  => 'LastNamelength',
                   4650:             );
                   4651:             if (open(my $fh,'<',$fullpath)) {
                   4652:                 my $output;
1.1403    raeburn  4653:                 my %lettdig = &letter_to_digits();
                   4654:                 my %diglett = reverse(%lettdig);
                   4655:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4656:                 my $num = 0;
1.1401    raeburn  4657:                 while (my $line=<$fh>) {
1.1404    raeburn  4658:                     $num ++;
                   4659:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4660:                     $line =~ s{[\r\n]+$}{};
                   4661:                     my %found;
                   4662:                     my @values = split(/,/,$line);
                   4663:                     my ($qstart,$record);
                   4664:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4665:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4666:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4667:                             if ($values[$i] eq '') {
                   4668:                                 $values[$i] = $scantronconf{'Qoff'};
                   4669:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4670:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4671:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4672:                                 }
                   4673:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4674:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4675:                                     $values[$i] = $diglett{$values[$i]};
                   4676:                                 }
                   4677:                             } else {
                   4678:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4679:                                     my $digit;
                   4680:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4681:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4682:                                         if ($values[$i] eq 'J') {
                   4683:                                             $digit += $numletts;
                   4684:                                         }
                   4685:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4686:                                         $digit = $values[$i]-1;
                   4687:                                         if ($values[$i] eq '0') {
                   4688:                                             $digit += $numletts;
                   4689:                                         }
                   4690:                                     }
                   4691:                                     my $qval='';
                   4692:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4693:                                         if ($j == $digit) {
                   4694:                                             $qval .= $scantronconf{'Qon'};
                   4695:                                         } else {
                   4696:                                             $qval .= $scantronconf{'Qoff'};
                   4697:                                         }
                   4698:                                     }
                   4699:                                     $values[$i] = $qval;
                   4700:                                 }
                   4701:                             }
                   4702:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4703:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4704:                             }
                   4705:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4706:                             if ($numblank > 0) {
                   4707:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4708:                             }
1.1401    raeburn  4709:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4710:                                 $qstart = $i;
1.1403    raeburn  4711:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  4712:                             } else {
1.1403    raeburn  4713:                                 $found{'FirstQuestion'} .= $values[$i];
                   4714:                             }
                   4715:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  4716:                             if ($csvoptions{'rem'}) {
                   4717:                                 $values[$i] =~ s/^\s+//;
                   4718:                             }
                   4719:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  4720:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4721:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  4722:                                 }
                   4723:                             }
                   4724:                             $found{$csvbynum{$i}} = $values[$i];
                   4725:                         }
                   4726:                     }
                   4727:                     foreach my $item (@ordered) {
                   4728:                         my $currlength = 1+length($record);
                   4729:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4730:                         if ($numspaces > 0) {
                   4731:                             $record .= (' ' x $numspaces);
                   4732:                         }
                   4733:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4734:                             unless ($item eq 'Qstart') {
                   4735:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4736:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4737:                                 }
                   4738:                             }
                   4739:                             $record .= $found{$mapstart{$item}};
                   4740:                         }
                   4741:                     }
                   4742:                     $output .= "$record\n";
                   4743:                 }
                   4744:                 close($fh);
                   4745:                 if ($output) {
                   4746:                     if (open(my $fh,'>',$fullpath)) {
                   4747:                         print $fh $output;
                   4748:                         close($fh);
                   4749:                     }
                   4750:                 }
                   4751:             }
                   4752:         }
                   4753:         return;
                   4754:     }
                   4755: }
                   4756: 
1.1403    raeburn  4757: sub letter_to_digits {
                   4758:     my %lettdig = (
                   4759:                     A => 1,
                   4760:                     B => 2,
                   4761:                     C => 3,
                   4762:                     D => 4,
                   4763:                     E => 5,
                   4764:                     F => 6,
                   4765:                     G => 7,
                   4766:                     H => 8,
                   4767:                     I => 9,
                   4768:                     J => 0,
                   4769:                   );
                   4770:     return %lettdig;
                   4771: }
                   4772: 
1.1401    raeburn  4773: sub get_scantron_config {
                   4774:     my ($which,$cdom) = @_;
                   4775:     my @lines = &get_scantronformat_file($cdom);
                   4776:     my %config;
                   4777:     #FIXME probably should move to XML it has already gotten a bit much now
                   4778:     foreach my $line (@lines) {
                   4779:         my ($name,$descrip)=split(/:/,$line);
                   4780:         if ($name ne $which ) { next; }
                   4781:         chomp($line);
                   4782:         my @config=split(/:/,$line);
                   4783:         $config{'name'}=$config[0];
                   4784:         $config{'description'}=$config[1];
                   4785:         $config{'CODElocation'}=$config[2];
                   4786:         $config{'CODEstart'}=$config[3];
                   4787:         $config{'CODElength'}=$config[4];
                   4788:         $config{'IDstart'}=$config[5];
                   4789:         $config{'IDlength'}=$config[6];
                   4790:         $config{'Qstart'}=$config[7];
                   4791:         $config{'Qlength'}=$config[8];
                   4792:         $config{'Qoff'}=$config[9];
                   4793:         $config{'Qon'}=$config[10];
                   4794:         $config{'PaperID'}=$config[11];
                   4795:         $config{'PaperIDlength'}=$config[12];
                   4796:         $config{'FirstName'}=$config[13];
                   4797:         $config{'FirstNamelength'}=$config[14];
                   4798:         $config{'LastName'}=$config[15];
                   4799:         $config{'LastNamelength'}=$config[16];
                   4800:         $config{'BubblesPerRow'}=$config[17];
                   4801:         last;
                   4802:     }
                   4803:     return %config;
                   4804: }
                   4805: 
                   4806: sub get_scantronformat_file {
                   4807:     my ($cdom) = @_;
                   4808:     if ($cdom eq '') {
                   4809:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4810:     }
                   4811:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4812:     my $gottab = 0;
                   4813:     my @lines;
                   4814:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4815:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4816:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4817:             if ($formatfile ne '-1') {
                   4818:                 @lines = split("\n",$formatfile,-1);
                   4819:                 $gottab = 1;
                   4820:             }
                   4821:         }
                   4822:     }
                   4823:     if (!$gottab) {
                   4824:         my $confname = $cdom.'-domainconfig';
                   4825:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4826:         my $formatfile = &getfile($default);
                   4827:         if ($formatfile ne '-1') {
                   4828:             @lines = split("\n",$formatfile,-1);
                   4829:             $gottab = 1;
                   4830:         }
                   4831:     }
                   4832:     if (!$gottab) {
                   4833:         my @domains = &current_machine_domains();
                   4834:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4835:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4836:                 @lines = <$fh>;
                   4837:                 close($fh);
1.1403    raeburn  4838:             }
1.1401    raeburn  4839:         } else {
                   4840:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4841:                 @lines = <$fh>;
                   4842:                 close($fh);
                   4843:             }
                   4844:         }
                   4845:     }
                   4846:     return @lines;
                   4847: }
                   4848: 
1.493     albertel 4849: sub removeuploadedurl {
1.984     neumanie 4850:     my ($url)=@_;	
                   4851:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4852:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4853: }
                   4854: 
                   4855: sub removeuserfile {
                   4856:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4857:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4858:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4859:     if ($result eq 'ok') {	
1.798     raeburn  4860:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4861:             my $metafile = $fname.'.meta';
                   4862:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4863: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4864:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4865:             my $sqlresult = 
1.823     albertel 4866:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4867:                                         'portfolio_metadata',$group,
                   4868:                                         'delete');
1.798     raeburn  4869:         }
                   4870:     }
                   4871:     return $result;
1.257     www      4872: }
1.15      www      4873: 
1.530     albertel 4874: sub mkdiruserfile {
                   4875:     my ($docuname,$docudom,$dir)=@_;
                   4876:     my $home=&homeserver($docuname,$docudom);
                   4877:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4878: }
                   4879: 
1.531     albertel 4880: sub renameuserfile {
                   4881:     my ($docuname,$docudom,$old,$new)=@_;
                   4882:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4883:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4884:                         &escape("$old").':'.&escape("$new"),$home);
                   4885:     if ($result eq 'ok') {
                   4886:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4887:             my $oldmeta = $old.'.meta';
                   4888:             my $newmeta = $new.'.meta';
                   4889:             my $metaresult = 
                   4890:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4891: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4892:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4893:             my $sqlresult = 
1.823     albertel 4894:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4895:                                         'portfolio_metadata',$group,
                   4896:                                         'delete');
1.798     raeburn  4897:         }
                   4898:     }
                   4899:     return $result;
1.531     albertel 4900: }
                   4901: 
1.14      www      4902: # ------------------------------------------------------------------------- Log
                   4903: 
                   4904: sub log {
                   4905:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4906:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4907: }
                   4908: 
                   4909: # ------------------------------------------------------------------ Course Log
1.352     www      4910: #
                   4911: # This routine flushes several buffers of non-mission-critical nature
                   4912: #
1.157     www      4913: 
                   4914: sub flushcourselogs {
1.352     www      4915:     &logthis('Flushing log buffers');
                   4916: #
                   4917: # course logs
                   4918: # This is a log of all transactions in a course, which can be used
                   4919: # for data mining purposes
                   4920: #
                   4921: # It also collects the courseid database, which lists last transaction
                   4922: # times and course titles for all courseids
                   4923: #
                   4924:     my %courseidbuffer=();
1.921     raeburn  4925:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4926:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4927: 		          &escape($courselogs{$crsid}),
                   4928: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4929: 	    delete $courselogs{$crsid};
                   4930:         } else {
                   4931:             &logthis('Failed to flush log buffer for '.$crsid);
                   4932:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4933:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4934:                         " exceeded maximum size, deleting.</font>");
                   4935:                delete $courselogs{$crsid};
                   4936:             }
1.352     www      4937:         }
1.920     raeburn  4938:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4939:             'description' => $coursedescrbuf{$crsid},
                   4940:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4941:             'type'        => $coursetypebuf{$crsid},
                   4942:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4943:         };
1.191     harris41 4944:     }
1.352     www      4945: #
                   4946: # Write course id database (reverse lookup) to homeserver of courses 
                   4947: # Is used in pickcourse
                   4948: #
1.840     albertel 4949:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4950:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4951:                                     $courseidbuffer{$crs_home},
                   4952:                                     $crs_home,'timeonly');
1.352     www      4953:     }
                   4954: #
                   4955: # File accesses
                   4956: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4957: #
1.449     matthew  4958:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4959:         if ($entry =~ /___count$/) {
                   4960:             my ($dom,$name);
1.807     albertel 4961:             ($dom,$name,undef)=
1.811     albertel 4962: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4963:             if (! defined($dom) || $dom eq '' || 
                   4964:                 ! defined($name) || $name eq '') {
1.620     albertel 4965:                 my $cid = $env{'request.course.id'};
                   4966:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4967:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4968:             }
1.450     matthew  4969:             my $value = $accesshash{$entry};
                   4970:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4971:             my %temphash=($url => $value);
1.449     matthew  4972:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4973:             if ($result eq 'ok') {
                   4974:                 delete $accesshash{$entry};
                   4975:             }
                   4976:         } else {
1.811     albertel 4977:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4978:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4979:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4980:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4981:                 delete $accesshash{$entry};
                   4982:             }
1.185     www      4983:         }
1.191     harris41 4984:     }
1.352     www      4985: #
                   4986: # Roles
                   4987: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4988: #
1.800     albertel 4989:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4990:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4991: 	    split(/\:/,$entry);
                   4992:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4993:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4994:                 $rudom,$runame) eq 'ok') {
                   4995: 	    delete $userrolehash{$entry};
                   4996:         }
                   4997:     }
1.662     raeburn  4998: #
1.1334    raeburn  4999: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  5000: #
                   5001:     my %domrolebuffer = ();
1.1000    raeburn  5002:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 5003:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  5004:         if ($domrolebuffer{$rudom}) {
                   5005:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   5006:                       '='.&escape($domainrolehash{$entry});
                   5007:         } else {
                   5008:             $domrolebuffer{$rudom}.=&escape($entry).
                   5009:                       '='.&escape($domainrolehash{$entry});
                   5010:         }
                   5011:         delete $domainrolehash{$entry};
                   5012:     }
                   5013:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  5014: 	my %servers;
                   5015: 	if (defined(&domain($dom,'primary'))) {
                   5016: 	    my $primary=&domain($dom,'primary');
                   5017: 	    my $hostname=&hostname($primary);
                   5018: 	    $servers{$primary} = $hostname;
                   5019: 	} else { 
                   5020: 	    %servers = &get_servers($dom,'library');
                   5021: 	}
1.841     albertel 5022: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  5023: 	    if (&reply('domroleput:'.$dom.':'.
                   5024: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5025: 		last;
                   5026: 	    } else {  
1.841     albertel 5027: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5028: 	    }
1.662     raeburn  5029:         }
                   5030:     }
1.186     www      5031:     $dumpcount++;
1.157     www      5032: }
                   5033: 
                   5034: sub courselog {
                   5035:     my $what=shift;
1.158     www      5036:     $what=time.':'.$what;
1.620     albertel 5037:     unless ($env{'request.course.id'}) { return ''; }
                   5038:     $coursedombuf{$env{'request.course.id'}}=
                   5039:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5040:     $coursenumbuf{$env{'request.course.id'}}=
                   5041:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5042:     $coursehombuf{$env{'request.course.id'}}=
                   5043:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5044:     $coursedescrbuf{$env{'request.course.id'}}=
                   5045:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5046:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5047:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5048:     $courseownerbuf{$env{'request.course.id'}}=
                   5049:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5050:     $coursetypebuf{$env{'request.course.id'}}=
                   5051:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5052:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5053: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5054:     } else {
1.620     albertel 5055: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5056:     }
1.620     albertel 5057:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5058: 	&flushcourselogs();
                   5059:     }
1.158     www      5060: }
                   5061: 
                   5062: sub courseacclog {
                   5063:     my $fnsymb=shift;
1.620     albertel 5064:     unless ($env{'request.course.id'}) { return ''; }
                   5065:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5066:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5067:         $what.=':POST';
1.583     matthew  5068:         # FIXME: Probably ought to escape things....
1.800     albertel 5069: 	foreach my $key (keys(%env)) {
                   5070:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5071:                 my $formitem = $1;
                   5072:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5073:                     $what.=':'.$formitem.'='.$env{$key};
                   5074:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432    raeburn  5075:                     if ($formitem eq 'proctorpassword') {
1.1433    raeburn  5076:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432    raeburn  5077:                     } else {
                   5078:                         $what.=':'.$formitem.'='.$env{$key};
                   5079:                     }
1.975     raeburn  5080:                 }
1.158     www      5081:             }
1.191     harris41 5082:         }
1.583     matthew  5083:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5084:         # FIXME: We should not be depending on a form parameter that someone
                   5085:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5086:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5087:             $what.= ':POST';
                   5088:             # FIXME: Probably ought to escape things....
                   5089:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5090:                                  'crsdiscuss') {
1.620     albertel 5091:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5092:             }
                   5093:         }
1.158     www      5094:     }
                   5095:     &courselog($what);
1.149     www      5096: }
                   5097: 
1.185     www      5098: sub countacc {
                   5099:     my $url=&declutter(shift);
1.458     matthew  5100:     return if (! defined($url) || $url eq '');
1.620     albertel 5101:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5102: #
                   5103: # Mark that this url was used in this course
                   5104: #
1.620     albertel 5105:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5106: #
                   5107: # Increase the access count for this resource in this child process
                   5108: #
1.281     www      5109:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5110:     $accesshash{$key}++;
1.185     www      5111: }
1.349     www      5112: 
1.361     www      5113: sub linklog {
                   5114:     my ($from,$to)=@_;
                   5115:     $from=&declutter($from);
                   5116:     $to=&declutter($to);
                   5117:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5118:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5119: }
1.1160    www      5120: 
                   5121: sub statslog {
                   5122:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5123:     if ($users<2) { return; }
                   5124:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5125:             'course'       => $env{'request.course.id'},
                   5126:             'sections'     => '"all"',
                   5127:             'num_students' => $users,
                   5128:             'part'         => $part,
                   5129:             'symb'         => $symb,
                   5130:             'mean_tries'   => $av_attempts,
                   5131:             'deg_of_diff'  => $degdiff});
                   5132:     foreach my $key (keys(%dynstore)) {
                   5133:         $accesshash{$key}=$dynstore{$key};
                   5134:     }
                   5135: }
1.361     www      5136:   
1.349     www      5137: sub userrolelog {
                   5138:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5139:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5140:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5141:        $userrolehash
                   5142:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5143:                     =$tend.':'.$tstart;
1.662     raeburn  5144:     }
1.1169    droeschl 5145:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5146:        $userrolehash
                   5147:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5148:                     =$tend.':'.$tstart;
                   5149:     }
1.1334    raeburn  5150:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5151:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5152:        $domainrolehash
                   5153:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5154:                     = $tend.':'.$tstart;
                   5155:     }
1.351     www      5156: }
                   5157: 
1.957     raeburn  5158: sub courserolelog {
                   5159:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  5160:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5161:         my $cdom = $1;
                   5162:         my $cnum = $2;
                   5163:         my $sec = $3;
                   5164:         my $namespace = 'rolelog';
                   5165:         my %storehash = (
                   5166:                            role    => $trole,
                   5167:                            start   => $tstart,
                   5168:                            end     => $tend,
                   5169:                            selfenroll => $selfenroll,
                   5170:                            context    => $context,
                   5171:                         );
                   5172:         if ($trole eq 'gr') {
                   5173:             $namespace = 'groupslog';
                   5174:             $storehash{'group'} = $sec;
                   5175:         } else {
                   5176:             $storehash{'section'} = $sec;
                   5177:         }
1.1188    raeburn  5178:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5179:                    $domain,$cnum,$cdom);
1.1184    raeburn  5180:         if (($trole ne 'st') || ($sec ne '')) {
                   5181:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5182:         }
                   5183:     }
                   5184:     return;
                   5185: }
                   5186: 
1.1184    raeburn  5187: sub domainrolelog {
                   5188:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5189:     if ($area =~ m{^/($match_domain)/$}) {
                   5190:         my $cdom = $1;
                   5191:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5192:         my $namespace = 'rolelog';
                   5193:         my %storehash = (
                   5194:                            role    => $trole,
                   5195:                            start   => $tstart,
                   5196:                            end     => $tend,
                   5197:                            context => $context,
                   5198:                         );
1.1188    raeburn  5199:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5200:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  5201:     }
                   5202:     return;
                   5203: 
                   5204: }
                   5205: 
                   5206: sub coauthorrolelog {
                   5207:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5208:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5209:         my $audom = $1;
                   5210:         my $auname = $2;
                   5211:         my $namespace = 'rolelog';
                   5212:         my %storehash = (
                   5213:                            role    => $trole,
                   5214:                            start   => $tstart,
                   5215:                            end     => $tend,
                   5216:                            context => $context,
                   5217:                         );
1.1188    raeburn  5218:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5219:                    $domain,$auname,$audom);
1.1184    raeburn  5220:     }
                   5221:     return;
                   5222: }
                   5223: 
1.351     www      5224: sub get_course_adv_roles {
1.948     raeburn  5225:     my ($cid,$codes) = @_;
1.620     albertel 5226:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5227:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5228:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5229:     my %nothide=();
1.800     albertel 5230:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5231:         if ($user !~ /:/) {
                   5232: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5233:         } else {
                   5234:             $nothide{$user}=1;
                   5235:         }
1.470     www      5236:     }
1.1219    raeburn  5237:     my @possdoms = ($coursehash{'domain'});
                   5238:     if ($coursehash{'checkforpriv'}) {
                   5239:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5240:     }
1.351     www      5241:     my %returnhash=();
                   5242:     my %dumphash=
                   5243:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5244:     my $now=time;
1.997     raeburn  5245:     my %privileged;
1.1000    raeburn  5246:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5247: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5248:         if (($tstart) && ($tstart<0)) { next; }
                   5249:         if (($tend) && ($tend<$now)) { next; }
                   5250:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5251:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5252: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5253:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5254:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5255: 	if ($role eq 'cr') { next; }
1.948     raeburn  5256:         if ($codes) {
                   5257:             if ($section) { $role .= ':'.$section; }
                   5258:             if ($returnhash{$role}) {
                   5259:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5260:             } else {
                   5261:                 $returnhash{$role}=$username.':'.$domain;
                   5262:             }
1.351     www      5263:         } else {
1.988     raeburn  5264:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5265:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5266:             if ($returnhash{$key}) {
                   5267: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5268:             } else {
                   5269:                 $returnhash{$key}=$username.':'.$domain;
                   5270:             }
1.351     www      5271:         }
1.948     raeburn  5272:     }
1.400     www      5273:     return %returnhash;
                   5274: }
                   5275: 
                   5276: sub get_my_roles {
1.937     raeburn  5277:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5278:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5279:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5280:     my (%dumphash,%nothide);
1.1086    raeburn  5281:     if ($context eq 'userroles') {
1.1166    raeburn  5282:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5283:     } else {
1.1219    raeburn  5284:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5285:         if ($hidepriv) {
                   5286:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5287:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5288:                 if ($user !~ /:/) {
                   5289:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5290:                 } else {
                   5291:                     $nothide{$user} = 1;
                   5292:                 }
                   5293:             }
                   5294:         }
1.858     raeburn  5295:     }
1.400     www      5296:     my %returnhash=();
                   5297:     my $now=time;
1.999     raeburn  5298:     my %privileged;
1.800     albertel 5299:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5300:         my ($role,$tend,$tstart);
                   5301:         if ($context eq 'userroles') {
1.1149    raeburn  5302:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5303: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5304:         } else {
                   5305:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5306:         }
1.400     www      5307:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5308:         my $status = 'active';
1.939     raeburn  5309:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5310:             $status = 'previous';
                   5311:         } 
                   5312:         if (($tstart) && ($now<$tstart)) {
                   5313:             $status = 'future';
                   5314:         }
                   5315:         if (ref($types) eq 'ARRAY') {
                   5316:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5317:                 next;
                   5318:             } 
                   5319:         } else {
                   5320:             if ($status ne 'active') {
                   5321:                 next;
                   5322:             }
                   5323:         }
1.867     raeburn  5324:         my ($rolecode,$username,$domain,$section,$area);
                   5325:         if ($context eq 'userroles') {
1.1186    raeburn  5326:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5327:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5328:         } else {
                   5329:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5330:         }
1.832     raeburn  5331:         if (ref($roledoms) eq 'ARRAY') {
                   5332:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5333:                 next;
                   5334:             }
                   5335:         }
                   5336:         if (ref($roles) eq 'ARRAY') {
                   5337:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5338:                 if ($role =~ /^cr\//) {
                   5339:                     if (!grep(/^cr$/,@{$roles})) {
                   5340:                         next;
                   5341:                     }
1.1104    raeburn  5342:                 } elsif ($role =~ /^gr\//) {
                   5343:                     if (!grep(/^gr$/,@{$roles})) {
                   5344:                         next;
                   5345:                     }
1.922     raeburn  5346:                 } else {
                   5347:                     next;
                   5348:                 }
1.832     raeburn  5349:             }
1.867     raeburn  5350:         }
1.937     raeburn  5351:         if ($hidepriv) {
1.1219    raeburn  5352:             my @privroles = ('dc','su');
1.999     raeburn  5353:             if ($context eq 'userroles') {
1.1219    raeburn  5354:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5355:             } else {
1.1219    raeburn  5356:                 my $possdoms = [$domain];
                   5357:                 if (ref($roledoms) eq 'ARRAY') {
                   5358:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5359:                 }
1.1219    raeburn  5360:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5361:                     if (!$nothide{$username.':'.$domain}) {
                   5362:                         next;
                   5363:                     }
                   5364:                 }
1.937     raeburn  5365:             }
                   5366:         }
1.933     raeburn  5367:         if ($withsec) {
                   5368:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5369:                 $tstart.':'.$tend;
                   5370:         } else {
                   5371:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5372:         }
1.832     raeburn  5373:     }
1.373     www      5374:     return %returnhash;
1.399     www      5375: }
                   5376: 
1.1333    raeburn  5377: sub get_all_adhocroles {
                   5378:     my ($dom) = @_;
                   5379:     my @roles_by_num = ();
                   5380:     my %domdefaults = &get_domain_defaults($dom);
                   5381:     my (%description,%access_in_dom,%access_info);
                   5382:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5383:         my $count = 0;
                   5384:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5385:         my %ordered;
                   5386:         foreach my $role (sort(keys(%domcurrent))) {
                   5387:             my ($order,$desc,$access_in_dom);
                   5388:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5389:                 $order = $domcurrent{$role}{'order'};
                   5390:                 $desc = $domcurrent{$role}{'desc'};
                   5391:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5392:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5393:             }
                   5394:             if ($order eq '') {
                   5395:                 $order = $count;
                   5396:             }
                   5397:             $ordered{$order} = $role;
                   5398:             if ($desc ne '') {
                   5399:                 $description{$role} = $desc;
                   5400:             } else {
                   5401:                 $description{$role}= $role;
                   5402:             }
                   5403:             $count++;
                   5404:         }
                   5405:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5406:             push(@roles_by_num,$ordered{$item});
                   5407:         }
                   5408:     }
                   5409:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5410: }
                   5411: 
1.1332    raeburn  5412: sub get_my_adhocroles {
1.1333    raeburn  5413:     my ($cid,$checkreg) = @_;
                   5414:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5415:     if ($env{'request.course.id'} eq $cid) {
                   5416:         $cdom = $env{'course.'.$cid.'.domain'};
                   5417:         $cnum = $env{'course.'.$cid.'.num'};
                   5418:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5419:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5420:         $cdom = $1;
                   5421:         $cnum = $2;
                   5422:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5423:                                      $cdom,$cnum);
                   5424:     }
                   5425:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5426:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5427:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5428:         if ($rosterhash{$user} ne '') {
                   5429:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5430:             return ([],{}) if ($type eq 'auto');
                   5431:         }
                   5432:     }
                   5433:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5434:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5435:             my $then=$env{'user.login.time'};
                   5436:             my $update=$env{'user.update.time'};
1.1335    raeburn  5437:             if (!$update) {
                   5438:                 $update = $then;
                   5439:             }
                   5440:             my @liveroles;
1.1334    raeburn  5441:             foreach my $role ('dh','da') {
                   5442:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5443:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5444:                     my $limit = $update;
                   5445:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5446:                         $limit = $then;
                   5447:                     }
1.1335    raeburn  5448:                     my $activerole = 1;
                   5449:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5450:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5451:                     if ($activerole) {
                   5452:                         push(@liveroles,$role);
                   5453:                     }
1.1334    raeburn  5454:                 }
1.1332    raeburn  5455:             }
1.1335    raeburn  5456:             if (@liveroles) {
1.1332    raeburn  5457:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5458:                     my ($accessref,$accessinfo,%access_in_dom);
                   5459:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5460:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5461:                         if (@{$roles_by_num}) {
1.1332    raeburn  5462:                             my %settings;
                   5463:                             if ($env{'request.course.id'} eq $cid) {
                   5464:                                 foreach my $envkey (keys(%env)) {
                   5465:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5466:                                         $settings{$1} = $env{$envkey};
                   5467:                                     }
                   5468:                                 }
                   5469:                             } else {
                   5470:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5471:                             }
                   5472:                             my %setincrs;
                   5473:                             if ($settings{'internal.adhocaccess'}) {
                   5474:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5475:                             }
                   5476:                             my @statuses;
                   5477:                             if ($env{'environment.inststatus'}) {
                   5478:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5479:                             }
                   5480:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5481:                             if (ref($accessref) eq 'HASH') {
                   5482:                                 %access_in_dom = %{$accessref};
                   5483:                             }
                   5484:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5485:                                 my ($curraccess,@okstatus,@personnel);
                   5486:                                 if ($setincrs{$role}) {
                   5487:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5488:                                     if ($curraccess eq 'status') {
                   5489:                                         @okstatus = split(/\&/,$rest);
                   5490:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5491:                                         @personnel = split(/\&/,$rest);
                   5492:                                     }
                   5493:                                 } else {
                   5494:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5495:                                     if (ref($accessinfo) eq 'HASH') {
                   5496:                                         if ($curraccess eq 'status') {
                   5497:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5498:                                                 @okstatus = @{$accessinfo->{$role}};
                   5499:                                             }
                   5500:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5501:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5502:                                                 @personnel = @{$accessinfo->{$role}};
                   5503:                                             }
1.1332    raeburn  5504:                                         }
                   5505:                                     }
                   5506:                                 }
                   5507:                                 if ($curraccess eq 'none') {
                   5508:                                     next;
                   5509:                                 } elsif ($curraccess eq 'all') {
                   5510:                                     push(@possroles,$role);
1.1336    raeburn  5511:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5512:                                     if (grep(/^dh$/,@liveroles)) {
                   5513:                                         push(@possroles,$role);
                   5514:                                     } else {
                   5515:                                         next;
                   5516:                                     }
1.1336    raeburn  5517:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5518:                                     if (grep(/^da$/,@liveroles)) {
                   5519:                                         push(@possroles,$role);
                   5520:                                     } else {
                   5521:                                         next;
                   5522:                                     }
1.1332    raeburn  5523:                                 } elsif ($curraccess eq 'status') {
                   5524:                                     if (@okstatus) {
                   5525:                                         if (!@statuses) {
                   5526:                                             if (grep(/^default$/,@okstatus)) {
                   5527:                                                 push(@possroles,$role);
                   5528:                                             }
                   5529:                                         } else {
                   5530:                                             foreach my $status (@okstatus) {
                   5531:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5532:                                                     push(@possroles,$role);
                   5533:                                                     last;
                   5534:                                                 }
                   5535:                                             }
                   5536:                                         }
                   5537:                                     }
                   5538:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5539:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5540:                                         if ($curraccess eq 'exc') {
                   5541:                                             push(@possroles,$role);
                   5542:                                         }
                   5543:                                     } elsif ($curraccess eq 'inc') {
                   5544:                                         push(@possroles,$role);
                   5545:                                     }
                   5546:                                 }
                   5547:                             }
                   5548:                         }
                   5549:                     }
                   5550:                 }
                   5551:             }
                   5552:         }
                   5553:     }
1.1333    raeburn  5554:     unless (ref($description) eq 'HASH') {
                   5555:         if (ref($roles_by_num) eq 'ARRAY') {
                   5556:             my %desc;
                   5557:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5558:             $description = \%desc;
                   5559:         } else {
                   5560:             $description = {};
                   5561:         }
                   5562:     }
                   5563:     return (\@possroles,$description);
1.1332    raeburn  5564: }
                   5565: 
1.399     www      5566: # ----------------------------------------------------- Frontpage Announcements
                   5567: #
                   5568: #
                   5569: 
                   5570: sub postannounce {
                   5571:     my ($server,$text)=@_;
1.844     albertel 5572:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5573:     unless ($text=~/\w/) { $text=''; }
                   5574:     return &reply('setannounce:'.&escape($text),$server);
                   5575: }
                   5576: 
                   5577: sub getannounce {
1.448     albertel 5578: 
1.1359    raeburn  5579:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5580: 	my $announcement='';
1.800     albertel 5581: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5582: 	close($fh);
1.399     www      5583: 	if ($announcement=~/\w/) { 
                   5584: 	    return 
                   5585:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5586:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5587: 	} else {
                   5588: 	    return '';
                   5589: 	}
                   5590:     } else {
                   5591: 	return '';
                   5592:     }
1.351     www      5593: }
1.353     www      5594: 
                   5595: # ---------------------------------------------------------- Course ID routines
                   5596: # Deal with domain's nohist_courseid.db files
                   5597: #
                   5598: 
                   5599: sub courseidput {
1.921     raeburn  5600:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5601:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5602:     my $outcome;
                   5603:     if ($caller eq 'timeonly') {
                   5604:         my $cids = '';
                   5605:         foreach my $item (keys(%$storehash)) {
                   5606:             $cids.=&escape($item).'&';
                   5607:         }
                   5608:         $cids=~s/\&$//;
                   5609:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5610:                           $coursehome);       
                   5611:     } else {
                   5612:         my $items = '';
                   5613:         foreach my $item (keys(%$storehash)) {
                   5614:             $items.= &escape($item).'='.
                   5615:                      &freeze_escape($$storehash{$item}).'&';
                   5616:         }
                   5617:         $items=~s/\&$//;
                   5618:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5619:                           $coursehome);
1.918     raeburn  5620:     }
                   5621:     if ($outcome eq 'unknown_cmd') {
                   5622:         my $what;
                   5623:         foreach my $cid (keys(%$storehash)) {
                   5624:             $what .= &escape($cid).'=';
1.921     raeburn  5625:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5626:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5627:             }
                   5628:             $what =~ s/\:$/&/;
                   5629:         }
                   5630:         $what =~ s/\&$//;  
                   5631:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5632:     } else {
                   5633:         return $outcome;
                   5634:     }
1.353     www      5635: }
                   5636: 
                   5637: sub courseiddump {
1.921     raeburn  5638:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5639:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5640:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5641:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5642:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5643:     my $as_hash = 1;
                   5644:     my %returnhash;
                   5645:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5646:     my %libserv = &all_library();
                   5647:     foreach my $tryserver (keys(%libserv)) {
                   5648:         if ( (  $hostidflag == 1 
                   5649: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5650: 	     || (!defined($hostidflag)) ) {
                   5651: 
1.918     raeburn  5652: 	    if (($domfilter eq '') ||
                   5653: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5654:                 my $rep;
                   5655:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5656:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5657:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5658:                                 &escape($descfilter), &escape($instcodefilter), 
                   5659:                                 &escape($ownerfilter), &escape($coursefilter),
                   5660:                                 &escape($typefilter), &escape($regexp_ok), 
                   5661:                                 $as_hash, &escape($selfenrollonly), 
                   5662:                                 &escape($catfilter), $showhidden, $caller, 
                   5663:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5664:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5665:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5666:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5667:                 } else {
                   5668:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5669:                              $sincefilter.':'.&escape($descfilter).':'.
                   5670:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5671:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5672:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5673:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5674:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5675:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5676:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5677:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5678:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5679:                 }
                   5680:                      
1.918     raeburn  5681:                 my @pairs=split(/\&/,$rep);
                   5682:                 foreach my $item (@pairs) {
                   5683:                     my ($key,$value)=split(/\=/,$item,2);
                   5684:                     $key = &unescape($key);
                   5685:                     next if ($key =~ /^error: 2 /);
                   5686:                     my $result = &thaw_unescape($value);
                   5687:                     if (ref($result) eq 'HASH') {
                   5688:                         $returnhash{$key}=$result;
                   5689:                     } else {
1.921     raeburn  5690:                         my @responses = split(/:/,$value);
                   5691:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5692:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5693:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5694:                         }
1.1008    raeburn  5695:                     }
1.353     www      5696:                 }
                   5697:             }
                   5698:         }
                   5699:     }
                   5700:     return %returnhash;
                   5701: }
                   5702: 
1.1055    raeburn  5703: sub courselastaccess {
                   5704:     my ($cdom,$cnum,$hostidref) = @_;
                   5705:     my %returnhash;
                   5706:     if ($cdom && $cnum) {
                   5707:         my $chome = &homeserver($cnum,$cdom);
                   5708:         if ($chome ne 'no_host') {
                   5709:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5710:             &extract_lastaccess(\%returnhash,$rep);
                   5711:         }
                   5712:     } else {
                   5713:         if (!$cdom) { $cdom=''; }
                   5714:         my %libserv = &all_library();
                   5715:         foreach my $tryserver (keys(%libserv)) {
                   5716:             if (ref($hostidref) eq 'ARRAY') {
                   5717:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5718:             } 
                   5719:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5720:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5721:                 &extract_lastaccess(\%returnhash,$rep);
                   5722:             }
                   5723:         }
                   5724:     }
                   5725:     return %returnhash;
                   5726: }
                   5727: 
                   5728: sub extract_lastaccess {
                   5729:     my ($returnhash,$rep) = @_;
                   5730:     if (ref($returnhash) eq 'HASH') {
                   5731:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5732:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5733:                  $rep eq '') {
                   5734:             my @pairs=split(/\&/,$rep);
                   5735:             foreach my $item (@pairs) {
                   5736:                 my ($key,$value)=split(/\=/,$item,2);
                   5737:                 $key = &unescape($key);
                   5738:                 next if ($key =~ /^error: 2 /);
                   5739:                 $returnhash->{$key} = &thaw_unescape($value);
                   5740:             }
                   5741:         }
                   5742:     }
                   5743:     return;
                   5744: }
                   5745: 
1.658     raeburn  5746: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5747: 
                   5748: sub dcmailput {
1.685     raeburn  5749:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5750:     my $status = &Apache::lonnet::critical(
1.740     www      5751:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5752:        &escape($message),$server);
1.662     raeburn  5753:     return $status;
                   5754: }
                   5755: 
1.658     raeburn  5756: sub dcmaildump {
                   5757:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5758:     my %returnhash=();
1.846     albertel 5759: 
                   5760:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5761:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5762:                                                          &escape($enddate).':';
                   5763: 	my @esc_senders=map { &escape($_)} @$senders;
                   5764: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5765: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5766:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5767:             if (($key) && ($value)) {
                   5768:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5769:             }
                   5770:         }
                   5771:     }
                   5772:     return %returnhash;
                   5773: }
1.662     raeburn  5774: # ---------------------------------------------------------- Domain roles
                   5775: 
                   5776: sub get_domain_roles {
                   5777:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5778:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5779:         $startdate = '.';
                   5780:     }
1.1018    raeburn  5781:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5782:         $enddate = '.';
                   5783:     }
1.922     raeburn  5784:     my $rolelist;
                   5785:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5786:         $rolelist = join('&',@{$roles});
1.922     raeburn  5787:     }
1.662     raeburn  5788:     my %personnel = ();
1.841     albertel 5789: 
                   5790:     my %servers = &get_servers($dom,'library');
                   5791:     foreach my $tryserver (keys(%servers)) {
                   5792: 	%{$personnel{$tryserver}}=();
                   5793: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5794: 					    &escape($startdate).':'.
                   5795: 					    &escape($enddate).':'.
                   5796: 					    &escape($rolelist), $tryserver))) {
                   5797: 	    my ($key,$value) = split(/\=/,$line,2);
                   5798: 	    if (($key) && ($value)) {
                   5799: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5800: 	    }
                   5801: 	}
1.662     raeburn  5802:     }
                   5803:     return %personnel;
                   5804: }
1.658     raeburn  5805: 
1.1332    raeburn  5806: sub get_active_domroles {
                   5807:     my ($dom,$roles) = @_;
                   5808:     return () unless (ref($roles) eq 'ARRAY');
                   5809:     my $now = time;
                   5810:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5811:     my %domroles;
                   5812:     foreach my $server (keys(%dompersonnel)) {
                   5813:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5814:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5815:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5816:         }
                   5817:     }
                   5818:     return %domroles;
                   5819: }
                   5820: 
1.1057    www      5821: # ----------------------------------------------------------- Interval timing 
1.149     www      5822: 
1.1153    www      5823: {
                   5824: # Caches needed for speedup of navmaps
                   5825: # We don't want to cache this for very long at all (5 seconds at most)
                   5826: # 
                   5827: # The user for whom we cache
                   5828: my $cachedkey='';
                   5829: # The cached times for this user
                   5830: my %cachedtimes=();
                   5831: # When this was last done
1.1282    raeburn  5832: my $cachedtime='';
1.1153    www      5833: 
                   5834: sub load_all_first_access {
1.1308    raeburn  5835:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5836:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5837:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5838:         (!$ignorecache)) {
1.1154    raeburn  5839:         return;
                   5840:     }
                   5841:     $cachedtime=time;
                   5842:     $cachedkey=$uname.':'.$udom;
                   5843:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5844: }
                   5845: 
1.504     albertel 5846: sub get_first_access {
1.1308    raeburn  5847:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5848:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5849:     if ($argsymb) { $symb=$argsymb; }
                   5850:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5851:     if ($argmap) { $map = $argmap; }
1.926     albertel 5852:     if ($type eq 'course') {
                   5853: 	$res='course';
                   5854:     } elsif ($type eq 'map') {
1.588     albertel 5855: 	$res=&symbread($map);
                   5856:     } else {
                   5857: 	$res=$symb;
                   5858:     }
1.1308    raeburn  5859:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5860:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5861: }
                   5862: 
                   5863: sub set_first_access {
1.1162    raeburn  5864:     my ($type,$interval)=@_;
1.790     albertel 5865:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5866:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5867:     if ($type eq 'course') {
                   5868: 	$res='course';
                   5869:     } elsif ($type eq 'map') {
1.588     albertel 5870: 	$res=&symbread($map);
                   5871:     } else {
                   5872: 	$res=$symb;
                   5873:     }
1.1153    www      5874:     $cachedkey='';
1.1162    raeburn  5875:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5876:     if ($firstaccess) {
                   5877:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5878:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5879:                  "in $courseid");
1.1386    raeburn  5880:         return 'already_set';
                   5881:     } else {
1.1162    raeburn  5882:         my $start = time;
                   5883: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5884:                           $udom,$uname);
                   5885:         if ($putres eq 'ok') {
                   5886:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5887:                  $udom,$uname); 
                   5888:             &appenv(
                   5889:                      {
                   5890:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5891:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5892:                      }
                   5893:                   );
1.1365    raeburn  5894:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5895:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5896:             }
1.1386    raeburn  5897:         } elsif ($putres ne 'refused') {
                   5898:             &logthis("Result: $putres when attempting to set first access time ".
                   5899:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5900:         }
                   5901:         return $putres;
1.505     albertel 5902:     }
                   5903:     return 'already_set';
1.504     albertel 5904: }
1.1153    www      5905: }
1.1282    raeburn  5906: 
1.110     www      5907: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5908: 
                   5909: sub expirespread {
                   5910:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5911:     my $cid=$env{'request.course.id'}; 
1.110     www      5912:     if ($cid) {
                   5913:        my $now=time;
                   5914:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5915:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5916:                             $env{'course.'.$cid.'.num'}.
1.110     www      5917: 	        	    ':nohist_expirationdates:'.
                   5918:                             &escape($key).'='.$now,
1.620     albertel 5919:                             $env{'course.'.$cid.'.home'})
1.110     www      5920:     }
                   5921:     return 'ok';
1.14      www      5922: }
                   5923: 
1.109     www      5924: # ----------------------------------------------------- Devalidate Spreadsheets
                   5925: 
                   5926: sub devalidate {
1.325     www      5927:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5928:     my $cid=$env{'request.course.id'}; 
1.109     www      5929:     if ($cid) {
1.391     matthew  5930:         # delete the stored spreadsheets for
                   5931:         # - the student level sheet of this user in course's homespace
                   5932:         # - the assessment level sheet for this resource 
                   5933:         #   for this user in user's homespace
1.553     albertel 5934: 	# - current conditional state info
1.325     www      5935: 	my $key=$uname.':'.$udom.':';
1.109     www      5936:         my $status=
1.299     matthew  5937: 	    &del('nohist_calculatedsheets',
1.391     matthew  5938: 		 [$key.'studentcalc:'],
1.620     albertel 5939: 		 $env{'course.'.$cid.'.domain'},
                   5940: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5941: 		.' '.
                   5942: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5943: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5944:         unless ($status eq 'ok ok') {
                   5945:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5946:                     $uname.' at '.$udom.' for '.
1.109     www      5947: 		    $symb.': '.$status);
1.133     albertel 5948:         }
1.553     albertel 5949: 	&delenv('user.state.'.$cid);
1.109     www      5950:     }
                   5951: }
                   5952: 
1.265     albertel 5953: sub get_scalar {
                   5954:     my ($string,$end) = @_;
                   5955:     my $value;
                   5956:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5957: 	$value = $1;
                   5958:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5959: 	$value = $1;
                   5960:     }
                   5961:     return &unescape($value);
                   5962: }
                   5963: 
                   5964: sub array2str {
                   5965:   my (@array) = @_;
                   5966:   my $result=&arrayref2str(\@array);
                   5967:   $result=~s/^__ARRAY_REF__//;
                   5968:   $result=~s/__END_ARRAY_REF__$//;
                   5969:   return $result;
                   5970: }
                   5971: 
1.204     albertel 5972: sub arrayref2str {
                   5973:   my ($arrayref) = @_;
1.265     albertel 5974:   my $result='__ARRAY_REF__';
1.204     albertel 5975:   foreach my $elem (@$arrayref) {
1.265     albertel 5976:     if(ref($elem) eq 'ARRAY') {
                   5977:       $result.=&arrayref2str($elem).'&';
                   5978:     } elsif(ref($elem) eq 'HASH') {
                   5979:       $result.=&hashref2str($elem).'&';
                   5980:     } elsif(ref($elem)) {
                   5981:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5982:     } else {
                   5983:       $result.=&escape($elem).'&';
                   5984:     }
                   5985:   }
                   5986:   $result=~s/\&$//;
1.265     albertel 5987:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5988:   return $result;
                   5989: }
                   5990: 
1.168     albertel 5991: sub hash2str {
1.204     albertel 5992:   my (%hash) = @_;
                   5993:   my $result=&hashref2str(\%hash);
1.265     albertel 5994:   $result=~s/^__HASH_REF__//;
                   5995:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5996:   return $result;
                   5997: }
                   5998: 
                   5999: sub hashref2str {
                   6000:   my ($hashref)=@_;
1.265     albertel 6001:   my $result='__HASH_REF__';
1.800     albertel 6002:   foreach my $key (sort(keys(%$hashref))) {
                   6003:     if (ref($key) eq 'ARRAY') {
                   6004:       $result.=&arrayref2str($key).'=';
                   6005:     } elsif (ref($key) eq 'HASH') {
                   6006:       $result.=&hashref2str($key).'=';
                   6007:     } elsif (ref($key)) {
1.265     albertel 6008:       $result.='=';
1.800     albertel 6009:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 6010:     } else {
1.1132    raeburn  6011: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 6012:     }
                   6013: 
1.800     albertel 6014:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   6015:       $result.=&arrayref2str($hashref->{$key}).'&';
                   6016:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   6017:       $result.=&hashref2str($hashref->{$key}).'&';
                   6018:     } elsif(ref($hashref->{$key})) {
1.265     albertel 6019:        $result.='&';
1.800     albertel 6020:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 6021:     } else {
1.800     albertel 6022:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 6023:     }
                   6024:   }
1.168     albertel 6025:   $result=~s/\&$//;
1.265     albertel 6026:   $result .= '__END_HASH_REF__';
1.168     albertel 6027:   return $result;
                   6028: }
                   6029: 
                   6030: sub str2hash {
1.265     albertel 6031:     my ($string)=@_;
                   6032:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6033:     return %$hash;
                   6034: }
                   6035: 
                   6036: sub str2hashref {
1.168     albertel 6037:   my ($string) = @_;
1.265     albertel 6038: 
                   6039:   my %hash;
                   6040: 
                   6041:   if($string !~ /^__HASH_REF__/) {
                   6042:       if (! ($string eq '' || !defined($string))) {
                   6043: 	  $hash{'error'}='Not hash reference';
                   6044:       }
                   6045:       return (\%hash, $string);
                   6046:   }
                   6047: 
                   6048:   $string =~ s/^__HASH_REF__//;
                   6049: 
                   6050:   while($string !~ /^__END_HASH_REF__/) {
                   6051:       #key
                   6052:       my $key='';
                   6053:       if($string =~ /^__HASH_REF__/) {
                   6054:           ($key, $string)=&str2hashref($string);
                   6055:           if(defined($key->{'error'})) {
                   6056:               $hash{'error'}='Bad data';
                   6057:               return (\%hash, $string);
                   6058:           }
                   6059:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6060:           ($key, $string)=&str2arrayref($string);
                   6061:           if($key->[0] eq 'Array reference error') {
                   6062:               $hash{'error'}='Bad data';
                   6063:               return (\%hash, $string);
                   6064:           }
                   6065:       } else {
                   6066:           $string =~ s/^(.*?)=//;
1.267     albertel 6067: 	  $key=&unescape($1);
1.265     albertel 6068:       }
                   6069:       $string =~ s/^=//;
                   6070: 
                   6071:       #value
                   6072:       my $value='';
                   6073:       if($string =~ /^__HASH_REF__/) {
                   6074:           ($value, $string)=&str2hashref($string);
                   6075:           if(defined($value->{'error'})) {
                   6076:               $hash{'error'}='Bad data';
                   6077:               return (\%hash, $string);
                   6078:           }
                   6079:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6080:           ($value, $string)=&str2arrayref($string);
                   6081:           if($value->[0] eq 'Array reference error') {
                   6082:               $hash{'error'}='Bad data';
                   6083:               return (\%hash, $string);
                   6084:           }
                   6085:       } else {
                   6086: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6087:       }
                   6088:       $string =~ s/^&//;
                   6089: 
                   6090:       $hash{$key}=$value;
1.204     albertel 6091:   }
1.265     albertel 6092: 
                   6093:   $string =~ s/^__END_HASH_REF__//;
                   6094: 
                   6095:   return (\%hash, $string);
1.204     albertel 6096: }
                   6097: 
                   6098: sub str2array {
1.265     albertel 6099:     my ($string)=@_;
                   6100:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6101:     return @$array;
                   6102: }
                   6103: 
                   6104: sub str2arrayref {
1.204     albertel 6105:   my ($string) = @_;
1.265     albertel 6106:   my @array;
                   6107: 
                   6108:   if($string !~ /^__ARRAY_REF__/) {
                   6109:       if (! ($string eq '' || !defined($string))) {
                   6110: 	  $array[0]='Array reference error';
                   6111:       }
                   6112:       return (\@array, $string);
                   6113:   }
                   6114: 
                   6115:   $string =~ s/^__ARRAY_REF__//;
                   6116: 
                   6117:   while($string !~ /^__END_ARRAY_REF__/) {
                   6118:       my $value='';
                   6119:       if($string =~ /^__HASH_REF__/) {
                   6120:           ($value, $string)=&str2hashref($string);
                   6121:           if(defined($value->{'error'})) {
                   6122:               $array[0] ='Array reference error';
                   6123:               return (\@array, $string);
                   6124:           }
                   6125:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6126:           ($value, $string)=&str2arrayref($string);
                   6127:           if($value->[0] eq 'Array reference error') {
                   6128:               $array[0] ='Array reference error';
                   6129:               return (\@array, $string);
                   6130:           }
                   6131:       } else {
                   6132: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6133:       }
                   6134:       $string =~ s/^&//;
                   6135: 
                   6136:       push(@array, $value);
1.191     harris41 6137:   }
1.265     albertel 6138: 
                   6139:   $string =~ s/^__END_ARRAY_REF__//;
                   6140: 
                   6141:   return (\@array, $string);
1.168     albertel 6142: }
                   6143: 
1.167     albertel 6144: # -------------------------------------------------------------------Temp Store
                   6145: 
1.168     albertel 6146: sub tmpreset {
                   6147:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6148:   if (!$symb) {
                   6149:     $symb=&symbread();
1.620     albertel 6150:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6151:   }
                   6152:   $symb=escape($symb);
                   6153: 
1.620     albertel 6154:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6155:   $namespace=~s/\//\_/g;
                   6156:   $namespace=~s/\W//g;
                   6157: 
1.620     albertel 6158:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6159:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6160:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6161:       $stuname=&get_requestor_ip();
1.591     albertel 6162:   }
1.1117    foxr     6163:   my $path=LONCAPA::tempdir();
1.168     albertel 6164:   my %hash;
                   6165:   if (tie(%hash,'GDBM_File',
                   6166: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6167: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6168:     foreach my $key (keys(%hash)) {
1.180     albertel 6169:       if ($key=~ /:$symb/) {
1.168     albertel 6170: 	delete($hash{$key});
                   6171:       }
                   6172:     }
                   6173:   }
                   6174: }
                   6175: 
1.167     albertel 6176: sub tmpstore {
1.168     albertel 6177:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6178: 
                   6179:   if (!$symb) {
                   6180:     $symb=&symbread();
1.620     albertel 6181:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6182:   }
                   6183:   $symb=escape($symb);
                   6184: 
                   6185:   if (!$namespace) {
                   6186:     # I don't think we would ever want to store this for a course.
                   6187:     # it seems this will only be used if we don't have a course.
1.620     albertel 6188:     #$namespace=$env{'request.course.id'};
1.168     albertel 6189:     #if (!$namespace) {
1.620     albertel 6190:       $namespace=$env{'request.state'};
1.168     albertel 6191:     #}
                   6192:   }
                   6193:   $namespace=~s/\//\_/g;
                   6194:   $namespace=~s/\W//g;
1.620     albertel 6195:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6196:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6197:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6198:       $stuname=&get_requestor_ip();
1.591     albertel 6199:   }
1.168     albertel 6200:   my $now=time;
                   6201:   my %hash;
1.1117    foxr     6202:   my $path=LONCAPA::tempdir();
1.168     albertel 6203:   if (tie(%hash,'GDBM_File',
                   6204: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6205: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6206:     $hash{"version:$symb"}++;
                   6207:     my $version=$hash{"version:$symb"};
                   6208:     my $allkeys=''; 
                   6209:     foreach my $key (keys(%$storehash)) {
                   6210:       $allkeys.=$key.':';
1.591     albertel 6211:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6212:     }
                   6213:     $hash{"$version:$symb:timestamp"}=$now;
                   6214:     $allkeys.='timestamp';
                   6215:     $hash{"$version:keys:$symb"}=$allkeys;
                   6216:     if (untie(%hash)) {
                   6217:       return 'ok';
                   6218:     } else {
                   6219:       return "error:$!";
                   6220:     }
                   6221:   } else {
                   6222:     return "error:$!";
                   6223:   }
                   6224: }
1.167     albertel 6225: 
1.168     albertel 6226: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6227: 
1.168     albertel 6228: sub tmprestore {
                   6229:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6230: 
1.168     albertel 6231:   if (!$symb) {
                   6232:     $symb=&symbread();
1.620     albertel 6233:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6234:   }
                   6235:   $symb=escape($symb);
                   6236: 
1.620     albertel 6237:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6238: 
1.620     albertel 6239:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6240:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6241:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6242:       $stuname=&get_requestor_ip();
1.591     albertel 6243:   }
1.168     albertel 6244:   my %returnhash;
                   6245:   $namespace=~s/\//\_/g;
                   6246:   $namespace=~s/\W//g;
                   6247:   my %hash;
1.1117    foxr     6248:   my $path=LONCAPA::tempdir();
1.168     albertel 6249:   if (tie(%hash,'GDBM_File',
                   6250: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6251: 	  &GDBM_READER(),0640)) {
1.168     albertel 6252:     my $version=$hash{"version:$symb"};
                   6253:     $returnhash{'version'}=$version;
                   6254:     my $scope;
                   6255:     for ($scope=1;$scope<=$version;$scope++) {
                   6256:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6257:       my @keys=split(/:/,$vkeys);
                   6258:       my $key;
                   6259:       $returnhash{"$scope:keys"}=$vkeys;
                   6260:       foreach $key (@keys) {
1.591     albertel 6261: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6262: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6263:       }
                   6264:     }
1.168     albertel 6265:     if (!(untie(%hash))) {
                   6266:       return "error:$!";
                   6267:     }
                   6268:   } else {
                   6269:     return "error:$!";
                   6270:   }
                   6271:   return %returnhash;
1.167     albertel 6272: }
                   6273: 
1.9       www      6274: # ----------------------------------------------------------------------- Store
                   6275: 
                   6276: sub store {
1.1269    raeburn  6277:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6278:     my $home='';
                   6279: 
1.168     albertel 6280:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6281: 
1.213     www      6282:     $symb=&symbclean($symb);
1.122     albertel 6283:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6284: 
1.620     albertel 6285:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6286:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6287: 
                   6288:     &devalidate($symb,$stuname,$domain);
1.109     www      6289: 
                   6290:     $symb=escape($symb);
1.187     www      6291:     if (!$namespace) { 
1.620     albertel 6292:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6293:           return ''; 
                   6294:        } 
                   6295:     }
1.620     albertel 6296:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6297: 
1.1434    raeburn  6298:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6299:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6300: 
1.12      www      6301:     my $namevalue='';
1.800     albertel 6302:     foreach my $key (keys(%$storehash)) {
                   6303:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6304:     }
1.12      www      6305:     $namevalue=~s/\&$//;
1.187     www      6306:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6307:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6308: }
                   6309: 
1.47      www      6310: # -------------------------------------------------------------- Critical Store
                   6311: 
                   6312: sub cstore {
1.1269    raeburn  6313:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6314:     my $home='';
                   6315: 
1.168     albertel 6316:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6317: 
1.213     www      6318:     $symb=&symbclean($symb);
1.122     albertel 6319:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6320: 
1.620     albertel 6321:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6322:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6323: 
                   6324:     &devalidate($symb,$stuname,$domain);
1.109     www      6325: 
                   6326:     $symb=escape($symb);
1.187     www      6327:     if (!$namespace) { 
1.620     albertel 6328:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6329:           return ''; 
                   6330:        } 
                   6331:     }
1.620     albertel 6332:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6333: 
1.1434    raeburn  6334:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6335:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6336: 
1.47      www      6337:     my $namevalue='';
1.800     albertel 6338:     foreach my $key (keys(%$storehash)) {
                   6339:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6340:     }
1.47      www      6341:     $namevalue=~s/\&$//;
1.187     www      6342:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6343:     return critical
1.1269    raeburn  6344:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6345: }
                   6346: 
1.9       www      6347: # --------------------------------------------------------------------- Restore
                   6348: 
                   6349: sub restore {
1.124     www      6350:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6351:     my $home='';
                   6352: 
1.168     albertel 6353:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6354: 
1.122     albertel 6355:     if (!$symb) {
1.1224    raeburn  6356:         return if ($namespace eq 'courserequests');
                   6357:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6358:     } else {
1.1224    raeburn  6359:         unless ($namespace eq 'courserequests') {
                   6360:             $symb=&escape(&symbclean($symb));
                   6361:         }
1.122     albertel 6362:     }
1.188     www      6363:     if (!$namespace) { 
1.620     albertel 6364:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6365:           return ''; 
                   6366:        } 
                   6367:     }
1.620     albertel 6368:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6369:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6370:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6371:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6372: 
1.12      www      6373:     my %returnhash=();
1.800     albertel 6374:     foreach my $line (split(/\&/,$answer)) {
                   6375: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6376:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6377:     }
1.75      www      6378:     my $version;
                   6379:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6380:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6381:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6382:        }
1.75      www      6383:     }
1.13      www      6384:     return %returnhash;
1.34      www      6385: }
                   6386: 
                   6387: # ---------------------------------------------------------- Course Description
1.1118    foxr     6388: #
                   6389: #  
1.34      www      6390: 
                   6391: sub coursedescription {
1.731     albertel 6392:     my ($courseid,$args)=@_;
1.34      www      6393:     $courseid=~s/^\///;
1.49      www      6394:     $courseid=~s/\_/\//g;
1.34      www      6395:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6396:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6397:     my $normalid=$cdomain.'_'.$cnum;
                   6398:     # need to always cache even if we get errors otherwise we keep 
                   6399:     # trying and trying and trying to get the course description.
                   6400:     my %envhash=();
                   6401:     my %returnhash=();
1.731     albertel 6402:     
                   6403:     my $expiretime=600;
                   6404:     if ($env{'request.course.id'} eq $normalid) {
                   6405: 	$expiretime=120;
                   6406:     }
                   6407: 
                   6408:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6409:     if (!$args->{'freshen_cache'}
                   6410: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6411: 	foreach my $key (keys(%env)) {
                   6412: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6413: 	    my ($setting) = $1;
                   6414: 	    $returnhash{$setting} = $env{$key};
                   6415: 	}
                   6416: 	return %returnhash;
                   6417:     }
                   6418: 
1.1118    foxr     6419:     # get the data again
                   6420: 
1.731     albertel 6421:     if (!$args->{'one_time'}) {
                   6422: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6423:     }
1.811     albertel 6424: 
1.34      www      6425:     if ($chome ne 'no_host') {
1.302     albertel 6426:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6427:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6428: 	   my $username = $env{'user.name'}; # Defult username
                   6429: 	   if(defined $args->{'user'}) {
                   6430: 	       $username = $args->{'user'};
                   6431: 	   }
1.129     albertel 6432:            $returnhash{'home'}= $chome;
                   6433: 	   $returnhash{'domain'} = $cdomain;
                   6434: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6435:            if (!defined($returnhash{'type'})) {
                   6436:                $returnhash{'type'} = 'Course';
                   6437:            }
1.130     albertel 6438:            while (my ($name,$value) = each %returnhash) {
1.53      www      6439:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6440:            }
1.270     www      6441:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6442:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6443: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6444:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6445:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6446:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6447:        }
                   6448:     }
1.731     albertel 6449:     if (!$args->{'one_time'}) {
1.949     raeburn  6450: 	&appenv(\%envhash);
1.731     albertel 6451:     }
1.302     albertel 6452:     return %returnhash;
1.461     www      6453: }
                   6454: 
1.1080    raeburn  6455: sub update_released_required {
                   6456:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6457:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6458:         $cid = $env{'request.course.id'};
                   6459:         $cdom = $env{'course.'.$cid.'.domain'};
                   6460:         $cnum = $env{'course.'.$cid.'.num'};
                   6461:         $chome = $env{'course.'.$cid.'.home'};
                   6462:     }
                   6463:     if ($needsrelease) {
                   6464:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6465:         my $needsupdate;
                   6466:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6467:             $needsupdate = 1;
                   6468:         } else {
                   6469:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6470:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6471:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6472:                 $needsupdate = 1;
                   6473:             }
                   6474:         }
                   6475:         if ($needsupdate) {
                   6476:             my %needshash = (
                   6477:                              'internal.releaserequired' => $needsrelease,
                   6478:                             );
                   6479:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6480:             if ($putresult eq 'ok') {
                   6481:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6482:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6483:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6484:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6485:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6486:                 }
                   6487:             }
                   6488:         }
                   6489:     }
                   6490:     return;
                   6491: }
                   6492: 
1.461     www      6493: # -------------------------------------------------See if a user is privileged
                   6494: 
                   6495: sub privileged {
1.1219    raeburn  6496:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6497:     my $now = time;
1.1219    raeburn  6498:     my $roles;
                   6499:     if (ref($possroles) eq 'ARRAY') {
                   6500:         $roles = $possroles; 
                   6501:     } else {
                   6502:         $roles = ['dc','su'];
                   6503:     }
                   6504:     if (ref($possdomains) eq 'ARRAY') {
                   6505:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6506:         foreach my $dom (@{$possdomains}) {
                   6507:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6508:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6509:                 foreach my $role (@{$roles}) {
                   6510:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6511:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6512:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6513:                             return 1 unless (($end && $end < $now) ||
                   6514:                                              ($start && $start > $now));
                   6515:                         }
                   6516:                     }
                   6517:                 }
                   6518:             }
                   6519:         }
                   6520:     } else {
                   6521:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6522:         my $now = time;
1.1170    droeschl 6523: 
1.1275    musolffc 6524:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6525:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6526:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6527:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6528:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6529:             }
1.1219    raeburn  6530:         }
                   6531:     }
                   6532:     return 0;
                   6533: }
1.1170    droeschl 6534: 
1.1219    raeburn  6535: sub privileged_by_domain {
                   6536:     my ($domains,$roles) = @_;
                   6537:     my %privileged = ();
                   6538:     my $cachetime = 60*60*24;
                   6539:     my $now = time;
                   6540:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6541:         return %privileged;
                   6542:     }
                   6543:     foreach my $dom (@{$domains}) {
                   6544:         next if (ref($privileged{$dom}) eq 'HASH');
                   6545:         my $needroles;
                   6546:         foreach my $role (@{$roles}) {
                   6547:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6548:             if (defined($cached)) {
                   6549:                 if (ref($result) eq 'HASH') {
                   6550:                     $privileged{$dom}{$role} = $result;
                   6551:                 }
                   6552:             } else {
                   6553:                 $needroles = 1;
                   6554:             }
                   6555:         }
                   6556:         if ($needroles) {
                   6557:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6558:             $privileged{$dom} = {};
                   6559:             foreach my $server (keys(%dompersonnel)) {
                   6560:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6561:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6562:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6563:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6564:                         next if ($end && $end < $now);
                   6565:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6566:                             $dompersonnel{$server}{$item};
                   6567:                     }
                   6568:                 }
                   6569:             }
                   6570:             if (ref($privileged{$dom}) eq 'HASH') {
                   6571:                 foreach my $role (@{$roles}) {
                   6572:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6573:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6574:                     } else {
                   6575:                         my %hash = ();
                   6576:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6577:                     }
                   6578:                 }
                   6579:             }
                   6580:         }
                   6581:     }
                   6582:     return %privileged;
1.9       www      6583: }
1.1       albertel 6584: 
1.103     harris41 6585: # -------------------------------------------------------- Get user privileges
1.11      www      6586: 
                   6587: sub rolesinit {
1.1169    droeschl 6588:     my ($domain, $username) = @_;
                   6589:     my %userroles = ('user.login.time' => time);
                   6590:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6591: 
                   6592:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6593:     # also, blocking can be triggered by an activating timer
                   6594:     # it's saved in the user's %env.
                   6595:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6596:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6597:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6598:         %timerintchk, %timerintenv);
                   6599: 
1.1162    raeburn  6600:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6601:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6602:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6603:     }
1.1169    droeschl 6604: 
1.1162    raeburn  6605:     foreach my $key (keys(%timerinterval)) {
                   6606:         my ($cid,$rest) = split(/\0/,$key);
                   6607:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6608:     }
1.1169    droeschl 6609: 
1.11      www      6610:     my %allroles=();
1.1162    raeburn  6611:     my %allgroups=();
1.11      www      6612: 
1.1274    raeburn  6613:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6614:         my $role = $rolesdump{$area};
                   6615:         $area =~ s/\_\w\w$//;
                   6616: 
                   6617:         my ($trole, $tend, $tstart, $group_privs);
                   6618: 
                   6619:         if ($role =~ /^cr/) {
                   6620:         # Custom role, defined by a user 
                   6621:         # e.g., user.role.cr/msu/smith/mynewrole
                   6622:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6623:                 $trole = $1;
                   6624:                 ($tend, $tstart) = split('_', $2);
                   6625:             } else {
                   6626:                 $trole = $role;
                   6627:             }
                   6628:         } elsif ($role =~ m|^gr/|) {
                   6629:         # Role of member in a group, defined within a course/community
                   6630:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6631:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6632:             next if $tstart eq '-1';
                   6633:             ($trole, $group_privs) = split(/\//, $trole);
                   6634:             $group_privs = &unescape($group_privs);
                   6635:         } else {
                   6636:         # Just a normal role, defined in roles.tab
                   6637:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6638:         }
                   6639: 
                   6640:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6641:                  $username);
                   6642:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6643: 
                   6644:         # role expired or not available yet?
                   6645:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6646:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6647: 
                   6648:         next if $area eq '' or $trole eq '';
                   6649: 
                   6650:         my $spec = "$trole.$area";
                   6651:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6652: 
                   6653:         if ($trole =~ /^cr\//) {
                   6654:         # Custom role, defined by a user
                   6655:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6656:         } elsif ($trole eq 'gr') {
                   6657:         # Role of a member in a group, defined within a course/community
                   6658:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6659:             next;
                   6660:         } else {
                   6661:         # Normal role, defined in roles.tab
                   6662:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6663:         }
                   6664: 
                   6665:         my $cid = $tdomain.'_'.$trest;
                   6666:         unless ($firstaccchk{$cid}) {
                   6667:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6668:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6669:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6670:                         $coursetimerstarts{$cid}{$item}; 
                   6671:                 }
                   6672:             }
                   6673:             $firstaccchk{$cid} = 1;
                   6674:         }
                   6675:         unless ($timerintchk{$cid}) {
                   6676:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6677:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6678:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6679:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6680:                 }
1.12      www      6681:             }
1.1169    droeschl 6682:             $timerintchk{$cid} = 1;
1.191     harris41 6683:         }
1.11      www      6684:     }
1.1169    droeschl 6685: 
1.1341    raeburn  6686:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6687:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6688:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6689:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6690: 
1.1162    raeburn  6691:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6692: }
                   6693: 
1.567     raeburn  6694: sub set_arearole {
1.1215    raeburn  6695:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6696:     unless ($nolog) {
1.567     raeburn  6697: # log the associated role with the area
1.1215    raeburn  6698:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6699:     }
1.743     albertel 6700:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6701: }
                   6702: 
                   6703: sub custom_roleprivs {
                   6704:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6705:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6706:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6707:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6708:         my ($rdummy,$roledef)=
                   6709:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6710:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6711:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6712:             if (defined($syspriv)) {
1.1043    raeburn  6713:                 if ($trest =~ /^$match_community$/) {
                   6714:                     $syspriv =~ s/bre\&S//; 
                   6715:                 }
1.567     raeburn  6716:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6717:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6718:             }
                   6719:             if ($tdomain ne '') {
                   6720:                 if (defined($dompriv)) {
                   6721:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6722:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6723:                 }
                   6724:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6725:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6726:                         my $rolename = $1;
                   6727:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6728:                     }
1.567     raeburn  6729:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6730:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6731:                 }
                   6732:             }
                   6733:         }
                   6734:     }
                   6735: }
                   6736: 
1.1332    raeburn  6737: sub course_adhocrole_privs {
                   6738:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6739:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6740:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6741:         my (%currprivs,%storeprivs);
                   6742:         foreach my $item (split(/:/,$coursepriv)) {
                   6743:             my ($priv,$restrict) = split(/\&/,$item);
                   6744:             $currprivs{$priv} = $restrict;
                   6745:         }
                   6746:         my (%possadd,%possremove,%full);
                   6747:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6748:             my ($priv,$restrict)=split(/\&/,$item);
                   6749:             $full{$priv} = $restrict;
                   6750:         }
                   6751:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6752:              next if ($item eq '');
                   6753:              my ($rule,$rest) = split(/=/,$item);
                   6754:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6755:              foreach my $priv (split(/:/,$rest)) {
                   6756:                  if ($priv ne '') {
                   6757:                      if ($rule eq 'off') {
                   6758:                          $possremove{$priv} = 1;
                   6759:                      } else {
                   6760:                          $possadd{$priv} = 1;
                   6761:                      }
                   6762:                  }
                   6763:              }
                   6764:          }
                   6765:          foreach my $priv (sort(keys(%full))) {
                   6766:              if (exists($currprivs{$priv})) {
                   6767:                  unless (exists($possremove{$priv})) {
                   6768:                      $storeprivs{$priv} = $currprivs{$priv};
                   6769:                  }
                   6770:              } elsif (exists($possadd{$priv})) {
                   6771:                  $storeprivs{$priv} = $full{$priv};
                   6772:              }
                   6773:          }
                   6774:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6775:      }
                   6776:      return $coursepriv;
                   6777: }
                   6778: 
1.678     raeburn  6779: sub group_roleprivs {
                   6780:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6781:     my $access = 1;
                   6782:     my $now = time;
                   6783:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6784:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6785:     if ($access) {
1.811     albertel 6786:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6787:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6788:     }
                   6789: }
1.567     raeburn  6790: 
                   6791: sub standard_roleprivs {
                   6792:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6793:     if (defined($pr{$trole.':s'})) {
                   6794:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6795:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6796:     }
                   6797:     if ($tdomain ne '') {
                   6798:         if (defined($pr{$trole.':d'})) {
                   6799:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6800:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6801:         }
                   6802:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6803:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6804:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6805:         }
                   6806:     }
                   6807: }
                   6808: 
                   6809: sub set_userprivs {
1.1064    raeburn  6810:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6811:     my $author=0;
                   6812:     my $adv=0;
1.1341    raeburn  6813:     my $rar=0;
1.678     raeburn  6814:     my %grouproles = ();
                   6815:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6816:         my @groupkeys; 
1.1000    raeburn  6817:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6818:             push(@groupkeys,$role);
                   6819:         }
                   6820:         if (ref($groups_roles) eq 'HASH') {
                   6821:             foreach my $key (keys(%{$groups_roles})) {
                   6822:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6823:                     push(@groupkeys,$key);
                   6824:                 }
                   6825:             }
                   6826:         }
                   6827:         if (@groupkeys > 0) {
                   6828:             foreach my $role (@groupkeys) {
                   6829:                 my ($trole,$area,$sec,$extendedarea);
                   6830:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6831:                     $trole = $1;
                   6832:                     $area = $2;
                   6833:                     $sec = $3;
                   6834:                     $extendedarea = $area.$sec;
                   6835:                     if (exists($$allgroups{$area})) {
                   6836:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6837:                             my $spec = $trole.'.'.$extendedarea;
                   6838:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6839:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6840:                         }
1.678     raeburn  6841:                     }
                   6842:                 }
                   6843:             }
                   6844:         }
                   6845:     }
1.800     albertel 6846:     foreach my $group (keys(%grouproles)) {
                   6847:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6848:     }
1.800     albertel 6849:     foreach my $role (keys(%{$allroles})) {
                   6850:         my %thesepriv;
1.941     raeburn  6851:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6852:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6853:             if ($item ne '') {
                   6854:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6855:                 if ($restrictions eq '') {
                   6856:                     $thesepriv{$privilege}='F';
                   6857:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6858:                     $thesepriv{$privilege}.=$restrictions;
                   6859:                 }
                   6860:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6861:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6862:             }
                   6863:         }
                   6864:         my $thesestr='';
1.1104    raeburn  6865:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6866: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6867: 	}
                   6868:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6869:     }
1.1341    raeburn  6870:     return ($author,$adv,$rar);
1.567     raeburn  6871: }
                   6872: 
1.994     raeburn  6873: sub role_status {
1.1104    raeburn  6874:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6875:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6876:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6877:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6878:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6879:             $$where = '/'.$two;
1.994     raeburn  6880:             $$trolecode=$$role.'.'.$$where;
                   6881:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6882:             $$tstatus='is';
1.1104    raeburn  6883:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6884:                 $$tstatus='future';
1.1034    raeburn  6885:                 if ($$tstart<$now) {
                   6886:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6887:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6888:                             my (%allroles,%allgroups,$group_privs,
                   6889:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6890:                             my %userroles = (
                   6891:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6892:                             );
1.1064    raeburn  6893:                             @rolecodes = ('cm'); 
1.1002    raeburn  6894:                             my $spec=$$role.'.'.$$where;
                   6895:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6896:                             if ($$role =~ /^cr\//) {
                   6897:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6898:                                 push(@rolecodes,'cr');
1.1002    raeburn  6899:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6900:                                 push(@rolecodes,$$role);
1.1002    raeburn  6901:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6902:                                                     $env{'user.name'});
1.1064    raeburn  6903:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6904:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6905:                                 $group_privs = &unescape($group_privs);
                   6906:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6907:                                 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  6908:                                 &get_groups_roles($tdomain,$trest,
                   6909:                                                   \%course_roles,\@rolecodes,
                   6910:                                                   \%groups_roles);
1.1002    raeburn  6911:                             } else {
1.1064    raeburn  6912:                                 push(@rolecodes,$$role);
1.1002    raeburn  6913:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6914:                             }
1.1341    raeburn  6915:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6916:                                                                    \%groups_roles);
1.1064    raeburn  6917:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6918:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6919:                         }
                   6920:                     }
1.1034    raeburn  6921:                     $$tstatus = 'is';
1.1002    raeburn  6922:                 }
1.994     raeburn  6923:             }
                   6924:             if ($$tend) {
1.1104    raeburn  6925:                 if ($$tend<$update) {
1.994     raeburn  6926:                     $$tstatus='expired';
                   6927:                 } elsif ($$tend<$now) {
                   6928:                     $$tstatus='will_not';
                   6929:                 }
                   6930:             }
                   6931:         }
                   6932:     }
                   6933: }
                   6934: 
1.1104    raeburn  6935: sub get_groups_roles {
                   6936:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6937:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6938:                   (ref($rolecodes) eq 'ARRAY') && 
                   6939:                   (ref($groups_roles) eq 'HASH')); 
                   6940:     if (keys(%{$cdom_courseroles}) > 0) {
                   6941:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6942:         if ($cdom ne '' && $cnum ne '') {
                   6943:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6944:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6945:                     my $crsrole = $1;
                   6946:                     my $crssec = $2;
                   6947:                     if ($crsrole =~ /^cr/) {
                   6948:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6949:                             push(@{$rolecodes},'cr');
                   6950:                         }
                   6951:                     } else {
                   6952:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6953:                             push(@{$rolecodes},$crsrole);
                   6954:                         }
                   6955:                     }
                   6956:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6957:                     if ($crssec ne '') {
                   6958:                         $rolekey .= "/$crssec";
                   6959:                     }
                   6960:                     $rolekey .= './';
                   6961:                     $groups_roles->{$rolekey} = $rolecodes;
                   6962:                 }
                   6963:             }
                   6964:         }
                   6965:     }
                   6966:     return;
                   6967: }
                   6968: 
                   6969: sub delete_env_groupprivs {
                   6970:     my ($where,$courseroles,$possroles) = @_;
                   6971:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6972:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6973:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6974:         %{$courseroles->{$udom}} =
                   6975:             &get_my_roles('','','userroles',['active'],
                   6976:                           $possroles,[$udom],1);
                   6977:     }
                   6978:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6979:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6980:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6981:             my $area = '/'.$cdom.'/'.$cnum;
                   6982:             my $privkey = "user.priv.$crsrole.$area";
                   6983:             if ($crssec ne '') {
                   6984:                 $privkey .= '/'.$crssec;
                   6985:             }
                   6986:             $privkey .= ".$area/$group";
                   6987:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6988:         }
                   6989:     }
                   6990:     return;
                   6991: }
                   6992: 
1.994     raeburn  6993: sub check_adhoc_privs {
1.1329    raeburn  6994:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6995:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6996:     if ($sec) {
                   6997:         $cckey .= '/'.$sec;
                   6998:     } 
1.1185    raeburn  6999:     my $setprivs;
1.994     raeburn  7000:     if ($env{$cckey}) {
                   7001:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  7002:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  7003:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  7004:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7005:             $setprivs = 1;
1.994     raeburn  7006:         }
                   7007:     } else {
1.1330    raeburn  7008:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7009:         $setprivs = 1;
1.994     raeburn  7010:     }
1.1185    raeburn  7011:     return $setprivs;
1.994     raeburn  7012: }
                   7013: 
                   7014: sub set_adhoc_privileges {
1.1326    raeburn  7015: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  7016:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7017:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  7018:     if ($sec ne '') {
                   7019:         $area .= '/'.$sec;
                   7020:     }
1.994     raeburn  7021:     my $spec = $role.'.'.$area;
                   7022:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  7023:                                   $env{'user.name'},1);
1.1326    raeburn  7024:     my %rolehash = ();
1.1332    raeburn  7025:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7026:         my $rolename = $1;
1.1326    raeburn  7027:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  7028:         my %domdef = &get_domain_defaults($dcdom);
                   7029:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7030:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7031:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7032:             }
                   7033:         }
1.1326    raeburn  7034:     } else {
                   7035:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7036:     }
1.1341    raeburn  7037:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7038:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  7039:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  7040:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7041:             ($caller eq 'tiny')) {
1.1088    raeburn  7042:         &appenv( {'request.role'        => $spec,
                   7043:                   'request.role.domain' => $dcdom,
1.1332    raeburn  7044:                   'request.course.sec'  => $sec,
1.1088    raeburn  7045:                  }
                   7046:                );
                   7047:         my $tadv=0;
                   7048:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7049:         &appenv({'request.role.adv'    => $tadv});
                   7050:     }
1.994     raeburn  7051: }
                   7052: 
1.12      www      7053: # --------------------------------------------------------------- get interface
                   7054: 
                   7055: sub get {
1.131     albertel 7056:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7057:    my $items='';
1.800     albertel 7058:    foreach my $item (@$storearr) {
                   7059:        $items.=&escape($item).'&';
1.191     harris41 7060:    }
1.12      www      7061:    $items=~s/\&$//;
1.620     albertel 7062:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7063:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7064:    my $uhome=&homeserver($uname,$udomain);
                   7065: 
1.133     albertel 7066:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7067:    my @pairs=split(/\&/,$rep);
1.273     albertel 7068:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7069:      return @pairs;
                   7070:    }
1.15      www      7071:    my %returnhash=();
1.42      www      7072:    my $i=0;
1.800     albertel 7073:    foreach my $item (@$storearr) {
                   7074:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7075:       $i++;
1.191     harris41 7076:    }
1.15      www      7077:    return %returnhash;
1.27      www      7078: }
                   7079: 
                   7080: # --------------------------------------------------------------- del interface
                   7081: 
                   7082: sub del {
1.133     albertel 7083:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7084:    my $items='';
1.800     albertel 7085:    foreach my $item (@$storearr) {
                   7086:        $items.=&escape($item).'&';
1.191     harris41 7087:    }
1.984     neumanie 7088: 
1.27      www      7089:    $items=~s/\&$//;
1.620     albertel 7090:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7091:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7092:    my $uhome=&homeserver($uname,$udomain);
                   7093:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7094: }
                   7095: 
                   7096: # -------------------------------------------------------------- dump interface
                   7097: 
1.1180    droeschl 7098: sub unserialize {
                   7099:     my ($rep, $escapedkeys) = @_;
                   7100: 
                   7101:     return {} if $rep =~ /^error/;
                   7102: 
                   7103:     my %returnhash=();
1.1252    raeburn  7104: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 7105: 	    my ($key, $value) = split(/=/, $item, 2);
                   7106: 	    $key = unescape($key) unless $escapedkeys;
                   7107: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  7108: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 7109: 	}
                   7110:     #return %returnhash;
                   7111:     return \%returnhash;
                   7112: }        
                   7113: 
                   7114: # see Lond::dump_with_regexp
                   7115: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7116: sub dump {
1.1462    raeburn  7117:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7118:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7119:     if (!$uname) { $uname=$env{'user.name'}; }
                   7120:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7121: 
1.1266    raeburn  7122:     if ($regexp) {
                   7123:         $regexp=&escape($regexp);
                   7124:     } else {
                   7125:         $regexp='.';
                   7126:     }
1.1180    droeschl 7127:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   7128:         # user is hosted on this machine
1.1266    raeburn  7129:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  7130:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 7131:         return %{unserialize($reply, $escapedkeys)};
                   7132:     }
1.1462    raeburn  7133:     my $rep;
                   7134:     if ($encrypt) {
                   7135:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463    raeburn  7136:     } else {
1.1462    raeburn  7137:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7138:     }
1.755     albertel 7139:     my @pairs=split(/\&/,$rep);
                   7140:     my %returnhash=();
1.1098    foxr     7141:     if (!($rep =~ /^error/ )) {
                   7142: 	foreach my $item (@pairs) {
                   7143: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 7144:         $key = unescape($key) unless $escapedkeys;
                   7145:         #$key = &unescape($key);
1.1098    foxr     7146: 	    next if ($key =~ /^error: 2 /);
                   7147: 	    $returnhash{$key}=&thaw_unescape($value);
                   7148: 	}
1.755     albertel 7149:     }
                   7150:     return %returnhash;
1.407     www      7151: }
                   7152: 
1.1098    foxr     7153: 
1.717     albertel 7154: # --------------------------------------------------------- dumpstore interface
                   7155: 
                   7156: sub dumpstore {
                   7157:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 7158:    # same as dump but keys must be escaped. They may contain colon separated
                   7159:    # lists of values that may themself contain colons (e.g. symbs).
                   7160:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7161: }
                   7162: 
1.407     www      7163: # -------------------------------------------------------------- keys interface
                   7164: 
                   7165: sub getkeys {
                   7166:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7167:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7168:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7169:    my $uhome=&homeserver($uname,$udomain);
                   7170:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7171:    my @keyarray=();
1.800     albertel 7172:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7173:       next if ($key =~ /^error: 2 /);
1.800     albertel 7174:       push(@keyarray,&unescape($key));
1.407     www      7175:    }
                   7176:    return @keyarray;
1.318     matthew  7177: }
                   7178: 
1.319     matthew  7179: # --------------------------------------------------------------- currentdump
                   7180: sub currentdump {
1.328     matthew  7181:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7182:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7183:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7184:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7185:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 7186:    my $rep;
                   7187: 
                   7188:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7189:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   7190:                    $courseid)));
                   7191:    } else {
                   7192:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7193:    }
                   7194: 
1.318     matthew  7195:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7196:    #
1.318     matthew  7197:    my %returnhash=();
1.319     matthew  7198:    #
1.1343    raeburn  7199:    if ($rep eq 'unknown_cmd') {
1.319     matthew  7200:        # an old lond will not know currentdump
                   7201:        # Do a dump and make it look like a currentdump
1.822     albertel 7202:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7203:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7204:        my %hash = @tmp;
                   7205:        @tmp=();
1.424     matthew  7206:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7207:    } else {
                   7208:        my @pairs=split(/\&/,$rep);
1.800     albertel 7209:        foreach my $pair (@pairs) {
                   7210:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7211:            my ($symb,$param) = split(/:/,$key);
                   7212:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7213:                                                         &thaw_unescape($value);
1.319     matthew  7214:        }
1.191     harris41 7215:    }
1.12      www      7216:    return %returnhash;
1.424     matthew  7217: }
                   7218: 
                   7219: sub convert_dump_to_currentdump{
                   7220:     my %hash = %{shift()};
                   7221:     my %returnhash;
                   7222:     # Code ripped from lond, essentially.  The only difference
                   7223:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7224:     # we might run in to problems with parameter names =~ /^v\./
                   7225:     while (my ($key,$value) = each(%hash)) {
                   7226:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7227: 	$symb  = &unescape($symb);
                   7228: 	$param = &unescape($param);
1.424     matthew  7229:         next if ($v eq 'version' || $symb eq 'keys');
                   7230:         next if (exists($returnhash{$symb}) &&
                   7231:                  exists($returnhash{$symb}->{$param}) &&
                   7232:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7233:         $returnhash{$symb}->{$param}=$value;
                   7234:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7235:     }
                   7236:     #
                   7237:     # Remove all of the keys in the hashes which keep track of
                   7238:     # the version of the parameter.
                   7239:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7240:         # use a foreach because we are going to delete from the hash.
                   7241:         foreach my $key (keys(%$param_hash)) {
                   7242:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7243:         }
                   7244:     }
                   7245:     return \%returnhash;
1.12      www      7246: }
                   7247: 
1.627     albertel 7248: # ------------------------------------------------------ critical inc interface
                   7249: 
                   7250: sub cinc {
                   7251:     return &inc(@_,'critical');
                   7252: }
                   7253: 
1.449     matthew  7254: # --------------------------------------------------------------- inc interface
                   7255: 
                   7256: sub inc {
1.627     albertel 7257:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7258:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7259:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7260:     my $uhome=&homeserver($uname,$udomain);
                   7261:     my $items='';
                   7262:     if (! ref($store)) {
                   7263:         # got a single value, so use that instead
                   7264:         $items = &escape($store).'=&';
                   7265:     } elsif (ref($store) eq 'SCALAR') {
                   7266:         $items = &escape($$store).'=&';        
                   7267:     } elsif (ref($store) eq 'ARRAY') {
                   7268:         $items = join('=&',map {&escape($_);} @{$store});
                   7269:     } elsif (ref($store) eq 'HASH') {
                   7270:         while (my($key,$value) = each(%{$store})) {
                   7271:             $items.= &escape($key).'='.&escape($value).'&';
                   7272:         }
                   7273:     }
                   7274:     $items=~s/\&$//;
1.627     albertel 7275:     if ($critical) {
                   7276: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7277:     } else {
                   7278: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7279:     }
1.449     matthew  7280: }
                   7281: 
1.12      www      7282: # --------------------------------------------------------------- put interface
                   7283: 
                   7284: sub put {
1.1462    raeburn  7285:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7286:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7287:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7288:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7289:    my $items='';
1.800     albertel 7290:    foreach my $item (keys(%$storehash)) {
                   7291:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7292:    }
1.12      www      7293:    $items=~s/\&$//;
1.1462    raeburn  7294:    if ($encrypt) {
                   7295:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7296:    } else {
                   7297:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7298:    }
1.47      www      7299: }
                   7300: 
1.631     albertel 7301: # ------------------------------------------------------------ newput interface
                   7302: 
                   7303: sub newput {
                   7304:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7305:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7306:    if (!$uname) { $uname=$env{'user.name'}; }
                   7307:    my $uhome=&homeserver($uname,$udomain);
                   7308:    my $items='';
                   7309:    foreach my $key (keys(%$storehash)) {
                   7310:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7311:    }
                   7312:    $items=~s/\&$//;
                   7313:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7314: }
                   7315: 
                   7316: # ---------------------------------------------------------  putstore interface
                   7317: 
1.524     raeburn  7318: sub putstore {
1.1269    raeburn  7319:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7320:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7321:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7322:    my $uhome=&homeserver($uname,$udomain);
                   7323:    my $items='';
1.715     albertel 7324:    foreach my $key (keys(%$storehash)) {
                   7325:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7326:    }
1.715     albertel 7327:    $items=~s/\&$//;
1.716     albertel 7328:    my $esc_symb=&escape($symb);
                   7329:    my $esc_v=&escape($version);
1.715     albertel 7330:    my $reply =
1.716     albertel 7331:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7332: 	      $uhome);
1.1269    raeburn  7333:    if (($tolog) && ($reply eq 'ok')) {
                   7334:        my $namevalue='';
                   7335:        foreach my $key (keys(%{$storehash})) {
                   7336:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7337:        }
1.1434    raeburn  7338:        my $ip = &get_requestor_ip();
                   7339:        $namevalue .= 'ip='.&escape($ip).
1.1269    raeburn  7340:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7341:                      '&version='.$esc_v.
                   7342:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7343:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7344:    }
1.715     albertel 7345:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7346:        # gfall back to way things use to be done
1.715     albertel 7347:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7348: 			    $uname);
1.524     raeburn  7349:    }
1.715     albertel 7350:    return $reply;
                   7351: }
                   7352: 
                   7353: sub old_putstore {
1.716     albertel 7354:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7355:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7356:     if (!$uname) { $uname=$env{'user.name'}; }
                   7357:     my $uhome=&homeserver($uname,$udomain);
                   7358:     my %newstorehash;
1.800     albertel 7359:     foreach my $item (keys(%$storehash)) {
                   7360: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7361: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7362:     }
                   7363:     my $items='';
                   7364:     my %allitems = ();
1.800     albertel 7365:     foreach my $item (keys(%newstorehash)) {
                   7366: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7367: 	    my $key = $1.':keys:'.$2;
                   7368: 	    $allitems{$key} .= $3.':';
                   7369: 	}
1.800     albertel 7370: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7371:     }
1.800     albertel 7372:     foreach my $item (keys(%allitems)) {
                   7373: 	$allitems{$item} =~ s/\:$//;
                   7374: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7375:     }
                   7376:     $items=~s/\&$//;
                   7377:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7378: }
                   7379: 
1.47      www      7380: # ------------------------------------------------------ critical put interface
                   7381: 
                   7382: sub cput {
1.134     albertel 7383:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7384:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7385:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7386:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7387:    my $items='';
1.800     albertel 7388:    foreach my $item (keys(%$storehash)) {
                   7389:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7390:    }
1.47      www      7391:    $items=~s/\&$//;
1.134     albertel 7392:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7393: }
                   7394: 
                   7395: # -------------------------------------------------------------- eget interface
                   7396: 
                   7397: sub eget {
1.133     albertel 7398:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7399:    my $items='';
1.800     albertel 7400:    foreach my $item (@$storearr) {
                   7401:        $items.=&escape($item).'&';
1.191     harris41 7402:    }
1.12      www      7403:    $items=~s/\&$//;
1.620     albertel 7404:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7405:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7406:    my $uhome=&homeserver($uname,$udomain);
                   7407:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7408:    my @pairs=split(/\&/,$rep);
                   7409:    my %returnhash=();
1.42      www      7410:    my $i=0;
1.800     albertel 7411:    foreach my $item (@$storearr) {
                   7412:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7413:       $i++;
1.191     harris41 7414:    }
1.12      www      7415:    return %returnhash;
                   7416: }
                   7417: 
1.667     albertel 7418: # ------------------------------------------------------------ tmpput interface
                   7419: sub tmpput {
1.802     raeburn  7420:     my ($storehash,$server,$context)=@_;
1.667     albertel 7421:     my $items='';
1.800     albertel 7422:     foreach my $item (keys(%$storehash)) {
                   7423: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7424:     }
                   7425:     $items=~s/\&$//;
1.802     raeburn  7426:     if (defined($context)) {
                   7427:         $items .= ':'.&escape($context);
                   7428:     }
1.667     albertel 7429:     return &reply("tmpput:$items",$server);
                   7430: }
                   7431: 
                   7432: # ------------------------------------------------------------ tmpget interface
                   7433: sub tmpget {
1.688     albertel 7434:     my ($token,$server)=@_;
                   7435:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7436:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7437:     my %returnhash;
1.1328    raeburn  7438:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7439:         return %returnhash;
                   7440:     }
1.667     albertel 7441:     foreach my $item (split(/\&/,$rep)) {
                   7442: 	my ($key,$value)=split(/=/,$item);
                   7443: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7444:     }
                   7445:     return %returnhash;
                   7446: }
                   7447: 
1.1113    raeburn  7448: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7449: sub tmpdel {
                   7450:     my ($token,$server)=@_;
                   7451:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7452:     return &reply("tmpdel:$token",$server);
                   7453: }
                   7454: 
1.1198    raeburn  7455: # ------------------------------------------------------------ get_timebased_id 
                   7456: 
                   7457: sub get_timebased_id {
                   7458:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7459:         $maxtries) = @_;
                   7460:     my ($newid,$error,$dellock);
                   7461:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7462:         return ('','ok','invalid call to get suffix');
                   7463:     }
                   7464: 
                   7465: # set defaults for any optional args for which values were not supplied
                   7466:     if ($who eq '') {
                   7467:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7468:     }
                   7469:     if (!$locktries) {
                   7470:         $locktries = 3;
                   7471:     }
                   7472:     if (!$maxtries) {
                   7473:         $maxtries = 10;
                   7474:     }
                   7475:     
                   7476:     if (($cdom eq '') || ($cnum eq '')) {
                   7477:         if ($env{'request.course.id'}) {
                   7478:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7479:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7480:         }
                   7481:         if (($cdom eq '') || ($cnum eq '')) {
                   7482:             return ('','ok','call to get suffix not in course context');
                   7483:         }
                   7484:     }
                   7485: 
                   7486: # construct locking item
                   7487:     my $lockhash = {
                   7488:                       $prefix."\0".'locked_'.$keyid => $who,
                   7489:                    };
                   7490:     my $tries = 0;
                   7491: 
                   7492: # attempt to get lock on nohist_$namespace file
                   7493:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7494:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7495:         $tries ++;
                   7496:         sleep 1;
                   7497:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7498:     }
                   7499: 
                   7500: # attempt to get unique identifier, based on current timestamp
                   7501:     if ($gotlock eq 'ok') {
                   7502:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7503:         my $id = time;
                   7504:         $newid = $id;
1.1268    raeburn  7505:         if ($idtype eq 'addcode') {
                   7506:             $newid .= &sixnum_code();
                   7507:         }
1.1198    raeburn  7508:         my $idtries = 0;
                   7509:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7510:             if ($idtype eq 'concat') {
                   7511:                 $newid = $id.$idtries;
1.1268    raeburn  7512:             } elsif ($idtype eq 'addcode') {
                   7513:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7514:             } else {
                   7515:                 $newid ++;
                   7516:             }
                   7517:             $idtries ++;
                   7518:         }
                   7519:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7520:             my %new_item =  (
                   7521:                               $prefix."\0".$newid => $who,
                   7522:                             );
                   7523:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7524:                                                  $cdom,$cnum);
                   7525:             if ($putresult ne 'ok') {
                   7526:                 undef($newid);
                   7527:                 $error = 'error saving new item: '.$putresult;
                   7528:             }
                   7529:         } else {
1.1268    raeburn  7530:              undef($newid);
1.1198    raeburn  7531:              $error = ('error: no unique suffix available for the new item ');
                   7532:         }
                   7533: #  remove lock
                   7534:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7535:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7536:     } else {
                   7537:         $error = "error: could not obtain lockfile\n";
                   7538:         $dellock = 'ok';
1.1276    raeburn  7539:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7540:             $dellock = 'nolock';
                   7541:         }
1.1198    raeburn  7542:     }
                   7543:     return ($newid,$dellock,$error);
                   7544: }
                   7545: 
1.1268    raeburn  7546: sub sixnum_code {
                   7547:     my $code;
                   7548:     for (0..6) {
                   7549:         $code .= int( rand(9) );
                   7550:     }
                   7551:     return $code;
                   7552: }
                   7553: 
1.765     albertel 7554: # -------------------------------------------------- portfolio access checking
                   7555: 
                   7556: sub portfolio_access {
1.1270    raeburn  7557:     my ($requrl,$clientip) = @_;
1.765     albertel 7558:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7559:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7560:     if ($result) {
                   7561:         my %setters;
                   7562:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7563:             my ($startblock,$endblock) =
                   7564:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7565:             if ($startblock && $endblock) {
                   7566:                 return 'B';
                   7567:             }
                   7568:         } else {
                   7569:             my ($startblock,$endblock) =
                   7570:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7571:             if ($startblock && $endblock) {
                   7572:                 return 'B';
                   7573:             }
                   7574:         }
                   7575:     }
1.765     albertel 7576:     if ($result eq 'ok') {
1.766     albertel 7577:        return 'F';
1.765     albertel 7578:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7579:        return 'A';
1.765     albertel 7580:     }
1.766     albertel 7581:     return '';
1.765     albertel 7582: }
                   7583: 
                   7584: sub get_portfolio_access {
1.1270    raeburn  7585:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7586: 
                   7587:     if (!ref($access_hash)) {
                   7588: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7589: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7590: 						   $file_name);
                   7591: 	$access_hash = $access_controls{$file_name};
                   7592:     }
                   7593: 
1.1270    raeburn  7594:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7595:     my $now = time;
                   7596:     if (ref($access_hash) eq 'HASH') {
                   7597:         foreach my $key (keys(%{$access_hash})) {
                   7598:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7599:             if ($start > $now) {
                   7600:                 next;
                   7601:             }
                   7602:             if ($end && $end<$now) {
                   7603:                 next;
                   7604:             }
                   7605:             if ($scope eq 'public') {
                   7606:                 $public = $key;
                   7607:                 last;
                   7608:             } elsif ($scope eq 'guest') {
                   7609:                 $guest = $key;
                   7610:             } elsif ($scope eq 'domains') {
                   7611:                 push(@domains,$key);
                   7612:             } elsif ($scope eq 'users') {
                   7613:                 push(@users,$key);
                   7614:             } elsif ($scope eq 'course') {
                   7615:                 push(@courses,$key);
                   7616:             } elsif ($scope eq 'group') {
                   7617:                 push(@groups,$key);
1.1270    raeburn  7618:             } elsif ($scope eq 'ip') {
                   7619:                 push(@ips,$key);
1.765     albertel 7620:             }
                   7621:         }
                   7622:         if ($public) {
                   7623:             return 'ok';
1.1270    raeburn  7624:         } elsif (@ips > 0) {
                   7625:             my $allowed;
                   7626:             foreach my $ipkey (@ips) {
                   7627:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7628:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7629:                         $allowed = 1;
                   7630:                         last; 
                   7631:                     }
                   7632:                 }
                   7633:             }
                   7634:             if ($allowed) {
                   7635:                 return 'ok';
                   7636:             }
1.765     albertel 7637:         }
                   7638:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7639:             if ($guest) {
                   7640:                 return $guest;
                   7641:             }
                   7642:         } else {
                   7643:             if (@domains > 0) {
                   7644:                 foreach my $domkey (@domains) {
                   7645:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7646:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7647:                             return 'ok';
                   7648:                         }
                   7649:                     }
                   7650:                 }
                   7651:             }
                   7652:             if (@users > 0) {
                   7653:                 foreach my $userkey (@users) {
1.865     raeburn  7654:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7655:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7656:                             if (ref($item) eq 'HASH') {
                   7657:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7658:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7659:                                     return 'ok';
                   7660:                                 }
                   7661:                             }
                   7662:                         }
                   7663:                     } 
1.765     albertel 7664:                 }
                   7665:             }
                   7666:             my %roleshash;
                   7667:             my @courses_and_groups = @courses;
                   7668:             push(@courses_and_groups,@groups); 
                   7669:             if (@courses_and_groups > 0) {
                   7670:                 my (%allgroups,%allroles); 
                   7671:                 my ($start,$end,$role,$sec,$group);
                   7672:                 foreach my $envkey (%env) {
1.1060    raeburn  7673:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7674:                         my $cid = $2.'_'.$3; 
                   7675:                         if ($1 eq 'gr') {
                   7676:                             $group = $4;
                   7677:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7678:                         } else {
                   7679:                             if ($4 eq '') {
                   7680:                                 $sec = 'none';
                   7681:                             } else {
                   7682:                                 $sec = $4;
                   7683:                             }
                   7684:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7685:                         }
1.811     albertel 7686:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7687:                         my $cid = $2.'_'.$3;
                   7688:                         if ($4 eq '') {
                   7689:                             $sec = 'none';
                   7690:                         } else {
                   7691:                             $sec = $4;
                   7692:                         }
                   7693:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7694:                     }
                   7695:                 }
                   7696:                 if (keys(%allroles) == 0) {
                   7697:                     return;
                   7698:                 }
                   7699:                 foreach my $key (@courses_and_groups) {
                   7700:                     my %content = %{$$access_hash{$key}};
                   7701:                     my $cnum = $content{'number'};
                   7702:                     my $cdom = $content{'domain'};
                   7703:                     my $cid = $cdom.'_'.$cnum;
                   7704:                     if (!exists($allroles{$cid})) {
                   7705:                         next;
                   7706:                     }    
                   7707:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7708:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7709:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7710:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7711:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7712:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7713:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7714:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7715:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7716:                                         if (grep/^all$/,@sections) {
                   7717:                                             return 'ok';
                   7718:                                         } else {
                   7719:                                             if (grep/^$sec$/,@sections) {
                   7720:                                                 return 'ok';
                   7721:                                             }
                   7722:                                         }
                   7723:                                     }
                   7724:                                 }
                   7725:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7726:                                     if (grep/^none$/,@groups) {
                   7727:                                         return 'ok';
                   7728:                                     }
                   7729:                                 } else {
                   7730:                                     if (grep/^all$/,@groups) {
                   7731:                                         return 'ok';
                   7732:                                     } 
                   7733:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7734:                                         if (grep/^$group$/,@groups) {
                   7735:                                             return 'ok';
                   7736:                                         }
                   7737:                                     }
                   7738:                                 } 
                   7739:                             }
                   7740:                         }
                   7741:                     }
                   7742:                 }
                   7743:             }
                   7744:             if ($guest) {
                   7745:                 return $guest;
                   7746:             }
                   7747:         }
                   7748:     }
                   7749:     return;
                   7750: }
                   7751: 
                   7752: sub course_group_datechecker {
                   7753:     my ($dates,$now,$status) = @_;
                   7754:     my ($start,$end) = split(/\./,$dates);
                   7755:     if (!$start && !$end) {
                   7756:         return 'ok';
                   7757:     }
                   7758:     if (grep/^active$/,@{$status}) {
                   7759:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7760:             return 'ok';
                   7761:         }
                   7762:     }
                   7763:     if (grep/^previous$/,@{$status}) {
                   7764:         if ($end > $now ) {
                   7765:             return 'ok';
                   7766:         }
                   7767:     }
                   7768:     if (grep/^future$/,@{$status}) {
                   7769:         if ($start > $now) {
                   7770:             return 'ok';
                   7771:         }
                   7772:     }
                   7773:     return; 
                   7774: }
                   7775: 
                   7776: sub parse_portfolio_url {
                   7777:     my ($url) = @_;
                   7778: 
                   7779:     my ($type,$udom,$unum,$group,$file_name);
                   7780:     
1.823     albertel 7781:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7782: 	$type = 1;
                   7783:         $udom = $1;
                   7784:         $unum = $2;
                   7785:         $file_name = $3;
1.823     albertel 7786:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7787: 	$type = 2;
                   7788:         $udom = $1;
                   7789:         $unum = $2;
                   7790:         $group = $3;
                   7791:         $file_name = $3.'/'.$4;
                   7792:     }
                   7793:     if (wantarray) {
                   7794: 	return ($type,$udom,$unum,$file_name,$group);
                   7795:     }
                   7796:     return $type;
                   7797: }
                   7798: 
                   7799: sub is_portfolio_url {
                   7800:     my ($url) = @_;
                   7801:     return scalar(&parse_portfolio_url($url));
                   7802: }
                   7803: 
1.798     raeburn  7804: sub is_portfolio_file {
                   7805:     my ($file) = @_;
1.820     raeburn  7806:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7807:         return 1;
                   7808:     }
                   7809:     return;
                   7810: }
                   7811: 
1.976     raeburn  7812: sub usertools_access {
1.1084    raeburn  7813:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7814:     my ($access,%tools);
                   7815:     if ($context eq '') {
                   7816:         $context = 'tools';
                   7817:     }
                   7818:     if ($context eq 'requestcourses') {
                   7819:         %tools = (
                   7820:                       official   => 1,
                   7821:                       unofficial => 1,
1.1006    raeburn  7822:                       community  => 1,
1.1246    raeburn  7823:                       textbook   => 1,
1.1305    raeburn  7824:                       placement  => 1,
1.1368    raeburn  7825:                       lti        => 1,
1.985     raeburn  7826:                  );
1.1183    raeburn  7827:     } elsif ($context eq 'requestauthor') {
                   7828:         %tools = (
                   7829:                       requestauthor => 1,
                   7830:                  );
1.985     raeburn  7831:     } else {
                   7832:         %tools = (
                   7833:                       aboutme   => 1,
                   7834:                       blog      => 1,
1.1177    raeburn  7835:                       webdav    => 1,
1.985     raeburn  7836:                       portfolio => 1,
                   7837:                  );
                   7838:     }
1.976     raeburn  7839:     return if (!defined($tools{$tool}));
                   7840: 
1.1242    raeburn  7841:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7842:         $udom = $env{'user.domain'};
                   7843:         $uname = $env{'user.name'};
                   7844:     }
                   7845: 
1.978     raeburn  7846:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7847:         if ($action ne 'reload') {
1.985     raeburn  7848:             if ($context eq 'requestcourses') {
                   7849:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7850:             } elsif ($context eq 'requestauthor') {
                   7851:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7852:             } else {
                   7853:                 return $env{'environment.availabletools.'.$tool};
                   7854:             }
                   7855:         }
1.976     raeburn  7856:     }
                   7857: 
1.1183    raeburn  7858:     my ($toolstatus,$inststatus,$envkey);
                   7859:     if ($context eq 'requestauthor') {
                   7860:         $envkey = $context; 
                   7861:     } else {
                   7862:         $envkey = $context.'.'.$tool;
                   7863:     }
1.976     raeburn  7864: 
1.985     raeburn  7865:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7866:          ($action ne 'reload')) {
1.1183    raeburn  7867:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7868:         $inststatus = $env{'environment.inststatus'};
                   7869:     } else {
1.1084    raeburn  7870:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7871:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7872:             $inststatus = $userenvref->{'inststatus'};
                   7873:         } else {
1.1183    raeburn  7874:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7875:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7876:             $inststatus = $userenv{'inststatus'};
                   7877:         }
1.976     raeburn  7878:     }
                   7879: 
                   7880:     if ($toolstatus ne '') {
                   7881:         if ($toolstatus) {
                   7882:             $access = 1;
                   7883:         } else {
                   7884:             $access = 0;
                   7885:         }
                   7886:         return $access;
                   7887:     }
                   7888: 
1.1084    raeburn  7889:     my ($is_adv,%domdef);
                   7890:     if (ref($is_advref) eq 'HASH') {
                   7891:         $is_adv = $is_advref->{'is_adv'};
                   7892:     } else {
                   7893:         $is_adv = &is_advanced_user($udom,$uname);
                   7894:     }
                   7895:     if (ref($domdefref) eq 'HASH') {
                   7896:         %domdef = %{$domdefref};
                   7897:     } else {
                   7898:         %domdef = &get_domain_defaults($udom);
                   7899:     }
1.976     raeburn  7900:     if (ref($domdef{$tool}) eq 'HASH') {
                   7901:         if ($is_adv) {
                   7902:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7903:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7904:                     $access = 1;
                   7905:                 } else {
                   7906:                     $access = 0;
                   7907:                 }
                   7908:                 return $access;
                   7909:             }
                   7910:         }
                   7911:         if ($inststatus ne '') {
                   7912:             my ($hasaccess,$hasnoaccess);
                   7913:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7914:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7915:                     if ($domdef{$tool}{$affiliation}) {
                   7916:                         $hasaccess = 1;
                   7917:                     } else {
                   7918:                         $hasnoaccess = 1;
                   7919:                     }
                   7920:                 }
                   7921:             }
                   7922:             if ($hasaccess || $hasnoaccess) {
                   7923:                 if ($hasaccess) {
                   7924:                     $access = 1;
                   7925:                 } elsif ($hasnoaccess) {
                   7926:                     $access = 0; 
                   7927:                 }
                   7928:                 return $access;
                   7929:             }
                   7930:         } else {
                   7931:             if ($domdef{$tool}{'default'} ne '') {
                   7932:                 if ($domdef{$tool}{'default'}) {
                   7933:                     $access = 1;
                   7934:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7935:                     $access = 0;
                   7936:                 }
                   7937:                 return $access;
                   7938:             }
                   7939:         }
                   7940:     } else {
1.1177    raeburn  7941:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7942:             $access = 1;
                   7943:         } else {
                   7944:             $access = 0;
                   7945:         }
1.976     raeburn  7946:         return $access;
                   7947:     }
                   7948: }
                   7949: 
1.1050    raeburn  7950: sub is_course_owner {
                   7951:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7952:     if (($udom eq '') || ($uname eq '')) {
                   7953:         $udom = $env{'user.domain'};
                   7954:         $uname = $env{'user.name'};
                   7955:     }
                   7956:     unless (($udom eq '') || ($uname eq '')) {
                   7957:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7958:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7959:                 return 1;
                   7960:             } else {
                   7961:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7962:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7963:                     return 1;
                   7964:                 }
                   7965:             }
                   7966:         }
                   7967:     }
                   7968:     return;
                   7969: }
                   7970: 
1.976     raeburn  7971: sub is_advanced_user {
                   7972:     my ($udom,$uname) = @_;
1.1085    raeburn  7973:     if ($udom ne '' && $uname ne '') {
                   7974:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7975:             if (wantarray) {
                   7976:                 return ($env{'user.adv'},$env{'user.author'});
                   7977:             } else {
                   7978:                 return $env{'user.adv'};
                   7979:             }
1.1085    raeburn  7980:         }
                   7981:     }
1.976     raeburn  7982:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7983:     my %allroles;
1.1128    raeburn  7984:     my ($is_adv,$is_author);
1.976     raeburn  7985:     foreach my $role (keys(%roleshash)) {
                   7986:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7987:         my $area = '/'.$tdomain.'/'.$trest;
                   7988:         if ($sec ne '') {
                   7989:             $area .= '/'.$sec;
                   7990:         }
                   7991:         if (($area ne '') && ($trole ne '')) {
                   7992:             my $spec=$trole.'.'.$area;
                   7993:             if ($trole =~ /^cr\//) {
                   7994:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7995:             } elsif ($trole ne 'gr') {
                   7996:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7997:             }
1.1128    raeburn  7998:             if ($trole eq 'au') {
                   7999:                 $is_author = 1;
                   8000:             }
1.976     raeburn  8001:         }
                   8002:     }
                   8003:     foreach my $role (keys(%allroles)) {
                   8004:         last if ($is_adv);
                   8005:         foreach my $item (split(/:/,$allroles{$role})) {
                   8006:             if ($item ne '') {
                   8007:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8008:                 if ($privilege eq 'adv') {
                   8009:                     $is_adv = 1;
                   8010:                     last;
                   8011:                 }
                   8012:             }
                   8013:         }
                   8014:     }
1.1128    raeburn  8015:     if (wantarray) {
                   8016:         return ($is_adv,$is_author);
                   8017:     }
1.976     raeburn  8018:     return $is_adv;
                   8019: }
1.798     raeburn  8020: 
1.1035    raeburn  8021: sub check_can_request {
1.1368    raeburn  8022:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8023:     my $canreq = 0;
1.1368    raeburn  8024:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8025:         $uname = $env{'user.name'};
                   8026:         $udom = $env{'user.domain'};
                   8027:     }
1.1035    raeburn  8028:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8029:     my @options = ('approval','validate','autolimit');
                   8030:     my $optregex = join('|',@options);
                   8031:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   8032:         foreach my $type (@{$types}) {
1.1368    raeburn  8033:             if (&usertools_access($uname,$udom,$type,undef,
                   8034:                                   'requestcourses')) {
1.1035    raeburn  8035:                 $canreq ++;
1.1036    raeburn  8036:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  8037:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8038:                 }
1.1368    raeburn  8039:                 if ($dom eq $udom) {
1.1035    raeburn  8040:                     $can_request->{$type} = 1;
                   8041:                 }
                   8042:             }
1.1368    raeburn  8043:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8044:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8045:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8046:                 if (@curr > 0) {
1.1036    raeburn  8047:                     foreach my $item (@curr) {
                   8048:                         if (ref($request_domains) eq 'HASH') {
                   8049:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8050:                             if ($otherdom ne '') {
                   8051:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8052:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8053:                                         push(@{$request_domains->{$type}},$otherdom);
                   8054:                                     }
                   8055:                                 } else {
                   8056:                                     push(@{$request_domains->{$type}},$otherdom);
                   8057:                                 }
                   8058:                             }
                   8059:                         }
                   8060:                     }
1.1368    raeburn  8061:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8062:                         $canreq ++;
1.1035    raeburn  8063:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8064:                             $can_request->{$type} = 1;
                   8065:                         }
                   8066:                     }
                   8067:                 }
                   8068:             }
                   8069:         }
                   8070:     }
                   8071:     return $canreq;
                   8072: }
                   8073: 
1.341     www      8074: # ---------------------------------------------- Custom access rule evaluation
                   8075: 
                   8076: sub customaccess {
                   8077:     my ($priv,$uri)=@_;
1.807     albertel 8078:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8079:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8080:     $udom = &LONCAPA::clean_domain($udom);
                   8081:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8082:     my $access=0;
1.800     albertel 8083:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8084: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8085: 	if ($type eq 'user') {
                   8086: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8087: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8088: 		if ($tdom) {
                   8089: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8090: 		}
1.896     albertel 8091: 		if ($tuname) {
                   8092: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8093: 		}
                   8094: 		$access=($effect eq 'allow');
                   8095: 		last;
                   8096: 	    }
                   8097: 	} else {
                   8098: 	    if ($role) {
                   8099: 		if ($role ne $urole) { next; }
                   8100: 	    }
                   8101: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8102: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8103: 		if ($tdom) {
                   8104: 		    if ($tdom ne $udom) { next; }
                   8105: 		}
                   8106: 		if ($tcrs) {
                   8107: 		    if ($tcrs ne $ucrs) { next; }
                   8108: 		}
                   8109: 		if ($tsec) {
                   8110: 		    if ($tsec ne $usec) { next; }
                   8111: 		}
                   8112: 		$access=($effect eq 'allow');
                   8113: 		last;
                   8114: 	    }
                   8115: 	    if ($realm eq '' && $role eq '') {
                   8116: 		$access=($effect eq 'allow');
                   8117: 	    }
1.402     bowersj2 8118: 	}
1.341     www      8119:     }
                   8120:     return $access;
                   8121: }
                   8122: 
1.103     harris41 8123: # ------------------------------------------------- Check for a user privilege
1.12      www      8124: 
                   8125: sub allowed {
1.1461    raeburn  8126:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8127:     my $ver_orguri=$uri;
1.439     www      8128:     $uri=&deversion($uri);
1.152     www      8129:     my $orguri=$uri;
1.52      www      8130:     $uri=&declutter($uri);
1.809     raeburn  8131: 
1.810     raeburn  8132:     if ($priv eq 'evb') {
                   8133: # Evade communication block restrictions for specified role in a course
                   8134:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8135:             return $1;
                   8136:         } else {
                   8137:             return;
                   8138:         }
                   8139:     }
                   8140: 
1.620     albertel 8141:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8142: # Free bre access to adm and meta resources
1.1436    raeburn  8143:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8144: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8145: 	&& ($priv eq 'bre')) {
1.14      www      8146: 	return 'F';
1.159     www      8147:     }
                   8148: 
1.545     banghart 8149: # Free bre access to user's own portfolio contents
1.714     raeburn  8150:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8151:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8152: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8153:         my %setters;
                   8154:         my ($startblock,$endblock) = 
                   8155:             &Apache::loncommon::blockcheck(\%setters,'port');
                   8156:         if ($startblock && $endblock) {
                   8157:             return 'B';
                   8158:         } else {
                   8159:             return 'F';
                   8160:         }
1.545     banghart 8161:     }
                   8162: 
1.762     raeburn  8163: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8164:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8165:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8166:         if (exists($env{'request.course.id'})) {
                   8167:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8168:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8169:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8170:                 my $courseprivid=$env{'request.course.id'};
                   8171:                 $courseprivid=~s/\_/\//;
                   8172:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8173:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8174:                     return $1; 
1.762     raeburn  8175:                 } else {
                   8176:                     if ($env{'request.course.sec'}) {
                   8177:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8178:                     }
                   8179:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8180:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8181:                         return $2;
                   8182:                     }
1.714     raeburn  8183:                 }
                   8184:             }
                   8185:         }
                   8186:     }
                   8187: 
1.159     www      8188: # Free bre to public access
                   8189: 
                   8190:     if ($priv eq 'bre') {
1.1362    raeburn  8191:         my $copyright;
                   8192:         unless ($uri =~ /ext\.tool/) {
                   8193:             $copyright=&metadata($uri,'copyright');
                   8194:         }
1.620     albertel 8195: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8196:            return 'F'; 
                   8197:         }
1.238     www      8198:         if ($copyright eq 'priv') {
                   8199:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8200: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8201: 		return '';
                   8202:             }
                   8203:         }
                   8204:         if ($copyright eq 'domain') {
                   8205:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8206: 	    unless (($env{'user.domain'} eq $1) ||
                   8207:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8208: 		return '';
                   8209:             }
1.262     matthew  8210:         }
1.620     albertel 8211:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8212:             # Library role, so allow browsing of resources in this domain.
                   8213:             return 'F';
1.238     www      8214:         }
1.341     www      8215:         if ($copyright eq 'custom') {
                   8216: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8217:         }
1.14      www      8218:     }
1.264     matthew  8219:     # Domain coordinator is trying to create a course
1.620     albertel 8220:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8221:         # uri is the requested domain in this case.
                   8222:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8223:         # a role of dc for the domain in question.
1.620     albertel 8224:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8225:     }
1.29      www      8226: 
1.52      www      8227:     my $thisallowed='';
                   8228:     my $statecond=0;
                   8229:     my $courseprivid='';
                   8230: 
1.1039    raeburn  8231:     my $ownaccess;
1.1043    raeburn  8232:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8233:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8234:         if ($uri eq '') {
                   8235:             $ownaccess = 1;
                   8236:         } else {
                   8237:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8238:                 my $udom = $env{'user.domain'};
                   8239:                 my $uname = $env{'user.name'};
                   8240:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8241:                     $ownaccess = 1;
1.1040    raeburn  8242:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8243:                     unless ($uri =~ m{\.\./}) {
                   8244:                         $ownaccess = 1;
                   8245:                     }
                   8246:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8247:                     my $now = time;
                   8248:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8249:                         my $adom = $1;
                   8250:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8251:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452    raeburn  8252:                                 my ($start,$end) = split(/\./,$env{$key});
                   8253:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8254:                                     $ownaccess = 1;
                   8255:                                     last;
                   8256:                                 }
                   8257:                             }
                   8258:                         }
                   8259:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8260:                         my $adom = $1;
                   8261:                         my $aname = $2;
1.1042    raeburn  8262:                         foreach my $role ('ca','aa') { 
                   8263:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8264:                                 my ($start,$end) =
1.1452    raeburn  8265:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8266:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8267:                                     $ownaccess = 1;
                   8268:                                     last;
                   8269:                                 }
1.1039    raeburn  8270:                             }
                   8271:                         }
                   8272:                     }
                   8273:                 }
                   8274:             }
                   8275:         }
                   8276:     }
                   8277: 
1.52      www      8278: # Course
                   8279: 
1.620     albertel 8280:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8281:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8282:             $thisallowed.=$1;
                   8283:         }
1.52      www      8284:     }
1.29      www      8285: 
1.52      www      8286: # Domain
                   8287: 
1.620     albertel 8288:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8289:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8290:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8291:             $thisallowed.=$1;
                   8292:         }
1.12      www      8293:     }
1.52      www      8294: 
1.1141    raeburn  8295: # User who is not author or co-author might still be able to edit
                   8296: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8297:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8298:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8299:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8300:             $thisallowed.=$1;
                   8301:         }
                   8302:     }
                   8303: 
1.52      www      8304: # Course: uri itself is a course
1.66      www      8305:     my $courseuri=$uri;
                   8306:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8307:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8308: 
1.620     albertel 8309:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8310:        =~/\Q$priv\E\&([^\:]*)/) {
1.1409    raeburn  8311:         if ($priv eq 'mip') {
                   8312:             my $rem = $1;
                   8313:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8314:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8315:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8316:                 if ($cdom ne '') {
1.1410    raeburn  8317:                     my %passwdconf = &get_passwdconf($cdom);
                   8318:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8319:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8320:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8321:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8322:                                 unless (@inststatuses) {
                   8323:                                     @inststatuses = ('default');
                   8324:                                 }
                   8325:                                 foreach my $status (@inststatuses) {
                   8326:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8327:                                         $thisallowed.=$rem;
                   8328:                                     }
                   8329:                                 }
                   8330:                             }
                   8331:                         }
1.1409    raeburn  8332:                     }
                   8333:                 }
                   8334:             }
                   8335:         } else {
                   8336:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8337:                 $thisallowed.=$1;
                   8338:             }
1.1039    raeburn  8339:         }
1.12      www      8340:     }
1.29      www      8341: 
1.665     albertel 8342: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8343: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8344:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8345: 	$thisallowed='';
1.671     raeburn  8346:         my ($match)=&is_on_map($uri);
                   8347:         if ($match) {
                   8348:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8349:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8350:                 my $value = $1;
1.1461    raeburn  8351:                 my $deeplinkblock;
                   8352:                 unless ($nodeeplinkcheck) {
                   8353:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8354:                 }
1.1402    raeburn  8355:                 if ($deeplinkblock) {
                   8356:                     $thisallowed='D';
                   8357:                 } elsif ($noblockcheck) {
1.1281    raeburn  8358:                     $thisallowed.=$value;
1.1162    raeburn  8359:                 } else {
1.1424    raeburn  8360:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8361:                     if (@blockers > 0) {
                   8362:                         $thisallowed = 'B';
                   8363:                     } else {
                   8364:                         $thisallowed.=$value;
                   8365:                     }
1.1162    raeburn  8366:                 }
1.671     raeburn  8367:             }
                   8368:         } else {
1.705     albertel 8369:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8370:             if ($refuri) {
                   8371:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8372:                     $thisallowed='F';
1.671     raeburn  8373:                 } else {
                   8374:                     $refuri=&declutter($refuri);
                   8375:                     my ($match) = &is_on_map($refuri);
                   8376:                     if ($match) {
1.1461    raeburn  8377:                         my $deeplinkblock;
                   8378:                         unless ($nodeeplinkcheck) {
                   8379:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8380:                         }
1.1402    raeburn  8381:                         if ($deeplinkblock) {
                   8382:                             $thisallowed='D';
                   8383:                         } elsif ($noblockcheck) {
1.1281    raeburn  8384:                             $thisallowed='F';
1.1162    raeburn  8385:                         } else {
1.1426    raeburn  8386:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8387:                             if (@blockers > 0) {
                   8388:                                 $thisallowed = 'B';
                   8389:                             } else {
                   8390:                                 $thisallowed='F';
                   8391:                             }
1.1162    raeburn  8392:                         }
1.671     raeburn  8393:                     }
1.669     raeburn  8394:                 }
1.671     raeburn  8395:             }
                   8396:         }
1.314     www      8397:     }
1.492     albertel 8398: 
1.766     albertel 8399:     if ($priv eq 'bre'
                   8400: 	&& $thisallowed ne 'F' 
                   8401: 	&& $thisallowed ne '2'
                   8402: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8403: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8404:     }
1.1250    raeburn  8405: 
1.52      www      8406: # Full access at system, domain or course-wide level? Exit.
1.29      www      8407:     if ($thisallowed=~/F/) {
                   8408: 	return 'F';
                   8409:     }
                   8410: 
1.52      www      8411: # If this is generating or modifying users, exit with special codes
1.29      www      8412: 
1.643     www      8413:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8414: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8415: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8416: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8417: 	    unless ($auname) { return $thisallowed; }
                   8418: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8419: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8420: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8421: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8422: 	}
1.52      www      8423: 	return $thisallowed;
                   8424:     }
                   8425: #
1.103     harris41 8426: # Gathered so far: system, domain and course wide privileges
1.52      www      8427: #
                   8428: # Course: See if uri or referer is an individual resource that is part of 
                   8429: # the course
                   8430: 
1.620     albertel 8431:     if ($env{'request.course.id'}) {
1.232     www      8432: 
1.1409    raeburn  8433: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8434: 
                   8435:         if ($priv eq 'mip') {
                   8436:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8437:                 return $thisallowed;
                   8438:             } else {
                   8439:                 return '';
                   8440:             }
                   8441:         }
                   8442: 
1.620     albertel 8443:        $courseprivid=$env{'request.course.id'};
                   8444:        if ($env{'request.course.sec'}) {
                   8445:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8446:        }
                   8447:        $courseprivid=~s/\_/\//;
                   8448:        my $checkreferer=1;
1.232     www      8449:        my ($match,$cond)=&is_on_map($uri);
                   8450:        if ($match) {
                   8451:            $statecond=$cond;
1.620     albertel 8452:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8453:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8454:                my $value = $1;
                   8455:                if ($priv eq 'bre') {
1.1461    raeburn  8456:                    my $deeplinkblock;
                   8457:                    unless ($nodeeplinkcheck) {
                   8458:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8459:                    }
1.1458    raeburn  8460:                    if ($deeplinkblock) {
                   8461:                        $thisallowed = 'D';
                   8462:                    } elsif ($noblockcheck) {
1.1281    raeburn  8463:                        $thisallowed.=$value;
1.1162    raeburn  8464:                    } else {
1.1424    raeburn  8465:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8466:                        if (@blockers > 0) {
                   8467:                            $thisallowed = 'B';
                   8468:                        } else {
                   8469:                            $thisallowed.=$value;
                   8470:                        }
1.1162    raeburn  8471:                    }
                   8472:                } else {
                   8473:                    $thisallowed.=$value;
                   8474:                }
1.52      www      8475:                $checkreferer=0;
                   8476:            }
1.29      www      8477:        }
1.1424    raeburn  8478: 
1.148     www      8479:        if ($checkreferer) {
1.620     albertel 8480: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8481:             unless ($refuri) {
1.800     albertel 8482:                 foreach my $key (keys(%env)) {
                   8483: 		    if ($key=~/^httpref\..*\*/) {
                   8484: 			my $pattern=$key;
1.156     www      8485:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8486:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8487:                         $pattern=~s/\//\\\//g;
1.152     www      8488:                         if ($orguri=~/$pattern/) {
1.800     albertel 8489: 			    $refuri=$env{$key};
1.148     www      8490:                         }
                   8491:                     }
1.191     harris41 8492:                 }
1.148     www      8493:             }
1.232     www      8494: 
1.148     www      8495:          if ($refuri) { 
1.152     www      8496: 	  $refuri=&declutter($refuri);
1.232     www      8497:           my ($match,$cond)=&is_on_map($refuri);
                   8498:             if ($match) {
                   8499:               my $refstatecond=$cond;
1.620     albertel 8500:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8501:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8502:                   my $value = $1;
                   8503:                   if ($priv eq 'bre') {
1.1461    raeburn  8504:                       my $deeplinkblock;
                   8505:                       unless ($nodeeplinkcheck) {
                   8506:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8507:                       }
1.1402    raeburn  8508:                       if ($deeplinkblock) {
                   8509:                           $thisallowed = 'D';
                   8510:                       } elsif ($noblockcheck) {
1.1281    raeburn  8511:                           $thisallowed.=$value;
1.1162    raeburn  8512:                       } else {
1.1426    raeburn  8513:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8514:                           if (@blockers > 0) {
                   8515:                               $thisallowed = 'B';
                   8516:                           } else {
                   8517:                               $thisallowed.=$value;
                   8518:                           }
1.1162    raeburn  8519:                       }
                   8520:                   } else {
                   8521:                       $thisallowed.=$value;
                   8522:                   }
1.53      www      8523:                   $uri=$refuri;
                   8524:                   $statecond=$refstatecond;
1.52      www      8525:               }
                   8526:           }
1.148     www      8527:         }
1.29      www      8528:        }
1.52      www      8529:    }
1.29      www      8530: 
1.52      www      8531: #
1.103     harris41 8532: # Gathered now: all privileges that could apply, and condition number
1.52      www      8533: # 
                   8534: #
                   8535: # Full or no access?
                   8536: #
1.29      www      8537: 
1.52      www      8538:     if ($thisallowed=~/F/) {
                   8539: 	return 'F';
                   8540:     }
1.29      www      8541: 
1.52      www      8542:     unless ($thisallowed) {
                   8543:         return '';
                   8544:     }
1.29      www      8545: 
1.52      www      8546: # Restrictions exist, deal with them
                   8547: #
                   8548: #   C:according to course preferences
                   8549: #   R:according to resource settings
                   8550: #   L:unless locked
                   8551: #   X:according to user session state
                   8552: #
                   8553: 
                   8554: # Possibly locked functionality, check all courses
1.1454    raeburn  8555: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8556: # Locks might take effect only after 10 minutes cache expiration for other
1.1454    raeburn  8557: # courses, and 2 minutes for current course, in which user has st or ta role
                   8558: # which is neither expired nor a future role (unless current course).
1.52      www      8559: 
1.1454    raeburn  8560:     my ($needlockcheck,$now,$crsonly);
1.52      www      8561:     if ($thisallowed=~/L/) {
1.1454    raeburn  8562:         $now = time;
                   8563:         if ($priv eq 'bre') {
                   8564:             if ($uri ne '') {
                   8565:                 if ($orguri =~ m{^/+res/}) {
                   8566:                     if ($uri =~ m{^lib/templates/}) {
                   8567:                         if ($env{'request.course.id'}) {
                   8568:                             $crsonly = 1;
                   8569:                             $needlockcheck = 1;
                   8570:                         }
                   8571:                     } else {
                   8572:                         $needlockcheck = 1;
                   8573:                     }
                   8574:                 } elsif ($env{'request.course.id'}) {
                   8575:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8576:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8577:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8578:                         $crsonly = 1;
                   8579:                     }
                   8580:                     $needlockcheck = 1;
                   8581:                 }
                   8582:             }
                   8583:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8584:             $needlockcheck = 1;
                   8585:         }
                   8586:     }
                   8587:     if ($needlockcheck) {
1.1453    raeburn  8588:         foreach my $envkey (keys(%env)) {
1.54      www      8589:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8590:                my $courseid=$2;
                   8591:                my $roleid=$1.'.'.$2;
1.92      www      8592:                $courseid=~s/^\///;
1.1453    raeburn  8593:                unless ($env{'request.role'} eq $roleid) {
                   8594:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8595:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8596:                }
1.54      www      8597:                my $expiretime=600;
1.620     albertel 8598:                if ($env{'request.role'} eq $roleid) {
1.54      www      8599: 		  $expiretime=120;
                   8600:                }
                   8601: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8602:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8603:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8604: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8605:                }
1.620     albertel 8606:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8607:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8608: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8609:                        &log($env{'user.domain'},$env{'user.name'},
                   8610:                             $env{'user.home'},
1.57      www      8611:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8612:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8613:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8614: 		       return '';
                   8615:                    }
                   8616:                }
1.620     albertel 8617:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8618:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455    raeburn  8619: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8620:                        &log($env{'user.domain'},$env{'user.name'},
                   8621:                             $env{'user.home'},
1.57      www      8622:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8623:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8624:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8625: 		       return '';
                   8626:                    }
                   8627:                }
                   8628: 	   }
1.29      www      8629:        }
1.52      www      8630:     }
1.1424    raeburn  8631: 
1.52      www      8632: #
                   8633: # Rest of the restrictions depend on selected course
                   8634: #
                   8635: 
1.620     albertel 8636:     unless ($env{'request.course.id'}) {
1.766     albertel 8637: 	if ($thisallowed eq 'A') {
                   8638: 	    return 'A';
1.814     raeburn  8639:         } elsif ($thisallowed eq 'B') {
                   8640:             return 'B';
1.766     albertel 8641: 	} else {
                   8642: 	    return '1';
                   8643: 	}
1.52      www      8644:     }
1.29      www      8645: 
1.52      www      8646: #
                   8647: # Now user is definitely in a course
                   8648: #
1.53      www      8649: 
                   8650: 
                   8651: # Course preferences
                   8652: 
                   8653:    if ($thisallowed=~/C/) {
1.620     albertel 8654:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8655:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8656:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8657: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8658: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8659: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8660: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8661: 			$env{'request.course.id'});
                   8662: 	   }
1.237     www      8663:            return '';
                   8664:        }
                   8665: 
1.620     albertel 8666:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8667: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8668: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8669: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8670: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8671: 			$env{'request.course.id'});
                   8672: 	   }
1.54      www      8673:            return '';
                   8674:        }
1.53      www      8675:    }
                   8676: 
                   8677: # Resource preferences
                   8678: 
                   8679:    if ($thisallowed=~/R/) {
1.620     albertel 8680:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8681:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8682: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8683: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8684: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8685: 	   }
                   8686: 	   return '';
1.54      www      8687:        }
1.53      www      8688:    }
1.30      www      8689: 
1.1461    raeburn  8690: # Restricted for deeplinked session?
                   8691: 
                   8692:     if ($env{'request.deeplink.login'}) {
                   8693:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8694:             if (!$symb) { $symb=&symbread($uri,1); }
                   8695:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8696:                 return '';
                   8697:             }
                   8698:         }
                   8699:     }
                   8700: 
1.246     www      8701: # Restricted by state or randomout?
1.30      www      8702: 
1.52      www      8703:    if ($thisallowed=~/X/) {
1.620     albertel 8704:       if ($env{'acc.randomout'}) {
1.579     albertel 8705: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8706:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8707:             return ''; 
                   8708:          }
1.247     www      8709:       }
                   8710:       if (&condval($statecond)) {
1.52      www      8711: 	 return '2';
                   8712:       } else {
                   8713:          return '';
                   8714:       }
                   8715:    }
1.30      www      8716: 
1.766     albertel 8717:     if ($thisallowed eq 'A') {
                   8718: 	return 'A';
1.814     raeburn  8719:     } elsif ($thisallowed eq 'B') {
                   8720:         return 'B';
1.1402    raeburn  8721:     } elsif ($thisallowed eq 'D') {
                   8722:         return 'D';
1.766     albertel 8723:     }
1.52      www      8724:    return 'F';
1.232     www      8725: }
1.1162    raeburn  8726: 
1.1192    raeburn  8727: # ------------------------------------------- Check construction space access
                   8728: 
                   8729: sub constructaccess {
                   8730:     my ($url,$setpriv)=@_;
                   8731: 
                   8732: # We do not allow editing of previous versions of files
                   8733:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8734: 
                   8735: # Get username and domain from URL
                   8736:     my ($ownername,$ownerdomain,$ownerhome);
                   8737: 
                   8738:     ($ownerdomain,$ownername) =
1.1325    raeburn  8739:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8740: 
                   8741: # The URL does not really point to any authorspace, forget it
                   8742:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8743: 
                   8744: # Now we need to see if the user has access to the authorspace of
                   8745: # $ownername at $ownerdomain
                   8746: 
                   8747:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8748: # Real author for this?
                   8749:        $ownerhome = $env{'user.home'};
                   8750:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8751:           return ($ownername,$ownerdomain,$ownerhome);
                   8752:        }
                   8753:     } else {
                   8754: # Co-author for this?
                   8755:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8756:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8757:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8758:             return ($ownername,$ownerdomain,$ownerhome);
                   8759:         }
1.1312    raeburn  8760:         if ($env{'request.course.id'}) {
                   8761:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8762:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8763:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8764:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8765:                     return ($ownername,$ownerdomain,$ownerhome);
                   8766:                 }
                   8767:             }
                   8768:         }
1.1192    raeburn  8769:     }
                   8770: 
                   8771: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8772: # we might as well leave
                   8773:    unless ($setpriv) { return ''; }
                   8774: 
                   8775: # Backdoor access?
                   8776:     my $allowed=&allowed('eco',$ownerdomain);
                   8777: # Nope
                   8778:     unless ($allowed) { return ''; }
                   8779: # Looks like we may have access, but could be locked by the owner of the construction space
                   8780:     if ($allowed eq 'U') {
                   8781:         my %blocked=&get('environment',['domcoord.author'],
                   8782:                          $ownerdomain,$ownername);
                   8783: # Is blocked by owner
                   8784:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8785:     }
                   8786:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8787: # Grant temporary access
                   8788:         my $then=$env{'user.login.time'};
1.1209    raeburn  8789:         my $update=$env{'user.update.time'};
1.1192    raeburn  8790:         if (!$update) { $update = $then; }
                   8791:         my $refresh=$env{'user.refresh.time'};
                   8792:         if (!$refresh) { $refresh = $update; }
                   8793:         my $now = time;
                   8794:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8795:                            $now,'ca','constructaccess');
                   8796:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8797:         return($ownername,$ownerdomain,$ownerhome);
                   8798:     }
                   8799: # No business here
                   8800:     return '';
                   8801: }
                   8802: 
1.1282    raeburn  8803: # ----------------------------------------------------------- Content Blocking
                   8804: 
                   8805: {
                   8806: # Caches for faster Course Contents display where content blocking
                   8807: # is in operation (i.e., interval param set) for timed quiz.
                   8808: #
                   8809: # User for whom data are being temporarily cached.
                   8810: my $cacheduser='';
1.1424    raeburn  8811: # Course for which data are being temporarily cached.
                   8812: my $cachedcid='';
1.1282    raeburn  8813: # Cached blockers for this user (a hash of blocking items). 
                   8814: my %cachedblockers=();
                   8815: # When the data were last cached.
                   8816: my $cachedlast='';
                   8817: 
                   8818: sub load_all_blockers {
1.1427    raeburn  8819:     my ($uname,$udom)=@_;
1.1282    raeburn  8820:     if (($uname ne '') && ($udom ne '')) { 
                   8821:         if (($cacheduser eq $uname.':'.$udom) &&
1.1424    raeburn  8822:             ($cachedcid eq $env{'request.course.id'}) &&
1.1427    raeburn  8823:             (abs($cachedlast-time)<5)) {
1.1282    raeburn  8824:             return;
                   8825:         }
                   8826:     }
                   8827:     $cachedlast=time;
                   8828:     $cacheduser=$uname.':'.$udom;
1.1424    raeburn  8829:     $cachedcid=$env{'request.course.id'};
1.1427    raeburn  8830:     %cachedblockers = &get_commblock_resources();
1.1424    raeburn  8831:     return;
1.1282    raeburn  8832: }
                   8833: 
1.1162    raeburn  8834: sub get_comm_blocks {
                   8835:     my ($cdom,$cnum) = @_;
                   8836:     if ($cdom eq '' || $cnum eq '') {
                   8837:         return unless ($env{'request.course.id'});
                   8838:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8839:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8840:     }
                   8841:     my %commblocks;
                   8842:     my $hashid=$cdom.'_'.$cnum;
                   8843:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8844:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8845:         %commblocks = %{$blocksref};
                   8846:     } else {
                   8847:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8848:         my $cachetime = 600;
                   8849:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8850:     }
                   8851:     return %commblocks;
                   8852: }
                   8853: 
1.1282    raeburn  8854: sub get_commblock_resources {
                   8855:     my ($blocks) = @_;
                   8856:     my %blockers = ();
                   8857:     return %blockers unless ($env{'request.course.id'});
                   8858:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8859:     my %commblocks;
                   8860:     if (ref($blocks) eq 'HASH') {
                   8861:         %commblocks = %{$blocks};
                   8862:     } else {
                   8863:         %commblocks = &get_comm_blocks();
                   8864:     }
1.1282    raeburn  8865:     return %blockers unless (keys(%commblocks) > 0); 
                   8866:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8867:     return %blockers unless (ref($navmap));
1.1162    raeburn  8868:     my $now = time;
                   8869:     foreach my $block (keys(%commblocks)) {
                   8870:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8871:             my ($start,$end) = ($1,$2);
                   8872:             if ($start <= $now && $end >= $now) {
                   8873:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8874:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8875:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8876:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8877:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8878:                             }
                   8879:                         }
                   8880:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8881:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8882:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8883:                             }
                   8884:                         }
                   8885:                     }
                   8886:                 }
                   8887:             }
                   8888:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8889:             my $item = $1;
1.1163    raeburn  8890:             my @to_test;
1.1162    raeburn  8891:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8892:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8893:                     my @interval;
                   8894:                     my $type = 'map';
                   8895:                     if ($item eq 'course') {
                   8896:                         $type = 'course';
                   8897:                         @interval=&EXT("resource.0.interval");
                   8898:                     } else {
                   8899:                         if ($item =~ /___\d+___/) {
                   8900:                             $type = 'resource';
                   8901:                             @interval=&EXT("resource.0.interval",$item);
                   8902:                             if (ref($navmap)) {                        
                   8903:                                 my $res = $navmap->getBySymb($item); 
                   8904:                                 push(@to_test,$res);
                   8905:                             }
1.1162    raeburn  8906:                         } else {
1.1282    raeburn  8907:                             my $mapsymb = &symbread($item,1);
                   8908:                             if ($mapsymb) {
                   8909:                                 if (ref($navmap)) {
                   8910:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1428    raeburn  8911:                                     if (ref($mapres)) {
                   8912:                                         my $first = $mapres->map_start();
                   8913:                                         my $finish = $mapres->map_finish();
                   8914:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
1.1429    raeburn  8915:                                         if (ref($it)) {
                   8916:                                             my $res;
                   8917:                                             while ($res = $it->next(undef,1)) {
                   8918:                                                 next unless (ref($res));
                   8919:                                                 my $symb = $res->symb();
                   8920:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8921:                                                 @interval=&EXT("resource.0.interval",$symb);
                   8922:                                                 if ($interval[1] eq 'map') {
                   8923:                                                     if ($res->answerable()) {
                   8924:                                                         push(@to_test,$res);
                   8925:                                                         last;
                   8926:                                                     }
1.1428    raeburn  8927:                                                 }
1.1162    raeburn  8928:                                             }
                   8929:                                         }
                   8930:                                     }
                   8931:                                 }
                   8932:                             }
                   8933:                         }
1.1282    raeburn  8934:                     }
1.1310    raeburn  8935:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8936:                         my $timelimit = $1; 
1.1282    raeburn  8937:                         my $first_access;
                   8938:                         if ($type eq 'resource') {
                   8939:                             $first_access=&get_first_access($interval[1],$item);
                   8940:                         } elsif ($type eq 'map') {
                   8941:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8942:                         } else {
                   8943:                             $first_access=&get_first_access($interval[1]);
                   8944:                         }
                   8945:                         if ($first_access) {
1.1292    raeburn  8946:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8947:                             if ($timesup > $now) {
                   8948:                                 my $activeblock;
                   8949:                                 foreach my $res (@to_test) {
1.1283    raeburn  8950:                                     if ($res->answerable()) {
1.1282    raeburn  8951:                                         $activeblock = 1;
                   8952:                                         last;
                   8953:                                     }
                   8954:                                 }
                   8955:                                 if ($activeblock) {
                   8956:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8957:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8958:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8959:                                          }
                   8960:                                     }
                   8961:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8962:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8963:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8964:                                         }
1.1162    raeburn  8965:                                     }
                   8966:                                 }
                   8967:                             }
                   8968:                         }
                   8969:                     }
                   8970:                 }
                   8971:             }
                   8972:         }
                   8973:     }
1.1282    raeburn  8974:     return %blockers;
1.1162    raeburn  8975: }
                   8976: 
1.1282    raeburn  8977: sub has_comm_blocking {
1.1427    raeburn  8978:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282    raeburn  8979:     my @blockers;
                   8980:     return unless ($env{'request.course.id'});
                   8981:     return unless ($priv eq 'bre');
                   8982:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8983:     return if ($env{'request.state'} eq 'construct');
1.1427    raeburn  8984:     my %blockinfo;
                   8985:     if (ref($blocks) eq 'HASH') {
                   8986:         %blockinfo = &get_commblock_resources($blocks);
                   8987:     } else {
                   8988:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8989:         %blockinfo = %cachedblockers;
                   8990:     }
                   8991:     return unless (keys(%blockinfo) > 0);
1.1282    raeburn  8992:     my (%possibles,@symbs);
                   8993:     if (!$symb) {
1.1427    raeburn  8994:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8995:     }
1.1282    raeburn  8996:     if ($symb) {
                   8997:         @symbs = ($symb);
                   8998:     } elsif (keys(%possibles)) { 
                   8999:         @symbs = keys(%possibles);
                   9000:     }
                   9001:     my $noblock;
                   9002:     foreach my $symb (@symbs) {
                   9003:         last if ($noblock);
                   9004:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427    raeburn  9005:         foreach my $block (keys(%blockinfo)) {
1.1282    raeburn  9006:             if ($block =~ /^firstaccess____(.+)$/) {
                   9007:                 my $item = $1;
1.1424    raeburn  9008:                 unless ($blocked) {
                   9009:                     if (($item eq $map) || ($item eq $symb)) {
                   9010:                         $noblock = 1;
                   9011:                         last;
                   9012:                     }
1.1282    raeburn  9013:                 }
                   9014:             }
1.1427    raeburn  9015:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9016:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9017:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282    raeburn  9018:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9019:                             push(@blockers,$block);
                   9020:                         }
                   9021:                     }
                   9022:                 }
1.1427    raeburn  9023:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9024:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1424    raeburn  9025:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9026:                             push(@blockers,$block);
                   9027:                         }
1.1282    raeburn  9028:                     }
                   9029:                 }
1.1162    raeburn  9030:             }
                   9031:         }
                   9032:     }
1.1424    raeburn  9033:     unless ($noblock) { 
                   9034:         return @blockers;
                   9035:     }
                   9036:     return;
1.1282    raeburn  9037: }
1.1162    raeburn  9038: }
                   9039: 
1.1402    raeburn  9040: sub deeplink_check {
                   9041:     my ($priv,$symb,$uri) = @_;
                   9042:     return unless ($env{'request.course.id'});
                   9043:     return unless ($priv eq 'bre');
                   9044:     return if ($env{'request.state'} eq 'construct');
                   9045:     return if ($env{'request.role.adv'});
                   9046:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9047:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9048:     my (%possibles,@symbs);
                   9049:     if (!$symb) {
                   9050:         $symb = &symbread($uri,1,1,1,\%possibles);
                   9051:     }
                   9052:     if ($symb) {
                   9053:         @symbs = ($symb);
                   9054:     } elsif (keys(%possibles)) {
                   9055:         @symbs = keys(%possibles);
                   9056:     }
                   9057: 
1.1461    raeburn  9058:     my ($deeplink_symb,$allow);
                   9059:     if ($env{'request.deeplink.login'}) {
                   9060:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402    raeburn  9061:     }
                   9062:     foreach my $symb (@symbs) {
                   9063:         last if ($allow);
                   9064:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9065:         if ($deeplink eq '') {
                   9066:             $allow = 1;
                   9067:         } else {
1.1463    raeburn  9068:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9069:             if ($state ne 'only') {
1.1402    raeburn  9070:                 $allow = 1;
1.1463    raeburn  9071:             } else {
                   9072:                 my $check_deeplink_entry;
                   9073:                 if ($protect ne 'none') {
                   9074:                     my ($acctype,$item) = split(/:/,$protect);
                   9075:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9076:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9077:                             $check_deeplink_entry = 1
                   9078:                         }
                   9079:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9080:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9081:                             $check_deeplink_entry = 1;
                   9082:                         }
                   9083:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9084:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9085:                             $check_deeplink_entry = 1;
                   9086:                         }
                   9087:                     }
                   9088:                 }
                   9089:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402    raeburn  9090:                     if ($scope eq 'res') {
1.1461    raeburn  9091:                         if ($symb eq $deeplink_symb) {
1.1402    raeburn  9092:                             $allow = 1;
                   9093:                         }
1.1459    raeburn  9094:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463    raeburn  9095:                         my ($map_from_symb,$map_from_login);
1.1461    raeburn  9096:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9097:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9098:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9099:                         } else {
                   9100:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9101:                         }
1.1459    raeburn  9102:                         if (($map_from_symb) && ($map_from_login)) {
                   9103:                             if ($map_from_symb eq $map_from_login) {
                   9104:                                 $allow = 1;
                   9105:                             } elsif ($scope eq 'rec') {
                   9106:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9107:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9108:                                     $allow = 1;
                   9109:                                 }
                   9110:                             }
                   9111:                         }
1.1402    raeburn  9112:                     }
                   9113:                 }
                   9114:             }
                   9115:         }
                   9116:     }
                   9117:     return if ($allow);
                   9118:     return 1;
                   9119: }
                   9120: 
1.1282    raeburn  9121: # -------------------------------- Deversion and split uri into path an filename   
                   9122: 
1.1133    foxr     9123: #
1.1282    raeburn  9124: #   Removes the version from a URI and
1.1133    foxr     9125: #   splits it in to its filename and path to the filename.
                   9126: #   Seems like File::Basename could have done this more clearly.
                   9127: #   Parameters:
                   9128: #      $uri   - input URI
                   9129: #   Returns:
                   9130: #     Two element list consisting of 
                   9131: #     $pathname  - the URI up to and excluding the trailing /
                   9132: #     $filename  - The part of the URI following the last /
                   9133: #  NOTE:
                   9134: #    Another realization of this is simply:
                   9135: #    use File::Basename;
                   9136: #    ...
                   9137: #    $uri = shift;
                   9138: #    $filename = basename($uri);
                   9139: #    $path     = dirname($uri);
                   9140: #    return ($filename, $path);
                   9141: #
                   9142: #     The implementation below is probably faster however.
                   9143: #
1.710     albertel 9144: sub split_uri_for_cond {
                   9145:     my $uri=&deversion(&declutter(shift));
                   9146:     my @uriparts=split(/\//,$uri);
                   9147:     my $filename=pop(@uriparts);
                   9148:     my $pathname=join('/',@uriparts);
                   9149:     return ($pathname,$filename);
                   9150: }
1.232     www      9151: # --------------------------------------------------- Is a resource on the map?
                   9152: 
                   9153: sub is_on_map {
1.710     albertel 9154:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9155:     #Trying to find the conditional for the file
1.620     albertel 9156:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9157: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9158:     if ($match) {
1.289     bowersj2 9159: 	return (1,$1);
                   9160:     } else {
1.434     www      9161: 	return (0,0);
1.289     bowersj2 9162:     }
1.12      www      9163: }
                   9164: 
1.427     www      9165: # --------------------------------------------------------- Get symb from alias
                   9166: 
                   9167: sub get_symb_from_alias {
                   9168:     my $symb=shift;
                   9169:     my ($map,$resid,$url)=&decode_symb($symb);
                   9170: # Already is a symb
                   9171:     if ($url) { return $symb; }
                   9172: # Must be an alias
                   9173:     my $aliassymb='';
                   9174:     my %bighash;
1.620     albertel 9175:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9176:                             &GDBM_READER(),0640)) {
                   9177:         my $rid=$bighash{'mapalias_'.$symb};
                   9178: 	if ($rid) {
                   9179: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9180: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9181: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9182: 	}
                   9183:         untie %bighash;
                   9184:     }
                   9185:     return $aliassymb;
                   9186: }
                   9187: 
1.12      www      9188: # ----------------------------------------------------------------- Define Role
                   9189: 
                   9190: sub definerole {
                   9191:   if (allowed('mcr','/')) {
1.1326    raeburn  9192:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9193:     foreach my $role (split(':',$sysrole)) {
                   9194: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9195:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9196:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9197: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9198:                return "refused:s:$crole&$cqual"; 
                   9199:             }
                   9200:         }
1.191     harris41 9201:     }
1.800     albertel 9202:     foreach my $role (split(':',$domrole)) {
                   9203: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9204:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9205:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9206: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9207:                return "refused:d:$crole&$cqual"; 
                   9208:             }
                   9209:         }
1.191     harris41 9210:     }
1.800     albertel 9211:     foreach my $role (split(':',$courole)) {
                   9212: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9213:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9214:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9215: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9216:                return "refused:c:$crole&$cqual"; 
                   9217:             }
                   9218:         }
1.191     harris41 9219:     }
1.1326    raeburn  9220:     my $uhome;
                   9221:     if (($uname ne '') && ($udom ne '')) {
                   9222:         $uhome = &homeserver($uname,$udom);
                   9223:         return $uhome if ($uhome eq 'no_host');
                   9224:     } else {
                   9225:         $uname = $env{'user.name'};
                   9226:         $udom = $env{'user.domain'};
                   9227:         $uhome = $env{'user.home'};
                   9228:     }
1.620     albertel 9229:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  9230:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9231:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  9232:     return reply($command,$uhome);
1.12      www      9233:   } else {
                   9234:     return 'refused';
                   9235:   }
1.105     harris41 9236: }
                   9237: 
                   9238: # ---------------- Make a metadata query against the network of library servers
                   9239: 
                   9240: sub metadata_query {
1.1237    raeburn  9241:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9242:     my %rhash;
1.845     albertel 9243:     my %libserv = &all_library();
1.244     matthew  9244:     my @server_list = (defined($server_array) ? @$server_array
                   9245:                                               : keys(%libserv) );
                   9246:     for my $server (@server_list) {
1.1237    raeburn  9247:         my $domains = ''; 
                   9248:         if (ref($domains_hash) eq 'HASH') {
                   9249:             $domains = $domains_hash->{$server}; 
                   9250:         }
1.118     harris41 9251: 	unless ($custom or $customshow) {
1.1237    raeburn  9252: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9253: 	    $rhash{$server}=$reply;
                   9254: 	}
                   9255: 	else {
                   9256: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  9257: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9258: 			     $server);
                   9259: 	    $rhash{$server}=$reply;
                   9260: 	}
1.112     harris41 9261:     }
1.118     harris41 9262:     return \%rhash;
1.240     www      9263: }
                   9264: 
                   9265: # ----------------------------------------- Send log queries and wait for reply
                   9266: 
                   9267: sub log_query {
                   9268:     my ($uname,$udom,$query,%filters)=@_;
                   9269:     my $uhome=&homeserver($uname,$udom);
                   9270:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9271:     my $uhost=&hostname($uhome);
1.800     albertel 9272:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9273:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9274:                        $uhome);
1.479     albertel 9275:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9276:     return get_query_reply($queryid);
                   9277: }
                   9278: 
1.818     raeburn  9279: # -------------------------- Update MySQL table for portfolio file
                   9280: 
                   9281: sub update_portfolio_table {
1.821     raeburn  9282:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9283:     if ($group ne '') {
                   9284:         $file_name =~s /^\Q$group\E//;
                   9285:     }
1.818     raeburn  9286:     my $homeserver = &homeserver($uname,$udom);
                   9287:     my $queryid=
1.821     raeburn  9288:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9289:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9290:     my $reply = &get_query_reply($queryid);
                   9291:     return $reply;
                   9292: }
                   9293: 
1.899     raeburn  9294: # -------------------------- Update MySQL allusers table
                   9295: 
                   9296: sub update_allusers_table {
                   9297:     my ($uname,$udom,$names) = @_;
                   9298:     my $homeserver = &homeserver($uname,$udom);
                   9299:     my $queryid=
                   9300:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9301:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9302:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9303:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9304:                'generation='.&escape($names->{'generation'}).'%%'.
                   9305:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9306:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9307:     return;
1.899     raeburn  9308: }
                   9309: 
1.508     raeburn  9310: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9311: 
                   9312: sub fetch_enrollment_query {
1.511     raeburn  9313:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  9314:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9315:     my $maxtries = 1;
1.508     raeburn  9316:     if ($context eq 'automated') {
                   9317:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  9318:         $sleep = 2;
                   9319:         $loopmax = 100;
1.547     raeburn  9320:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9321:     } else {
                   9322:         $homeserver = &homeserver($cnum,$dom);
                   9323:     }
1.838     albertel 9324:     my $host=&hostname($homeserver);
1.506     raeburn  9325:     my $cmd = '';
1.1000    raeburn  9326:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9327:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9328:     }
                   9329:     $cmd =~ s/%%$//;
                   9330:     $cmd = &escape($cmd);
                   9331:     my $query = 'fetchenrollment';
1.620     albertel 9332:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9333:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9334:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9335:         return 'error: '.$queryid;
                   9336:     }
1.1317    raeburn  9337:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9338:     my $tries = 1;
                   9339:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  9340:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9341:         $tries ++;
                   9342:     }
1.526     raeburn  9343:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9344:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9345:     } else {
1.901     albertel 9346:         my @responses = split(/:/,$reply);
1.1322    raeburn  9347:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9348:             foreach my $line (@responses) {
                   9349:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9350:                 $$replyref{$key} = $value;
                   9351:             }
                   9352:         } else {
1.1117    foxr     9353:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9354:             foreach my $line (@responses) {
                   9355:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9356:                 $$replyref{$key} = $value;
                   9357:                 if ($value > 0) {
1.800     albertel 9358:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9359:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9360:                         my $destname = $pathname.'/'.$filename;
                   9361:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9362:                         if ($xml_classlist =~ /^error/) {
                   9363:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9364:                         } else {
1.1359    raeburn  9365:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9366:                                 print FILE &unescape($xml_classlist);
                   9367:                                 close(FILE);
1.526     raeburn  9368:                             } else {
                   9369:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9370:                             }
                   9371:                         }
                   9372:                     }
                   9373:                 }
                   9374:             }
                   9375:         }
                   9376:         return 'ok';
                   9377:     }
                   9378:     return 'error';
                   9379: }
                   9380: 
1.242     www      9381: sub get_query_reply {
1.1317    raeburn  9382:     my ($queryid,$sleep,$loopmax) = @_;;
                   9383:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9384:         $sleep = 0.2;
                   9385:     }
                   9386:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9387:         $loopmax = 100;
                   9388:     }
1.1117    foxr     9389:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9390:     my $reply='';
1.1317    raeburn  9391:     for (1..$loopmax) {
                   9392: 	sleep($sleep);
1.240     www      9393:         if (-e $replyfile.'.end') {
1.1359    raeburn  9394: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9395: 		$reply = join('',<$fh>);
                   9396: 		close($fh);
1.240     www      9397: 	   } else { return 'error: reply_file_error'; }
1.242     www      9398:            return &unescape($reply);
                   9399: 	}
1.240     www      9400:     }
1.242     www      9401:     return 'timeout:'.$queryid;
1.240     www      9402: }
                   9403: 
                   9404: sub courselog_query {
1.241     www      9405: #
                   9406: # possible filters:
                   9407: # url: url or symb
                   9408: # username
                   9409: # domain
                   9410: # action: view, submit, grade
                   9411: # start: timestamp
                   9412: # end: timestamp
                   9413: #
1.240     www      9414:     my (%filters)=@_;
1.620     albertel 9415:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9416:     if ($filters{'url'}) {
                   9417: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9418:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9419:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9420:     }
1.620     albertel 9421:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9422:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9423:     return &log_query($cname,$cdom,'courselog',%filters);
                   9424: }
                   9425: 
                   9426: sub userlog_query {
1.858     raeburn  9427: #
                   9428: # possible filters:
                   9429: # action: log check role
                   9430: # start: timestamp
                   9431: # end: timestamp
                   9432: #
1.240     www      9433:     my ($uname,$udom,%filters)=@_;
                   9434:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9435: }
                   9436: 
1.506     raeburn  9437: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9438: 
                   9439: sub auto_run {
1.508     raeburn  9440:     my ($cnum,$cdom) = @_;
1.876     raeburn  9441:     my $response = 0;
                   9442:     my $settings;
                   9443:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9444:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9445:         $settings = $domconfig{'autoenroll'};
                   9446:         if ($settings->{'run'} eq '1') {
                   9447:             $response = 1;
                   9448:         }
                   9449:     } else {
1.934     raeburn  9450:         my $homeserver;
                   9451:         if (&is_course($cdom,$cnum)) {
                   9452:             $homeserver = &homeserver($cnum,$cdom);
                   9453:         } else {
                   9454:             $homeserver = &domain($cdom,'primary');
                   9455:         }
                   9456:         if ($homeserver ne 'no_host') {
                   9457:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9458:         }
1.876     raeburn  9459:     }
1.506     raeburn  9460:     return $response;
                   9461: }
1.776     albertel 9462: 
1.506     raeburn  9463: sub auto_get_sections {
1.508     raeburn  9464:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9465:     my $homeserver;
                   9466:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9467:         $homeserver = &homeserver($cnum,$cdom);
                   9468:     }
                   9469:     if (!defined($homeserver)) { 
                   9470:         if ($cdom =~ /^$match_domain$/) {
                   9471:             $homeserver = &domain($cdom,'primary');
                   9472:         }
                   9473:     }
                   9474:     my @secs;
                   9475:     if (defined($homeserver)) {
                   9476:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9477:         unless ($response eq 'refused') {
                   9478:             @secs = split(/:/,$response);
                   9479:         }
1.506     raeburn  9480:     }
                   9481:     return @secs;
                   9482: }
1.776     albertel 9483: 
1.506     raeburn  9484: sub auto_new_course {
1.1099    raeburn  9485:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9486:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9487:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9488:     return $response;
                   9489: }
1.776     albertel 9490: 
1.506     raeburn  9491: sub auto_validate_courseID {
1.508     raeburn  9492:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9493:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9494:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9495:     return $response;
                   9496: }
1.776     albertel 9497: 
1.1007    raeburn  9498: sub auto_validate_instcode {
1.1020    raeburn  9499:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9500:     my ($homeserver,$response);
                   9501:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9502:         $homeserver = &homeserver($cnum,$cdom);
                   9503:     }
                   9504:     if (!defined($homeserver)) {
                   9505:         if ($cdom =~ /^$match_domain$/) {
                   9506:             $homeserver = &domain($cdom,'primary');
                   9507:         }
                   9508:     }
1.1065    raeburn  9509:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9510:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9511:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9512:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9513: }
                   9514: 
1.1444    raeburn  9515: sub auto_validate_inst_crosslist {
                   9516:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9517:     my ($homeserver,$response);
                   9518:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9519:         $homeserver = &homeserver($cnum,$cdom);
                   9520:     }
                   9521:     if (!defined($homeserver)) {
                   9522:         if ($cdom =~ /^$match_domain$/) {
                   9523:             $homeserver = &domain($cdom,'primary');
                   9524:         }
                   9525:     }
                   9526:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9527:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9528:                          &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445    raeburn  9529:                          &escape($coowner),$homeserver);
1.1444    raeburn  9530:     }
                   9531:     return $response;
                   9532: }
                   9533: 
1.506     raeburn  9534: sub auto_create_password {
1.873     raeburn  9535:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9536:     my ($homeserver,$response);
1.506     raeburn  9537:     my $create_passwd = 0;
                   9538:     my $authchk = '';
1.873     raeburn  9539:     if ($udom =~ /^$match_domain$/) {
                   9540:         $homeserver = &domain($udom,'primary');
                   9541:     }
                   9542:     if ($homeserver eq '') {
                   9543:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9544:             $homeserver = &homeserver($cnum,$cdom);
                   9545:         }
                   9546:     }
                   9547:     if ($homeserver eq '') {
                   9548:         $authchk = 'nodomain';
1.506     raeburn  9549:     } else {
1.873     raeburn  9550:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9551:         if ($response eq 'refused') {
                   9552:             $authchk = 'refused';
                   9553:         } else {
1.901     albertel 9554:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9555:         }
1.506     raeburn  9556:     }
                   9557:     return ($authparam,$create_passwd,$authchk);
                   9558: }
                   9559: 
1.706     raeburn  9560: sub auto_photo_permission {
                   9561:     my ($cnum,$cdom,$students) = @_;
                   9562:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9563:     my ($outcome,$perm_reqd,$conditions) = 
                   9564: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9565:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9566: 	return (undef,undef);
                   9567:     }
1.706     raeburn  9568:     return ($outcome,$perm_reqd,$conditions);
                   9569: }
                   9570: 
                   9571: sub auto_checkphotos {
                   9572:     my ($uname,$udom,$pid) = @_;
                   9573:     my $homeserver = &homeserver($uname,$udom);
                   9574:     my ($result,$resulttype);
                   9575:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9576: 				   &escape($uname).':'.&escape($pid),
                   9577: 				   $homeserver));
1.709     albertel 9578:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9579: 	return (undef,undef);
                   9580:     }
1.706     raeburn  9581:     if ($outcome) {
                   9582:         ($result,$resulttype) = split(/:/,$outcome);
                   9583:     } 
                   9584:     return ($result,$resulttype);
                   9585: }
                   9586: 
                   9587: sub auto_photochoice {
                   9588:     my ($cnum,$cdom) = @_;
                   9589:     my $homeserver = &homeserver($cnum,$cdom);
                   9590:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9591: 						       &escape($cdom),
                   9592: 						       $homeserver)));
1.709     albertel 9593:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9594: 	return (undef,undef);
                   9595:     }
1.706     raeburn  9596:     return ($update,$comment);
                   9597: }
                   9598: 
                   9599: sub auto_photoupdate {
                   9600:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9601:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9602:     my $host=&hostname($homeserver);
1.706     raeburn  9603:     my $cmd = '';
                   9604:     my $maxtries = 1;
1.800     albertel 9605:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9606:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9607:     }
                   9608:     $cmd =~ s/%%$//;
                   9609:     $cmd = &escape($cmd);
                   9610:     my $query = 'institutionalphotos';
                   9611:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9612:     unless ($queryid=~/^\Q$host\E\_/) {
                   9613:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9614:         return 'error: '.$queryid;
                   9615:     }
                   9616:     my $reply = &get_query_reply($queryid);
                   9617:     my $tries = 1;
                   9618:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9619:         $reply = &get_query_reply($queryid);
                   9620:         $tries ++;
                   9621:     }
                   9622:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9623:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9624:     } else {
                   9625:         my @responses = split(/:/,$reply);
                   9626:         my $outcome = shift(@responses); 
                   9627:         foreach my $item (@responses) {
                   9628:             my ($key,$value) = split(/=/,$item);
                   9629:             $$photo{$key} = $value;
                   9630:         }
                   9631:         return $outcome;
                   9632:     }
                   9633:     return 'error';
                   9634: }
                   9635: 
1.521     raeburn  9636: sub auto_instcode_format {
1.793     albertel 9637:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9638: 	$cat_order) = @_;
1.521     raeburn  9639:     my $courses = '';
1.772     raeburn  9640:     my @homeservers;
1.521     raeburn  9641:     if ($caller eq 'global') {
1.841     albertel 9642: 	my %servers = &get_servers($codedom,'library');
                   9643: 	foreach my $tryserver (keys(%servers)) {
                   9644: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9645: 		push(@homeservers,$tryserver);
                   9646: 	    }
1.584     raeburn  9647:         }
1.1022    raeburn  9648:     } elsif ($caller eq 'requests') {
                   9649:         if ($codedom =~ /^$match_domain$/) {
                   9650:             my $chome = &domain($codedom,'primary');
                   9651:             unless ($chome eq 'no_host') {
                   9652:                 push(@homeservers,$chome);
                   9653:             }
                   9654:         }
1.521     raeburn  9655:     } else {
1.772     raeburn  9656:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9657:     }
1.793     albertel 9658:     foreach my $code (keys(%{$instcodes})) {
                   9659:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9660:     }
                   9661:     chop($courses);
1.772     raeburn  9662:     my $ok_response = 0;
                   9663:     my $response;
                   9664:     while (@homeservers > 0 && $ok_response == 0) {
                   9665:         my $server = shift(@homeservers); 
                   9666:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9667:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9668:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9669: 		split(/:/,$response);
1.772     raeburn  9670:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9671:             push(@{$codetitles},&str2array($codetitles_str));
                   9672:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9673:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9674:             $ok_response = 1;
                   9675:         }
                   9676:     }
                   9677:     if ($ok_response) {
1.521     raeburn  9678:         return 'ok';
1.772     raeburn  9679:     } else {
                   9680:         return $response;
1.521     raeburn  9681:     }
                   9682: }
                   9683: 
1.792     raeburn  9684: sub auto_instcode_defaults {
                   9685:     my ($domain,$returnhash,$code_order) = @_;
                   9686:     my @homeservers;
1.841     albertel 9687: 
                   9688:     my %servers = &get_servers($domain,'library');
                   9689:     foreach my $tryserver (keys(%servers)) {
                   9690: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9691: 	    push(@homeservers,$tryserver);
                   9692: 	}
1.792     raeburn  9693:     }
1.841     albertel 9694: 
1.792     raeburn  9695:     my $response;
1.841     albertel 9696:     foreach my $server (@homeservers) {
1.792     raeburn  9697:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9698:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9699: 	
                   9700: 	foreach my $pair (split(/\&/,$response)) {
                   9701: 	    my ($name,$value)=split(/\=/,$pair);
                   9702: 	    if ($name eq 'code_order') {
                   9703: 		@{$code_order} = split(/\&/,&unescape($value));
                   9704: 	    } else {
                   9705: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9706: 	    }
                   9707: 	}
                   9708: 	return 'ok';
1.792     raeburn  9709:     }
1.841     albertel 9710: 
                   9711:     return $response;
1.1003    raeburn  9712: }
                   9713: 
                   9714: sub auto_possible_instcodes {
1.1007    raeburn  9715:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9716:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9717:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9718:         return;
                   9719:     }
1.1003    raeburn  9720:     my (@homeservers,$uhome);
                   9721:     if (defined(&domain($domain,'primary'))) {
                   9722:         $uhome=&domain($domain,'primary');
                   9723:         push(@homeservers,&domain($domain,'primary'));
                   9724:     } else {
                   9725:         my %servers = &get_servers($domain,'library');
                   9726:         foreach my $tryserver (keys(%servers)) {
                   9727:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9728:                 push(@homeservers,$tryserver);
                   9729:             }
                   9730:         }
                   9731:     }
                   9732:     my $response;
                   9733:     foreach my $server (@homeservers) {
                   9734:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9735:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9736:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9737:             split(':',$response);
                   9738:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9739:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9740:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9741:             my ($name,$value)=split('=',$item);
                   9742:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9743:         }
                   9744:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9745:             my ($name,$value)=split('=',$item);
                   9746:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9747:         }
                   9748:         return 'ok';
                   9749:     }
                   9750:     return $response;
                   9751: }
1.792     raeburn  9752: 
1.1010    raeburn  9753: sub auto_courserequest_checks {
                   9754:     my ($dom) = @_;
1.1020    raeburn  9755:     my ($homeserver,%validations);
                   9756:     if ($dom =~ /^$match_domain$/) {
                   9757:         $homeserver = &domain($dom,'primary');
                   9758:     }
                   9759:     unless ($homeserver eq 'no_host') {
                   9760:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9761:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9762:             my @items = split(/&/,$response);
                   9763:             foreach my $item (@items) {
                   9764:                 my ($key,$value) = split('=',$item);
                   9765:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9766:             }
                   9767:         }
                   9768:     }
1.1010    raeburn  9769:     return %validations; 
                   9770: }
                   9771: 
1.1020    raeburn  9772: sub auto_courserequest_validation {
1.1255    raeburn  9773:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9774:     my ($homeserver,$response);
                   9775:     if ($dom =~ /^$match_domain$/) {
                   9776:         $homeserver = &domain($dom,'primary');
                   9777:     }
1.1255    raeburn  9778:     unless ($homeserver eq 'no_host') {
                   9779:         my $customdata;
                   9780:         if (ref($custominfo) eq 'HASH') {
                   9781:             $customdata = &freeze_escape($custominfo);
                   9782:         }
1.1020    raeburn  9783:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9784:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9785:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9786:                                     $customdata,$homeserver));
1.1020    raeburn  9787:     }
                   9788:     return $response;
                   9789: }
                   9790: 
1.777     albertel 9791: sub auto_validate_class_sec {
1.918     raeburn  9792:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9793:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9794:     my $ownerlist;
                   9795:     if (ref($owners) eq 'ARRAY') {
                   9796:         $ownerlist = join(',',@{$owners});
                   9797:     } else {
                   9798:         $ownerlist = $owners;
                   9799:     }
1.773     raeburn  9800:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9801:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9802:     return $response;
                   9803: }
                   9804: 
1.1460    raeburn  9805: sub auto_instsec_reformat {
                   9806:     my ($cdom,$action,$instsecref) = @_;
                   9807:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9808:     my @homeservers;
                   9809:     if (defined(&domain($cdom,'primary'))) {
                   9810:         push(@homeservers,&domain($cdom,'primary'));
                   9811:     } else {
                   9812:         my %servers = &get_servers($cdom,'library');
                   9813:         foreach my $tryserver (keys(%servers)) {
                   9814:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9815:                 push(@homeservers,$tryserver);
                   9816:             }
                   9817:         }
                   9818:     }
                   9819:     my $response;
                   9820:     my %reformatted = %{$instsecref};
                   9821:     foreach my $server (@homeservers) {
                   9822:         if (ref($instsecref) eq 'HASH') {
                   9823:             my $info = &freeze_escape($instsecref);
                   9824:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9825:                                 $action.':'.$info,$server);
                   9826:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9827:             my @items = split(/&/,$response);
                   9828:             foreach my $item (@items) {
                   9829:                 my ($key,$value) = split(/=/,$item);
                   9830:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9831:             }
                   9832:         }
                   9833:     }
                   9834:     return %reformatted;
                   9835: }
                   9836: 
1.1367    raeburn  9837: sub auto_validate_instclasses {
                   9838:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9839:     my ($homeserver,%validations);
                   9840:     $homeserver = &homeserver($cnum,$cdom);
                   9841:     unless ($homeserver eq 'no_host') {
                   9842:         my $ownerlist;
                   9843:         if (ref($owners) eq 'ARRAY') {
                   9844:             $ownerlist = join(',',@{$owners});
                   9845:         } else {
                   9846:             $ownerlist = $owners;
                   9847:         }
                   9848:         if (ref($classesref) eq 'HASH') {
                   9849:             my $classes = &freeze_escape($classesref);
                   9850:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9851:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9852:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9853:                 my @items = split(/&/,$response);
                   9854:                 foreach my $item (@items) {
                   9855:                     my ($key,$value) = split('=',$item);
                   9856:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9857:                 }
                   9858:             }
                   9859:         }
                   9860:     }
                   9861:     return %validations;
                   9862: }
                   9863: 
1.1248    raeburn  9864: sub auto_crsreq_update {
                   9865:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9866:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9867:     my ($homeserver,%crsreqresponse);
                   9868:     if ($cdom =~ /^$match_domain$/) {
                   9869:         $homeserver = &domain($cdom,'primary');
                   9870:     }
                   9871:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9872:         my $info;
                   9873:         if (ref($inbound) eq 'HASH') {
                   9874:             $info = &freeze_escape($inbound);
                   9875:         }
                   9876:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9877:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9878:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9879:                             &escape($title).':'.&escape($code).':'.
                   9880:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9881:                             $homeserver);
1.1248    raeburn  9882:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9883:             my @items = split(/&/,$response);
                   9884:             foreach my $item (@items) {
                   9885:                 my ($key,$value) = split('=',$item);
                   9886:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9887:             }
                   9888:         }
                   9889:     }
                   9890:     return \%crsreqresponse;
                   9891: }
                   9892: 
1.1305    raeburn  9893: sub auto_export_grades {
1.1309    raeburn  9894:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9895:     my ($homeserver,%exportresponse);
                   9896:     if ($cdom =~ /^$match_domain$/) {
                   9897:         $homeserver = &domain($cdom,'primary');
                   9898:     }
                   9899:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9900:         my $info;
                   9901:         if (ref($inforef) eq 'HASH') {
                   9902:             $info = &freeze_escape($inforef);
                   9903:         }
                   9904:         if (ref($gradesref) eq 'HASH') {
                   9905:             my $grades = &freeze_escape($gradesref);
                   9906:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9907:                                 $info.':'.$grades,$homeserver);
                   9908:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9909:                 my @items = split(/&/,$response);
                   9910:                 foreach my $item (@items) {
                   9911:                     my ($key,$value) = split('=',$item);
                   9912:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9913:                 }
                   9914:             }
                   9915:         }
                   9916:     }
                   9917:     return \%exportresponse;
1.1305    raeburn  9918: }
                   9919: 
1.1287    raeburn  9920: sub check_instcode_cloning {
                   9921:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9922:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9923:         return;
                   9924:     }
                   9925:     my $canclone;
                   9926:     if (@{$code_order} > 0) {
                   9927:         my $instcoderegexp ='^';
                   9928:         my @clonecodes = split(/\&/,$cloner);
                   9929:         foreach my $item (@{$code_order}) {
                   9930:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9931:                 foreach my $pair (@clonecodes) {
                   9932:                     my ($key,$val) = split(/\=/,$pair,2);
                   9933:                     $val = &unescape($val);
                   9934:                     if ($key eq $item) {
                   9935:                         $instcoderegexp .= '('.$val.')';
                   9936:                         last;
                   9937:                     }
                   9938:                 }
                   9939:             } else {
                   9940:                 $instcoderegexp .= $codedefaults->{$item};
                   9941:             }
                   9942:         }
                   9943:         $instcoderegexp .= '$';
                   9944:         my (@from,@to);
                   9945:         eval {
                   9946:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9947:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9948:         };
                   9949:         if ((@from > 0) && (@to > 0)) {
                   9950:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9951:             if (!@diffs) {
                   9952:                 $canclone = 1;
                   9953:             }
                   9954:         }
                   9955:     }
                   9956:     return $canclone;
                   9957: }
                   9958: 
                   9959: sub default_instcode_cloning {
                   9960:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9961:     my (%codedefaults,@code_order,$canclone);
                   9962:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9963:         %codedefaults = %{$codedefaultsref};
                   9964:         @code_order = @{$codeorderref};
                   9965:     } elsif ($clonedom) {
                   9966:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9967:     }
                   9968:     if (($domdefclone) && (@code_order)) {
                   9969:         my @clonecodes = split(/\+/,$domdefclone);
                   9970:         my $instcoderegexp ='^';
                   9971:         foreach my $item (@code_order) {
                   9972:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9973:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9974:             } else {
                   9975:                 $instcoderegexp .= $codedefaults{$item};
                   9976:             }
                   9977:         }
                   9978:         $instcoderegexp .= '$';
                   9979:         my (@from,@to);
                   9980:         eval {
                   9981:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9982:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9983:         };
                   9984:         if ((@from > 0) && (@to > 0)) {
                   9985:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9986:             if (!@diffs) {
                   9987:                 $canclone = 1;
                   9988:             }
                   9989:         }
                   9990:     }
                   9991:     return $canclone;
                   9992: }
                   9993: 
1.679     raeburn  9994: # ------------------------------------------------------- Course Group routines
                   9995: 
                   9996: sub get_coursegroups {
1.809     raeburn  9997:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9998:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9999: }
                   10000: 
1.679     raeburn  10001: sub modify_coursegroup {
                   10002:     my ($cdom,$cnum,$groupsettings) = @_;
                   10003:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10004: }
                   10005: 
1.809     raeburn  10006: sub toggle_coursegroup_status {
                   10007:     my ($cdom,$cnum,$group,$action) = @_;
                   10008:     my ($from_namespace,$to_namespace);
                   10009:     if ($action eq 'delete') {
                   10010:         $from_namespace = 'coursegroups';
                   10011:         $to_namespace = 'deleted_groups';
                   10012:     } else {
                   10013:         $from_namespace = 'deleted_groups';
                   10014:         $to_namespace = 'coursegroups';
                   10015:     }
                   10016:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10017:     if (my $tmp = &error(%curr_group)) {
                   10018:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10019:         return ('read error',$tmp);
                   10020:     } else {
                   10021:         my %savedsettings = %curr_group; 
1.809     raeburn  10022:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10023:         my $deloutcome;
                   10024:         if ($result eq 'ok') {
1.809     raeburn  10025:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10026:         } else {
                   10027:             return ('write error',$result);
                   10028:         }
                   10029:         if ($deloutcome eq 'ok') {
                   10030:             return 'ok';
                   10031:         } else {
                   10032:             return ('delete error',$deloutcome);
                   10033:         }
                   10034:     }
                   10035: }
                   10036: 
1.679     raeburn  10037: sub modify_group_roles {
1.957     raeburn  10038:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  10039:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10040:     my $role = 'gr/'.&escape($userprivs);
                   10041:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  10042:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  10043:     if ($result eq 'ok') {
                   10044:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10045:     }
1.679     raeburn  10046:     return $result;
                   10047: }
                   10048: 
                   10049: sub modify_coursegroup_membership {
                   10050:     my ($cdom,$cnum,$membership) = @_;
                   10051:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10052:     return $result;
                   10053: }
                   10054: 
1.682     raeburn  10055: sub get_active_groups {
                   10056:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10057:     my $now = time;
                   10058:     my %groups = ();
                   10059:     foreach my $key (keys(%env)) {
1.811     albertel 10060:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10061:             my ($start,$end) = split(/\./,$env{$key});
                   10062:             if (($end!=0) && ($end<$now)) { next; }
                   10063:             if (($start!=0) && ($start>$now)) { next; }
                   10064:             if ($1 eq $cdom && $2 eq $cnum) {
                   10065:                 $groups{$3} = $env{$key} ;
                   10066:             }
                   10067:         }
                   10068:     }
                   10069:     return %groups;
                   10070: }
                   10071: 
1.683     raeburn  10072: sub get_group_membership {
                   10073:     my ($cdom,$cnum,$group) = @_;
                   10074:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10075: }
                   10076: 
                   10077: sub get_users_groups {
                   10078:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10079:     my @usersgroups;
1.683     raeburn  10080:     my $cachetime=1800;
                   10081: 
                   10082:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10083:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10084:     if (defined($cached)) {
1.734     albertel 10085:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10086:     } else {  
                   10087:         $grouplist = '';
1.816     raeburn  10088:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10089:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10090:         my $access_end = $env{'course.'.$courseid.
                   10091:                               '.default_enrollment_end_date'};
                   10092:         my $now = time;
                   10093:         foreach my $key (keys(%roleshash)) {
                   10094:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10095:                 my $group = $1;
                   10096:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10097:                     my $start = $2;
                   10098:                     my $end = $1;
                   10099:                     if ($start == -1) { next; } # deleted from group
                   10100:                     if (($start!=0) && ($start>$now)) { next; }
                   10101:                     if (($end!=0) && ($end<$now)) {
                   10102:                         if ($access_end && $access_end < $now) {
                   10103:                             if ($access_end - $end < 86400) {
                   10104:                                 push(@usersgroups,$group);
1.733     raeburn  10105:                             }
                   10106:                         }
1.817     raeburn  10107:                         next;
1.733     raeburn  10108:                     }
1.817     raeburn  10109:                     push(@usersgroups,$group);
1.683     raeburn  10110:                 }
                   10111:             }
                   10112:         }
1.817     raeburn  10113:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10114:         $grouplist = join(':',@usersgroups);
                   10115:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10116:     }
1.733     raeburn  10117:     return @usersgroups;
1.683     raeburn  10118: }
                   10119: 
                   10120: sub devalidate_getgroups_cache {
                   10121:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10122:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10123: 
1.683     raeburn  10124:     my $hashid="$udom:$uname:$courseid";
                   10125:     &devalidate_cache_new('getgroups',$hashid);
                   10126: }
                   10127: 
1.12      www      10128: # ------------------------------------------------------------------ Plain Text
                   10129: 
                   10130: sub plaintext {
1.988     raeburn  10131:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10132:     if ($short =~ m{^cr/}) {
1.758     albertel 10133: 	return (split('/',$short))[-1];
                   10134:     }
1.742     raeburn  10135:     if (!defined($cid)) {
                   10136:         $cid = $env{'request.course.id'};
                   10137:     }
                   10138:     my %rolenames = (
1.1008    raeburn  10139:                       Course    => 'std',
                   10140:                       Community => 'alt1',
1.1305    raeburn  10141:                       Placement => 'std',
1.742     raeburn  10142:                     );
1.1037    raeburn  10143:     if ($cid ne '') {
                   10144:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10145:             unless ($forcedefault) {
                   10146:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10147:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10148:                 return &Apache::lonlocal::mt($roletext);
                   10149:             }
                   10150:         }
                   10151:     }
                   10152:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10153:         (defined($rolenames{$type})) && 
                   10154:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10155:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10156:     } elsif ($cid ne '') {
                   10157:         my $crstype = $env{'course.'.$cid.'.type'};
                   10158:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10159:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10160:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10161:         }
1.742     raeburn  10162:     }
1.1037    raeburn  10163:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10164: }
                   10165: 
                   10166: # ----------------------------------------------------------------- Assign Role
                   10167: 
                   10168: sub assignrole {
1.957     raeburn  10169:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10170:         $context)=@_;
1.21      www      10171:     my $mrole;
                   10172:     if ($role =~ /^cr\//) {
1.393     www      10173:         my $cwosec=$url;
1.811     albertel 10174:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10175: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10176:            my $refused = 1;
                   10177:            if ($context eq 'requestcourses') {
                   10178:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10179:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10180:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10181:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10182:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10183:                            if ($crsenv{'internal.courseowner'} eq
                   10184:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10185:                                $refused = '';
                   10186:                            }
                   10187:                        }
                   10188:                    }
                   10189:                }
                   10190:            }
                   10191:            if ($refused) {
                   10192:                &logthis('Refused custom assignrole: '.
                   10193:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10194:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10195:                return 'refused';
                   10196:            }
1.104     www      10197:         }
1.21      www      10198:         $mrole='cr';
1.678     raeburn  10199:     } elsif ($role =~ /^gr\//) {
                   10200:         my $cwogrp=$url;
1.811     albertel 10201:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10202:         unless (&allowed('mdg',$cwogrp)) {
                   10203:             &logthis('Refused group assignrole: '.
                   10204:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10205:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10206:             return 'refused';
                   10207:         }
                   10208:         $mrole='gr';
1.21      www      10209:     } else {
1.82      www      10210:         my $cwosec=$url;
1.811     albertel 10211:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10212:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10213:             my $refused;
                   10214:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10215:                 if (!(&allowed('c'.$role,$url))) {
                   10216:                     $refused = 1;
                   10217:                 }
                   10218:             } else {
                   10219:                 $refused = 1;
                   10220:             }
1.947     raeburn  10221:             if ($refused) {
1.1045    raeburn  10222:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  10223:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  10224:                     my %crsenv;
                   10225:                     if ($role eq 'cc' || $role eq 'co') {
                   10226:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10227:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10228:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10229:                                 if ($crsenv{'internal.courseowner'} eq 
                   10230:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10231:                                     $refused = '';
                   10232:                                 }
                   10233:                             }
                   10234:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10235:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10236:                                 if ($crsenv{'internal.courseowner'} eq 
                   10237:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10238:                                     $refused = '';
                   10239:                                 }
                   10240:                             }
                   10241:                         }
                   10242:                     }
1.1368    raeburn  10243:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10244:                     if ($role eq 'st') {
                   10245:                         $refused = '';
1.1377    raeburn  10246:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  10247:                         $refused = '';
                   10248:                     }
1.1017    raeburn  10249:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10250:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10251:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10252:                         my $wrongcc;
                   10253:                         if ($cnum =~ /^$match_community$/) {
                   10254:                             $wrongcc = 1 if ($role eq 'cc');
                   10255:                         } else {
                   10256:                             $wrongcc = 1 if ($role eq 'co');
                   10257:                         }
                   10258:                         unless ($wrongcc) {
                   10259:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10260:                             if ($crsenv{'internal.courseowner'} eq 
                   10261:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10262:                                 $refused = '';
                   10263:                             }
1.1017    raeburn  10264:                         }
                   10265:                     }
1.1183    raeburn  10266:                 } elsif ($context eq 'requestauthor') {
                   10267:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   10268:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10269:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10270:                             $refused = '';
                   10271:                         } else {
                   10272:                             my %domdefaults = &get_domain_defaults($udom);
                   10273:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10274:                                 my $checkbystatus;
                   10275:                                 if ($env{'user.adv'}) { 
                   10276:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10277:                                     if ($disposition eq 'automatic') {
                   10278:                                         $refused = '';
                   10279:                                     } elsif ($disposition eq '') {
                   10280:                                         $checkbystatus = 1;
                   10281:                                     } 
                   10282:                                 } else {
                   10283:                                     $checkbystatus = 1;
                   10284:                                 }
                   10285:                                 if ($checkbystatus) {
                   10286:                                     if ($env{'environment.inststatus'}) {
                   10287:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10288:                                         foreach my $type (@inststatuses) {
                   10289:                                             if (($type ne '') &&
                   10290:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10291:                                                 $refused = '';
                   10292:                                             }
                   10293:                                         }
                   10294:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10295:                                         $refused = '';
                   10296:                                     }
                   10297:                                 }
                   10298:                             }
                   10299:                         }
                   10300:                     }
1.1017    raeburn  10301:                 }
                   10302:                 if ($refused) {
1.947     raeburn  10303:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10304:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10305: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10306:                     return 'refused';
                   10307:                 }
1.932     raeburn  10308:             }
1.1131    raeburn  10309:         } elsif ($role eq 'au') {
                   10310:             if ($url ne '/'.$udom.'/') {
                   10311:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10312:                          ' to assign author role for '.$uname.':'.$udom.
                   10313:                          ' in domain: '.$url.' refused (wrong domain).');
                   10314:                 return 'refused';
                   10315:             }
1.104     www      10316:         }
1.21      www      10317:         $mrole=$role;
                   10318:     }
1.620     albertel 10319:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10320:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10321:     if ($end) { $command.='_'.$end; }
1.21      www      10322:     if ($start) {
                   10323: 	if ($end) { 
1.81      www      10324:            $command.='_'.$start; 
1.21      www      10325:         } else {
1.81      www      10326:            $command.='_0_'.$start;
1.21      www      10327:         }
                   10328:     }
1.739     raeburn  10329:     my $origstart = $start;
                   10330:     my $origend = $end;
1.957     raeburn  10331:     my $delflag;
1.357     www      10332: # actually delete
                   10333:     if ($deleteflag) {
1.373     www      10334: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10335: # modify command to delete the role
1.620     albertel 10336:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10337:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10338: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10339: # set start and finish to negative values for userrolelog
                   10340:            $start=-1;
                   10341:            $end=-1;
1.957     raeburn  10342:            $delflag = 1;
1.357     www      10343:         }
                   10344:     }
                   10345: # send command
1.349     www      10346:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10347: # log new user role if status is ok
1.349     www      10348:     if ($answer eq 'ok') {
1.663     raeburn  10349: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  10350:         if (($role eq 'cc') || ($role eq 'in') ||
                   10351:             ($role eq 'ep') || ($role eq 'ad') ||
                   10352:             ($role eq 'ta') || ($role eq 'st') ||
                   10353:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10354:             ($role eq 'co')) {
1.1200    raeburn  10355: # for course roles, perform group memberships changes triggered by role change.
                   10356:             unless ($role =~ /^gr/) {
                   10357:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10358:                                                  $origstart,$selfenroll,$context);
                   10359:             }
1.1184    raeburn  10360:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10361:                            $selfenroll,$context);
                   10362:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  10363:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10364:                  ($role eq 'da')) {
1.1184    raeburn  10365:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10366:                            $context);
                   10367:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10368:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10369:                              $context); 
                   10370:         }
1.1053    raeburn  10371:         if ($role eq 'cc') {
                   10372:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10373:         }
1.349     www      10374:     }
                   10375:     return $answer;
1.169     harris41 10376: }
                   10377: 
1.1053    raeburn  10378: sub autoupdate_coowners {
                   10379:     my ($url,$end,$start,$uname,$udom) = @_;
                   10380:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10381:     if (($cdom ne '') && ($cnum ne '')) {
                   10382:         my $now = time;
                   10383:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10384:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10385:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10386:             my $instcode = $coursehash{'internal.coursecode'};
1.1444    raeburn  10387:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10388:             if ($instcode ne '') {
1.1056    raeburn  10389:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10390:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10391:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10392:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444    raeburn  10393:                         unless ($result eq 'valid') {
                   10394:                             if ($xlists ne '') {
                   10395:                                 foreach my $xlist (split(',',$xlists)) {
                   10396:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10397:                                     $result =
1.1446    raeburn  10398:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10399:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10400:                                     last if ($result eq 'valid');
1.1444    raeburn  10401:                                 }
                   10402:                             }
                   10403:                         }
1.1056    raeburn  10404:                         if ($result eq 'valid') {
                   10405:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10406:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10407:                                     push(@newcoowners,$coowner);
                   10408:                                 }
                   10409:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10410:                                     push(@newcoowners,$uname.':'.$udom);
                   10411:                                 }
                   10412:                                 @newcoowners = sort(@newcoowners);
                   10413:                             } else {
                   10414:                                 push(@newcoowners,$uname.':'.$udom);
                   10415:                             }
1.1444    raeburn  10416:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10417:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10418:                                 unless ($coowner eq $uname.':'.$udom) {
                   10419:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10420:                                 }
1.1444    raeburn  10421:                             }
                   10422:                             unless (@newcoowners > 0) {
                   10423:                                 $delcoowners = 1;
                   10424:                                 $coowners = '';
1.1053    raeburn  10425:                             }
                   10426:                         }
                   10427:                         if (@newcoowners || $delcoowners) {
                   10428:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10429:                                             $delcoowners,@newcoowners);
                   10430:                         }
                   10431:                     }
                   10432:                 }
                   10433:             }
                   10434:         }
                   10435:     }
                   10436: }
                   10437: 
                   10438: sub store_coowners {
                   10439:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10440:     my $cid = $cdom.'_'.$cnum;
                   10441:     my ($coowners,$delresult,$putresult);
                   10442:     if (@newcoowners) {
                   10443:         $coowners = join(',',@newcoowners);
                   10444:         my %coownershash = (
                   10445:                             'internal.co-owners' => $coowners,
                   10446:                            );
                   10447:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10448:         if ($putresult eq 'ok') {
                   10449:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10450:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10451:             }
                   10452:         }
                   10453:     }
                   10454:     if ($delcoowners) {
                   10455:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10456:         if ($delresult eq 'ok') {
                   10457:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10458:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10459:             }
                   10460:         }
                   10461:     }
                   10462:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10463:         my %crsinfo =
                   10464:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10465:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10466:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10467:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10468:         }
                   10469:     }
                   10470: }
                   10471: 
1.169     harris41 10472: # -------------------------------------------------- Modify user authentication
1.197     www      10473: # Overrides without validation
                   10474: 
1.169     harris41 10475: sub modifyuserauth {
                   10476:     my ($udom,$uname,$umode,$upass)=@_;
                   10477:     my $uhome=&homeserver($uname,$udom);
1.1409    raeburn  10478:     my $allowed;
                   10479:     if (&allowed('mau',$udom)) {
                   10480:         $allowed = 1;
                   10481:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10482:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10483:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10484:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10485:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10486:         if (($cdom ne '') && ($cnum ne '')) {
                   10487:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10488:             if ($is_owner) {
                   10489:                 $allowed = 1;
                   10490:             }
                   10491:         }
                   10492:     }
                   10493:     unless ($allowed) { return 'refused'; }
1.197     www      10494:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10495:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10496:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10497:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10498: 		     &escape($upass),$uhome);
1.1434    raeburn  10499:     my $ip = &get_requestor_ip();
1.620     albertel 10500:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10501:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434    raeburn  10502:          '(Remote '.$ip.'): '.$reply);
1.197     www      10503:     &log($udom,,$uname,$uhome,
1.620     albertel 10504:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10505:                                      $env{'user.name'}.', '.$umode.
1.1435    raeburn  10506:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10507:     unless ($reply eq 'ok') {
1.197     www      10508:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10509: 	return 'error: '.$reply;
                   10510:     }   
1.170     harris41 10511:     return 'ok';
1.80      www      10512: }
                   10513: 
1.81      www      10514: # --------------------------------------------------------------- Modify a user
1.80      www      10515: 
1.81      www      10516: sub modifyuser {
1.206     matthew  10517:     my ($udom,    $uname, $uid,
                   10518:         $umode,   $upass, $first,
                   10519:         $middle,  $last,  $gene,
1.1058    raeburn  10520:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10521:     $udom= &LONCAPA::clean_domain($udom);
                   10522:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10523:     my $showcandelete = 'none';
                   10524:     if (ref($candelete) eq 'ARRAY') {
                   10525:         if (@{$candelete} > 0) {
                   10526:             $showcandelete = join(', ',@{$candelete});
                   10527:         }
                   10528:     }
1.81      www      10529:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10530:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10531: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10532:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10533:                                      ' desiredhome not specified'). 
1.620     albertel 10534:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10535:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10536:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10537:     my $newuser;
                   10538:     if ($uhome eq 'no_host') {
                   10539:         $newuser = 1;
1.1368    raeburn  10540:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10541:                 ($umode eq 'lti')) {
                   10542:             return 'error: more information needed to create new user';
                   10543:         }
1.1075    raeburn  10544:     }
1.80      www      10545: # ----------------------------------------------------------------- Create User
1.406     albertel 10546:     if (($uhome eq 'no_host') && 
1.1368    raeburn  10547: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10548:         my $unhome='';
1.844     albertel 10549:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10550:             $unhome = $desiredhome;
1.620     albertel 10551: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10552: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10553:         } else { # load balancing routine for determining $unhome
1.81      www      10554:             my $loadm=10000000;
1.841     albertel 10555: 	    my %servers = &get_servers($udom,'library');
                   10556: 	    foreach my $tryserver (keys(%servers)) {
                   10557: 		my $answer=reply('load',$tryserver);
                   10558: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10559: 		    $loadm=$answer;
                   10560: 		    $unhome=$tryserver;
                   10561: 		}
1.80      www      10562: 	    }
                   10563:         }
                   10564:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10565: 	    return 'error: unable to find a home server for '.$uname.
                   10566:                    ' in domain '.$udom;
1.80      www      10567:         }
                   10568:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10569:                          &escape($upass),$unhome);
                   10570: 	unless ($reply eq 'ok') {
                   10571:             return 'error: '.$reply;
                   10572:         }   
1.230     stredwic 10573:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10574:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10575: 	    return 'error: unable verify users home machine.';
1.80      www      10576:         }
1.209     matthew  10577:     }   # End of creation of new user
1.80      www      10578: # ---------------------------------------------------------------------- Add ID
                   10579:     if ($uid) {
                   10580:        $uid=~tr/A-Z/a-z/;
                   10581:        my %uidhash=&idrget($udom,$uname);
1.196     www      10582:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10583:          && (!$forceid)) {
1.80      www      10584: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10585: 	      return 'error: user id "'.$uid.'" does not match '.
                   10586:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10587:           }
                   10588:        } else {
1.1300    raeburn  10589: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      10590:        }
                   10591:     }
                   10592: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10593:     my @tmp=&get('environment',
1.899     raeburn  10594: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10595:                     'permanentemail','inststatus'],
1.134     albertel 10596: 		   $udom,$uname);
1.1075    raeburn  10597:     my (%names,%oldnames);
1.313     matthew  10598:     if ($tmp[0] =~ m/^error:.*/) { 
                   10599:         %names=(); 
                   10600:     } else {
                   10601:         %names = @tmp;
1.1075    raeburn  10602:         %oldnames = %names;
1.313     matthew  10603:     }
1.388     www      10604: #
1.1058    raeburn  10605: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10606: # of users did not contain them), do not overwrite existing values
                   10607: # unless field is in $candelete array ref.  
                   10608: #
                   10609: 
                   10610:     my @fields = ('firstname','middlename','lastname','generation',
                   10611:                   'permanentemail','id');
                   10612:     my %newvalues;
                   10613:     if (ref($candelete) eq 'ARRAY') {
                   10614:         foreach my $field (@fields) {
                   10615:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10616:                 if ($field eq 'firstname') {
                   10617:                     $names{$field} = $first;
                   10618:                 } elsif ($field eq 'middlename') {
                   10619:                     $names{$field} = $middle;
                   10620:                 } elsif ($field eq 'lastname') {
                   10621:                     $names{$field} = $last;
                   10622:                 } elsif ($field eq 'generation') { 
                   10623:                     $names{$field} = $gene;
                   10624:                 } elsif ($field eq 'permanentemail') {
                   10625:                     $names{$field} = $email;
                   10626:                 } elsif ($field eq 'id') {
                   10627:                     $names{$field}  = $uid;
                   10628:                 }
                   10629:             }
                   10630:         }
                   10631:     }
1.388     www      10632:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10633:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10634:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10635:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10636:     if ($email) {
                   10637:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10638:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10639:     }
1.899     raeburn  10640:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10641:     if (defined($inststatus)) {
                   10642:         $names{'inststatus'} = '';
                   10643:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10644:         if (ref($usertypes) eq 'HASH') {
                   10645:             my @okstatuses; 
                   10646:             foreach my $item (split(/:/,$inststatus)) {
                   10647:                 if (defined($usertypes->{$item})) {
                   10648:                     push(@okstatuses,$item);  
                   10649:                 }
                   10650:             }
                   10651:             if (@okstatuses) {
                   10652:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10653:             }
                   10654:         }
                   10655:     }
1.1075    raeburn  10656:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10657:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10658:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10659:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10660:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10661:     } else {
                   10662:         $logmsg .= ' during self creation';
                   10663:     }
1.1075    raeburn  10664:     my $changed;
                   10665:     if ($newuser) {
                   10666:         $changed = 1;
                   10667:     } else {
                   10668:         foreach my $field (@fields) {
                   10669:             if ($names{$field} ne $oldnames{$field}) {
                   10670:                 $changed = 1;
                   10671:                 last;
                   10672:             }
                   10673:         }
                   10674:     }
                   10675:     unless ($changed) {
                   10676:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10677:         &logthis($logmsg);
                   10678:         return 'ok';
                   10679:     }
                   10680:     my $reply = &put('environment', \%names, $udom,$uname);
                   10681:     if ($reply ne 'ok') { 
                   10682:         return 'error: '.$reply;
                   10683:     }
1.1087    raeburn  10684:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10685:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10686:     }
1.1075    raeburn  10687:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10688:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10689:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10690:     &logthis($logmsg);
1.134     albertel 10691:     return 'ok';
1.80      www      10692: }
                   10693: 
1.81      www      10694: # -------------------------------------------------------------- Modify student
1.80      www      10695: 
1.81      www      10696: sub modifystudent {
                   10697:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10698:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  10699:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10700:     if (!$cid) {
1.620     albertel 10701: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10702: 	    return 'not_in_class';
                   10703: 	}
1.80      www      10704:     }
                   10705: # --------------------------------------------------------------- Make the user
1.81      www      10706:     my $reply=&modifyuser
1.209     matthew  10707: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10708:          $desiredhome,$email,$inststatus);
1.80      www      10709:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10710:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  10711:     # student's environment
1.297     matthew  10712:     $uid = undef if (!$forceid);
1.455     albertel 10713:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  10714:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  10715:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10716:     return $reply;
                   10717: }
                   10718: 
                   10719: sub modify_student_enrollment {
1.1216    raeburn  10720:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  10721:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10722:     my ($cdom,$cnum,$chome);
                   10723:     if (!$cid) {
1.620     albertel 10724: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10725: 	    return 'not_in_class';
                   10726: 	}
1.620     albertel 10727: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10728: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10729:     } else {
                   10730: 	($cdom,$cnum)=split(/_/,$cid);
                   10731:     }
1.620     albertel 10732:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10733:     if (!$chome) {
1.457     raeburn  10734: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10735:     }
1.455     albertel 10736:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10737:     # Make sure the user exists
1.81      www      10738:     my $uhome=&homeserver($uname,$udom);
                   10739:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10740: 	return 'error: no such user';
                   10741:     }
1.297     matthew  10742:     # Get student data if we were not given enough information
                   10743:     if (!defined($first)  || $first  eq '' || 
                   10744:         !defined($last)   || $last   eq '' || 
                   10745:         !defined($uid)    || $uid    eq '' || 
                   10746:         !defined($middle) || $middle eq '' || 
                   10747:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10748:         # They did not supply us with enough data to enroll the student, so
                   10749:         # we need to pick up more information.
1.297     matthew  10750:         my %tmp = &get('environment',
1.294     matthew  10751:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10752:                        ,$udom,$uname);
                   10753: 
1.800     albertel 10754:         #foreach my $key (keys(%tmp)) {
                   10755:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10756:         #}
1.294     matthew  10757:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10758:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10759:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10760:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10761:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10762:     }
1.556     albertel 10763:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10764:     my $user = "$uname:$udom";
                   10765:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10766:     my $reply=cput('classlist',
1.1148    raeburn  10767: 		   {$user => 
1.1314    raeburn  10768: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10769: 		   $cdom,$cnum);
1.1148    raeburn  10770:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10771:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10772:     } else { 
1.81      www      10773: 	return 'error: '.$reply;
                   10774:     }
1.297     matthew  10775:     # Add student role to user
1.83      www      10776:     my $uurl='/'.$cid;
1.81      www      10777:     $uurl=~s/\_/\//g;
                   10778:     if ($usec) {
                   10779: 	$uurl.='/'.$usec;
                   10780:     }
1.1148    raeburn  10781:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10782:                              $selfenroll,$context);
                   10783:     if ($result ne 'ok') {
                   10784:         if ($old_entry{$user} ne '') {
                   10785:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10786:         } else {
                   10787:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10788:         }
                   10789:     }
                   10790:     return $result; 
1.21      www      10791: }
                   10792: 
1.556     albertel 10793: sub format_name {
                   10794:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10795:     my $name;
                   10796:     if ($first ne 'lastname') {
                   10797: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10798:     } else {
                   10799: 	if ($lastname=~/\S/) {
                   10800: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10801: 	    $name=~s/\s+,/,/;
                   10802: 	} else {
                   10803: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10804: 	}
                   10805:     }
                   10806:     $name=~s/^\s+//;
                   10807:     $name=~s/\s+$//;
                   10808:     $name=~s/\s+/ /g;
                   10809:     return $name;
                   10810: }
                   10811: 
1.84      www      10812: # ------------------------------------------------- Write to course preferences
                   10813: 
                   10814: sub writecoursepref {
                   10815:     my ($courseid,%prefs)=@_;
                   10816:     $courseid=~s/^\///;
                   10817:     $courseid=~s/\_/\//g;
                   10818:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10819:     my $chome=homeserver($cnum,$cdomain);
                   10820:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10821: 	return 'error: no such course';
                   10822:     }
                   10823:     my $cstring='';
1.800     albertel 10824:     foreach my $pref (keys(%prefs)) {
                   10825: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10826:     }
1.84      www      10827:     $cstring=~s/\&$//;
                   10828:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10829: }
                   10830: 
                   10831: # ---------------------------------------------------------- Make/modify course
                   10832: 
                   10833: sub createcourse {
1.741     raeburn  10834:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423    raeburn  10835:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10836:     $url=&declutter($url);
                   10837:     my $cid='';
1.1028    raeburn  10838:     if ($context eq 'requestcourses') {
                   10839:         my $can_create = 0;
                   10840:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10841:         if ($udom eq $ownerdom) {
1.1423    raeburn  10842:             my $reload;
                   10843:             if (($callercontext eq 'auto') &&
                   10844:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10845:                 $reload = 'reload';
                   10846:             }
                   10847:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10848:                                   $context)) {
                   10849:                 $can_create = 1;
                   10850:             }
                   10851:         } else {
                   10852:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10853:                                            $category);
                   10854:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10855:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10856:                 if (@curr > 0) {
                   10857:                     my @options = qw(approval validate autolimit);
                   10858:                     my $optregex = join('|',@options);
                   10859:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10860:                         $can_create = 1;
                   10861:                     }
                   10862:                 }
                   10863:             }
                   10864:         }
                   10865:         if ($can_create) {
                   10866:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10867:                 unless (&allowed('ccc',$udom)) {
                   10868:                     return 'refused'; 
                   10869:                 }
1.1017    raeburn  10870:             }
                   10871:         } else {
                   10872:             return 'refused';
                   10873:         }
1.1028    raeburn  10874:     } elsif (!&allowed('ccc',$udom)) {
                   10875:         return 'refused';
1.84      www      10876:     }
1.1011    raeburn  10877: # --------------------------------------------------------------- Get Unique ID
                   10878:     my $uname;
                   10879:     if ($cnum =~ /^$match_courseid$/) {
                   10880:         my $chome=&homeserver($cnum,$udom,'true');
                   10881:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10882:             $uname = $cnum;
                   10883:         } else {
1.1038    raeburn  10884:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10885:         }
                   10886:     } else {
1.1038    raeburn  10887:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10888:     }
                   10889:     return $uname if ($uname =~ /^error/);
                   10890: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10891:     if (!defined($course_server)) {
                   10892:         if (defined(&domain($udom,'primary'))) {
                   10893:             $course_server = &domain($udom,'primary');
                   10894:         } else {
                   10895:             $course_server = $env{'user.home'}; 
                   10896:         }
                   10897:     }
                   10898:     my %host_servers =
                   10899:         &Apache::lonnet::get_servers($udom,'library');
                   10900:     unless ($host_servers{$course_server}) {
                   10901:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10902:     }
1.84      www      10903: # ------------------------------------------------------------- Make the course
                   10904:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10905:                       $course_server);
1.84      www      10906:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10907:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10908:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10909: 	return 'error: no such course';
                   10910:     }
1.271     www      10911: # ----------------------------------------------------------------- Course made
1.516     raeburn  10912: # log existence
1.1029    raeburn  10913:     my $now = time;
1.918     raeburn  10914:     my $newcourse = {
                   10915:                     $udom.'_'.$uname => {
1.921     raeburn  10916:                                      description => $description,
                   10917:                                      inst_code   => $inst_code,
                   10918:                                      owner       => $course_owner,
                   10919:                                      type        => $crstype,
1.1029    raeburn  10920:                                      creator     => $env{'user.name'}.':'.
                   10921:                                                     $env{'user.domain'},
                   10922:                                      created     => $now,
                   10923:                                      context     => $context,
1.918     raeburn  10924:                                                 },
                   10925:                     };
1.921     raeburn  10926:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10927: # set toplevel url
1.271     www      10928:     my $topurl=$url;
                   10929:     unless ($nonstandard) {
                   10930: # ------------------------------------------ For standard courses, make top url
                   10931:         my $mapurl=&clutter($url);
1.278     www      10932:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10933:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10934: <map>
                   10935: <resource id="1" type="start"></resource>
                   10936: <resource id="2" src="$mapurl"></resource>
                   10937: <resource id="3" type="finish"></resource>
                   10938: <link index="1" from="1" to="2"></link>
                   10939: <link index="2" from="2" to="3"></link>
                   10940: </map>
                   10941: ENDINITMAP
                   10942:         $topurl=&declutter(
1.638     albertel 10943:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10944:                           );
                   10945:     }
                   10946: # ----------------------------------------------------------- Write preferences
1.84      www      10947:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10948:                      ('description'              => $description,
                   10949:                       'url'                      => $topurl,
                   10950:                       'internal.creator'         => $env{'user.name'}.':'.
                   10951:                                                     $env{'user.domain'},
                   10952:                       'internal.created'         => $now,
                   10953:                       'internal.creationcontext' => $context)
                   10954:                     );
1.84      www      10955:     return '/'.$udom.'/'.$uname;
                   10956: }
                   10957: 
1.1011    raeburn  10958: # ------------------------------------------------------------------- Create ID
                   10959: sub generate_coursenum {
1.1038    raeburn  10960:     my ($udom,$crstype) = @_;
1.1011    raeburn  10961:     my $domdesc = &domain($udom);
                   10962:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10963:     my $first;
                   10964:     if ($crstype eq 'Community') {
                   10965:         $first = '0';
                   10966:     } else {
                   10967:         $first = int(1+rand(9)); 
                   10968:     } 
                   10969:     my $uname=$first.
1.1011    raeburn  10970:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10971:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10972:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10973: # ----------------------------------------------- Make sure that does not exist
                   10974:     my $uhome=&homeserver($uname,$udom,'true');
                   10975:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10976:         if ($crstype eq 'Community') {
                   10977:             $first = '0';
                   10978:         } else {
                   10979:             $first = int(1+rand(9));
                   10980:         }
                   10981:         $uname=$first.
1.1011    raeburn  10982:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10983:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10984:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10985:         $uhome=&homeserver($uname,$udom,'true');
                   10986:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10987:             return 'error: unable to generate unique course-ID';
                   10988:         }
                   10989:     }
                   10990:     return $uname;
                   10991: }
                   10992: 
1.813     albertel 10993: sub is_course {
1.1167    droeschl 10994:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10995:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10996: 
1.1381    raeburn  10997:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10998:     my $uhome=&homeserver($cnum,$cdom);
                   10999:     my $iscourse;
                   11000:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  11001:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  11002:     } else {
                   11003:         my $hashid = $cdom.':'.$cnum;
                   11004:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11005:         unless (defined($cached)) {
                   11006:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11007:                                         $cnum,undef,undef,'.');
                   11008:             $iscourse = 0;
                   11009:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11010:                 $iscourse = 1;
                   11011:             }
                   11012:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11013:         }
                   11014:     }
                   11015:     return unless ($iscourse);
1.1167    droeschl 11016:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11017: }
                   11018: 
1.1015    raeburn  11019: sub store_userdata {
                   11020:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  11021:     my $result;
1.1016    raeburn  11022:     if ($datakey ne '') {
1.1013    raeburn  11023:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11024:             if ($udom eq '' || $uname eq '') {
                   11025:                 $udom = $env{'user.domain'};
                   11026:                 $uname = $env{'user.name'};
                   11027:             }
                   11028:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11029:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11030:                 $result = 'error: no_host';
                   11031:             } else {
1.1434    raeburn  11032:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  11033:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11034: 
                   11035:                 my $namevalue='';
                   11036:                 foreach my $key (keys(%{$storehash})) {
                   11037:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11038:                 }
                   11039:                 $namevalue=~s/\&$//;
1.1224    raeburn  11040:                 unless ($namespace eq 'courserequests') {
                   11041:                     $datakey = &escape($datakey);
                   11042:                 }
1.1105    raeburn  11043:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11044:                                   $namevalue,$uhome);
1.1013    raeburn  11045:             }
                   11046:         } else {
                   11047:             $result = 'error: data to store was not a hash reference'; 
                   11048:         }
                   11049:     } else {
                   11050:         $result= 'error: invalid requestkey'; 
                   11051:     }
                   11052:     return $result;
                   11053: }
                   11054: 
1.21      www      11055: # ---------------------------------------------------------- Assign Custom Role
                   11056: 
                   11057: sub assigncustomrole {
1.957     raeburn  11058:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11059:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  11060:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      11061: }
                   11062: 
                   11063: # ----------------------------------------------------------------- Revoke Role
                   11064: 
                   11065: sub revokerole {
1.957     raeburn  11066:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11067:     my $now=time;
1.965     raeburn  11068:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11069: }
                   11070: 
                   11071: # ---------------------------------------------------------- Revoke Custom Role
                   11072: 
                   11073: sub revokecustomrole {
1.957     raeburn  11074:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11075:     my $now=time;
1.357     www      11076:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11077:            $deleteflag,$selfenroll,$context);
1.17      www      11078: }
                   11079: 
1.533     banghart 11080: # ------------------------------------------------------------ Disk usage
1.535     albertel 11081: sub diskusage {
1.955     raeburn  11082:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11083:     $directorypath =~ s/\/$//;
                   11084:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11085:                        .&escape($getpropath).':'.&escape($uname).':'
                   11086:                        .&escape($udom),homeserver($uname,$udom));
                   11087:     if ($listing eq 'unknown_cmd') {
                   11088:         if ($getpropath) {
                   11089:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11090:         }
                   11091:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11092:     }
1.514     albertel 11093:     return $listing;
1.512     banghart 11094: }
                   11095: 
1.566     banghart 11096: sub is_locked {
1.1096    raeburn  11097:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11098:     my @check;
                   11099:     my $is_locked;
1.1093    raeburn  11100:     push (@check,$file_name);
1.613     albertel 11101:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11102: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11103:     my ($tmp)=keys(%locked);
                   11104:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11105:     
1.566     banghart 11106:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11107:         $is_locked = 'false';
                   11108:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11109:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11110:                $is_locked = 'true';
1.1096    raeburn  11111:                if (ref($which) eq 'ARRAY') {
                   11112:                    push(@{$which},$entry);
                   11113:                } else {
                   11114:                    last;
                   11115:                }
1.745     raeburn  11116:            }
                   11117:        }
1.566     banghart 11118:     } else {
                   11119:         $is_locked = 'false';
                   11120:     }
1.1093    raeburn  11121:     return $is_locked;
1.566     banghart 11122: }
                   11123: 
1.759     albertel 11124: sub declutter_portfile {
                   11125:     my ($file) = @_;
1.833     albertel 11126:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11127:     return $file;
                   11128: }
                   11129: 
1.559     banghart 11130: # ------------------------------------------------------------- Mark as Read Only
                   11131: 
                   11132: sub mark_as_readonly {
                   11133:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11134:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11135:     my ($tmp)=keys(%current_permissions);
                   11136:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11137:     foreach my $file (@{$files}) {
1.759     albertel 11138: 	$file = &declutter_portfile($file);
1.561     banghart 11139:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11140:     }
1.613     albertel 11141:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11142:     return;
                   11143: }
                   11144: 
1.572     banghart 11145: # ------------------------------------------------------------Save Selected Files
                   11146: 
                   11147: sub save_selected_files {
                   11148:     my ($user, $path, @files) = @_;
                   11149:     my $filename = $user."savedfiles";
1.573     banghart 11150:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  11151:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11152:     foreach my $file (@files) {
1.620     albertel 11153:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11154:     }
                   11155:     foreach my $file (@other_files) {
1.574     banghart 11156:         print (OUT $file."\n");
1.572     banghart 11157:     }
1.574     banghart 11158:     close (OUT);
1.572     banghart 11159:     return 'ok';
                   11160: }
                   11161: 
1.574     banghart 11162: sub clear_selected_files {
                   11163:     my ($user) = @_;
                   11164:     my $filename = $user."savedfiles";
1.1359    raeburn  11165:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11166:     print (OUT undef);
                   11167:     close (OUT);
                   11168:     return ("ok");    
                   11169: }
                   11170: 
1.572     banghart 11171: sub files_in_path {
                   11172:     my ($user, $path) = @_;
                   11173:     my $filename = $user."savedfiles";
                   11174:     my %return_files;
1.1359    raeburn  11175:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11176:     while (my $line_in = <IN>) {
1.574     banghart 11177:         chomp ($line_in);
                   11178:         my @paths_and_file = split (m!/!, $line_in);
                   11179:         my $file_part = pop (@paths_and_file);
                   11180:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11181:         $path_part.='/';
                   11182:         my $path_and_file = $path_part.$file_part;
                   11183:         if ($path_part eq $path) {
                   11184:             $return_files{$file_part}= 'selected';
                   11185:         }
                   11186:     }
1.574     banghart 11187:     close (IN);
                   11188:     return (\%return_files);
1.572     banghart 11189: }
                   11190: 
                   11191: # called in portfolio select mode, to show files selected NOT in current directory
                   11192: sub files_not_in_path {
                   11193:     my ($user, $path) = @_;
                   11194:     my $filename = $user."savedfiles";
                   11195:     my @return_files;
                   11196:     my $path_part;
1.1359    raeburn  11197:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11198:     while (my $line = <IN>) {
1.572     banghart 11199:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11200:         my @paths_and_file = split(m|/|, $line);
                   11201:         my $file_part = pop(@paths_and_file);
                   11202:         chomp($file_part);
                   11203:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11204:         $path_part .= '/';
                   11205:         my $path_and_file = $path_part.$file_part;
                   11206:         if ($path_part ne $path) {
1.800     albertel 11207:             push(@return_files, ($path_and_file));
1.572     banghart 11208:         }
                   11209:     }
1.800     albertel 11210:     close(OUT);
1.574     banghart 11211:     return (@return_files);
1.572     banghart 11212: }
                   11213: 
1.1273    raeburn  11214: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   11215:  
                   11216: sub portfiles_versioning {
                   11217:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   11218:     my $portfolio_root = '/userfiles/portfolio';
                   11219:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   11220:     foreach my $file (@{$portfiles}) {
                   11221:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   11222:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   11223:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   11224:         my $getpropath = 1;
                   11225:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   11226:                                              $stu_name,$getpropath);
                   11227:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   11228:         my $new_answer = 
                   11229:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   11230:         if ($new_answer ne 'problem getting file') {
                   11231:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   11232:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   11233:                               [$symb,$env{'request.course.id'},'graded']);
                   11234:         }
                   11235:     }
                   11236: }
                   11237: 
                   11238: sub get_next_version {
                   11239:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   11240:     my $version;
                   11241:     if (ref($dir_list) eq 'ARRAY') {
                   11242:         foreach my $row (@{$dir_list}) {
                   11243:             my ($file) = split(/\&/,$row,2);
                   11244:             my ($file_name,$file_version,$file_ext) =
                   11245:                 &file_name_version_ext($file);
                   11246:             if (($file_name eq $answer_name) &&
                   11247:                 ($file_ext eq $answer_ext)) {
                   11248:                      # gets here if filename and extension match,
                   11249:                      # regardless of version
                   11250:                 if ($file_version ne '') {
                   11251:                     # a versioned file is found  so save it for later
                   11252:                     if ($file_version > $version) {
                   11253:                         $version = $file_version;
                   11254:                     }
                   11255:                 }
                   11256:             }
                   11257:         }
                   11258:     }
                   11259:     $version ++;
                   11260:     return($version);
                   11261: }
                   11262: 
                   11263: sub version_selected_portfile {
                   11264:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   11265:     my ($answer_name,$answer_ver,$answer_ext) =
                   11266:         &file_name_version_ext($file_name);
                   11267:     my $new_answer;
                   11268:     $env{'form.copy'} =
                   11269:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   11270:     if($env{'form.copy'} eq '-1') {
                   11271:         $new_answer = 'problem getting file';
                   11272:     } else {
                   11273:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   11274:         my $copy_result = 
                   11275:             &finishuserfileupload($stu_name,$domain,'copy',
                   11276:                                   '/portfolio'.$directory.$new_answer);
                   11277:     }
                   11278:     undef($env{'form.copy'});
                   11279:     return ($new_answer);
                   11280: }
                   11281: 
                   11282: sub file_name_version_ext {
                   11283:     my ($file)=@_;
                   11284:     my @file_parts = split(/\./, $file);
                   11285:     my ($name,$version,$ext);
                   11286:     if (@file_parts > 1) {
                   11287:         $ext=pop(@file_parts);
                   11288:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   11289:             $version=pop(@file_parts);
                   11290:         }
                   11291:         $name=join('.',@file_parts);
                   11292:     } else {
                   11293:         $name=join('.',@file_parts);
                   11294:     }
                   11295:     return($name,$version,$ext);
                   11296: }
                   11297: 
1.745     raeburn  11298: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11299: 
1.745     raeburn  11300: sub get_portfile_permissions {
                   11301:     my ($domain,$user) = @_;
1.613     albertel 11302:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11303:     my ($tmp)=keys(%current_permissions);
                   11304:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11305:     return \%current_permissions;
                   11306: }
                   11307: 
                   11308: #---------------------------------------------Get portfolio file access controls
                   11309: 
1.749     raeburn  11310: sub get_access_controls {
1.745     raeburn  11311:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11312:     my %access;
                   11313:     my $real_file = $file;
                   11314:     $file =~ s/\.meta$//;
1.745     raeburn  11315:     if (defined($file)) {
1.749     raeburn  11316:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11317:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11318:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11319:             }
                   11320:         }
1.745     raeburn  11321:     } else {
1.749     raeburn  11322:         foreach my $key (keys(%{$current_permissions})) {
                   11323:             if ($key =~ /\0accesscontrol$/) {
                   11324:                 if (defined($group)) {
                   11325:                     if ($key !~ m-^\Q$group\E/-) {
                   11326:                         next;
                   11327:                     }
                   11328:                 }
                   11329:                 my ($fullpath) = split(/\0/,$key);
                   11330:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11331:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11332:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11333:                     }
                   11334:                 }
                   11335:             }
                   11336:         }
                   11337:     }
                   11338:     return %access;
                   11339: }
                   11340: 
                   11341: sub modify_access_controls {
                   11342:     my ($file_name,$changes,$domain,$user)=@_;
                   11343:     my ($outcome,$deloutcome);
                   11344:     my %store_permissions;
                   11345:     my %new_values;
                   11346:     my %new_control;
                   11347:     my %translation;
                   11348:     my @deletions = ();
                   11349:     my $now = time;
                   11350:     if (exists($$changes{'activate'})) {
                   11351:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11352:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11353:             my $numnew = scalar(@newitems);
                   11354:             for (my $i=0; $i<$numnew; $i++) {
                   11355:                 my $newkey = $newitems[$i];
                   11356:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11357:                 if ($newkey =~ /^\d+:/) { 
                   11358:                     $newkey =~ s/^(\d+)/$newid/;
                   11359:                     $translation{$1} = $newid;
                   11360:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11361:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11362:                     $translation{$1} = $newid;
                   11363:                 }
1.749     raeburn  11364:                 $new_values{$file_name."\0".$newkey} = 
                   11365:                                           $$changes{'activate'}{$newitems[$i]};
                   11366:                 $new_control{$newkey} = $now;
                   11367:             }
                   11368:         }
                   11369:     }
                   11370:     my %todelete;
                   11371:     my %changed_items;
                   11372:     foreach my $action ('delete','update') {
                   11373:         if (exists($$changes{$action})) {
                   11374:             if (ref($$changes{$action}) eq 'HASH') {
                   11375:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11376:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11377:                     if ($action eq 'delete') { 
                   11378:                         $todelete{$itemnum} = 1;
                   11379:                     } else {
                   11380:                         $changed_items{$itemnum} = $key;
                   11381:                     }
                   11382:                 }
1.745     raeburn  11383:             }
                   11384:         }
1.749     raeburn  11385:     }
                   11386:     # get lock on access controls for file.
                   11387:     my $lockhash = {
                   11388:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11389:                                                        ':'.$env{'user.domain'},
                   11390:                    }; 
                   11391:     my $tries = 0;
                   11392:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11393:    
1.1288    damieng  11394:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11395:         $tries ++;
1.1289    damieng  11396:         sleep(0.1);
1.749     raeburn  11397:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11398:     }
                   11399:     if ($gotlock eq 'ok') {
                   11400:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11401:         my ($tmp)=keys(%curr_permissions);
                   11402:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11403:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11404:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11405:             if (ref($curr_controls) eq 'HASH') {
                   11406:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11407:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11408:                     if (defined($todelete{$itemnum})) {
                   11409:                         push(@deletions,$file_name."\0".$control_item);
                   11410:                     } else {
                   11411:                         if (defined($changed_items{$itemnum})) {
                   11412:                             $new_control{$changed_items{$itemnum}} = $now;
                   11413:                             push(@deletions,$file_name."\0".$control_item);
                   11414:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11415:                         } else {
                   11416:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11417:                         }
                   11418:                     }
1.745     raeburn  11419:                 }
                   11420:             }
                   11421:         }
1.970     raeburn  11422:         my ($group);
                   11423:         if (&is_course($domain,$user)) {
                   11424:             ($group,my $file) = split(/\//,$file_name,2);
                   11425:         }
1.749     raeburn  11426:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11427:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11428:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11429:         #  remove lock
                   11430:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11431:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11432:         my $sqlresult =
1.970     raeburn  11433:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11434:                                     $group);
1.749     raeburn  11435:     } else {
                   11436:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11437:     }
1.749     raeburn  11438:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11439: }
                   11440: 
1.827     raeburn  11441: sub make_public_indefinitely {
1.1271    raeburn  11442:     my (@requrl) = @_;
                   11443:     return &automated_portfile_access('public',\@requrl);
                   11444: }
                   11445: 
                   11446: sub automated_portfile_access {
                   11447:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  11448:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   11449:         return 'invalid';
                   11450:     }
1.1271    raeburn  11451:     my %urls;
                   11452:     if (ref($addsref) eq 'ARRAY') {
                   11453:         foreach my $requrl (@{$addsref}) {
                   11454:             if (&is_portfolio_url($requrl)) {
                   11455:                 unless (exists($urls{$requrl})) {
                   11456:                     $urls{$requrl} = 'add';
                   11457:                 }
                   11458:             }
                   11459:         }
                   11460:     }
                   11461:     if (ref($delsref) eq 'ARRAY') {
                   11462:         foreach my $requrl (@{$delsref}) { 
                   11463:             if (&is_portfolio_url($requrl)) {
                   11464:                 unless (exists($urls{$requrl})) {
                   11465:                     $urls{$requrl} = 'delete'; 
                   11466:                 }
                   11467:             }
                   11468:         }
                   11469:     }
                   11470:     unless (keys(%urls)) {
                   11471:         return 'invalid';
                   11472:     }
                   11473:     my $ip;
                   11474:     if ($accesstype eq 'ip') {
                   11475:         if (ref($info) eq 'HASH') {
                   11476:             if ($info->{'ip'} ne '') {
                   11477:                 $ip = $info->{'ip'};
                   11478:             }
                   11479:         }
                   11480:         if ($ip eq '') {
                   11481:             return 'invalid';
                   11482:         }
                   11483:     }
                   11484:     my $errors;
1.827     raeburn  11485:     my $now = time;
1.1271    raeburn  11486:     my %current_perms;
                   11487:     foreach my $requrl (sort(keys(%urls))) {
                   11488:         my $action;
                   11489:         if ($urls{$requrl} eq 'add') {
                   11490:             $action = 'activate';
                   11491:         } else {
                   11492:             $action = 'none';
                   11493:         }
                   11494:         my $aclnum = 0;
1.827     raeburn  11495:         my (undef,$udom,$unum,$file_name,$group) =
                   11496:             &parse_portfolio_url($requrl);
1.1271    raeburn  11497:         unless (exists($current_perms{$unum.':'.$udom})) {
                   11498:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   11499:         }
                   11500:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  11501:                                                    $group,$file_name);
                   11502:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11503:             my ($num,$scope,$end,$start) = 
                   11504:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  11505:             if ($scope eq $accesstype) {
                   11506:                 if (($start <= $now) && ($end == 0)) {
                   11507:                     if ($accesstype eq 'ip') {
                   11508:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   11509:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   11510:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   11511:                                     if ($urls{$requrl} eq 'add') {
                   11512:                                         $action = 'none';
                   11513:                                         last;
                   11514:                                     } else {
                   11515:                                         $action = 'delete';
                   11516:                                         $aclnum = $num;
                   11517:                                         last;
                   11518:                                     }
                   11519:                                 }
                   11520:                             }
                   11521:                         }
                   11522:                     } elsif ($accesstype eq 'public') {
                   11523:                         if ($urls{$requrl} eq 'add') {
                   11524:                             $action = 'none';
                   11525:                             last;
                   11526:                         } else {
                   11527:                             $action = 'delete';
                   11528:                             $aclnum = $num;
                   11529:                             last;
                   11530:                         }
                   11531:                     }
                   11532:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  11533:                     $action = 'update';
                   11534:                     $aclnum = $num;
1.1271    raeburn  11535:                     last;
1.827     raeburn  11536:                 }
                   11537:             }
                   11538:         }
                   11539:         if ($action eq 'none') {
1.1271    raeburn  11540:             next;
1.827     raeburn  11541:         } else {
                   11542:             my %changes;
                   11543:             my $newend = 0;
                   11544:             my $newstart = $now;
1.1271    raeburn  11545:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  11546:             $changes{$action}{$newkey} = {
1.1271    raeburn  11547:                 type => $accesstype,
1.827     raeburn  11548:                 time => {
                   11549:                     start => $newstart,
                   11550:                     end   => $newend,
                   11551:                 },
                   11552:             };
1.1271    raeburn  11553:             if ($accesstype eq 'ip') {
                   11554:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   11555:             }
1.827     raeburn  11556:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11557:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  11558:             unless ($outcome eq 'ok') {
                   11559:                 $errors .= $outcome.' ';
                   11560:             }
1.827     raeburn  11561:         }
1.1271    raeburn  11562:     }
                   11563:     if ($errors) {
                   11564:         $errors =~ s/\s$//;
                   11565:         return $errors;
1.827     raeburn  11566:     } else {
1.1271    raeburn  11567:         return 'ok';
1.827     raeburn  11568:     }
                   11569: }
                   11570: 
1.745     raeburn  11571: #------------------------------------------------------Get Marked as Read Only
                   11572: 
                   11573: sub get_marked_as_readonly {
                   11574:     my ($domain,$user,$what,$group) = @_;
                   11575:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11576:     my @readonly_files;
1.629     banghart 11577:     my $cmp1=$what;
                   11578:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11579:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11580:         if (defined($group)) {
                   11581:             if ($file_name !~ m-^\Q$group\E/-) {
                   11582:                 next;
                   11583:             }
                   11584:         }
1.561     banghart 11585:         if (ref($value) eq "ARRAY"){
                   11586:             foreach my $stored_what (@{$value}) {
1.629     banghart 11587:                 my $cmp2=$stored_what;
1.759     albertel 11588:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11589:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11590:                 }
1.629     banghart 11591:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11592:                     push(@readonly_files, $file_name);
1.745     raeburn  11593:                     last;
1.563     banghart 11594:                 } elsif (!defined($what)) {
                   11595:                     push(@readonly_files, $file_name);
1.745     raeburn  11596:                     last;
1.561     banghart 11597:                 }
                   11598:             }
1.745     raeburn  11599:         }
1.561     banghart 11600:     }
                   11601:     return @readonly_files;
                   11602: }
1.577     banghart 11603: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11604: 
1.577     banghart 11605: sub get_marked_as_readonly_hash {
1.745     raeburn  11606:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11607:     my %readonly_files;
1.745     raeburn  11608:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11609:         if (defined($group)) {
                   11610:             if ($file_name !~ m-^\Q$group\E/-) {
                   11611:                 next;
                   11612:             }
                   11613:         }
1.577     banghart 11614:         if (ref($value) eq "ARRAY"){
                   11615:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11616:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11617:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11618:                         if ($lock_descriptor eq 'graded') {
                   11619:                             $readonly_files{$file_name} = 'graded';
                   11620:                         } elsif ($lock_descriptor eq 'handback') {
                   11621:                             $readonly_files{$file_name} = 'handback';
                   11622:                         } else {
                   11623:                             if (!exists($readonly_files{$file_name})) {
                   11624:                                 $readonly_files{$file_name} = 'locked';
                   11625:                             }
                   11626:                         }
1.745     raeburn  11627:                     }
1.750     banghart 11628:                 } 
1.577     banghart 11629:             }
                   11630:         } 
                   11631:     }
                   11632:     return %readonly_files;
                   11633: }
1.559     banghart 11634: # ------------------------------------------------------------ Unmark as Read Only
                   11635: 
                   11636: sub unmark_as_readonly {
1.629     banghart 11637:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11638:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11639:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11640:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11641:     my $symb_crs = $what;
                   11642:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11643:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11644:     my ($tmp)=keys(%current_permissions);
                   11645:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11646:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11647:     foreach my $file (@readonly_files) {
1.759     albertel 11648: 	my $clean_file = &declutter_portfile($file);
                   11649: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11650: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11651:         my @new_locks;
                   11652:         my @del_keys;
                   11653:         if (ref($current_locks) eq "ARRAY"){
                   11654:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11655:                 my $compare=$locker;
1.749     raeburn  11656:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11657:                     $compare=join('',@{$locker});
1.746     raeburn  11658:                     if ($compare ne $symb_crs) {
                   11659:                         push(@new_locks, $locker);
                   11660:                     }
1.563     banghart 11661:                 }
                   11662:             }
1.650     albertel 11663:             if (scalar(@new_locks) > 0) {
1.563     banghart 11664:                 $current_permissions{$file} = \@new_locks;
                   11665:             } else {
                   11666:                 push(@del_keys, $file);
1.613     albertel 11667:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11668:                 delete($current_permissions{$file});
1.563     banghart 11669:             }
                   11670:         }
1.561     banghart 11671:     }
1.613     albertel 11672:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11673:     return;
                   11674: }
1.512     banghart 11675: 
1.17      www      11676: # ------------------------------------------------------------ Directory lister
                   11677: 
                   11678: sub dirlist {
1.955     raeburn  11679:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11680:     $uri=~s/^\///;
                   11681:     $uri=~s/\/$//;
1.253     stredwic 11682:     my ($udom, $uname);
1.955     raeburn  11683:     if ($getuserdir) {
1.253     stredwic 11684:         $udom = $userdomain;
                   11685:         $uname = $username;
1.955     raeburn  11686:     } else {
                   11687:         (undef,$udom,$uname)=split(/\//,$uri);
                   11688:         if(defined($userdomain)) {
                   11689:             $udom = $userdomain;
                   11690:         }
                   11691:         if(defined($username)) {
                   11692:             $uname = $username;
                   11693:         }
1.253     stredwic 11694:     }
1.955     raeburn  11695:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11696: 
1.955     raeburn  11697:     $dirRoot = $perlvar{'lonDocRoot'};
                   11698:     if (defined($getpropath)) {
                   11699:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11700:         $dirRoot =~ s/\/$//;
1.955     raeburn  11701:     } elsif (defined($getuserdir)) {
                   11702:         my $subdir=$uname.'__';
                   11703:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11704:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11705:                    ."/$udom/$subdir/$uname";
                   11706:     } elsif (defined($alternateRoot)) {
                   11707:         $dirRoot = $alternateRoot;
1.751     banghart 11708:     }
1.253     stredwic 11709: 
                   11710:     if($udom) {
                   11711:         if($uname) {
1.1135    raeburn  11712:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11713:             if ($uhome eq 'no_host') {
                   11714:                 return ([],'no_host');
                   11715:             }
1.955     raeburn  11716:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11717:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11718:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11719:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11720:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11721:             } else {
                   11722:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11723:             }
1.605     matthew  11724:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11725:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11726:                 @listing_results = split(/:/,$listing);
                   11727:             } else {
                   11728:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11729:             }
1.1135    raeburn  11730:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11731:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11732:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11733:                 return ([],$listing);
                   11734:             } else {
                   11735:                 return (\@listing_results);
1.1135    raeburn  11736:             }
1.955     raeburn  11737:         } elsif(!$alternateRoot) {
1.1136    raeburn  11738:             my (%allusers,%listerror);
1.841     albertel 11739: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11740:  	    foreach my $tryserver (keys(%servers)) {
                   11741:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11742:                                   &escape($udom),$tryserver);
                   11743:                 if ($listing eq 'unknown_cmd') {
                   11744: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11745: 				      $udom, $tryserver);
                   11746:                 } else {
                   11747:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11748:                 }
1.841     albertel 11749: 		if ($listing eq 'unknown_cmd') {
                   11750: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11751: 				      $udom, $tryserver);
                   11752: 		    @listing_results = split(/:/,$listing);
                   11753: 		} else {
                   11754: 		    @listing_results =
                   11755: 			map { &unescape($_); } split(/:/,$listing);
                   11756: 		}
1.1136    raeburn  11757:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11758:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11759:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11760:                     $listerror{$tryserver} = $listing;
                   11761:                 } else {
1.841     albertel 11762: 		    foreach my $line (@listing_results) {
                   11763: 			my ($entry) = split(/&/,$line,2);
                   11764: 			$allusers{$entry} = 1;
                   11765: 		    }
                   11766: 		}
1.253     stredwic 11767:             }
1.1136    raeburn  11768:             my @alluserslist=();
1.800     albertel 11769:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11770:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11771:             }
1.1318    droeschl 11772: 
                   11773:             if (!%listerror) {
                   11774:                 # no errors
                   11775:                 return (\@alluserslist);
                   11776:             } elsif (scalar(keys(%servers)) == 1) {
                   11777:                 # one library server, one error 
                   11778:                 my ($key) = keys(%listerror);
                   11779:                 return (\@alluserslist, $listerror{$key});
                   11780:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11781:                 # con_lost indicates that we might miss data from at least one
                   11782:                 # library server
                   11783:                 return (\@alluserslist, 'con_lost');
                   11784:             } else {
                   11785:                 # multiple library servers and no con_lost -> data should be
                   11786:                 # complete. 
                   11787:                 return (\@alluserslist);
                   11788:             }
                   11789: 
1.253     stredwic 11790:         } else {
1.1136    raeburn  11791:             return ([],'missing username');
1.253     stredwic 11792:         }
1.955     raeburn  11793:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11794:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11795:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11796:         return (\@all_domains);
1.955     raeburn  11797:     } else {
1.1136    raeburn  11798:         return ([],'missing domain');
1.275     stredwic 11799:     }
                   11800: }
                   11801: 
                   11802: # --------------------------------------------- GetFileTimestamp
                   11803: # This function utilizes dirlist and returns the date stamp for
                   11804: # when it was last modified.  It will also return an error of -1
                   11805: # if an error occurs
                   11806: 
                   11807: sub GetFileTimestamp {
1.955     raeburn  11808:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11809:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11810:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11811:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11812:                                     undef,$getuserdir);
                   11813:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11814:         return -1;
                   11815:     }
                   11816:     if (ref($fileref) eq 'ARRAY') {
                   11817:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11818:         # @stats contains first the filename, then the stat output
                   11819:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11820:     } else {
                   11821:         return -1;
1.253     stredwic 11822:     }
1.26      www      11823: }
                   11824: 
1.712     albertel 11825: sub stat_file {
                   11826:     my ($uri) = @_;
1.787     albertel 11827:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11828: 
1.955     raeburn  11829:     my ($udom,$uname,$file);
1.712     albertel 11830:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11831: 	($udom,$uname,$file) =
1.811     albertel 11832: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11833: 	$file = 'userfiles/'.$file;
                   11834:     }
                   11835:     if ($uri =~ m-^/res/-) {
                   11836: 	($udom,$uname) = 
1.807     albertel 11837: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11838: 	$file = $uri;
                   11839:     }
                   11840: 
                   11841:     if (!$udom || !$uname || !$file) {
                   11842: 	# unable to handle the uri
                   11843: 	return ();
                   11844:     }
1.956     raeburn  11845:     my $getpropath;
                   11846:     if ($file =~ /^userfiles\//) {
                   11847:         $getpropath = 1;
                   11848:     }
1.1136    raeburn  11849:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11850:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11851:         return ();
                   11852:     } else {
                   11853:         if (ref($listref) eq 'ARRAY') {
                   11854:             my @stats = split('&',$listref->[0]);
                   11855: 	    shift(@stats); #filename is first
                   11856: 	    return @stats;
                   11857:         }
1.712     albertel 11858:     }
                   11859:     return ();
                   11860: }
                   11861: 
1.1313    raeburn  11862: # --------------------------------------------------------- recursedirs
                   11863: # Recursive function to traverse either a specific user's Authoring Space
                   11864: # or corresponding Published Resource Space, and populate the hash ref:
                   11865: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11866: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11867: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11868: # files in Authoring Space.
                   11869: #
                   11870: # Inputs:
                   11871: #
                   11872: # $is_home - true if current server is home server for user's space
                   11873: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11874: # $docroot - Document root (i.e., /home/httpd/html
                   11875: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11876: # $relpath - Current path (relative to top level).
                   11877: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11878: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11879: #
                   11880: # Returns: nothing
                   11881: #
                   11882: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11883: #
                   11884: # Currently used by interface/londocs.pm to create linked select boxes for
                   11885: # directory and filename to import a Course "Author" resource into a course, and
                   11886: # also to create linked select boxes for Authoring Space and Directory to choose
                   11887: # save location for creation of a new "standard" problem from the Course Editor.
                   11888: #
                   11889: 
                   11890: sub recursedirs {
                   11891:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11892:     return unless (ref($dirhashref) eq 'HASH');
                   11893:     my $currpath = $docroot.$toppath;
                   11894:     if ($relpath) {
                   11895:         $currpath .= "/$relpath";
                   11896:     }
                   11897:     my $savefile;
                   11898:     if (ref($filehashref)) {
                   11899:         $savefile = 1;
                   11900:     }
                   11901:     if ($is_home) {
                   11902:         if (opendir(my $dirh,$currpath)) {
                   11903:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11904:                 next if ($item eq '');
                   11905:                 if (-d "$currpath/$item") {
                   11906:                     my $newpath;
                   11907:                     if ($relpath) {
                   11908:                         $newpath = "$relpath/$item";
                   11909:                     } else {
                   11910:                         $newpath = $item;
                   11911:                     }
                   11912:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11913:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11914:                 } elsif ($savefile) {
                   11915:                     if ($context eq 'priv') {
                   11916:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11917:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11918:                         }
                   11919:                     } else {
                   11920:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11921:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11922:                         }
                   11923:                     }
                   11924:                 }
                   11925:             }
                   11926:             closedir($dirh);
                   11927:         }
                   11928:     } else {
                   11929:         my ($dirlistref,$listerror) =
                   11930:             &dirlist($toppath.$relpath);
                   11931:         my @dir_lines;
                   11932:         my $dirptr=16384;
                   11933:         if (ref($dirlistref) eq 'ARRAY') {
                   11934:             foreach my $dir_line (sort
                   11935:                               {
                   11936:                                   my ($afile)=split('&',$a,2);
                   11937:                                   my ($bfile)=split('&',$b,2);
                   11938:                                   return (lc($afile) cmp lc($bfile));
                   11939:                               } (@{$dirlistref})) {
                   11940:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11941:                     split(/\&/,$dir_line,16);
                   11942:                 $item =~ s/\s+$//;
                   11943:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11944:                 if ($dirptr&$testdir) {
                   11945:                     my $newpath;
                   11946:                     if ($relpath) {
                   11947:                         $newpath = "$relpath/$item";
                   11948:                     } else {
                   11949:                         $relpath = '/';
                   11950:                         $newpath = $item;
                   11951:                     }
                   11952:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11953:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11954:                 } elsif ($savefile) {
                   11955:                     if ($context eq 'priv') {
                   11956:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11957:                             $filehashref->{$relpath}{$item} = 1;
                   11958:                         }
                   11959:                     } else {
                   11960:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11961:                             $filehashref->{$relpath}{$item} = 1;
                   11962:                         }
                   11963:                     }
                   11964:                 }
                   11965:             }
                   11966:         }
                   11967:     }
                   11968:     return;
                   11969: }
                   11970: 
1.26      www      11971: # -------------------------------------------------------- Value of a Condition
                   11972: 
1.713     albertel 11973: # gets the value of a specific preevaluated condition
                   11974: #    stored in the string  $env{user.state.<cid>}
                   11975: # or looks up a condition reference in the bighash and if if hasn't
                   11976: # already been evaluated recurses into docondval to get the value of
                   11977: # the condition, then memoizing it to 
                   11978: #   $env{user.state.<cid>.<condition>}
1.40      www      11979: sub directcondval {
                   11980:     my $number=shift;
1.620     albertel 11981:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11982: 	&Apache::lonuserstate::evalstate();
                   11983:     }
1.713     albertel 11984:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11985: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11986:     } elsif ($number =~ /^_/) {
                   11987: 	my $sub_condition;
                   11988: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11989: 		&GDBM_READER(),0640)) {
                   11990: 	    $sub_condition=$bighash{'conditions'.$number};
                   11991: 	    untie(%bighash);
                   11992: 	}
                   11993: 	my $value = &docondval($sub_condition);
1.949     raeburn  11994: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11995: 	return $value;
                   11996:     }
1.620     albertel 11997:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11998:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11999:     } else {
                   12000:        return 2;
                   12001:     }
                   12002: }
                   12003: 
1.713     albertel 12004: # get the collection of conditions for this resource
1.26      www      12005: sub condval {
                   12006:     my $condidx=shift;
1.54      www      12007:     my $allpathcond='';
1.713     albertel 12008:     foreach my $cond (split(/\|/,$condidx)) {
                   12009: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   12010: 	    $allpathcond.=
                   12011: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   12012: 	}
1.191     harris41 12013:     }
1.54      www      12014:     $allpathcond=~s/\|$//;
1.713     albertel 12015:     return &docondval($allpathcond);
                   12016: }
                   12017: 
                   12018: #evaluates an expression of conditions
                   12019: sub docondval {
                   12020:     my ($allpathcond) = @_;
                   12021:     my $result=0;
                   12022:     if ($env{'request.course.id'}
                   12023: 	&& defined($allpathcond)) {
                   12024: 	my $operand='|';
                   12025: 	my @stack;
                   12026: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   12027: 	    if ($chunk eq '(') {
                   12028: 		push @stack,($operand,$result);
                   12029: 	    } elsif ($chunk eq ')') {
                   12030: 		my $before=pop @stack;
                   12031: 		if (pop @stack eq '&') {
                   12032: 		    $result=$result>$before?$before:$result;
                   12033: 		} else {
                   12034: 		    $result=$result>$before?$result:$before;
                   12035: 		}
                   12036: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   12037: 		$operand=$chunk;
                   12038: 	    } else {
                   12039: 		my $new=directcondval($chunk);
                   12040: 		if ($operand eq '&') {
                   12041: 		    $result=$result>$new?$new:$result;
                   12042: 		} else {
                   12043: 		    $result=$result>$new?$result:$new;
                   12044: 		}
                   12045: 	    }
                   12046: 	}
1.26      www      12047:     }
                   12048:     return $result;
1.421     albertel 12049: }
                   12050: 
                   12051: # ---------------------------------------------------- Devalidate courseresdata
                   12052: 
                   12053: sub devalidatecourseresdata {
                   12054:     my ($coursenum,$coursedomain)=@_;
                   12055:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12056:     &devalidate_cache_new('courseres',$hashid);
1.28      www      12057: }
                   12058: 
1.763     www      12059: 
1.200     www      12060: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     12061: #
                   12062: #  Parameters:
                   12063: #      $coursenum    - Number of the course.
                   12064: #      $coursedomain - Domain at which the course was created.
                   12065: #  Returns:
                   12066: #     A hash of the course parameters along (I think) with timestamps
                   12067: #     and version info.
1.877     foxr     12068: 
1.624     albertel 12069: sub get_courseresdata {
                   12070:     my ($coursenum,$coursedomain)=@_;
1.200     www      12071:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   12072:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12073:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 12074:     my %dumpreply;
1.417     albertel 12075:     unless (defined($cached)) {
1.624     albertel 12076: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 12077: 	$result=\%dumpreply;
1.251     albertel 12078: 	my ($tmp) = keys(%dumpreply);
                   12079: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 12080: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 12081: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   12082: 	    return $tmp;
1.416     albertel 12083: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 12084: 	    $result=undef;
1.599     albertel 12085: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 12086: 	}
                   12087:     }
1.624     albertel 12088:     return $result;
                   12089: }
                   12090: 
1.633     albertel 12091: sub devalidateuserresdata {
                   12092:     my ($uname,$udom)=@_;
                   12093:     my $hashid="$udom:$uname";
                   12094:     &devalidate_cache_new('userres',$hashid);
                   12095: }
                   12096: 
1.624     albertel 12097: sub get_userresdata {
                   12098:     my ($uname,$udom)=@_;
                   12099:     #most student don\'t have any data set, check if there is some data
                   12100:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   12101: 
                   12102:     my $hashid="$udom:$uname";
                   12103:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   12104:     if (!defined($cached)) {
                   12105: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   12106: 	$result=\%resourcedata;
                   12107: 	&do_cache_new('userres',$hashid,$result,600);
                   12108:     }
                   12109:     my ($tmp)=keys(%$result);
                   12110:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   12111: 	return $result;
                   12112:     }
                   12113:     #error 2 occurs when the .db doesn't exist
                   12114:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  12115:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   12116: 	    &logthis("<font color=\"blue\">WARNING:".
                   12117: 		     " Trying to get resource data for ".
                   12118: 		     $uname." at ".$udom.": ".
                   12119: 		     $tmp."</font>");
                   12120:         }
1.624     albertel 12121:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 12122: 	#&EXT_cache_set($udom,$uname);
                   12123: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 12124: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 12125:     }
                   12126:     return $tmp;
                   12127: }
1.879     foxr     12128: #----------------------------------------------- resdata - return resource data
                   12129: #  Purpose:
                   12130: #    Return resource data for either users or for a course.
                   12131: #  Parameters:
                   12132: #     $name      - Course/user name.
                   12133: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  12134: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  12135: #     $mapp      - decluttered URL of enclosing map  
                   12136: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   12137: #     $recurseup - Ref to array of map URLs, starting with map containing
                   12138: #                  $mapp up through hierarchy of nested maps to top level map.  
                   12139: #     $courseid  - CourseID (first part of param identifier).
                   12140: #     $modifier  - Middle part of param identifier.
                   12141: #     $what      - Last part of param identifier.
1.879     foxr     12142: #     @which     - Array of names of resources desired.
                   12143: #  Returns:
                   12144: #     The value of the first reasource in @which that is found in the
                   12145: #     resource hash.
                   12146: #  Exceptional Conditions:
                   12147: #     If the $type passed in is not valid (not the string 'course' or 
                   12148: #     'user', an undefined  reference is returned.
                   12149: #     If none of the resources are found, an undef is returned
1.624     albertel 12150: sub resdata {
1.1301    raeburn  12151:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   12152:         $modifier,$what,@which)=@_;
1.624     albertel 12153:     my $result;
                   12154:     if ($type eq 'course') {
                   12155: 	$result=&get_courseresdata($name,$domain);
                   12156:     } elsif ($type eq 'user') {
                   12157: 	$result=&get_userresdata($name,$domain);
                   12158:     }
                   12159:     if (!ref($result)) { return $result; }    
1.251     albertel 12160:     foreach my $item (@which) {
1.1301    raeburn  12161:         if ($item->[1] eq 'course') {
                   12162:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   12163:                 unless ($$recursed) {
1.1302    raeburn  12164:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  12165:                     $$recursed = 1;
                   12166:                 }
                   12167:                 foreach my $item (@${recurseup}) {
                   12168:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   12169:                     last if (defined($result->{$norecursechk}));
                   12170:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   12171:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   12172:                 }
                   12173:             }
                   12174:         }
                   12175:         if (defined($result->{$item->[0]})) {
1.927     albertel 12176: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12177: 	}
1.250     albertel 12178:     }
1.291     albertel 12179:     return undef;
1.200     www      12180: }
                   12181: 
1.1360    raeburn  12182: sub get_domain_lti {
                   12183:     my ($cdom,$context) = @_;
                   12184:     my ($name,%lti);
                   12185:     if ($context eq 'consumer') {
                   12186:         $name = 'ltitools';
                   12187:     } elsif ($context eq 'provider') {
                   12188:         $name = 'lti';
                   12189:     } else {
                   12190:         return %lti;
                   12191:     }
                   12192:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  12193:     if (defined($cached)) {
                   12194:         if (ref($result) eq 'HASH') {
1.1360    raeburn  12195:             %lti = %{$result};
1.1298    raeburn  12196:         }
                   12197:     } else {
1.1360    raeburn  12198:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12199:         if (ref($domconfig{$name}) eq 'HASH') {
                   12200:             %lti = %{$domconfig{$name}};
1.1462    raeburn  12201:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
1.1360    raeburn  12202:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   12203:                 foreach my $id (keys(%lti)) {
                   12204:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  12205:                         foreach my $item ('key','secret') {
1.1360    raeburn  12206:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  12207:                         }
                   12208:                     }
                   12209:                 }
                   12210:             }
1.1298    raeburn  12211:         }
                   12212:         my $cachetime = 24*60*60;
1.1360    raeburn  12213:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  12214:     }
1.1360    raeburn  12215:     return %lti;
1.1298    raeburn  12216: }
                   12217: 
1.1463    raeburn  12218: sub get_course_lti {
                   12219:     my ($cnum,$cdom) = @_;
                   12220:     my $hashid=$cdom.'_'.$cnum;
                   12221:     my %courselti;
                   12222:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
                   12223:     if (defined($cached)) {
                   12224:         if (ref($result) eq 'HASH') {
                   12225:             %courselti = %{$result};
                   12226:         }
                   12227:     } else {
                   12228:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
                   12229:         my $cachetime = 24*60*60;
                   12230:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
                   12231:     }
                   12232:     return %courselti;
                   12233: }
                   12234: 
1.1236    raeburn  12235: sub get_numsuppfiles {
                   12236:     my ($cnum,$cdom,$ignorecache)=@_;
                   12237:     my $hashid=$cnum.':'.$cdom;
                   12238:     my ($suppcount,$cached);
                   12239:     unless ($ignorecache) {
                   12240:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   12241:     }
                   12242:     unless (defined($cached)) {
                   12243:         my $chome=&homeserver($cnum,$cdom);
                   12244:         unless ($chome eq 'no_host') {
1.1366    raeburn  12245:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  12246:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  12247:             ($suppcount,$supptools,$errors) =
                   12248:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   12249:                                                          $supptools,$errors);
1.1236    raeburn  12250:         }
                   12251:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   12252:     }
                   12253:     return $suppcount;
                   12254: }
                   12255: 
1.379     matthew  12256: #
                   12257: # EXT resource caching routines
                   12258: #
                   12259: 
1.1302    raeburn  12260: {
                   12261: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12262: #
                   12263: # The course for which we cache
                   12264: my $cachedmapkey='';
                   12265: # The cached recursive maps for this course
                   12266: my %cachedmaps=();
                   12267: # When this was last done
                   12268: my $cachedmaptime='';
                   12269: 
1.379     matthew  12270: sub clear_EXT_cache_status {
1.383     albertel 12271:     &delenv('cache.EXT.');
1.379     matthew  12272: }
                   12273: 
                   12274: sub EXT_cache_status {
                   12275:     my ($target_domain,$target_user) = @_;
1.383     albertel 12276:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12277:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12278:         # We know already the user has no data
                   12279:         return 1;
                   12280:     } else {
                   12281:         return 0;
                   12282:     }
                   12283: }
                   12284: 
                   12285: sub EXT_cache_set {
                   12286:     my ($target_domain,$target_user) = @_;
1.383     albertel 12287:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12288:     #&appenv({$cachename => time});
1.379     matthew  12289: }
                   12290: 
1.28      www      12291: # --------------------------------------------------------- Value of a Variable
1.58      www      12292: sub EXT {
1.715     albertel 12293: 
1.1461    raeburn  12294:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68      www      12295:     unless ($varname) { return ''; }
1.218     albertel 12296:     #get real user name/domain, courseid and symb
                   12297:     my $courseid;
1.359     albertel 12298:     my $publicuser;
1.427     www      12299:     if ($symbparm) {
                   12300: 	$symbparm=&get_symb_from_alias($symbparm);
                   12301:     }
1.218     albertel 12302:     if (!($uname && $udom)) {
1.790     albertel 12303:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12304:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12305:     } else {
1.620     albertel 12306: 	$courseid=$env{'request.course.id'};
1.218     albertel 12307:     }
1.48      www      12308:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12309:     my $rest;
1.320     albertel 12310:     if (defined($therest[0])) {
1.48      www      12311:        $rest=join('.',@therest);
                   12312:     } else {
                   12313:        $rest='';
                   12314:     }
1.320     albertel 12315: 
1.57      www      12316:     my $qualifierrest=$qualifier;
                   12317:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12318:     my $spacequalifierrest=$space;
                   12319:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12320:     if ($realm eq 'user') {
1.48      www      12321: # --------------------------------------------------------------- user.resource
                   12322: 	if ($space eq 'resource') {
1.651     albertel 12323: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12324: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12325: 		 &&
1.744     albertel 12326: 		 ($symbparm eq &symbread()) ) {	
                   12327: 		# if we are in the middle of processing the resource the
                   12328: 		# get the value we are planning on committing
                   12329:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12330:                     return $Apache::lonhomework::results{$qualifierrest};
                   12331:                 } else {
                   12332:                     return $Apache::lonhomework::history{$qualifierrest};
                   12333:                 }
1.335     albertel 12334: 	    } else {
1.359     albertel 12335: 		my %restored;
1.620     albertel 12336: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12337: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12338: 		} else {
                   12339: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12340: 		}
1.335     albertel 12341: 		return $restored{$qualifierrest};
                   12342: 	    }
1.48      www      12343: # ----------------------------------------------------------------- user.access
                   12344:         } elsif ($space eq 'access') {
1.218     albertel 12345: 	    # FIXME - not supporting calls for a specific user
1.48      www      12346:             return &allowed($qualifier,$rest);
                   12347: # ------------------------------------------ user.preferences, user.environment
                   12348:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12349: 	    if (($uname eq $env{'user.name'}) &&
                   12350: 		($udom eq $env{'user.domain'})) {
                   12351: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12352: 	    } else {
1.359     albertel 12353: 		my %returnhash;
                   12354: 		if (!$publicuser) {
                   12355: 		    %returnhash=&userenvironment($udom,$uname,
                   12356: 						 $qualifierrest);
                   12357: 		}
1.218     albertel 12358: 		return $returnhash{$qualifierrest};
                   12359: 	    }
1.48      www      12360: # ----------------------------------------------------------------- user.course
                   12361:         } elsif ($space eq 'course') {
1.218     albertel 12362: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12363:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12364: # ------------------------------------------------------------------- user.role
                   12365:         } elsif ($space eq 'role') {
1.218     albertel 12366: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12367:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12368:             if ($qualifier eq 'value') {
                   12369: 		return $role;
                   12370:             } elsif ($qualifier eq 'extent') {
                   12371:                 return $where;
                   12372:             }
                   12373: # ----------------------------------------------------------------- user.domain
                   12374:         } elsif ($space eq 'domain') {
1.218     albertel 12375:             return $udom;
1.48      www      12376: # ------------------------------------------------------------------- user.name
                   12377:         } elsif ($space eq 'name') {
1.218     albertel 12378:             return $uname;
1.48      www      12379: # ---------------------------------------------------- Any other user namespace
1.29      www      12380:         } else {
1.359     albertel 12381: 	    my %reply;
                   12382: 	    if (!$publicuser) {
                   12383: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12384: 	    }
                   12385: 	    return $reply{$qualifierrest};
1.48      www      12386:         }
1.236     www      12387:     } elsif ($realm eq 'query') {
                   12388: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12389:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12390: 						[$spacequalifierrest]);
1.620     albertel 12391: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12392:    } elsif ($realm eq 'request') {
1.48      www      12393: # ------------------------------------------------------------- request.browser
                   12394:         if ($space eq 'browser') {
1.1145    bisitz   12395:             return $env{'browser.'.$qualifier};
1.57      www      12396: # ------------------------------------------------------------ request.filename
                   12397:         } else {
1.620     albertel 12398:             return $env{'request.'.$spacequalifierrest};
1.29      www      12399:         }
1.28      www      12400:     } elsif ($realm eq 'course') {
1.48      www      12401: # ---------------------------------------------------------- course.description
1.620     albertel 12402:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12403:     } elsif ($realm eq 'resource') {
1.165     www      12404: 
1.620     albertel 12405: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12406: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12407: 	}
1.693     albertel 12408: 
1.1232    raeburn  12409:         if ($qualifier eq '') {
                   12410: 	    if ($space eq 'title') {
                   12411: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12412: 	        return &gettitle($symbparm);
                   12413: 	    }
1.693     albertel 12414: 	
1.1232    raeburn  12415: 	    if ($space eq 'map') {
                   12416: 	        my ($map) = &decode_symb($symbparm);
                   12417: 	        return &symbread($map);
                   12418: 	    }
                   12419:             if ($space eq 'maptitle') {
                   12420:                 my ($map) = &decode_symb($symbparm);
                   12421:                 return &gettitle($map);
                   12422:             }
                   12423: 	    if ($space eq 'filename') {
                   12424: 	        if ($symbparm) {
                   12425: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12426: 	        }
                   12427: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12428: 	    }
1.1232    raeburn  12429: 
1.1233    raeburn  12430:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12431:                 if ($space eq 'visibleparts') {
                   12432:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12433:                     my $item;
                   12434:                     if (ref($navmap)) {
                   12435:                         my $res = $navmap->getBySymb($symbparm);
                   12436:                         my $parts = $res->parts();
                   12437:                         if (ref($parts) eq 'ARRAY') {
                   12438:                             $item = join(',',@{$parts});
                   12439:                         }
                   12440:                         undef($navmap);
1.1232    raeburn  12441:                     }
1.1233    raeburn  12442:                     return $item;
1.1232    raeburn  12443:                 }
                   12444:             }
                   12445:         }
1.693     albertel 12446: 
1.1301    raeburn  12447: 	my ($section, $group, @groups, @recurseup, $recursed);
1.1461    raeburn  12448:         if (ref($recurseupref) eq 'ARRAY') {
                   12449:             @recurseup = @{$recurseupref};
                   12450:             $recursed = 1;
                   12451:         }
1.1301    raeburn  12452: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  12453:         if (($courseid eq '') && ($cid)) {
                   12454:             $courseid = $cid;
                   12455:         }
                   12456: 	if (($symbparm && $courseid) && 
                   12457: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      12458: 
1.218     albertel 12459: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12460: 
1.60      www      12461: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12462: 	    my $symbp=$symbparm;
1.1301    raeburn  12463: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12464: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  12465:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 12466: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 12467: 	    if (($env{'user.name'} eq $uname) &&
                   12468: 		($env{'user.domain'} eq $udom)) {
                   12469: 		$section=$env{'request.course.sec'};
1.733     raeburn  12470:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12471:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12472: 	    } else {
1.539     albertel 12473: 		if (! defined($usection)) {
1.551     albertel 12474: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12475: 		} else {
                   12476: 		    $section = $usection;
                   12477: 		}
1.733     raeburn  12478:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12479: 	    }
                   12480: 
                   12481: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12482: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  12483:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 12484: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12485: 
1.593     albertel 12486: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12487: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  12488:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 12489: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12490: 
1.60      www      12491: # ----------------------------------------------------------- first, check user
1.624     albertel 12492: 
1.1301    raeburn  12493: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   12494:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 12495: 				       ([$courselevelr,'resource'],
                   12496: 					[$courselevelm,'map'     ],
1.1301    raeburn  12497:                                         [$courseleveli,'map'     ],
1.927     albertel 12498: 					[$courselevel, 'course'  ]));
1.931     albertel 12499: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12500: 
1.594     albertel 12501: # ------------------------------------------------ second, check some of course
1.684     raeburn  12502:             my $coursereply;
1.691     raeburn  12503:             if (@groups > 0) {
                   12504:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  12505:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   12506:                                        $mapp,\$recursed,\@recurseup);
                   12507:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  12508:             }
1.96      www      12509: 
1.684     raeburn  12510: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12511: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12512: 				  'course',$mapp,\$recursed,\@recurseup,
                   12513:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 12514: 				  ([$seclevelr,   'resource'],
                   12515: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  12516:                                    [$secleveli,   'map'     ],
1.927     albertel 12517: 				   [$seclevel,    'course'  ],
                   12518: 				   [$courselevelr,'resource']));
                   12519: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12520: 
1.60      www      12521: # ------------------------------------------------------ third, check map parms
1.218     albertel 12522: 	    my %parmhash=();
                   12523: 	    my $thisparm='';
                   12524: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12525: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12526: 		    &GDBM_READER(),0640)) {
1.218     albertel 12527: 		$thisparm=$parmhash{$symbparm};
                   12528: 		untie(%parmhash);
                   12529: 	    }
1.927     albertel 12530: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12531: 	}
1.594     albertel 12532: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  12533:  
                   12534:         my $what = $spacequalifierrest;
                   12535: 	$what=~s/\./\_/;
1.282     albertel 12536: 	my $filename;
                   12537: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12538: 	if ($symbparm) {
1.409     www      12539: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12540: 	} else {
1.620     albertel 12541: 	    $filename=$env{'request.filename'};
1.282     albertel 12542: 	}
1.1362    raeburn  12543:         my $toolsymb;
                   12544:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12545:             $toolsymb = $symbparm;
                   12546:         }
                   12547: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12548: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  12549: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12550: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12551: 
1.1301    raeburn  12552: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12553: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12554: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12555: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12556: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12557: 				     'course',$mapp,\$recursed,\@recurseup,
                   12558:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 12559: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  12560:                                       [$courseleveli,'map'   ],
1.927     albertel 12561: 				      [$courselevel, 'course']));
                   12562: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12563: 	}
1.145     www      12564: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12565: 	unless ($space eq '0') {
1.336     albertel 12566: 	    my @parts=split(/_/,$space);
                   12567: 	    my $id=pop(@parts);
                   12568: 	    my $part=join('_',@parts);
                   12569: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12570: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12571: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12572: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12573: 	}
1.395     albertel 12574: 	if ($recurse) { return undef; }
1.1362    raeburn  12575: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12576: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12577: # ---------------------------------------------------- Any other user namespace
                   12578:     } elsif ($realm eq 'environment') {
                   12579: # ----------------------------------------------------------------- environment
1.620     albertel 12580: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12581: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12582: 	} else {
1.770     albertel 12583: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12584: 		return '';
                   12585: 	    }
1.219     albertel 12586: 	    my %returnhash=&userenvironment($udom,$uname,
                   12587: 					    $spacequalifierrest);
                   12588: 	    return $returnhash{$spacequalifierrest};
                   12589: 	}
1.28      www      12590:     } elsif ($realm eq 'system') {
1.48      www      12591: # ----------------------------------------------------------------- system.time
                   12592: 	if ($space eq 'time') {
                   12593: 	    return time;
                   12594:         }
1.696     albertel 12595:     } elsif ($realm eq 'server') {
                   12596: # ----------------------------------------------------------------- system.time
                   12597: 	if ($space eq 'name') {
                   12598: 	    return $ENV{'SERVER_NAME'};
                   12599:         }
1.1415    raeburn  12600:     } elsif ($realm eq 'client') {
                   12601:         if ($space eq 'remote_addr') {
1.1441    raeburn  12602:             return &get_requestor_ip();
1.1415    raeburn  12603:         }
1.28      www      12604:     }
1.48      www      12605:     return '';
1.61      www      12606: }
                   12607: 
1.927     albertel 12608: sub get_reply {
                   12609:     my ($reply_value) = @_;
1.940     raeburn  12610:     if (ref($reply_value) eq 'ARRAY') {
                   12611:         if (wantarray) {
                   12612: 	    return @$reply_value;
                   12613:         }
                   12614:         return $reply_value->[0];
                   12615:     } else {
                   12616:         return $reply_value;
1.927     albertel 12617:     }
                   12618: }
                   12619: 
1.691     raeburn  12620: sub check_group_parms {
1.1301    raeburn  12621:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   12622:         $recursed,$recurseupref) = @_;
                   12623:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   12624:                   [$what,'course']);
                   12625:     my $coursereply;
1.691     raeburn  12626:     foreach my $group (@{$groups}) {
1.1301    raeburn  12627:         my @groupitems = ();
1.691     raeburn  12628:         foreach my $level (@levels) {
1.927     albertel 12629:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12630:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12631:         }
1.1301    raeburn  12632:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12633:                                    $env{'course.'.$courseid.'.domain'},
                   12634:                                    'course',$mapp,$recursed,$recurseupref,
                   12635:                                    $courseid,'.['.$group.'].',$what,
                   12636:                                    @groupitems);
                   12637:         last if (defined($coursereply));
1.691     raeburn  12638:     }
                   12639:     return $coursereply;
                   12640: }
                   12641: 
1.1301    raeburn  12642: sub get_map_hierarchy {
1.1302    raeburn  12643:     my ($mapname,$courseid) = @_;
                   12644:     my @recurseup = ();
1.1301    raeburn  12645:     if ($mapname) {
1.1302    raeburn  12646:         if (($cachedmapkey eq $courseid) &&
                   12647:             (abs($cachedmaptime-time)<5)) {
                   12648:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12649:                 return @{$cachedmaps{$mapname}};
                   12650:             }
                   12651:         }
1.1301    raeburn  12652:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12653:         if (ref($navmap)) {
                   12654:             @recurseup = $navmap->recurseup_maps($mapname);
                   12655:             undef($navmap);
1.1302    raeburn  12656:             $cachedmaps{$mapname} = \@recurseup;
                   12657:             $cachedmaptime=time;
                   12658:             $cachedmapkey=$courseid;
1.1301    raeburn  12659:         }
                   12660:     }
                   12661:     return @recurseup;
                   12662: }
                   12663: 
1.1302    raeburn  12664: }
                   12665: 
1.691     raeburn  12666: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12667:     my ($courseid,@groups) = @_;
                   12668:     @groups = sort(@groups);
1.691     raeburn  12669:     return @groups;
                   12670: }
                   12671: 
1.395     albertel 12672: sub packages_tab_default {
1.1362    raeburn  12673:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12674:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12675: 
                   12676:     my (@extension,@specifics,$do_default);
1.1362    raeburn  12677:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12678: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12679: 	if ($pack_type eq 'default') {
                   12680: 	    $do_default=1;
                   12681: 	} elsif ($pack_type eq 'extension') {
                   12682: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12683: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12684: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12685: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12686: 	}
                   12687:     }
                   12688:     # first look for a package that matches the requested part id
                   12689:     foreach my $package (@specifics) {
                   12690: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12691: 	next if ($pack_part ne $part);
                   12692: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12693: 	    return $packagetab{"$pack_type&$name&default"};
                   12694: 	}
                   12695:     }
                   12696:     # look for any possible matching non extension_ package
                   12697:     foreach my $package (@specifics) {
                   12698: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12699: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12700: 	    return $packagetab{"$pack_type&$name&default"};
                   12701: 	}
1.585     albertel 12702: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12703: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12704: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12705: 	}
                   12706:     }
1.738     albertel 12707:     # look for any posible extension_ match
                   12708:     foreach my $package (@extension) {
                   12709: 	my ($package,$pack_type)=@{$package};
                   12710: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12711: 	    return $packagetab{"$pack_type&$name&default"};
                   12712: 	}
                   12713: 	if (defined($packagetab{$package."&$name&default"})) {
                   12714: 	    return $packagetab{$package."&$name&default"};
                   12715: 	}
                   12716:     }
                   12717:     # look for a global default setting
                   12718:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12719: 	return $packagetab{"default&$name&default"};
                   12720:     }
1.395     albertel 12721:     return undef;
                   12722: }
                   12723: 
1.334     albertel 12724: sub add_prefix_and_part {
                   12725:     my ($prefix,$part)=@_;
                   12726:     my $keyroot;
                   12727:     if (defined($prefix) && $prefix !~ /^__/) {
                   12728: 	# prefix that has a part already
                   12729: 	$keyroot=$prefix;
                   12730:     } elsif (defined($prefix)) {
                   12731: 	# prefix that is missing a part
                   12732: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12733:     } else {
                   12734: 	# no prefix at all
                   12735: 	if (defined($part)) { $keyroot='_'.$part; }
                   12736:     }
                   12737:     return $keyroot;
                   12738: }
                   12739: 
1.71      www      12740: # ---------------------------------------------------------------- Get metadata
                   12741: 
1.599     albertel 12742: my %metaentry;
1.1070    www      12743: my %importedpartids;
1.1369    raeburn  12744: my %importedrespids;
1.71      www      12745: sub metadata {
1.1362    raeburn  12746:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12747:     $uri=&declutter($uri);
1.288     albertel 12748:     # if it is a non metadata possible uri return quickly
1.529     albertel 12749:     if (($uri eq '') || 
                   12750: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  12751: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12752:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12753: 	return undef;
                   12754:     }
1.1261    raeburn  12755:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12756: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12757: 	return undef;
1.288     albertel 12758:     }
1.73      www      12759:     my $filename=$uri;
                   12760:     $uri=~s/\.meta$//;
1.172     www      12761: #
                   12762: # Is the metadata already cached?
1.177     www      12763: # Look at timestamp of caching
1.172     www      12764: # Everything is cached by the main uri, libraries are never directly cached
                   12765: #
1.428     albertel 12766:     if (!defined($liburi)) {
1.599     albertel 12767: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12768: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12769:     }
1.1362    raeburn  12770: 
                   12771: #
                   12772: # If the uri is for an external tool the file from
                   12773: # which metadata should be retrieved depends on whether
                   12774: # the tool had been configured to be gradable (set in the Course
                   12775: # Editor or Resource Editor).
                   12776: #
                   12777: # If a valid symb has been included as the third arg in the call
                   12778: # to &metadata() that can be used to retrieve the value of
                   12779: # parameter_0_gradable set for the resource, and included in the
                   12780: # uploaded map containing the tool. The value is retrieved via
                   12781: # &EXT(), if a valid symb is available.  Otherwise the value of
                   12782: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  12783: # is retrieved via &get().
                   12784: #
                   12785: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   12786: # hiddenresource and encrypturl (during course initialization)
                   12787: # the map-level parameter for resource.0.gradable included in the 
                   12788: # uploaded map containing the tool will not yet have been stored
                   12789: # in the user_course_parms.db file for the user's session, so in 
                   12790: # this case fall back to retrieving gradable status from the
                   12791: # exttool_$marker.db file.
1.1362    raeburn  12792: #
                   12793: # In order to avoid an infinite loop, &metadata() will return
                   12794: # before a call to &EXT(), if the uri is for an external tool
                   12795: # and the $what for which metadata is being requested is
                   12796: # parameter_0_gradable or 0_gradable.
                   12797: #
                   12798: 
                   12799:     if ($uri =~ /ext\.tool$/) {
                   12800:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12801:             return;
                   12802:         } else {
                   12803:             my ($checked,$use_passback);
                   12804:             if ($toolsymb ne '') {
                   12805:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  12806:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  12807:                     $checked = 1;
                   12808:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12809:                         $use_passback = 1;
                   12810:                     }
                   12811:                 }
                   12812:             }
                   12813:             unless ($checked) {
                   12814:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12815:                 $marker=~s/\D//g;
1.1363    raeburn  12816:                 if ($marker) {
1.1362    raeburn  12817:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12818:                     $use_passback = $toolsettings{'gradable'};
                   12819:                 }
                   12820:             }
                   12821:             if ($use_passback) {
                   12822:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12823:             } else {
                   12824:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12825:             }
                   12826:         }
                   12827:     }
                   12828: 
1.428     albertel 12829:     {
1.1069    www      12830: # Imported parts would go here
1.1369    raeburn  12831:         my @origfiletagids=();
1.1069    www      12832:         my $importedparts=0;
1.1369    raeburn  12833: 
                   12834: # Imported responseids would go here
                   12835:         my $importedresponses=0;
1.172     www      12836: #
                   12837: # Is this a recursive call for a library?
                   12838: #
1.599     albertel 12839: #	if (! exists($metacache{$uri})) {
                   12840: #	    $metacache{$uri}={};
                   12841: #	}
1.924     albertel 12842: 	my $cachetime = 60*60;
1.171     www      12843:         if ($liburi) {
                   12844: 	    $liburi=&declutter($liburi);
                   12845:             $filename=$liburi;
1.401     bowersj2 12846:         } else {
1.599     albertel 12847: 	    &devalidate_cache_new('meta',$uri);
                   12848: 	    undef(%metaentry);
1.401     bowersj2 12849: 	}
1.140     www      12850:         my %metathesekeys=();
1.73      www      12851:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12852: 	my $metastring;
1.1140    www      12853: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12854: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12855: 	    $metastring = 
1.929     albertel 12856: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12857: 					  ('grade_target' => 'meta'));
                   12858: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12859: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12860:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12861: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12862: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12863: 	    $metastring=&getfile($file);
1.489     albertel 12864: 	}
1.208     albertel 12865:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12866:         my $token;
1.140     www      12867:         undef %metathesekeys;
1.71      www      12868:         while ($token=$parser->get_token) {
1.339     albertel 12869: 	    if ($token->[0] eq 'S') {
                   12870: 		if (defined($token->[2]->{'package'})) {
1.172     www      12871: #
                   12872: # This is a package - get package info
                   12873: #
1.339     albertel 12874: 		    my $package=$token->[2]->{'package'};
                   12875: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12876: 		    if (defined($token->[2]->{'id'})) { 
                   12877: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12878: 		    }
1.599     albertel 12879: 		    if ($metaentry{':packages'}) {
                   12880: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12881: 		    } else {
1.599     albertel 12882: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12883: 		    }
1.736     albertel 12884: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12885: 			my $part=$keyroot;
                   12886: 			$part=~s/^\_//;
1.736     albertel 12887: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12888: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12889: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12890: 			    # ignore package.tab specified default values
                   12891:                             # here &package_tab_default() will fetch those
                   12892: 			    if ($subp eq 'default') { next; }
1.736     albertel 12893: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12894: 			    my $unikey;
                   12895: 			    if ($pack =~ /_0$/) {
                   12896: 				$unikey='parameter_0_'.$name;
                   12897: 				$part=0;
                   12898: 			    } else {
                   12899: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12900: 			    }
1.339     albertel 12901: 			    if ($subp eq 'display') {
                   12902: 				$value.=' [Part: '.$part.']';
                   12903: 			    }
1.599     albertel 12904: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12905: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12906: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12907: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12908: 			    }
1.599     albertel 12909: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12910: 				$metaentry{':'.$unikey}=
                   12911: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12912: 			    }
1.339     albertel 12913: 			}
                   12914: 		    }
                   12915: 		} else {
1.172     www      12916: #
                   12917: # This is not a package - some other kind of start tag
1.339     albertel 12918: #
                   12919: 		    my $entry=$token->[1];
1.1068    www      12920: 		    my $unikey='';
1.175     www      12921: 
1.339     albertel 12922: 		    if ($entry eq 'import') {
1.175     www      12923: #
                   12924: # Importing a library here
1.339     albertel 12925: #
1.1067    www      12926:                         my $location=$parser->get_text('/import');
                   12927:                         my $dir=$filename;
                   12928:                         $dir=~s|[^/]*$||;
                   12929:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12930: 
                   12931:                         my $importid=$token->[2]->{'id'};
1.1068    www      12932:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12933: #
                   12934: # Check metadata for imported file to
                   12935: # see if it contained response items
                   12936: #
1.1372    raeburn  12937:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12938:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12939:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12940:                                                            $depthcount+1));
                   12941:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12942:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12943:                                                              undef,$depthcount+1);
                   12944:                             if ($libresponseorder ne '') {
                   12945:                                 if ($#origfiletagids<0) {
                   12946:                                     undef(%importedrespids);
                   12947:                                     undef(%importedpartids);
                   12948:                                 }
1.1373    raeburn  12949:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12950:                                 if (@respids) {
                   12951:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12952:                                 }
                   12953:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12954:                                     $importedresponses = 1;
1.1369    raeburn  12955: # We need to get the original file and the imported file to get the response order correct
                   12956: # Load and inspect original file
1.1372    raeburn  12957:                                     if ($#origfiletagids<0) {
                   12958:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12959:                                         $origfile=&getfile($origfilelocation);
                   12960:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12961:                                     }
1.1369    raeburn  12962:                                 }
                   12963:                             }
                   12964:                         }
1.1370    raeburn  12965: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12966: # hash populated for imported library file
                   12967:                         %metaentry = %currmetaentry;
                   12968:                         undef(%currmetaentry);
1.1374    raeburn  12969:                         if ($importmode eq 'part') {
1.1068    www      12970: # Import as part(s)
1.1069    www      12971:                            $importedparts=1;
                   12972: # We need to get the original file and the imported file to get the part order correct
                   12973: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12974: # Load and inspect original file if we didn't do that already
                   12975:                            if ($#origfiletagids<0) {
                   12976:                                undef(%importedrespids);
                   12977:                                undef(%importedpartids);
                   12978:                                if ($origfile eq '') {
                   12979:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12980:                                    $origfile=&getfile($origfilelocation);
                   12981:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12982:                                }
1.1070    www      12983:                            }
1.1372    raeburn  12984:                            my @impfilepartids;
                   12985: # If <partorder> tag is included in metadata for the imported file
                   12986: # get the parts in the imported file from that.
                   12987:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12988:                                %currmetaentry = %metaentry;
                   12989:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12990:                                                             $depthcount+1);
                   12991:                                %metaentry = %currmetaentry;
                   12992:                                undef(%currmetaentry);
                   12993:                                if ($libpartorder ne '') {
                   12994:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12995:                                }
                   12996:                            } else {
                   12997: # If no <partorder> tag available, load and inspect imported file
                   12998:                                my $impfile=&getfile($location);
                   12999:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13000:                            }
1.1069    www      13001:                            if ($#impfilepartids>=0) {
                   13002: # This problem had parts
1.1070    www      13003:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      13004:                            } else {
                   13005: # Importing by turning a single problem into a problem part
                   13006: # It gets the import-tags ID as part-ID
                   13007:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      13008:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      13009:                            }
1.1068    www      13010:                         } else {
1.1374    raeburn  13011: # Import as problem or as normal import
                   13012:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13013:                             unless ($importmode eq 'problem') {
1.1068    www      13014: # Normal import
1.1374    raeburn  13015:                                 if (defined($token->[2]->{'id'})) {
                   13016:                                     $unikey.='_'.$token->[2]->{'id'};
                   13017:                                 }
                   13018:                             }
                   13019: # Check metadata for imported file to
                   13020: # see if it contained parts
                   13021:                             if (grep(/^partorder$/,@libfilekeys)) {
                   13022:                                 %currmetaentry = %metaentry;
                   13023:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13024:                                                              $depthcount+1);
                   13025:                                 %metaentry = %currmetaentry;
                   13026:                                 undef(%currmetaentry);
                   13027:                                 if ($libpartorder ne '') {
                   13028:                                     $importedparts = 1;
                   13029:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   13030:                                 }
                   13031:                             }
1.1067    www      13032:                         }
1.339     albertel 13033: 			if ($depthcount<20) {
1.736     albertel 13034: 			    my $metadata = 
1.1362    raeburn  13035: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 13036: 					  $depthcount+1);
                   13037: 			    foreach my $meta (split(',',$metadata)) {
                   13038: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   13039: 				$metathesekeys{$meta}=1;
1.339     albertel 13040: 			    }
1.1068    www      13041:                         }
1.1067    www      13042: 		    } else {
                   13043: #
                   13044: # Not importing, some other kind of non-package, non-library start tag
                   13045: # 
                   13046:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13047:                         if (defined($token->[2]->{'id'})) {
                   13048:                             $unikey.='_'.$token->[2]->{'id'};
                   13049:                         }
1.339     albertel 13050: 			if (defined($token->[2]->{'name'})) { 
                   13051: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   13052: 			}
                   13053: 			$metathesekeys{$unikey}=1;
1.736     albertel 13054: 			foreach my $param (@{$token->[3]}) {
                   13055: 			    $metaentry{':'.$unikey.'.'.$param} =
                   13056: 				$token->[2]->{$param};
1.339     albertel 13057: 			}
                   13058: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 13059: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 13060: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   13061: 		 # only ws inside the tag, and not in default, so use default
                   13062: 		 # as value
1.599     albertel 13063: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 13064: 			} elsif ( $internaltext =~ /\S/ ) {
                   13065: 		  # something interesting inside the tag
                   13066: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 13067: 			} else {
1.908     albertel 13068: 		  # no interesting values, don't set a default
1.339     albertel 13069: 			}
1.172     www      13070: # end of not-a-package not-a-library import
1.339     albertel 13071: 		    }
1.172     www      13072: # end of not-a-package start tag
1.339     albertel 13073: 		}
1.172     www      13074: # the next is the end of "start tag"
1.339     albertel 13075: 	    }
                   13076: 	}
1.483     albertel 13077: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 13078: 	$extension = lc($extension);
                   13079: 	if ($extension eq 'htm') { $extension='html'; }
                   13080: 
1.737     albertel 13081: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 13082: 	    #no specific packages #how's our extension
                   13083: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 13084: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 13085: 					 \%metathesekeys);
                   13086: 	}
1.883     albertel 13087: 
                   13088: 	if (!exists($metaentry{':packages'})
                   13089: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 13090: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 13091: 		#no specific packages well let's get default then
                   13092: 		if ($key!~/^default&/) { next; }
1.488     albertel 13093: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 13094: 					     \%metathesekeys);
                   13095: 	    }
                   13096: 	}
1.338     www      13097: # are there custom rights to evaluate
1.599     albertel 13098: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 13099: 
1.338     www      13100:     #
                   13101:     # Importing a rights file here
1.339     albertel 13102:     #
                   13103: 	    unless ($depthcount) {
1.599     albertel 13104: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 13105: 		my $dir=$filename;
                   13106: 		$dir=~s|[^/]*$||;
                   13107: 		$location=&filelocation($dir,$location);
1.736     albertel 13108: 		my $rights_metadata =
1.1362    raeburn  13109: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 13110: 			      $depthcount+1);
                   13111: 		foreach my $rights (split(',',$rights_metadata)) {
                   13112: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   13113: 		    $metathesekeys{$rights}=1;
1.339     albertel 13114: 		}
                   13115: 	    }
                   13116: 	}
1.737     albertel 13117: 	# uniqifiy package listing
                   13118: 	my %seen;
                   13119: 	my @uniq_packages =
                   13120: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   13121: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   13122: 
1.1369    raeburn  13123:         if (($importedresponses) || ($importedparts)) {
                   13124:             if ($importedparts) {
1.1070    www      13125: # We had imported parts and need to rebuild partorder
1.1369    raeburn  13126:                 $metaentry{':partorder'}='';
                   13127:                 $metathesekeys{'partorder'}=1;
                   13128:             }
                   13129:             if ($importedresponses) {
                   13130: # We had imported responses and need to rebuil responseorder
                   13131:                 $metaentry{':responseorder'}='';
                   13132:                 $metathesekeys{'responseorder'}=1;
                   13133:             }
                   13134:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   13135:                 my $origid = $origfiletagids[$index+1];
                   13136:                 if ($origfiletagids[$index] eq 'part') {
                   13137: # Original part, part of the problem
                   13138:                     if ($importedparts) {
                   13139:                         $metaentry{':partorder'}.=','.$origid;
                   13140:                     }
                   13141:                 } elsif ($origfiletagids[$index] eq 'import') {
                   13142:                     if ($importedparts) {
                   13143: # We have imported parts at this position
1.1373    raeburn  13144:                         if ($importedpartids{$origid} ne '') {
                   13145:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   13146:                         }
1.1369    raeburn  13147:                     }
                   13148:                     if ($importedresponses) {
                   13149: # We have imported responses at this position
1.1373    raeburn  13150:                         if ($importedrespids{$origid} ne '') {
                   13151:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  13152:                         }
                   13153:                     }
                   13154:                 } else {
                   13155: # Original response item, part of the problem
                   13156:                     if ($importedresponses) {
                   13157:                         $metaentry{':responseorder'}.=','.$origid;
                   13158:                     }
                   13159:                 }
                   13160:             }
                   13161:             if ($importedparts) {
                   13162:                 $metaentry{':partorder'}=~s/^\,//;
                   13163:             }
                   13164:             if ($importedresponses) {
                   13165:                 $metaentry{':responseorder'}=~s/^\,//;
                   13166:             }
1.1070    www      13167:         }
1.737     albertel 13168: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 13169: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  13170: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  13171:         unless ($liburi) {
                   13172: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   13173:         }
1.177     www      13174: # this is the end of "was not already recently cached
1.71      www      13175:     }
1.599     albertel 13176:     return $metaentry{':'.$what};
1.261     albertel 13177: }
                   13178: 
1.488     albertel 13179: sub metadata_create_package_def {
1.483     albertel 13180:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13181:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13182:     if ($subp eq 'default') { next; }
                   13183:     
1.599     albertel 13184:     if (defined($metaentry{':packages'})) {
                   13185: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13186:     } else {
1.599     albertel 13187: 	$metaentry{':packages'}=$package;
1.483     albertel 13188:     }
                   13189:     my $value=$packagetab{$key};
                   13190:     my $unikey;
                   13191:     $unikey='parameter_0_'.$name;
1.599     albertel 13192:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13193:     $$metathesekeys{$unikey}=1;
1.599     albertel 13194:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13195: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13196:     }
1.599     albertel 13197:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13198: 	$metaentry{':'.$unikey}=
                   13199: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13200:     }
                   13201: }
                   13202: 
1.261     albertel 13203: sub metadata_generate_part0 {
                   13204:     my ($metadata,$metacache,$uri) = @_;
                   13205:     my %allnames;
1.737     albertel 13206:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13207: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13208: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13209: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13210: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13211: 	    $allnames{$name}=$part;
                   13212: 	  }
                   13213: 	}
                   13214:     }
                   13215:     foreach my $name (keys(%allnames)) {
                   13216:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13217:       my $key=":parameter_0_$name";
1.261     albertel 13218:       $$metacache{"$key.part"}='0';
                   13219:       $$metacache{"$key.name"}=$name;
1.428     albertel 13220:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13221: 					   $allnames{$name}.'_'.$name.
                   13222: 					   '.type'};
1.428     albertel 13223:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13224: 			     '.display'};
1.644     www      13225:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13226:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13227:       $$metacache{"$key.display"}=$olddis;
                   13228:     }
1.71      www      13229: }
                   13230: 
1.764     albertel 13231: # ------------------------------------------------------ Devalidate title cache
                   13232: 
                   13233: sub devalidate_title_cache {
                   13234:     my ($url)=@_;
                   13235:     if (!$env{'request.course.id'}) { return; }
                   13236:     my $symb=&symbread($url);
                   13237:     if (!$symb) { return; }
                   13238:     my $key=$env{'request.course.id'}."\0".$symb;
                   13239:     &devalidate_cache_new('title',$key);
                   13240: }
                   13241: 
1.1014    droeschl 13242: # ------------------------------------------------- Get the title of a course
                   13243: 
                   13244: sub current_course_title {
                   13245:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13246: }
1.301     www      13247: # ------------------------------------------------- Get the title of a resource
                   13248: 
                   13249: sub gettitle {
                   13250:     my $urlsymb=shift;
                   13251:     my $symb=&symbread($urlsymb);
1.534     albertel 13252:     if ($symb) {
1.620     albertel 13253: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13254: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13255: 	if (defined($cached)) { 
                   13256: 	    return $result;
                   13257: 	}
1.534     albertel 13258: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13259: 	my $title='';
1.907     albertel 13260: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13261: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13262: 	} else {
                   13263: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13264: 		    &GDBM_READER(),0640)) {
                   13265: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13266: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13267: 		untie(%bighash);
                   13268: 	    }
1.534     albertel 13269: 	}
                   13270: 	$title=~s/\&colon\;/\:/gs;
                   13271: 	if ($title) {
1.1159    www      13272: # Remember both $symb and $title for dynamic metadata
                   13273:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13274:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13275: # Cache this title and then return it
1.599     albertel 13276: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13277: 	}
                   13278: 	$urlsymb=$url;
                   13279:     }
                   13280:     my $title=&metadata($urlsymb,'title');
                   13281:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13282:     return $title;
1.301     www      13283: }
1.613     albertel 13284: 
1.614     albertel 13285: sub get_slot {
                   13286:     my ($which,$cnum,$cdom)=@_;
                   13287:     if (!$cnum || !$cdom) {
1.790     albertel 13288: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13289: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13290: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13291:     }
1.703     albertel 13292:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13293:     my %slotinfo;
                   13294:     if (exists($remembered{$key})) {
                   13295: 	$slotinfo{$which} = $remembered{$key};
                   13296:     } else {
                   13297: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13298: 	&Apache::lonhomework::showhash(%slotinfo);
                   13299: 	my ($tmp)=keys(%slotinfo);
                   13300: 	if ($tmp=~/^error:/) { return (); }
                   13301: 	$remembered{$key} = $slotinfo{$which};
                   13302:     }
1.616     albertel 13303:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13304: 	return %{$slotinfo{$which}};
                   13305:     }
                   13306:     return $slotinfo{$which};
1.614     albertel 13307: }
1.1150    raeburn  13308: 
                   13309: sub get_reservable_slots {
                   13310:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13311:     my $now = time;
                   13312:     my $reservable_info;
                   13313:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13314:     if (exists($remembered{$key})) {
                   13315:         $reservable_info = $remembered{$key};
                   13316:     } else {
                   13317:         my %resv;
                   13318:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13319:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13320:         $reservable_info = \%resv;
                   13321:         $remembered{$key} = $reservable_info;
                   13322:     }
                   13323:     return $reservable_info;
                   13324: }
                   13325: 
                   13326: sub get_course_slots {
                   13327:     my ($cnum,$cdom) = @_;
                   13328:     my $hashid=$cnum.':'.$cdom;
                   13329:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13330:     if (defined($cached)) {
                   13331:         if (ref($result) eq 'HASH') {
                   13332:             return %{$result};
                   13333:         }
                   13334:     } else {
                   13335:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13336:         my ($tmp) = keys(%slots);
                   13337:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  13338:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13339:             return %slots;
                   13340:         }
                   13341:     }
                   13342:     return;
                   13343: }
                   13344: 
                   13345: sub devalidate_slots_cache {
                   13346:     my ($cnum,$cdom)=@_;
                   13347:     my $hashid=$cnum.':'.$cdom;
                   13348:     &devalidate_cache_new('allslots',$hashid);
                   13349: }
                   13350: 
1.1181    raeburn  13351: sub get_coursechange {
                   13352:     my ($cdom,$cnum) = @_;
                   13353:     if ($cdom eq '' || $cnum eq '') {
                   13354:         return unless ($env{'request.course.id'});
                   13355:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13356:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13357:     }
                   13358:     my $hashid=$cdom.'_'.$cnum;
                   13359:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13360:     if ((defined($cached)) && ($change ne '')) {
                   13361:         return $change;
                   13362:     } else {
                   13363:         my %crshash;
                   13364:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13365:         if ($crshash{'internal.contentchange'} eq '') {
                   13366:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13367:             if ($change eq '') {
                   13368:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13369:                 $change = $crshash{'internal.created'};
                   13370:             }
                   13371:         } else {
                   13372:             $change = $crshash{'internal.contentchange'};
                   13373:         }
                   13374:         my $cachetime = 600;
                   13375:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13376:     }
                   13377:     return $change;
                   13378: }
                   13379: 
                   13380: sub devalidate_coursechange_cache {
                   13381:     my ($cnum,$cdom)=@_;
                   13382:     my $hashid=$cnum.':'.$cdom;
                   13383:     &devalidate_cache_new('crschange',$hashid);
                   13384: }
                   13385: 
1.31      www      13386: # ------------------------------------------------- Update symbolic store links
                   13387: 
                   13388: sub symblist {
                   13389:     my ($mapname,%newhash)=@_;
1.438     www      13390:     $mapname=&deversion(&declutter($mapname));
1.31      www      13391:     my %hash;
1.620     albertel 13392:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13393:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13394:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13395: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13396: 		next if ($url eq 'last_known'
                   13397: 			 && $env{'form.no_update_last_known'});
                   13398: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13399: 						    $newhash{$url}->[1],
                   13400: 						    $newhash{$url}->[0]);
1.191     harris41 13401:             }
1.31      www      13402:             if (untie(%hash)) {
                   13403: 		return 'ok';
                   13404:             }
                   13405:         }
                   13406:     }
                   13407:     return 'error';
1.212     www      13408: }
                   13409: 
                   13410: # --------------------------------------------------------------- Verify a symb
                   13411: 
                   13412: sub symbverify {
1.1190    raeburn  13413:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13414:     my $thisfn=$thisurl;
1.439     www      13415:     $thisfn=&declutter($thisfn);
1.215     www      13416: # direct jump to resource in page or to a sequence - will construct own symbs
                   13417:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13418: # check URL part
1.409     www      13419:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13420: 
1.431     www      13421:     unless ($url eq $thisfn) { return 0; }
1.213     www      13422: 
1.216     www      13423:     $symb=&symbclean($symb);
1.510     www      13424:     $thisurl=&deversion($thisurl);
1.439     www      13425:     $thisfn=&deversion($thisfn);
1.213     www      13426: 
                   13427:     my %bighash;
                   13428:     my $okay=0;
1.431     www      13429: 
1.620     albertel 13430:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13431:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13432:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13433:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  13434:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13435:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13436:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13437:             }
                   13438:         }
                   13439:         my $ids;
1.1419    raeburn  13440:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13441:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204    raeburn  13442:         } else {
                   13443:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13444:         }
1.1102    raeburn  13445:         unless ($ids) {
                   13446:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   13447:             $ids=$bighash{$idkey};
1.216     www      13448:         }
                   13449:         if ($ids) {
                   13450: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  13451:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  13452:                 $symb =~ s/\?.+$//;
1.1202    raeburn  13453:             }
1.800     albertel 13454: 	    foreach my $id (split(/\,/,$ids)) {
                   13455: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13456:                if (
                   13457:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  13458:    eq $symb) {
                   13459:                    if (ref($encstate)) {
                   13460:                        $$encstate = $bighash{'encrypted_'.$id};
                   13461:                    }
1.620     albertel 13462: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  13463: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   13464:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  13465: 		       $okay=1;
1.1202    raeburn  13466:                        last;
1.582     albertel 13467: 		   }
                   13468: 	       }
1.216     www      13469: 	   }
                   13470:         }
1.213     www      13471: 	untie(%bighash);
                   13472:     }
                   13473:     return $okay;
1.31      www      13474: }
                   13475: 
1.210     www      13476: # --------------------------------------------------------------- Clean-up symb
                   13477: 
                   13478: sub symbclean {
                   13479:     my $symb=shift;
1.568     albertel 13480:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13481: # remove version from map
                   13482:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13483: 
1.210     www      13484: # remove version from URL
                   13485:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13486: 
1.507     www      13487: # remove wrapper
                   13488: 
1.510     www      13489:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13490:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13491:     return $symb;
1.409     www      13492: }
                   13493: 
                   13494: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13495: 
                   13496: sub encode_symb {
                   13497:     my ($map,$resid,$url)=@_;
                   13498:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13499: }
1.409     www      13500: 
                   13501: sub decode_symb {
1.568     albertel 13502:     my $symb=shift;
                   13503:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13504:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13505:     return (&fixversion($map),$resid,&fixversion($url));
                   13506: }
                   13507: 
                   13508: sub fixversion {
                   13509:     my $fn=shift;
1.609     banghart 13510:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13511:     my %bighash;
                   13512:     my $uri=&clutter($fn);
1.620     albertel 13513:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13514: # is this cached?
1.599     albertel 13515:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13516:     if (defined($cached)) { return $result; }
                   13517: # unfortunately not cached, or expired
1.620     albertel 13518:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13519: 	    &GDBM_READER(),0640)) {
                   13520:  	if ($bighash{'version_'.$uri}) {
                   13521:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13522:  	    unless (($version eq 'mostrecent') || 
                   13523: 		    ($version==&getversion($uri))) {
1.440     www      13524:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13525:  	    }
                   13526:  	}
                   13527:  	untie %bighash;
1.413     www      13528:     }
1.599     albertel 13529:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13530: }
                   13531: 
                   13532: sub deversion {
                   13533:     my $url=shift;
                   13534:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13535:     return $url;
1.210     www      13536: }
                   13537: 
1.31      www      13538: # ------------------------------------------------------ Return symb list entry
                   13539: 
                   13540: sub symbread {
1.1424    raeburn  13541:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427    raeburn  13542:         $ignoresymbdb,$noenccheck)=@_;
1.1265    raeburn  13543:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1427    raeburn  13544:     if (defined($env{$cache_str})) {
1.1424    raeburn  13545:         unless (ref($possibles) eq 'HASH') {
                   13546:             if ($ignorecachednull) {
                   13547:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13548:             } else {
                   13549:                 return $env{$cache_str};
                   13550:             }
1.1282    raeburn  13551:         }
                   13552:     }
1.242     www      13553: # no filename provided? try from environment
1.1265    raeburn  13554:     unless ($thisfn) {
1.620     albertel 13555:         if ($env{'request.symb'}) {
1.1427    raeburn  13556:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 13557: 	}
1.620     albertel 13558: 	$thisfn=$env{'request.filename'};
1.44      www      13559:     }
1.569     albertel 13560:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13561: # is that filename actually a symb? Verify, clean, and return
                   13562:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13563: 	if (&symbverify($thisfn,$1)) {
1.1427    raeburn  13564: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13565: 	}
1.242     www      13566:     }
1.44      www      13567:     $thisfn=declutter($thisfn);
1.31      www      13568:     my %hash;
1.37      www      13569:     my %bighash;
                   13570:     my $syval='';
1.620     albertel 13571:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13572:         my $targetfn = $thisfn;
1.609     banghart 13573:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13574:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13575:         }
1.687     albertel 13576: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13577: 	    $targetfn=$1;
                   13578: 	}
1.1427    raeburn  13579:         unless ($ignoresymbdb) {
1.1424    raeburn  13580:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13581:                           &GDBM_READER(),0640)) {
                   13582: 	        $syval=$hash{$targetfn};
                   13583:                 untie(%hash);
                   13584:             }
1.1427    raeburn  13585:             if ($syval && $checkforblock) {
                   13586:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424    raeburn  13587:                 if (@blockers) {
                   13588:                     $syval='';
                   13589:                 }
                   13590:             }
1.37      www      13591:         }
                   13592: # ---------------------------------------------------------- There was an entry
                   13593:         if ($syval) {
1.601     albertel 13594: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13595: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13596: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13597: 		    #return $env{$cache_str}='';
1.601     albertel 13598: 		#}    
                   13599: 		#$syval.=$1;
                   13600: 	    #}
1.37      www      13601:         } else {
                   13602: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13603:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13604:                             &GDBM_READER(),0640)) {
1.37      www      13605: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13606:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13607:               unless ($ids) { 
                   13608:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13609:               }
                   13610:               unless ($ids) {
                   13611: # alias?
                   13612: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13613:               }
1.37      www      13614:               if ($ids) {
                   13615: # ------------------------------------------------------------------- Has ID(s)
                   13616:                  my @possibilities=split(/\,/,$ids);
1.39      www      13617:                  if ($#possibilities==0) {
                   13618: # ----------------------------------------------- There is only one possibility
1.37      www      13619: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13620: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13621: 						    $resid,$thisfn);
1.1282    raeburn  13622:                      if (ref($possibles) eq 'HASH') {
1.1424    raeburn  13623:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13624:                              $possibles->{$syval} = 1;
                   13625:                          }
1.1282    raeburn  13626:                      }
                   13627:                      if ($checkforblock) {
1.1424    raeburn  13628:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426    raeburn  13629:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424    raeburn  13630:                              if (@blockers) {
                   13631:                                  $syval = '';
1.1425    raeburn  13632:                                  untie(%bighash);
                   13633:                                  return $env{$cache_str}='';
1.1424    raeburn  13634:                              }
1.1282    raeburn  13635:                          }
                   13636:                      }
                   13637:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      13638: # ------------------------------------------ There is more than one possibility
                   13639:                      my $realpossible=0;
1.800     albertel 13640:                      foreach my $id (@possibilities) {
                   13641: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  13642:                          my $canaccess;
                   13643:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13644:                              $canaccess = 1;
                   13645:                          } else { 
                   13646:                              $canaccess = &allowed('bre',$file);
                   13647:                          }
                   13648:                          if ($canaccess) {
                   13649:          		     my ($mapid,$resid)=split(/\./,$id);
                   13650:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13651:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13652: 						             $resid,$thisfn);
1.1424    raeburn  13653:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426    raeburn  13654:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282    raeburn  13655:                                  if ($checkforblock) {
1.1426    raeburn  13656:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424    raeburn  13657:                                      if (@blockers > 0) {
                   13658:                                          $syval = '';
                   13659:                                      } else {
1.1282    raeburn  13660:                                          $syval = $poss_syval;
                   13661:                                          $realpossible++;
                   13662:                                      }
                   13663:                                  } else {
                   13664:                                      $syval = $poss_syval;
                   13665:                                      $realpossible++;
                   13666:                                  }
1.1424    raeburn  13667:                                  if ($syval) {
                   13668:                                      if (ref($possibles) eq 'HASH') {
                   13669:                                          $possibles->{$syval} = 1;
                   13670:                                      }
                   13671:                                  }
1.1282    raeburn  13672:                              }
1.39      www      13673: 			 }
1.191     harris41 13674:                      }
1.39      www      13675: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13676:                  } else {
                   13677:                      $syval='';
1.37      www      13678:                  }
                   13679: 	      }
1.1282    raeburn  13680:               untie(%bighash);
1.481     raeburn  13681:            }
1.31      www      13682:         }
1.62      www      13683:         if ($syval) {
1.1427    raeburn  13684: 	    return $env{$cache_str}=$syval;
1.62      www      13685:         }
1.31      www      13686:     }
1.949     raeburn  13687:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13688:     return $env{$cache_str}='';
1.31      www      13689: }
                   13690: 
                   13691: # ---------------------------------------------------------- Return random seed
                   13692: 
1.32      www      13693: sub numval {
                   13694:     my $txt=shift;
                   13695:     $txt=~tr/A-J/0-9/;
                   13696:     $txt=~tr/a-j/0-9/;
                   13697:     $txt=~tr/K-T/0-9/;
                   13698:     $txt=~tr/k-t/0-9/;
                   13699:     $txt=~tr/U-Z/0-5/;
                   13700:     $txt=~tr/u-z/0-5/;
                   13701:     $txt=~s/\D//g;
1.564     albertel 13702:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13703:     return int($txt);
1.368     albertel 13704: }
                   13705: 
1.484     albertel 13706: sub numval2 {
                   13707:     my $txt=shift;
                   13708:     $txt=~tr/A-J/0-9/;
                   13709:     $txt=~tr/a-j/0-9/;
                   13710:     $txt=~tr/K-T/0-9/;
                   13711:     $txt=~tr/k-t/0-9/;
                   13712:     $txt=~tr/U-Z/0-5/;
                   13713:     $txt=~tr/u-z/0-5/;
                   13714:     $txt=~s/\D//g;
                   13715:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13716:     my $total;
                   13717:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13718:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13719:     return int($total);
                   13720: }
                   13721: 
1.575     albertel 13722: sub numval3 {
                   13723:     use integer;
                   13724:     my $txt=shift;
                   13725:     $txt=~tr/A-J/0-9/;
                   13726:     $txt=~tr/a-j/0-9/;
                   13727:     $txt=~tr/K-T/0-9/;
                   13728:     $txt=~tr/k-t/0-9/;
                   13729:     $txt=~tr/U-Z/0-5/;
                   13730:     $txt=~tr/u-z/0-5/;
                   13731:     $txt=~s/\D//g;
                   13732:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13733:     my $total;
                   13734:     foreach my $val (@txts) { $total+=$val; }
                   13735:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13736:     return $total;
                   13737: }
                   13738: 
1.675     albertel 13739: sub digest {
                   13740:     my ($data)=@_;
                   13741:     my $digest=&Digest::MD5::md5($data);
                   13742:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13743:     my ($e,$f);
                   13744:     {
                   13745:         use integer;
                   13746:         $e=($a+$b);
                   13747:         $f=($c+$d);
                   13748:         if ($_64bit) {
                   13749:             $e=(($e<<32)>>32);
                   13750:             $f=(($f<<32)>>32);
                   13751:         }
                   13752:     }
                   13753:     if (wantarray) {
                   13754: 	return ($e,$f);
                   13755:     } else {
                   13756: 	my $g;
                   13757: 	{
                   13758: 	    use integer;
                   13759: 	    $g=($e+$f);
                   13760: 	    if ($_64bit) {
                   13761: 		$g=(($g<<32)>>32);
                   13762: 	    }
                   13763: 	}
                   13764: 	return $g;
                   13765:     }
                   13766: }
                   13767: 
1.368     albertel 13768: sub latest_rnd_algorithm_id {
1.675     albertel 13769:     return '64bit5';
1.366     albertel 13770: }
1.32      www      13771: 
1.503     albertel 13772: sub get_rand_alg {
                   13773:     my ($courseid)=@_;
1.790     albertel 13774:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13775:     if ($courseid) {
1.620     albertel 13776: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13777:     }
                   13778:     return &latest_rnd_algorithm_id();
                   13779: }
                   13780: 
1.562     albertel 13781: sub validCODE {
                   13782:     my ($CODE)=@_;
                   13783:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13784:     return 0;
                   13785: }
                   13786: 
1.491     albertel 13787: sub getCODE {
1.620     albertel 13788:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13789:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13790: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13791: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13792: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13793:     }
                   13794:     return undef;
                   13795: }
1.1133    foxr     13796: #
                   13797: #  Determines the random seed for a specific context:
                   13798: #
                   13799: # parameters:
                   13800: #   symb      - in course context the symb for the seed.
                   13801: #   course_id - The course id of the form domain_coursenum.
                   13802: #   domain    - Domain for the user.
                   13803: #   course    - Course for the user.
                   13804: #   cenv      - environment of the course.
                   13805: #
                   13806: # NOTE:
                   13807: #   All parameters are picked out of the environment if missing
                   13808: #   or not defined.
                   13809: #   If a symb cannot be determined the current time is used instead.
                   13810: #
                   13811: #  For a given well defined symb, courside, domain, username,
                   13812: #  and course environment, the seed is reproducible.
                   13813: #
1.31      www      13814: sub rndseed {
1.1133    foxr     13815:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13816:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13817:     if (!defined($symb)) {
1.366     albertel 13818: 	unless ($symb=$wsymb) { return time; }
                   13819:     }
1.1146    foxr     13820:     if (!defined $courseid) { 
                   13821: 	$courseid=$wcourseid; 
                   13822:     }
                   13823:     if (!defined $domain) { $domain=$wdomain; }
                   13824:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13825: 
                   13826:     my $which;
                   13827:     if (defined($cenv->{'rndseed'})) {
                   13828: 	$which = $cenv->{'rndseed'};
                   13829:     } else {
                   13830: 	$which =&get_rand_alg($courseid);
                   13831:     }
1.491     albertel 13832:     if (defined(&getCODE())) {
1.1133    foxr     13833: 
1.675     albertel 13834: 	if ($which eq '64bit5') {
                   13835: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13836: 	} elsif ($which eq '64bit4') {
1.575     albertel 13837: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13838: 	} else {
                   13839: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13840: 	}
1.675     albertel 13841:     } elsif ($which eq '64bit5') {
                   13842: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13843:     } elsif ($which eq '64bit4') {
                   13844: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13845:     } elsif ($which eq '64bit3') {
                   13846: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13847:     } elsif ($which eq '64bit2') {
                   13848: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13849:     } elsif ($which eq '64bit') {
                   13850: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13851:     }
                   13852:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13853: }
                   13854: 
                   13855: sub rndseed_32bit {
                   13856:     my ($symb,$courseid,$domain,$username)=@_;
                   13857:     {
                   13858: 	use integer;
                   13859: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13860: 	my $symbseed=numval($symb) << 22;
                   13861: 	my $namechck=unpack("%32C*",$username) << 17;
                   13862: 	my $nameseed=numval($username) << 12;
                   13863: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13864: 	my $courseseed=unpack("%32C*",$courseid);
                   13865: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13866: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13867: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13868: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13869: 	return $num;
                   13870:     }
                   13871: }
                   13872: 
                   13873: sub rndseed_64bit {
                   13874:     my ($symb,$courseid,$domain,$username)=@_;
                   13875:     {
                   13876: 	use integer;
                   13877: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13878: 	my $symbseed=numval($symb) << 10;
                   13879: 	my $namechck=unpack("%32S*",$username);
                   13880: 	
                   13881: 	my $nameseed=numval($username) << 21;
                   13882: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13883: 	my $courseseed=unpack("%32S*",$courseid);
                   13884: 	
                   13885: 	my $num1=$symbchck+$symbseed+$namechck;
                   13886: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13887: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13888: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13889: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13890: 	return "$num1,$num2";
1.155     albertel 13891:     }
1.366     albertel 13892: }
                   13893: 
1.443     albertel 13894: sub rndseed_64bit2 {
                   13895:     my ($symb,$courseid,$domain,$username)=@_;
                   13896:     {
                   13897: 	use integer;
                   13898: 	# strings need to be an even # of cahracters long, it it is odd the
                   13899:         # last characters gets thrown away
                   13900: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13901: 	my $symbseed=numval($symb) << 10;
                   13902: 	my $namechck=unpack("%32S*",$username.' ');
                   13903: 	
                   13904: 	my $nameseed=numval($username) << 21;
1.501     albertel 13905: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13906: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13907: 	
                   13908: 	my $num1=$symbchck+$symbseed+$namechck;
                   13909: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13910: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13911: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13912: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13913: 	return "$num1,$num2";
                   13914:     }
                   13915: }
                   13916: 
                   13917: sub rndseed_64bit3 {
                   13918:     my ($symb,$courseid,$domain,$username)=@_;
                   13919:     {
                   13920: 	use integer;
                   13921: 	# strings need to be an even # of cahracters long, it it is odd the
                   13922:         # last characters gets thrown away
                   13923: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13924: 	my $symbseed=numval2($symb) << 10;
                   13925: 	my $namechck=unpack("%32S*",$username.' ');
                   13926: 	
                   13927: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13928: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13929: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13930: 	
                   13931: 	my $num1=$symbchck+$symbseed+$namechck;
                   13932: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13933: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13934: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13935: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13936: 	
1.503     albertel 13937: 	return "$num1:$num2";
1.443     albertel 13938:     }
                   13939: }
                   13940: 
1.575     albertel 13941: sub rndseed_64bit4 {
                   13942:     my ($symb,$courseid,$domain,$username)=@_;
                   13943:     {
                   13944: 	use integer;
                   13945: 	# strings need to be an even # of cahracters long, it it is odd the
                   13946:         # last characters gets thrown away
                   13947: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13948: 	my $symbseed=numval3($symb) << 10;
                   13949: 	my $namechck=unpack("%32S*",$username.' ');
                   13950: 	
                   13951: 	my $nameseed=numval3($username) << 21;
                   13952: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13953: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13954: 	
                   13955: 	my $num1=$symbchck+$symbseed+$namechck;
                   13956: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13957: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13958: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13959: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13960: 	
1.575     albertel 13961: 	return "$num1:$num2";
                   13962:     }
                   13963: }
                   13964: 
1.675     albertel 13965: sub rndseed_64bit5 {
                   13966:     my ($symb,$courseid,$domain,$username)=@_;
                   13967:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13968:     return "$num1:$num2";
                   13969: }
                   13970: 
1.366     albertel 13971: sub rndseed_CODE_64bit {
                   13972:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13973:     {
1.366     albertel 13974: 	use integer;
1.443     albertel 13975: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13976: 	my $symbseed=numval2($symb);
1.491     albertel 13977: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13978: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13979: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13980: 	my $num1=$symbseed+$CODEchck;
                   13981: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13982: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13983: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13984: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13985: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13986: 	return "$num1:$num2";
1.366     albertel 13987:     }
                   13988: }
                   13989: 
1.575     albertel 13990: sub rndseed_CODE_64bit4 {
                   13991:     my ($symb,$courseid,$domain,$username)=@_;
                   13992:     {
                   13993: 	use integer;
                   13994: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13995: 	my $symbseed=numval3($symb);
                   13996: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13997: 	my $CODEseed=numval3(&getCODE());
                   13998: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13999: 	my $num1=$symbseed+$CODEchck;
                   14000: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14001: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14002: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 14003: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14004: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   14005: 	return "$num1:$num2";
                   14006:     }
                   14007: }
                   14008: 
1.675     albertel 14009: sub rndseed_CODE_64bit5 {
                   14010:     my ($symb,$courseid,$domain,$username)=@_;
                   14011:     my $code = &getCODE();
                   14012:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   14013:     return "$num1:$num2";
                   14014: }
                   14015: 
1.366     albertel 14016: sub setup_random_from_rndseed {
                   14017:     my ($rndseed)=@_;
1.503     albertel 14018:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  14019:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   14020:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   14021:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   14022:         } else {
                   14023:             &Math::Random::random_set_seed($num1,$num2);
                   14024:         }
1.366     albertel 14025:     } else {
                   14026: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 14027:     }
1.36      albertel 14028: }
                   14029: 
1.474     albertel 14030: sub latest_receipt_algorithm_id {
1.835     albertel 14031:     return 'receipt3';
1.474     albertel 14032: }
                   14033: 
1.480     www      14034: sub recunique {
                   14035:     my $fucourseid=shift;
                   14036:     my $unique;
1.835     albertel 14037:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   14038: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14039: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      14040:     } else {
                   14041: 	$unique=$perlvar{'lonReceipt'};
                   14042:     }
                   14043:     return unpack("%32C*",$unique);
                   14044: }
                   14045: 
                   14046: sub recprefix {
                   14047:     my $fucourseid=shift;
                   14048:     my $prefix;
1.835     albertel 14049:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   14050: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14051: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      14052:     } else {
                   14053: 	$prefix=$perlvar{'lonHostID'};
                   14054:     }
                   14055:     return unpack("%32C*",$prefix);
                   14056: }
                   14057: 
1.76      www      14058: sub ireceipt {
1.474     albertel 14059:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 14060: 
                   14061:     my $return =&recprefix($fucourseid).'-';
                   14062: 
                   14063:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   14064: 	$env{'request.state'} eq 'construct') {
                   14065: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   14066: 	return $return;
                   14067:     }
                   14068: 
1.76      www      14069:     my $cuname=unpack("%32C*",$funame);
                   14070:     my $cudom=unpack("%32C*",$fudom);
                   14071:     my $cucourseid=unpack("%32C*",$fucourseid);
                   14072:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      14073:     my $cunique=&recunique($fucourseid);
1.474     albertel 14074:     my $cpart=unpack("%32S*",$part);
1.835     albertel 14075:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   14076: 
1.790     albertel 14077: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 14078: 			       
                   14079: 	$return.= ($cunique%$cuname+
                   14080: 		   $cunique%$cudom+
                   14081: 		   $cusymb%$cuname+
                   14082: 		   $cusymb%$cudom+
                   14083: 		   $cucourseid%$cuname+
                   14084: 		   $cucourseid%$cudom+
                   14085: 		   $cpart%$cuname+
                   14086: 		   $cpart%$cudom);
                   14087:     } else {
                   14088: 	$return.= ($cunique%$cuname+
                   14089: 		   $cunique%$cudom+
                   14090: 		   $cusymb%$cuname+
                   14091: 		   $cusymb%$cudom+
                   14092: 		   $cucourseid%$cuname+
                   14093: 		   $cucourseid%$cudom);
                   14094:     }
                   14095:     return $return;
1.76      www      14096: }
                   14097: 
                   14098: sub receipt {
1.474     albertel 14099:     my ($part)=@_;
1.790     albertel 14100:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 14101:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      14102: }
1.260     ng       14103: 
1.790     albertel 14104: sub whichuser {
                   14105:     my ($passedsymb)=@_;
                   14106:     my ($symb,$courseid,$domain,$name,$publicuser);
                   14107:     if (defined($env{'form.grade_symb'})) {
                   14108: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   14109: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   14110: 	if (!$allowed &&
                   14111: 	    exists($env{'request.course.sec'}) &&
                   14112: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   14113: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   14114: 			      '/'.$env{'request.course.sec'});
                   14115: 	}
                   14116: 	if ($allowed) {
                   14117: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   14118: 	    $courseid=$tmp_courseid;
                   14119: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   14120: 	    ($name)=&get_env_multiple('form.grade_username');
                   14121: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   14122: 	}
                   14123:     }
                   14124:     if (!$passedsymb) {
                   14125: 	$symb=&symbread();
                   14126:     } else {
                   14127: 	$symb=$passedsymb;
                   14128:     }
                   14129:     $courseid=$env{'request.course.id'};
                   14130:     $domain=$env{'user.domain'};
                   14131:     $name=$env{'user.name'};
                   14132:     if ($name eq 'public' && $domain eq 'public') {
                   14133: 	if (!defined($env{'form.username'})) {
                   14134: 	    $env{'form.username'}.=time.rand(10000000);
                   14135: 	}
                   14136: 	$name.=$env{'form.username'};
                   14137:     }
                   14138:     return ($symb,$courseid,$domain,$name,$publicuser);
                   14139: 
                   14140: }
                   14141: 
1.36      albertel 14142: # ------------------------------------------------------------ Serves up a file
1.472     albertel 14143: # returns either the contents of the file or 
                   14144: # -1 if the file doesn't exist
1.481     raeburn  14145: #
                   14146: # if the target is a file that was uploaded via DOCS, 
                   14147: # a check will be made to see if a current copy exists on the local server,
                   14148: # if it does this will be served, otherwise a copy will be retrieved from
                   14149: # the home server for the course and stored in /home/httpd/html/userfiles on
                   14150: # the local server.   
1.472     albertel 14151: 
1.36      albertel 14152: sub getfile {
1.538     albertel 14153:     my ($file) = @_;
1.609     banghart 14154:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 14155:     &repcopy($file);
                   14156:     return &readfile($file);
                   14157: }
                   14158: 
                   14159: sub repcopy_userfile {
                   14160:     my ($file)=@_;
1.1142    raeburn  14161:     my $londocroot = $perlvar{'lonDocRoot'};
                   14162:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  14163:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 14164:     my ($cdom,$cnum,$filename) = 
1.811     albertel 14165: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 14166:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   14167:     if (-e "$file") {
1.828     www      14168: # we already have a local copy, check it out
1.538     albertel 14169: 	my @fileinfo = stat($file);
1.828     www      14170: 	my $rtncode;
                   14171: 	my $info;
1.538     albertel 14172: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 14173: 	if ($lwpresp ne 'ok') {
1.828     www      14174: # there is no such file anymore, even though we had a local copy
1.482     albertel 14175: 	    if ($rtncode eq '404') {
1.538     albertel 14176: 		unlink($file);
1.482     albertel 14177: 	    }
                   14178: 	    return -1;
                   14179: 	}
                   14180: 	if ($info < $fileinfo[9]) {
1.828     www      14181: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  14182: 	    return 'ok';
1.828     www      14183: 	} else {
                   14184: # the file is outdated, get rid of it
                   14185: 	    unlink($file);
1.482     albertel 14186: 	}
1.828     www      14187:     }
                   14188: # one way or the other, at this point, we don't have the file
                   14189: # construct the correct path for the file
                   14190:     my @parts = ($cdom,$cnum); 
                   14191:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   14192: 	push @parts, split(/\//,$1);
                   14193:     }
                   14194:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   14195:     foreach my $part (@parts) {
                   14196: 	$path .= '/'.$part;
                   14197: 	if (!-e $path) {
                   14198: 	    mkdir($path,0770);
1.482     albertel 14199: 	}
                   14200:     }
1.828     www      14201: # now the path exists for sure
                   14202: # get a user agent
                   14203:     my $transferfile=$file.'.in.transfer';
                   14204: # FIXME: this should flock
                   14205:     if (-e $transferfile) { return 'ok'; }
                   14206:     my $request;
                   14207:     $uri=~s/^\///;
1.980     raeburn  14208:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  14209:     my $hostname = &hostname($homeserver);
1.980     raeburn  14210:     my $protocol = $protocol{$homeserver};
                   14211:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14212:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  14213:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      14214: # did it work?
                   14215:     if ($response->is_error()) {
                   14216: 	unlink($transferfile);
                   14217: 	&logthis("Userfile repcopy failed for $uri");
                   14218: 	return -1;
                   14219:     }
                   14220: # worked, rename the transfer file
                   14221:     rename($transferfile,$file);
1.607     raeburn  14222:     return 'ok';
1.481     raeburn  14223: }
                   14224: 
1.517     albertel 14225: sub tokenwrapper {
                   14226:     my $uri=shift;
1.980     raeburn  14227:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14228:     $uri=~s|^/||;
1.620     albertel 14229:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14230:     my $token=$1;
1.552     albertel 14231:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14232:     if ($udom && $uname && $file) {
                   14233: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14234:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14235:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  14236:         my $hostname = &hostname($homeserver);
1.980     raeburn  14237:         my $protocol = $protocol{$homeserver};
                   14238:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14239:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14240:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14241:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14242:     } else {
                   14243:         return '/adm/notfound.html';
                   14244:     }
                   14245: }
                   14246: 
1.828     www      14247: # call with reqtype HEAD: get last modification time
                   14248: # call with reqtype GET: get the file contents
                   14249: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14250: #
1.481     raeburn  14251: sub getuploaded {
                   14252:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14253:     $uri=~s/^\///;
1.980     raeburn  14254:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  14255:     my $hostname = &hostname($homeserver);
1.980     raeburn  14256:     my $protocol = $protocol{$homeserver};
                   14257:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14258:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14259:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  14260:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  14261:     $$rtncode = $response->code;
1.482     albertel 14262:     if (! $response->is_success()) {
                   14263: 	return 'failed';
                   14264:     }      
                   14265:     if ($reqtype eq 'HEAD') {
1.486     www      14266: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14267:     } elsif ($reqtype eq 'GET') {
                   14268: 	$$info = $response->content;
1.472     albertel 14269:     }
1.482     albertel 14270:     return 'ok';
1.36      albertel 14271: }
                   14272: 
1.481     raeburn  14273: sub readfile {
                   14274:     my $file = shift;
                   14275:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14276:     my $fh;
1.1359    raeburn  14277:     open($fh,"<",$file);
1.481     raeburn  14278:     my $a='';
1.800     albertel 14279:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14280:     return $a;
                   14281: }
                   14282: 
1.36      albertel 14283: sub filelocation {
1.590     banghart 14284:     my ($dir,$file) = @_;
                   14285:     my $location;
                   14286:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14287: 
                   14288:     if ($file =~ m-^/adm/-) {
                   14289: 	$file=~s-^/adm/wrapper/-/-;
                   14290: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14291:     }
1.882     albertel 14292: 
1.1139    www      14293:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14294:         $location = $file;
1.609     banghart 14295:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14296:         my ($udom,$uname,$filename)=
1.811     albertel 14297:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14298:         my $home=&homeserver($uname,$udom);
                   14299:         my $is_me=0;
                   14300:         my @ids=&current_machine_ids();
                   14301:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14302:         if ($is_me) {
1.1117    foxr     14303:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14304:         } else {
                   14305:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14306:   	      $udom.'/'.$uname.'/'.$filename;
                   14307:         }
1.882     albertel 14308:     } elsif ($file =~ m-^/adm/-) {
                   14309: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14310:     } else {
                   14311:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14312:         $file=~s:^/(res|priv)/:/:;
                   14313:         my $space=$1;
1.590     banghart 14314:         if ( !( $file =~ m:^/:) ) {
                   14315:             $location = $dir. '/'.$file;
                   14316:         } else {
1.1142    raeburn  14317:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14318:         }
1.59      albertel 14319:     }
1.590     banghart 14320:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14321:     while ($location=~m{/\.\./}) {
                   14322: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14323: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14324: 	} else {
                   14325: 	    $location=~ s{/\.\./}{/}g;
                   14326: 	}
                   14327:     } #remove dir/..
1.590     banghart 14328:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14329:     return $location;
1.46      www      14330: }
1.36      albertel 14331: 
1.46      www      14332: sub hreflocation {
                   14333:     my ($dir,$file)=@_;
1.980     raeburn  14334:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14335: 	$file=filelocation($dir,$file);
1.700     albertel 14336:     } elsif ($file=~m-^/adm/-) {
                   14337: 	$file=~s-^/adm/wrapper/-/-;
                   14338: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14339:     }
                   14340:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14341: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14342:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14343: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14344: 	        {/uploaded/$1/$2/}x;
1.46      www      14345:     }
1.913     albertel 14346:     if ($file=~ m{^/userfiles/}) {
                   14347: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14348:     }
1.462     albertel 14349:     return $file;
1.465     albertel 14350: }
                   14351: 
1.1139    www      14352: 
                   14353: 
                   14354: 
                   14355: 
1.465     albertel 14356: sub current_machine_domains {
1.853     albertel 14357:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14358: }
                   14359: 
                   14360: sub machine_domains {
                   14361:     my ($hostname) = @_;
1.465     albertel 14362:     my @domains;
1.838     albertel 14363:     my %hostname = &all_hostnames();
1.465     albertel 14364:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14365: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14366: 	if ($hostname eq $name) {
1.844     albertel 14367: 	    push(@domains,&host_domain($id));
1.465     albertel 14368: 	}
                   14369:     }
                   14370:     return @domains;
                   14371: }
                   14372: 
                   14373: sub current_machine_ids {
1.853     albertel 14374:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14375: }
                   14376: 
                   14377: sub machine_ids {
                   14378:     my ($hostname) = @_;
                   14379:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14380:     my @ids;
1.888     albertel 14381:     my %name_to_host = &all_names();
1.889     albertel 14382:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14383: 	return @{ $name_to_host{$hostname} };
                   14384:     }
                   14385:     return;
1.31      www      14386: }
                   14387: 
1.824     raeburn  14388: sub additional_machine_domains {
                   14389:     my @domains;
1.1466  ! raeburn  14390:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
        !          14391:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
        !          14392:             while (my $line = <$fh>) {
        !          14393:                 chomp($line);           
        !          14394:                 $line =~ s/\s//g;
        !          14395:                 push(@domains,$line);
        !          14396:             }
        !          14397:             close($fh);
        !          14398:         }
1.824     raeburn  14399:     }
                   14400:     return @domains;
                   14401: }
                   14402: 
                   14403: sub default_login_domain {
                   14404:     my $domain = $perlvar{'lonDefDomain'};
                   14405:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14406:     foreach my $posdom (&current_machine_domains(),
                   14407:                         &additional_machine_domains()) {
                   14408:         if (lc($posdom) eq lc($testdomain)) {
                   14409:             $domain=$posdom;
                   14410:             last;
                   14411:         }
                   14412:     }
                   14413:     return $domain;
                   14414: }
                   14415: 
1.1414    raeburn  14416: sub shared_institution {
1.1439    raeburn  14417:     my ($dom,$lonhost) = @_;
                   14418:     if ($lonhost eq '') {
                   14419:         $lonhost = $perlvar{'lonHostID'};
                   14420:     }
1.1414    raeburn  14421:     my $same_intdom;
1.1439    raeburn  14422:     my $hostintdom = &internet_dom($lonhost);
1.1414    raeburn  14423:     if ($hostintdom ne '') {
                   14424:         my %iphost = &get_iphost();
                   14425:         my $primary_id = &domain($dom,'primary');
                   14426:         my $primary_ip = &get_host_ip($primary_id);
                   14427:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14428:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14429:                 my $intdom = &internet_dom($id);
                   14430:                 if ($intdom eq $hostintdom) {
                   14431:                     $same_intdom = 1;
                   14432:                     last;
                   14433:                 }
                   14434:             }
                   14435:         }
                   14436:     }
                   14437:     return $same_intdom;
                   14438: }
                   14439: 
1.1398    raeburn  14440: sub uses_sts {
                   14441:     my ($ignore_cache) = @_;
                   14442:     my $lonhost = $perlvar{'lonHostID'};
                   14443:     my $hostname = &hostname($lonhost);
                   14444:     my $sts_on;
                   14445:     if ($protocol{$lonhost} eq 'https') {
                   14446:         my $cachetime = 12*3600;
                   14447:         if (!$ignore_cache) {
                   14448:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14449:             if (defined($cached)) {
                   14450:                 return $sts_on;
                   14451:             }
                   14452:         }
                   14453:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14454:         my $request=new HTTP::Request('HEAD',$url);
                   14455:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   14456:         if ($response->is_success) {
                   14457:             my $has_sts = $response->header('Strict-Transport-Security');
                   14458:             if ($has_sts eq '') {
                   14459:                 $sts_on = 0;
                   14460:             } else {
                   14461:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14462:                     my $maxage = $1;
                   14463:                     if ($maxage) {
                   14464:                         $sts_on = 1;
                   14465:                     } else {
                   14466:                         $sts_on = 0;
                   14467:                     }
                   14468:                 } else {
                   14469:                     $sts_on = 0;
                   14470:                 }
                   14471:             }
                   14472:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14473:         }
                   14474:     }
                   14475:     return;
                   14476: }
                   14477: 
1.1449    raeburn  14478: sub waf_allssl {
                   14479:     my ($host_name) = @_;
                   14480:     my $alias = &get_proxy_alias();
                   14481:     if ($host_name eq '') {
                   14482:         $host_name = $ENV{'SERVER_NAME'};
                   14483:     }
                   14484:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14485:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14486:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14487:         if ($defdomdefaults{'waf_sslopt'}) {
                   14488:             return $defdomdefaults{'waf_sslopt'};
                   14489:         }
                   14490:     }
                   14491:     return;
                   14492: }
                   14493: 
1.1434    raeburn  14494: sub get_requestor_ip {
                   14495:     my ($r,$nolookup,$noproxy) = @_;
                   14496:     my $from_ip;
                   14497:     if (ref($r)) {
1.1447    raeburn  14498:         if ($r->can('useragent_ip')) {
                   14499:             if ($noproxy && $r->can('client_ip')) {
                   14500:                 $from_ip = $r->client_ip();
                   14501:             } else {
                   14502:                 $from_ip = $r->useragent_ip();
                   14503:             }
                   14504:         } elsif ($r->connection->can('remote_ip')) {
                   14505:             $from_ip = $r->connection->remote_ip();
                   14506:         } else {
                   14507:             $from_ip = $r->get_remote_host($nolookup);
                   14508:         }
1.1434    raeburn  14509:     } else {
                   14510:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14511:     }
                   14512:     return $from_ip if ($noproxy); 
                   14513:     # Who controls proxy settings for server
                   14514:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14515:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14516:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437    raeburn  14517:         if ($proxyinfo->{'vpnint'}) {
                   14518:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434    raeburn  14519:                 return $from_ip;
                   14520:             }
                   14521:         }
                   14522:         if ($proxyinfo->{'trusted'}) {
                   14523:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14524:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14525:                 my ($ip,$xfor);
                   14526:                 if (ref($r)) {
                   14527:                     if ($ipheader) {
                   14528:                         $ip = $r->headers_in->{$ipheader};
                   14529:                     }
                   14530:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14531:                 } else {
                   14532:                     if ($ipheader) {
                   14533:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14534:                     }
                   14535:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14536:                 }
                   14537:                 if (($ip eq '') && ($xfor ne '')) {
                   14538:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14539:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14540:                             $ip = $poss_ip;
1.1435    raeburn  14541:                             last;
1.1434    raeburn  14542:                         }
                   14543:                     }
                   14544:                 }
                   14545:                 if ($ip ne '') {
                   14546:                     return $ip;
                   14547:                 }
                   14548:             }
                   14549:         }
                   14550:     }
                   14551:     return $from_ip;
                   14552: }
                   14553: 
                   14554: sub get_proxy_settings {
                   14555:     my ($dom_in_use) = @_;
                   14556:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14557:     my $proxyinfo = {
                   14558:                        ipheader => $domdefaults{'waf_ipheader'},
                   14559:                        trusted  => $domdefaults{'waf_trusted'},
1.1437    raeburn  14560:                        vpnint   => $domdefaults{'waf_vpnint'},
1.1438    raeburn  14561:                        vpnext   => $domdefaults{'waf_vpnext'},
1.1449    raeburn  14562:                        sslopt   => $domdefaults{'waf_sslopt'},
1.1434    raeburn  14563:                     };
                   14564:     return $proxyinfo;
                   14565: }
                   14566: 
                   14567: sub ip_match {
                   14568:     my ($ip,$pattern_str) = @_;
                   14569:     $ip=Net::CIDR::cidrvalidate($ip);
                   14570:     if ($ip) {
                   14571:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14572:     }
                   14573:     return;
                   14574: }
                   14575: 
                   14576: sub get_proxy_alias {
1.1450    raeburn  14577:     my ($lonid) = @_;
                   14578:     if ($lonid eq '') {
                   14579:         $lonid = $perlvar{'lonHostID'};
                   14580:     }
                   14581:     if (!defined(&hostname($lonid))) {
                   14582:         return;
                   14583:     }
                   14584:     if ($lonid ne '') {
                   14585:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434    raeburn  14586:         if ($cached) {
                   14587:             return $alias;
                   14588:         }
1.1450    raeburn  14589:         my $dom = &Apache::lonnet::host_domain($lonid);
1.1434    raeburn  14590:         if ($dom ne '') {
                   14591:             my $cachetime = 60*60*24;
                   14592:             my %domconfig =
1.1437    raeburn  14593:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14594:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14595:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450    raeburn  14596:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14597:                 }
                   14598:             }
                   14599:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14600:         }
                   14601:     }
                   14602:     return;
                   14603: }
                   14604: 
                   14605: sub use_proxy_alias {
                   14606:     my ($r,$lonid) = @_;
                   14607:     my $alias = &get_proxy_alias($lonid);
                   14608:     if ($alias) {
                   14609:         my $dom = &host_domain($lonid);
                   14610:         if ($dom ne '') {
                   14611:             my $proxyinfo = &get_proxy_settings($dom );
                   14612:             my ($vpnint,$remote_ip);
                   14613:             if (ref($proxyinfo) eq 'HASH') {
                   14614:                 $vpnint = $proxyinfo->{'vpnint'};
                   14615:                 if ($vpnint) {
                   14616:                     $remote_ip = &get_requestor_ip($r,1,1);
1.1434    raeburn  14617:                 }
                   14618:             }
1.1450    raeburn  14619:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14620:                 return $alias;
                   14621:             }
1.1434    raeburn  14622:         }
                   14623:     }
                   14624:     return;
                   14625: }
                   14626: 
1.1465    raeburn  14627: sub get_saml_landing {
                   14628:     my ($lonid) = @_;
                   14629:     if ($lonid eq '') {
                   14630:         my $defdom = &default_login_domain();
                   14631:         my @hosts = &current_machine_ids();
                   14632:         if (@hosts > 1) {
                   14633:             foreach my $hostid (@hosts) {
                   14634:                 if (&host_domain($hostid) eq $defdom) {
                   14635:                     $lonid = $hostid;
                   14636:                     last;
                   14637:                 }
                   14638:             }
                   14639:         } else {
                   14640:             $lonid = $perlvar{'lonHostID'};
                   14641:         }
                   14642:         if ($lonid) {
                   14643:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14644:                 return;
                   14645:             }
                   14646:         } else {
                   14647:             return;
                   14648:         }
                   14649:     } elsif (!defined(&hostname($lonid))) {
                   14650:         return;
                   14651:     }
                   14652:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14653:     if ($cached) {
                   14654:         return $landing;
                   14655:     }
                   14656:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14657:     if ($dom ne '') {
                   14658:         my $cachetime = 60*60*24;
                   14659:         my %domconfig =
                   14660:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14661:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14662:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14663:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14664:                     $landing = 1;
                   14665:                 }
                   14666:             }
                   14667:         }
                   14668:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14669:     }
                   14670:     return;
                   14671: }
                   14672: 
1.31      www      14673: # ------------------------------------------------------------- Declutters URLs
                   14674: 
                   14675: sub declutter {
                   14676:     my $thisfn=shift;
1.569     albertel 14677:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  14678:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14679:         $thisfn=~s{^/home/httpd/html}{};
                   14680:     }
1.31      www      14681:     $thisfn=~s/^\///;
1.697     albertel 14682:     $thisfn=~s|^adm/wrapper/||;
                   14683:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14684:     $thisfn=~s/^res\///;
1.1172    bisitz   14685:     $thisfn=~s/^priv\///;
1.1032    raeburn  14686:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14687:         $thisfn=~s/\?.+$//;
                   14688:     }
1.268     www      14689:     return $thisfn;
                   14690: }
                   14691: 
                   14692: # ------------------------------------------------------------- Clutter up URLs
                   14693: 
                   14694: sub clutter {
                   14695:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14696:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14697: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14698:        $thisfn='/res'.$thisfn; 
                   14699:     }
1.1031    raeburn  14700:     if ($thisfn !~m|^/adm|) {
                   14701: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14702: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14703: 	} else {
                   14704: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14705: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14706: 	    if ($embstyle eq 'ssi'
                   14707: 		|| ($embstyle eq 'hdn')
                   14708: 		|| ($embstyle eq 'rat')
                   14709: 		|| ($embstyle eq 'prv')
                   14710: 		|| ($embstyle eq 'ign')) {
                   14711: 		#do nothing with these
                   14712: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14713: 		|| ($embstyle eq 'emb')
                   14714: 		|| ($embstyle eq 'wrp')) {
                   14715: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14716: 	    } elsif ($embstyle eq 'unk'
                   14717: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14718: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14719: 	    } else {
1.718     www      14720: #		&logthis("Got a blank emb style");
1.695     albertel 14721: 	    }
1.694     albertel 14722: 	}
1.1343    raeburn  14723:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  14724:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14725:     }
1.31      www      14726:     return $thisfn;
1.12      www      14727: }
                   14728: 
1.787     albertel 14729: sub clutter_with_no_wrapper {
                   14730:     my $uri = &clutter(shift);
                   14731:     if ($uri =~ m-^/adm/-) {
                   14732: 	$uri =~ s-^/adm/wrapper/-/-;
                   14733: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14734:     }
                   14735:     return $uri;
                   14736: }
                   14737: 
1.557     albertel 14738: sub freeze_escape {
                   14739:     my ($value)=@_;
                   14740:     if (ref($value)) {
                   14741: 	$value=&nfreeze($value);
                   14742: 	return '__FROZEN__'.&escape($value);
                   14743:     }
                   14744:     return &escape($value);
                   14745: }
                   14746: 
1.11      www      14747: 
1.557     albertel 14748: sub thaw_unescape {
                   14749:     my ($value)=@_;
                   14750:     if ($value =~ /^__FROZEN__/) {
                   14751: 	substr($value,0,10,undef);
                   14752: 	$value=&unescape($value);
                   14753: 	return &thaw($value);
                   14754:     }
                   14755:     return &unescape($value);
                   14756: }
                   14757: 
1.436     albertel 14758: sub correct_line_ends {
                   14759:     my ($result)=@_;
                   14760:     $$result =~s/\r\n/\n/mg;
                   14761:     $$result =~s/\r/\n/mg;
1.415     albertel 14762: }
1.1       albertel 14763: # ================================================================ Main Program
                   14764: 
1.184     www      14765: sub goodbye {
1.204     albertel 14766:    &logthis("Starting Shut down");
1.443     albertel 14767: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14768:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14769: #converted
1.599     albertel 14770: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14771:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14772: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14773: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14774: #1.1 only
1.870     albertel 14775: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14776: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14777: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14778: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14779:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14780:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14781:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14782:    &flushcourselogs();
                   14783:    &logthis("Shutting down");
                   14784: }
                   14785: 
1.852     albertel 14786: sub get_dns {
1.1210    raeburn  14787:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14788:     if (!$ignore_cache) {
                   14789: 	my ($content,$cached)=
                   14790: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14791: 	if ($cached) {
1.1210    raeburn  14792: 	    &$func($content,$hashref);
1.869     albertel 14793: 	    return;
                   14794: 	}
                   14795:     }
                   14796: 
                   14797:     my %alldns;
1.1379    raeburn  14798:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14799:         foreach my $dns (<$config>) {
                   14800: 	    next if ($dns !~ /^\^(\S*)/x);
                   14801:             my $line = $1;
                   14802:             my ($host,$protocol) = split(/:/,$line);
                   14803:             if ($protocol ne 'https') {
                   14804:                 $protocol = 'http';
                   14805:             }
                   14806: 	    $alldns{$host} = $protocol;
1.979     raeburn  14807:         }
1.1379    raeburn  14808:         close($config);
1.869     albertel 14809:     }
                   14810:     while (%alldns) {
1.1263    raeburn  14811: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456    raeburn  14812:         my ($contents,@content);
                   14813:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14814:             my $command = (split('/',$url))[3];
                   14815:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14816:             delete($alldns{$dns});
                   14817:             next if (($dir eq '') || ($file eq ''));
                   14818:             if (open(my $config,'<',"$dir/$file")) {
1.1457    raeburn  14819:                 @content = <$config>;
1.1456    raeburn  14820:                 close($config);
                   14821:             }
                   14822:             if ($url eq '/adm/dns/loncapaCRL') {
                   14823:                 $contents = join('',@content);
                   14824:             }
                   14825:         } else {
                   14826: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14827:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
                   14828:             delete($alldns{$dns});
                   14829: 	    next if ($response->is_error());
                   14830:             if ($url eq '/adm/dns/loncapaCRL') {
                   14831:                 $contents = $response->content;
                   14832:             } else {
                   14833:                 @content = split("\n",$response->content);
                   14834:             }
                   14835:         }
1.1379    raeburn  14836:         if ($url eq '/adm/dns/loncapaCRL') {
1.1456    raeburn  14837:             return &$func($contents);
1.1379    raeburn  14838:         } else {
                   14839: 	    unless ($nocache) {
                   14840: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   14841: 	    }
                   14842: 	    &$func(\@content,$hashref);
                   14843:             return;
                   14844:         }
                   14845:     }
                   14846:     my $which = (split('/',$url,4))[3];
                   14847:     if ($which eq 'loncapaCRL') {
                   14848:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   14849:         if (-e $diskfile) {
                   14850:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   14851:         } else {
                   14852:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   14853:         }
                   14854:     } else {
                   14855:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   14856:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14857:             my @content = <$config>;
                   14858:             close($config);
                   14859:             &$func(\@content,$hashref);
                   14860:         }
1.852     albertel 14861:     }
1.1210    raeburn  14862:     return;
                   14863: }
                   14864: 
                   14865: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  14866: sub parse_dns_checksums_tab {
1.1210    raeburn  14867:     my ($lines,$hashref) = @_;
1.1264    raeburn  14868:     my $lonhost = $perlvar{'lonHostID'};
                   14869:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  14870:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  14871:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14872:     my $webconfdir = '/etc/httpd/conf';
                   14873:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14874:         $webconfdir = '/etc/apache2';
                   14875:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14876:         if ($1 >= 10) {
                   14877:             $webconfdir = '/etc/apache2';
                   14878:         }
                   14879:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14880:         if ($1 >= 10.0) {
                   14881:             $webconfdir = '/etc/apache2';
                   14882:         }
                   14883:     }
1.1210    raeburn  14884:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14885:     my (%chksum,%revnum);
                   14886:     if (ref($lines) eq 'ARRAY') {
                   14887:         chomp(@{$lines});
1.1238    raeburn  14888:         my $version = shift(@{$lines});
                   14889:         if ($version eq $release) {  
1.1210    raeburn  14890:             foreach my $line (@{$lines}) {
1.1238    raeburn  14891:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  14892:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14893:                     if ($webconfdir eq '/etc/apache2') {
                   14894:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14895:                     }
                   14896:                 }
1.1238    raeburn  14897:                 $chksum{$file} = $shasum;
                   14898:                 $revnum{$file} = $version;
1.1210    raeburn  14899:             }
                   14900:             if (ref($hashref) eq 'HASH') {
                   14901:                 %{$hashref} = (
                   14902:                                 sums     => \%chksum,
                   14903:                                 versions => \%revnum,
                   14904:                               );
                   14905:             }
                   14906:         }
                   14907:     }
1.869     albertel 14908:     return;
1.852     albertel 14909: }
1.1210    raeburn  14910: 
                   14911: sub fetch_dns_checksums {
1.1238    raeburn  14912:     my %checksums;
                   14913:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  14914:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  14915:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14916:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  14917:              \%checksums);
1.1210    raeburn  14918:     return \%checksums;
                   14919: }
                   14920: 
1.1379    raeburn  14921: sub fetch_crl_pemfile {
                   14922:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   14923: }
                   14924: 
                   14925: sub save_crl_pem {
1.1456    raeburn  14926:     my ($content) = @_;
1.1380    raeburn  14927:     my ($msg,$hadchanges);
1.1456    raeburn  14928:     if ($content ne '') {
1.1379    raeburn  14929:         my $now = time;
                   14930:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   14931:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   14932:         if (open(my $fh,'>',"$tmpcrl")) {
1.1456    raeburn  14933:             print $fh $content;
1.1379    raeburn  14934:             close($fh);
                   14935:             if (-e $lonca) {
                   14936:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   14937:                     my $check = <PIPE>;
                   14938:                     close(PIPE);
                   14939:                     chomp($check);
                   14940:                     if ($check eq 'verify OK') {
                   14941:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  14942:                         my $backup;
1.1379    raeburn  14943:                         if (-e $dest) {
1.1380    raeburn  14944:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   14945:                                 $backup = 'ok';
                   14946:                             }
1.1379    raeburn  14947:                         }
                   14948:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   14949:                             $msg = 'ok';
1.1380    raeburn  14950:                             if ($backup) {
                   14951:                                 my (%oldnums,%newnums);
                   14952:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   14953:                                     while (<PIPE>) {
                   14954:                                         $oldnums{(split(/:/))[1]} = 1;
                   14955:                                     }
                   14956:                                     close(PIPE);
                   14957:                                 }
                   14958:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   14959:                                     while(<PIPE>) {
                   14960:                                         $newnums{(split(/:/))[1]} = 1;
                   14961:                                     }
                   14962:                                     close(PIPE);
                   14963:                                 }
                   14964:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   14965:                                     unless (exists($oldnums{$key})) {
                   14966:                                         $hadchanges = 1;
                   14967:                                         last;
                   14968:                                     }
                   14969:                                 }
                   14970:                                 unless ($hadchanges) {
                   14971:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   14972:                                         unless (exists($newnums{$key})) {
                   14973:                                             $hadchanges = 1;
                   14974:                                             last;
                   14975:                                         }
                   14976:                                     }
                   14977:                                 }
                   14978:                             }
1.1379    raeburn  14979:                         }
                   14980:                     } else {
                   14981:                         unlink($tmpcrl);
                   14982:                     }
                   14983:                 } else {
                   14984:                     unlink($tmpcrl);
                   14985:                 }
                   14986:             } else {
                   14987:                 unlink($tmpcrl);
                   14988:             }
                   14989:         }
                   14990:     }
1.1380    raeburn  14991:     return ($msg,$hadchanges);
1.1379    raeburn  14992: }
                   14993: 
1.1456    raeburn  14994: sub parse_getdns_url {
                   14995:     my ($command,$url) = @_;
                   14996:     my $dir = $perlvar{'lonTabDir'};
                   14997:     my $file;
                   14998:     if ($command eq 'hosts') {
                   14999:         $file = 'dns_hosts.tab';
                   15000:     } elsif ($command eq 'domain') {
                   15001:         $file = 'dns_domain.tab';
                   15002:     } elsif ($command eq 'checksums') {
                   15003:         my $version = (split('/',$url))[4];
                   15004:         $file = "dns_checksums/$version.tab",
                   15005:     } elsif ($command eq 'loncapaCRL') {
                   15006:         $dir = $perlvar{'lonCertificateDirectory'};
                   15007:         $file = $perlvar{'lonnetCertRevocationList'};
                   15008:     }
                   15009:     return ($dir,$file);
                   15010: }
                   15011: 
1.327     albertel 15012: # ------------------------------------------------------------ Read domain file
                   15013: {
1.852     albertel 15014:     my $loaded;
1.846     albertel 15015:     my %domain;
                   15016: 
1.852     albertel 15017:     sub parse_domain_tab {
                   15018: 	my ($lines) = @_;
                   15019: 	foreach my $line (@$lines) {
                   15020: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      15021: 
1.846     albertel 15022: 	    chomp($line);
1.852     albertel 15023: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 15024: 	    my %this_domain;
                   15025: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   15026: 			       'lang_def', 'city', 'longi', 'lati',
                   15027: 			       'primary') {
                   15028: 		$this_domain{$field} = shift(@elements);
                   15029: 	    }
                   15030: 	    $domain{$name} = \%this_domain;
1.852     albertel 15031: 	}
                   15032:     }
1.864     albertel 15033: 
                   15034:     sub reset_domain_info {
                   15035: 	undef($loaded);
                   15036: 	undef(%domain);
                   15037:     }
                   15038: 
1.852     albertel 15039:     sub load_domain_tab {
1.1293    raeburn  15040: 	my ($ignore_cache,$nocache) = @_;
                   15041: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 15042: 	my $fh;
1.1359    raeburn  15043: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 15044: 	    my @lines = <$fh>;
                   15045: 	    &parse_domain_tab(\@lines);
1.448     albertel 15046: 	}
1.852     albertel 15047: 	close($fh);
                   15048: 	$loaded = 1;
1.327     albertel 15049:     }
1.846     albertel 15050: 
                   15051:     sub domain {
1.852     albertel 15052: 	&load_domain_tab() if (!$loaded);
                   15053: 
1.846     albertel 15054: 	my ($name,$what) = @_;
                   15055: 	return if ( !exists($domain{$name}) );
                   15056: 
                   15057: 	if (!$what) {
                   15058: 	    return $domain{$name}{'description'};
                   15059: 	}
                   15060: 	return $domain{$name}{$what};
                   15061:     }
1.974     raeburn  15062: 
                   15063:     sub domain_info {
                   15064:         &load_domain_tab() if (!$loaded);
                   15065:         return %domain;
                   15066:     }
                   15067: 
1.327     albertel 15068: }
                   15069: 
                   15070: 
1.1       albertel 15071: # ------------------------------------------------------------- Read hosts file
                   15072: {
1.838     albertel 15073:     my %hostname;
1.844     albertel 15074:     my %hostdom;
1.845     albertel 15075:     my %libserv;
1.852     albertel 15076:     my $loaded;
1.888     albertel 15077:     my %name_to_host;
1.1074    raeburn  15078:     my %internetdom;
1.1107    raeburn  15079:     my %LC_dns_serv;
1.852     albertel 15080: 
                   15081:     sub parse_hosts_tab {
                   15082: 	my ($file) = @_;
                   15083: 	foreach my $configline (@$file) {
                   15084: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  15085:             chomp($configline);
                   15086: 	    if ($configline =~ /^\^/) {
                   15087:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   15088:                     $LC_dns_serv{$1} = 1;
                   15089:                 }
                   15090:                 next;
                   15091:             }
1.1074    raeburn  15092: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 15093: 	    $name=~s/\s//g;
                   15094: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  15095:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   15096:                     my $curr = $hostname{$id};
                   15097:                     my $skip;
                   15098:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   15099:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   15100:                             $skip = 1;
                   15101:                         } else {
                   15102:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   15103:                         }
                   15104:                     }
                   15105:                     unless ($skip) {
                   15106:                         push(@{$name_to_host{$name}},$id);
                   15107:                     }
                   15108:                 } else {
                   15109:                     push(@{$name_to_host{$name}},$id);
                   15110:                 }
1.852     albertel 15111: 		$hostname{$id}=$name;
                   15112: 		$hostdom{$id}=$domain;
                   15113: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  15114:                 if (defined($protocol)) {
                   15115:                     if ($protocol eq 'https') {
                   15116:                         $protocol{$id} = $protocol;
                   15117:                     } else {
                   15118:                         $protocol{$id} = 'http'; 
                   15119:                     }
1.968     raeburn  15120:                 } else {
1.969     raeburn  15121:                     $protocol{$id} = 'http';
1.968     raeburn  15122:                 }
1.1074    raeburn  15123:                 if (defined($intdom)) {
                   15124:                     $internetdom{$id} = $intdom;
                   15125:                 }
1.852     albertel 15126: 	    }
                   15127: 	}
                   15128:     }
1.864     albertel 15129:     
                   15130:     sub reset_hosts_info {
1.897     albertel 15131: 	&purge_remembered();
1.864     albertel 15132: 	&reset_domain_info();
                   15133: 	&reset_hosts_ip_info();
1.1339    raeburn  15134:         undef(%internetdom);
1.892     albertel 15135: 	undef(%name_to_host);
1.864     albertel 15136: 	undef(%hostname);
                   15137: 	undef(%hostdom);
                   15138: 	undef(%libserv);
                   15139: 	undef($loaded);
                   15140:     }
1.1       albertel 15141: 
1.852     albertel 15142:     sub load_hosts_tab {
1.1293    raeburn  15143: 	my ($ignore_cache,$nocache) = @_;
                   15144: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  15145: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 15146: 	my @config = <$config>;
                   15147: 	&parse_hosts_tab(\@config);
                   15148: 	close($config);
                   15149: 	$loaded=1;
1.1       albertel 15150:     }
1.852     albertel 15151: 
1.838     albertel 15152:     sub hostname {
1.852     albertel 15153: 	&load_hosts_tab() if (!$loaded);
                   15154: 
1.838     albertel 15155: 	my ($lonid) = @_;
                   15156: 	return $hostname{$lonid};
                   15157:     }
1.845     albertel 15158: 
1.838     albertel 15159:     sub all_hostnames {
1.852     albertel 15160: 	&load_hosts_tab() if (!$loaded);
                   15161: 
1.838     albertel 15162: 	return %hostname;
                   15163:     }
1.845     albertel 15164: 
1.888     albertel 15165:     sub all_names {
1.1293    raeburn  15166:         my ($ignore_cache,$nocache) = @_;
                   15167: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 15168: 
                   15169: 	return %name_to_host;
                   15170:     }
                   15171: 
1.974     raeburn  15172:     sub all_host_domain {
                   15173:         &load_hosts_tab() if (!$loaded);
                   15174:         return %hostdom;
                   15175:     }
                   15176: 
1.1339    raeburn  15177:     sub all_host_intdom {
                   15178:         &load_hosts_tab() if (!$loaded);
                   15179:         return %internetdom;
                   15180:     }
                   15181: 
1.845     albertel 15182:     sub is_library {
1.852     albertel 15183: 	&load_hosts_tab() if (!$loaded);
                   15184: 
1.845     albertel 15185: 	return exists($libserv{$_[0]});
                   15186:     }
                   15187: 
                   15188:     sub all_library {
1.852     albertel 15189: 	&load_hosts_tab() if (!$loaded);
                   15190: 
1.845     albertel 15191: 	return %libserv;
                   15192:     }
                   15193: 
1.1062    droeschl 15194:     sub unique_library {
                   15195: 	#2x reverse removes all hostnames that appear more than once
                   15196:         my %unique = reverse &all_library();
                   15197:         return reverse %unique;
                   15198:     }
                   15199: 
1.841     albertel 15200:     sub get_servers {
1.852     albertel 15201: 	&load_hosts_tab() if (!$loaded);
                   15202: 
1.841     albertel 15203: 	my ($domain,$type) = @_;
                   15204: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   15205: 	                                          : %hostname;
                   15206: 	my %result;
1.842     albertel 15207: 	if (ref($domain) eq 'ARRAY') {
                   15208: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 15209: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 15210: 		    $result{$host} = $hostname;
                   15211: 		}
                   15212: 	    }
                   15213: 	} else {
                   15214: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   15215: 		if ($hostdom{$host} eq $domain) {
                   15216: 		    $result{$host} = $hostname;
                   15217: 		}
1.841     albertel 15218: 	    }
                   15219: 	}
                   15220: 	return %result;
                   15221:     }
1.845     albertel 15222: 
1.1062    droeschl 15223:     sub get_unique_servers {
                   15224:         my %unique = reverse &get_servers(@_);
                   15225: 	return reverse %unique;
                   15226:     }
                   15227: 
1.844     albertel 15228:     sub host_domain {
1.852     albertel 15229: 	&load_hosts_tab() if (!$loaded);
                   15230: 
1.844     albertel 15231: 	my ($lonid) = @_;
                   15232: 	return $hostdom{$lonid};
                   15233:     }
                   15234: 
1.841     albertel 15235:     sub all_domains {
1.852     albertel 15236: 	&load_hosts_tab() if (!$loaded);
                   15237: 
1.841     albertel 15238: 	my %seen;
                   15239: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   15240: 	return @uniq;
                   15241:     }
1.1074    raeburn  15242: 
                   15243:     sub internet_dom {
                   15244:         &load_hosts_tab() if (!$loaded);
                   15245: 
                   15246:         my ($lonid) = @_;
                   15247:         return $internetdom{$lonid};
                   15248:     }
1.1107    raeburn  15249: 
                   15250:     sub is_LC_dns {
                   15251:         &load_hosts_tab() if (!$loaded);
                   15252: 
                   15253:         my ($hostname) = @_;
                   15254:         return exists($LC_dns_serv{$hostname});
                   15255:     }
                   15256: 
1.1       albertel 15257: }
                   15258: 
1.847     albertel 15259: { 
                   15260:     my %iphost;
1.856     albertel 15261:     my %name_to_ip;
                   15262:     my %lonid_to_ip;
1.869     albertel 15263: 
1.847     albertel 15264:     sub get_hosts_from_ip {
                   15265: 	my ($ip) = @_;
                   15266: 	my %iphosts = &get_iphost();
                   15267: 	if (ref($iphosts{$ip})) {
                   15268: 	    return @{$iphosts{$ip}};
                   15269: 	}
                   15270: 	return;
1.839     albertel 15271:     }
1.864     albertel 15272:     
                   15273:     sub reset_hosts_ip_info {
                   15274: 	undef(%iphost);
                   15275: 	undef(%name_to_ip);
                   15276: 	undef(%lonid_to_ip);
                   15277:     }
1.856     albertel 15278: 
                   15279:     sub get_host_ip {
                   15280: 	my ($lonid) = @_;
                   15281: 	if (exists($lonid_to_ip{$lonid})) {
                   15282: 	    return $lonid_to_ip{$lonid};
                   15283: 	}
                   15284: 	my $name=&hostname($lonid);
                   15285:    	my $ip = gethostbyname($name);
                   15286: 	return if (!$ip || length($ip) ne 4);
                   15287: 	$ip=inet_ntoa($ip);
                   15288: 	$name_to_ip{$name}   = $ip;
                   15289: 	$lonid_to_ip{$lonid} = $ip;
                   15290: 	return $ip;
                   15291:     }
1.847     albertel 15292:     
                   15293:     sub get_iphost {
1.1293    raeburn  15294: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 15295: 
1.869     albertel 15296: 	if (!$ignore_cache) {
                   15297: 	    if (%iphost) {
                   15298: 		return %iphost;
                   15299: 	    }
                   15300: 	    my ($ip_info,$cached)=
                   15301: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   15302: 	    if ($cached) {
                   15303: 		%iphost      = %{$ip_info->[0]};
                   15304: 		%name_to_ip  = %{$ip_info->[1]};
                   15305: 		%lonid_to_ip = %{$ip_info->[2]};
                   15306: 		return %iphost;
                   15307: 	    }
                   15308: 	}
1.894     albertel 15309: 
                   15310: 	# get yesterday's info for fallback
                   15311: 	my %old_name_to_ip;
                   15312: 	my ($ip_info,$cached)=
                   15313: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   15314: 	if ($cached) {
                   15315: 	    %old_name_to_ip = %{$ip_info->[1]};
                   15316: 	}
                   15317: 
1.1293    raeburn  15318: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 15319: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 15320: 	    my $ip;
                   15321: 	    if (!exists($name_to_ip{$name})) {
                   15322: 		$ip = gethostbyname($name);
                   15323: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 15324: 		    if (defined($old_name_to_ip{$name})) {
                   15325: 			$ip = $old_name_to_ip{$name};
                   15326: 			&logthis("Can't find $name defaulting to old $ip");
                   15327: 		    } else {
                   15328: 			&logthis("Name $name no IP found");
                   15329: 			next;
                   15330: 		    }
                   15331: 		} else {
                   15332: 		    $ip=inet_ntoa($ip);
1.847     albertel 15333: 		}
                   15334: 		$name_to_ip{$name} = $ip;
                   15335: 	    } else {
                   15336: 		$ip = $name_to_ip{$name};
1.653     albertel 15337: 	    }
1.888     albertel 15338: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   15339: 		$lonid_to_ip{$id} = $ip;
                   15340: 	    }
                   15341: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 15342: 	}
1.1293    raeburn  15343:         unless ($nocache) {
                   15344: 	    &do_cache_new('iphost','iphost',
                   15345: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   15346: 		          48*60*60);
                   15347:         }
1.869     albertel 15348: 
1.847     albertel 15349: 	return %iphost;
1.598     albertel 15350:     }
                   15351: 
1.992     raeburn  15352:     #
                   15353:     #  Given a DNS returns the loncapa host name for that DNS 
                   15354:     # 
                   15355:     sub host_from_dns {
                   15356:         my ($dns) = @_;
                   15357:         my @hosts;
                   15358:         my $ip;
                   15359: 
1.993     raeburn  15360:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  15361:             $ip = $name_to_ip{$dns};
                   15362:         }
                   15363:         if (!$ip) {
                   15364:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   15365:             if (length($ip) == 4) { 
                   15366: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   15367:             }
                   15368:         }
                   15369:         if ($ip) {
                   15370: 	    @hosts = get_hosts_from_ip($ip);
                   15371: 	    return $hosts[0];
                   15372:         }
                   15373:         return undef;
1.986     foxr     15374:     }
1.992     raeburn  15375: 
1.1074    raeburn  15376:     sub get_internet_names {
                   15377:         my ($lonid) = @_;
                   15378:         return if ($lonid eq '');
                   15379:         my ($idnref,$cached)=
                   15380:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   15381:         if ($cached) {
                   15382:             return $idnref;
                   15383:         }
                   15384:         my $ip = &get_host_ip($lonid);
                   15385:         my @hosts = &get_hosts_from_ip($ip);
                   15386:         my %iphost = &get_iphost();
                   15387:         my (@idns,%seen);
                   15388:         foreach my $id (@hosts) {
                   15389:             my $dom = &host_domain($id);
                   15390:             my $prim_id = &domain($dom,'primary');
                   15391:             my $prim_ip = &get_host_ip($prim_id);
                   15392:             next if ($seen{$prim_ip});
                   15393:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   15394:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   15395:                     my $intdom = &internet_dom($id);
                   15396:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   15397:                         push(@idns,$intdom);
                   15398:                     }
                   15399:                 }
                   15400:             }
                   15401:             $seen{$prim_ip} = 1;
                   15402:         }
1.1219    raeburn  15403:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15404:     }
                   15405: 
1.986     foxr     15406: }
                   15407: 
1.1079    raeburn  15408: sub all_loncaparevs {
1.1249    raeburn  15409:     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  15410: }
                   15411: 
1.1227    raeburn  15412: # ---------------------------------------------------------- Read loncaparev table
                   15413: {
                   15414:     sub load_loncaparevs { 
                   15415:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  15416:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  15417:                 while (my $configline=<$config>) {
                   15418:                     chomp($configline);
                   15419:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15420:                     $loncaparevs{$hostid}=$loncaparev;
                   15421:                 }
                   15422:                 close($config);
                   15423:             }
                   15424:         }
                   15425:     }
                   15426: }
                   15427: 
                   15428: # ---------------------------------------------------------- Read serverhostID table
                   15429: {
                   15430:     sub load_serverhomeIDs {
                   15431:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  15432:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  15433:                 while (my $configline=<$config>) {
                   15434:                     chomp($configline);
                   15435:                     my ($name,$id)=split(/:/,$configline);
                   15436:                     $serverhomeIDs{$name}=$id;
                   15437:                 }
                   15438:                 close($config);
                   15439:             }
                   15440:         }
                   15441:     }
                   15442: }
                   15443: 
                   15444: 
1.862     albertel 15445: BEGIN {
                   15446: 
                   15447: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15448:     unless ($readit) {
                   15449: {
                   15450:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15451:     %perlvar = (%perlvar,%{$configvars});
                   15452: }
                   15453: 
                   15454: 
1.1       albertel 15455: # ------------------------------------------------------ Read spare server file
                   15456: {
1.1359    raeburn  15457:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15458: 
                   15459:     while (my $configline=<$config>) {
                   15460:        chomp($configline);
1.284     matthew  15461:        if ($configline) {
1.784     albertel 15462: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15463: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15464: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15465:        }
                   15466:     }
1.448     albertel 15467:     close($config);
1.1       albertel 15468: }
1.11      www      15469: # ------------------------------------------------------------ Read permissions
                   15470: {
1.1359    raeburn  15471:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15472: 
                   15473:     while (my $configline=<$config>) {
1.448     albertel 15474: 	chomp($configline);
                   15475: 	if ($configline) {
                   15476: 	    my ($role,$perm)=split(/ /,$configline);
                   15477: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15478: 	}
1.11      www      15479:     }
1.448     albertel 15480:     close($config);
1.11      www      15481: }
                   15482: 
                   15483: # -------------------------------------------- Read plain texts for permissions
                   15484: {
1.1359    raeburn  15485:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15486: 
                   15487:     while (my $configline=<$config>) {
1.448     albertel 15488: 	chomp($configline);
                   15489: 	if ($configline) {
1.742     raeburn  15490: 	    my ($short,@plain)=split(/:/,$configline);
                   15491:             %{$prp{$short}} = ();
                   15492: 	    if (@plain > 0) {
                   15493:                 $prp{$short}{'std'} = $plain[0];
                   15494:                 for (my $i=1; $i<@plain; $i++) {
                   15495:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15496:                 }
                   15497:             }
1.448     albertel 15498: 	}
1.135     www      15499:     }
1.448     albertel 15500:     close($config);
1.135     www      15501: }
                   15502: 
                   15503: # ---------------------------------------------------------- Read package table
                   15504: {
1.1359    raeburn  15505:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15506: 
                   15507:     while (my $configline=<$config>) {
1.483     albertel 15508: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15509: 	chomp($configline);
                   15510: 	my ($short,$plain)=split(/:/,$configline);
                   15511: 	my ($pack,$name)=split(/\&/,$short);
                   15512: 	if ($plain ne '') {
                   15513: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15514: 	    $packagetab{$short}=$plain; 
                   15515: 	}
1.11      www      15516:     }
1.448     albertel 15517:     close($config);
1.329     matthew  15518: }
                   15519: 
1.1073    raeburn  15520: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  15521: 
                   15522: &load_loncaparevs();
1.1073    raeburn  15523: 
1.1074    raeburn  15524: # ---------------------------------------------------------- Read serverhostID table
                   15525: 
1.1227    raeburn  15526: &load_serverhomeIDs();
                   15527: 
                   15528: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15529: {
                   15530:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15531:     if (-e $file) {
                   15532:         my $parser = HTML::LCParser->new($file);
                   15533:         while (my $token = $parser->get_token()) {
                   15534:             if ($token->[0] eq 'S') {
                   15535:                 my $item = $token->[1];
                   15536:                 my $name = $token->[2]{'name'};
                   15537:                 my $value = $token->[2]{'value'};
1.1285    raeburn  15538:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  15539:                 my $namematch = $token->[2]{'namematch'};
                   15540:                 if ($item eq 'parameter') {
                   15541:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   15542:                         my $release = $parser->get_text();
                   15543:                         $release =~ s/(^\s*|\s*$ )//gx;
                   15544:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   15545:                     }
                   15546:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  15547:                     my $release = $parser->get_text();
                   15548:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  15549:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  15550:                 }
                   15551:             }
                   15552:         }
                   15553:     }
1.1073    raeburn  15554: }
                   15555: 
1.1138    raeburn  15556: # ---------------------------------------------------------- Read managers table
                   15557: {
                   15558:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  15559:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15560:             while (my $configline=<$config>) {
                   15561:                 chomp($configline);
                   15562:                 next if ($configline =~ /^\#/);
                   15563:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15564:                     $managerstab{$configline} = 1;
                   15565:                 }
                   15566:             }
                   15567:             close($config);
                   15568:         }
                   15569:     }
                   15570: }
                   15571: 
1.329     matthew  15572: # ------------- set up temporary directory
                   15573: {
1.1117    foxr     15574:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15575: 
1.11      www      15576: }
                   15577: 
1.1405    raeburn  15578: # ------------- set default texengine (domain default overrides this)
                   15579: {
                   15580:     $deftex = LONCAPA::texengine();
                   15581: }
                   15582: 
1.1416    raeburn  15583: # ------------- set default minimum length for passwords for internal auth users
                   15584: {
                   15585:     $passwdmin = LONCAPA::passwd_min();
                   15586: }
                   15587: 
1.794     albertel 15588: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15589: 				'compress_threshold'=> 20_000,
                   15590:  			        });
1.185     www      15591: 
1.281     www      15592: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15593: $dumpcount=0;
1.958     www      15594: $locknum=0;
1.22      www      15595: 
1.163     harris41 15596: &logtouch();
1.672     albertel 15597: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15598: $readit=1;
1.564     albertel 15599:     {
                   15600: 	use integer;
                   15601: 	my $test=(2**32)+1;
1.568     albertel 15602: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15603: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15604:     }
1.195     www      15605: }
1.1       albertel 15606: }
1.179     www      15607: 
1.1       albertel 15608: 1;
1.191     harris41 15609: __END__
                   15610: 
1.243     albertel 15611: =pod
                   15612: 
1.191     harris41 15613: =head1 NAME
                   15614: 
1.243     albertel 15615: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15616: 
                   15617: =head1 SYNOPSIS
                   15618: 
1.243     albertel 15619: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15620: 
                   15621:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15622: 
1.243     albertel 15623: Common parameters:
                   15624: 
                   15625: =over 4
                   15626: 
                   15627: =item *
                   15628: 
                   15629: $uname : an internal username (if $cname expecting a course Id specifically)
                   15630: 
                   15631: =item *
                   15632: 
                   15633: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15634: 
                   15635: =item *
                   15636: 
                   15637: $symb : a resource instance identifier
                   15638: 
                   15639: =item *
                   15640: 
                   15641: $namespace : the name of a .db file that contains the data needed or
                   15642: being set.
                   15643: 
                   15644: =back
                   15645: 
1.394     bowersj2 15646: =head1 OVERVIEW
1.191     harris41 15647: 
1.394     bowersj2 15648: lonnet provides subroutines which interact with the
                   15649: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15650: about classes, users, and resources.
1.243     albertel 15651: 
                   15652: For many of these objects you can also use this to store data about
                   15653: them or modify them in various ways.
1.191     harris41 15654: 
1.394     bowersj2 15655: =head2 Symbs
1.191     harris41 15656: 
1.394     bowersj2 15657: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15658: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15659: map, the resource number of the resource in the map, and the URL of
                   15660: the resource itself. The latter is somewhat redundant, but might help
                   15661: if maps change.
                   15662: 
                   15663: An example is
                   15664: 
                   15665:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15666: 
                   15667: The respective map entry is
                   15668: 
                   15669:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15670:   title="Problem 2">
                   15671:  </resource>
                   15672: 
                   15673: Symbs are used by the random number generator, as well as to store and
                   15674: restore data specific to a certain instance of for example a problem.
                   15675: 
                   15676: =head2 Storing And Retrieving Data
                   15677: 
                   15678: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15679: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15680: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15681: is is the non-critical message twin of cstore. These functions are for
                   15682: handlers to store a perl hash to a user's permanent data space in an
                   15683: easy manner, and to retrieve it again on another call. It is expected
                   15684: that a handler would use this once at the beginning to retrieve data,
                   15685: and then again once at the end to send only the new data back.
                   15686: 
                   15687: The data is stored in the user's data directory on the user's
                   15688: homeserver under the ID of the course.
                   15689: 
                   15690: The hash that is returned by restore will have all of the previous
                   15691: value for all of the elements of the hash.
                   15692: 
                   15693: Example:
                   15694: 
                   15695:  #creating a hash
                   15696:  my %hash;
                   15697:  $hash{'foo'}='bar';
                   15698: 
                   15699:  #storing it
                   15700:  &Apache::lonnet::cstore(\%hash);
                   15701: 
                   15702:  #changing a value
                   15703:  $hash{'foo'}='notbar';
                   15704: 
                   15705:  #adding a new value
                   15706:  $hash{'bar'}='foo';
                   15707:  &Apache::lonnet::cstore(\%hash);
                   15708: 
                   15709:  #retrieving the hash
                   15710:  my %history=&Apache::lonnet::restore();
                   15711: 
                   15712:  #print the hash
                   15713:  foreach my $key (sort(keys(%history))) {
                   15714:    print("\%history{$key} = $history{$key}");
                   15715:  }
                   15716: 
                   15717: Will print out:
1.191     harris41 15718: 
1.394     bowersj2 15719:  %history{1:foo} = bar
                   15720:  %history{1:keys} = foo:timestamp
                   15721:  %history{1:timestamp} = 990455579
                   15722:  %history{2:bar} = foo
                   15723:  %history{2:foo} = notbar
                   15724:  %history{2:keys} = foo:bar:timestamp
                   15725:  %history{2:timestamp} = 990455580
                   15726:  %history{bar} = foo
                   15727:  %history{foo} = notbar
                   15728:  %history{timestamp} = 990455580
                   15729:  %history{version} = 2
                   15730: 
                   15731: Note that the special hash entries C<keys>, C<version> and
                   15732: C<timestamp> were added to the hash. C<version> will be equal to the
                   15733: total number of versions of the data that have been stored. The
                   15734: C<timestamp> attribute will be the UNIX time the hash was
                   15735: stored. C<keys> is available in every historical section to list which
                   15736: keys were added or changed at a specific historical revision of a
                   15737: hash.
                   15738: 
                   15739: B<Warning>: do not store the hash that restore returns directly. This
                   15740: will cause a mess since it will restore the historical keys as if the
                   15741: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15742: 
1.394     bowersj2 15743: Calling convention:
1.191     harris41 15744: 
1.1225    raeburn  15745:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  15746:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15747: 
1.394     bowersj2 15748: For more detailed information, see lonnet specific documentation.
1.191     harris41 15749: 
1.394     bowersj2 15750: =head1 RETURN MESSAGES
1.191     harris41 15751: 
1.394     bowersj2 15752: =over 4
1.191     harris41 15753: 
1.394     bowersj2 15754: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15755: 
1.394     bowersj2 15756: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15757: when the connection is brought back up
1.191     harris41 15758: 
1.394     bowersj2 15759: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15760: for later delivery
1.191     harris41 15761: 
1.967     bisitz   15762: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15763: 
1.394     bowersj2 15764: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15765: that was requested
1.191     harris41 15766: 
1.243     albertel 15767: =back
1.191     harris41 15768: 
1.243     albertel 15769: =head1 PUBLIC SUBROUTINES
1.191     harris41 15770: 
1.243     albertel 15771: =head2 Session Environment Functions
1.191     harris41 15772: 
1.243     albertel 15773: =over 4
1.191     harris41 15774: 
1.394     bowersj2 15775: =item * 
                   15776: X<appenv()>
1.949     raeburn  15777: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15778: the user envirnoment file, and will be restored for each access this
1.620     albertel 15779: user makes during this session, also modifies the %env for the current
1.949     raeburn  15780: process. Optional rolesarrayref - if defined contains a reference to an array
                   15781: of roles which are exempt from the restriction on modifying user.role entries 
                   15782: in the user's environment.db and in %env.    
1.191     harris41 15783: 
                   15784: =item *
1.394     bowersj2 15785: X<delenv()>
1.987     raeburn  15786: B<delenv($delthis,$regexp)>: removes all items from the session
                   15787: environment file that begin with $delthis. If the 
                   15788: optional second arg - $regexp - is true, $delthis is treated as a 
                   15789: regular expression, otherwise \Q$delthis\E is used. 
                   15790: The values are also deleted from the current processes %env.
1.191     harris41 15791: 
1.795     albertel 15792: =item * get_env_multiple($name) 
                   15793: 
                   15794: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15795: values may be defined and end up as an array ref.
                   15796: 
                   15797: returns an array of values
                   15798: 
1.243     albertel 15799: =back
                   15800: 
                   15801: =head2 User Information
1.191     harris41 15802: 
1.243     albertel 15803: =over 4
1.191     harris41 15804: 
                   15805: =item *
1.394     bowersj2 15806: X<queryauthenticate()>
                   15807: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15808: authentication scheme
                   15809: 
                   15810: =item *
1.394     bowersj2 15811: X<authenticate()>
1.1073    raeburn  15812: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15813: authenticate user from domain's lib servers (first use the current
                   15814: one). C<$upass> should be the users password.
1.1073    raeburn  15815: $checkdefauth is optional (value is 1 if a check should be made to
                   15816:    authenticate user using default authentication method, and allow
                   15817:    account creation if username does not have account in the domain).
                   15818: $clientcancheckhost is optional (value is 1 if checking whether the
                   15819:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15820: 
                   15821: =item *
1.394     bowersj2 15822: X<homeserver()>
                   15823: B<homeserver($uname,$udom)>: find the server which has
                   15824: the user's directory and files (there must be only one), this caches
                   15825: the answer, and also caches if there is a borken connection.
1.191     harris41 15826: 
                   15827: =item *
1.394     bowersj2 15828: X<idget()>
1.1300    raeburn  15829: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   15830: a list of student/employee IDs or clicker IDs
                   15831: (student/employee IDs are a unique resource in a domain, there must be 
                   15832: only 1 ID per username, and only 1 username per ID in a specific domain).
                   15833: clickerIDs are not necessarily unique, as students might share clickers.
                   15834: (returns hash: id=>name,id=>name)
1.191     harris41 15835: 
                   15836: =item *
1.394     bowersj2 15837: X<idrget()>
                   15838: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15839: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15840: 
                   15841: =item *
1.394     bowersj2 15842: X<idput()>
1.1300    raeburn  15843: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   15844: names and associated student/employee IDs or clicker IDs.
                   15845: 
                   15846: =item *
                   15847: X<iddel()>
                   15848: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   15849: student/employee ID or clicker ID username look-ups from domain.
                   15850: The homeserver ($uhome) and namespace ($namespace) are optional.
                   15851: If no $uhome is provided, it will be determined usig &homeserver()
                   15852: for each user.  If no $namespace is provided, the default is ids.
                   15853: 
                   15854: =item *
                   15855: X<updateclickers()>
                   15856: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   15857: clicker ID-to-username look-ups in clickers.db on library server.
                   15858: Permitted actions are add or del (i.e., add or delete). The 
                   15859: clickers.db contains clickerID as keys (escaped), and each corresponding
                   15860: value is an escaped comma-separated list of usernames (for whom the
                   15861: library server is the homeserver), who registered that particular ID.
                   15862: If $critical is true, the update will be sent via &critical, otherwise
                   15863: &reply() will be used.
1.191     harris41 15864: 
                   15865: =item *
1.394     bowersj2 15866: X<rolesinit()>
1.1169    droeschl 15867: B<rolesinit($udom,$username)>: get user privileges.
                   15868: returns user role, first access and timer interval hashes
1.243     albertel 15869: 
                   15870: =item *
1.1171    droeschl 15871: X<privileged()>
                   15872: B<privileged($username,$domain)>: returns a true if user has a
                   15873: privileged and active role (i.e. su or dc), false otherwise.
                   15874: 
                   15875: =item *
1.551     albertel 15876: X<getsection()>
                   15877: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15878: course $cname, return section name/number or '' for "not in course"
                   15879: and '-1' for "no section"
                   15880: 
                   15881: =item *
1.394     bowersj2 15882: X<userenvironment()>
                   15883: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15884: passed in @what from the requested user's environment, returns a hash
                   15885: 
1.858     raeburn  15886: =item * 
                   15887: X<userlog_query()>
1.859     albertel 15888: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15889: activity.log file. %filters defines filters applied when parsing the
                   15890: log file. These can be start or end timestamps, or the type of action
                   15891: - log to look for Login or Logout events, check for Checkin or
                   15892: Checkout, role for role selection. The response is in the form
                   15893: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15894: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15895: 
1.243     albertel 15896: =back
                   15897: 
                   15898: =head2 User Roles
                   15899: 
                   15900: =over 4
                   15901: 
                   15902: =item *
                   15903: 
1.1284    raeburn  15904: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15905: returns codes for allowed actions.
                   15906: 
                   15907: The first argument is required, all others are optional.
                   15908: 
                   15909: $priv is the privilege being checked.
                   15910: $uri contains additional information about what is being checked for access (e.g.,
                   15911: URL, course ID etc.). 
                   15912: $symb is the unique resource instance identifier in a course; if needed,
                   15913: but not provided, it will be retrieved via a call to &symbread(). 
                   15914: $role is the role for which a priv is being checked (only used if priv is evb). 
                   15915: $clientip is the user's IP address (only used when checking for access to portfolio 
                   15916: files).
                   15917: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   15918: prevents recursive calls to &allowed.
                   15919: 
1.243     albertel 15920:  F: full access
                   15921:  U,I,K: authentication modes (cxx only)
                   15922:  '': forbidden
                   15923:  1: user needs to choose course
                   15924:  2: browse allowed
1.766     albertel 15925:  A: passphrase authentication needed
1.1284    raeburn  15926:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  15927:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 15928: 
                   15929: =item *
                   15930: 
1.1192    raeburn  15931: constructaccess($url,$setpriv) : check for access to construction space URL
                   15932: 
                   15933: See if the owner domain and name in the URL match those in the
                   15934: expected environment.  If so, return three element list
                   15935: ($ownername,$ownerdomain,$ownerhome).
                   15936: 
                   15937: Otherwise return the null string.
                   15938: 
                   15939: If second argument 'setpriv' is true, it assigns the privileges,
                   15940: and returns the same three element list, unless the owner has
                   15941: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15942: in which case the null string is returned.
                   15943: 
                   15944: =item *
                   15945: 
1.1326    raeburn  15946: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15947: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15948: for system, domain, and course level. $uname and $udom are optional (current
                   15949: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15950: 
                   15951: =item *
                   15952: 
1.988     raeburn  15953: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15954: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15955: $type is Course (default) or Community.
1.988     raeburn  15956: If $forcedefault evaluates to true, text returned will be default 
                   15957: text for $type. Otherwise, if this is a course, the text returned 
                   15958: will be a custom name for the role (if defined in the course's 
                   15959: environment).  If no custom name is defined the default is returned.
                   15960:    
1.832     raeburn  15961: =item *
                   15962: 
1.1219    raeburn  15963: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15964: All arguments are optional. Returns a hash of a roles, either for
                   15965: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15966: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15967: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15968: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15969: For each key, value is set to colon-separated start and end times for
                   15970: the role.  If no username and domain are specified, will default to
1.934     raeburn  15971: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15972: of role statuses (active, future or previous), roles 
                   15973: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15974: to restrict the list of roles reported. If no array ref is 
                   15975: provided for types, will default to return only active roles.
1.834     albertel 15976: 
1.1195    raeburn  15977: =item *
                   15978: 
                   15979: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  15980: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   15981: 
                   15982: Additional optional arguments are: $type (if role checking is to be restricted 
                   15983: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  15984: available roles) or future (roles available in the future), and
                   15985: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  15986: have active Domain Coordinator role in course's domain or in additional
                   15987: domains (specified in 'Domains to check for privileged users' in course
                   15988: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15989: 
                   15990: =item *
                   15991: 
                   15992: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15993: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15994: $possdomains and $possroles are optional array refs -- to domains to check and
                   15995: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15996: users' roles.db to check for a dc or su role in any domain. This can be
                   15997: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15998: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15999: this then allows &privileged_by_domain() to be used, which caches the identity
                   16000: of privileged users, eliminating the need for repeated calls to &dump().
                   16001: 
                   16002: =item *
                   16003: 
                   16004: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   16005: where the outer hash keys are domains specified in the $possdomains array ref,
                   16006: next inner hash keys are privileged roles specified in the $roles array ref,
                   16007: and the innermost hash contains key = value pairs for username:domain = end:start
                   16008: for active or future "privileged" users with that role in that domain. To avoid
                   16009: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   16010: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  16011: 
1.243     albertel 16012: =back
                   16013: 
                   16014: =head2 User Modification
                   16015: 
                   16016: =over 4
                   16017: 
                   16018: =item *
                   16019: 
1.957     raeburn  16020: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 16021: user for the level given by URL.  Optional start and end dates (leave empty
                   16022: string or zero for "no date")
1.191     harris41 16023: 
                   16024: =item *
                   16025: 
1.243     albertel 16026: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   16027: change a users, password, possible return values are: ok,
                   16028: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   16029: refused
1.191     harris41 16030: 
                   16031: =item *
                   16032: 
1.243     albertel 16033: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 16034: 
                   16035: =item *
                   16036: 
1.1058    raeburn  16037: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   16038:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   16039: 
                   16040: will update user information (firstname,middlename,lastname,generation,
                   16041: permanentemail), and if forceid is true, student/employee ID also.
                   16042: A user's institutional affiliation(s) can also be updated.
                   16043: User information fields will not be overwritten with empty entries 
                   16044: unless the field is included in the $candelete array reference.
                   16045: This array is included when a single user is modified via "Manage Users",
                   16046: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 16047: 
                   16048: =item *
                   16049: 
1.286     matthew  16050: modifystudent
                   16051: 
1.957     raeburn  16052: modify a student's enrollment and identification information.
1.1235    raeburn  16053: The course id is resolved based on the current user's environment.  
                   16054: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  16055: associated with a course.
                   16056: 
1.297     matthew  16057: This call is essentially a wrapper for lonnet::modifyuser and
                   16058: lonnet::modify_student_enrollment
1.286     matthew  16059: 
                   16060: Inputs: 
                   16061: 
                   16062: =over 4
                   16063: 
1.957     raeburn  16064: =item B<$udom> Student's loncapa domain
1.286     matthew  16065: 
1.957     raeburn  16066: =item B<$uname> Student's loncapa login name
1.286     matthew  16067: 
1.964     bisitz   16068: =item B<$uid> Student/Employee ID
1.286     matthew  16069: 
1.957     raeburn  16070: =item B<$umode> Student's authentication mode
1.286     matthew  16071: 
1.957     raeburn  16072: =item B<$upass> Student's password
1.286     matthew  16073: 
1.957     raeburn  16074: =item B<$first> Student's first name
1.286     matthew  16075: 
1.957     raeburn  16076: =item B<$middle> Student's middle name
1.286     matthew  16077: 
1.957     raeburn  16078: =item B<$last> Student's last name
1.286     matthew  16079: 
1.957     raeburn  16080: =item B<$gene> Student's generation
1.286     matthew  16081: 
1.957     raeburn  16082: =item B<$usec> Student's section in course
1.286     matthew  16083: 
                   16084: =item B<$end> Unix time of the roles expiration
                   16085: 
                   16086: =item B<$start> Unix time of the roles start date
                   16087: 
                   16088: =item B<$forceid> If defined, allow $uid to be changed
                   16089: 
                   16090: =item B<$desiredhome> server to use as home server for student
                   16091: 
1.957     raeburn  16092: =item B<$email> Student's permanent e-mail address
                   16093: 
                   16094: =item B<$type> Type of enrollment (auto or manual)
                   16095: 
1.963     raeburn  16096: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   16097: 
                   16098: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  16099: 
1.963     raeburn  16100: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  16101: 
1.963     raeburn  16102: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  16103: 
1.1216    raeburn  16104: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   16105: 
                   16106: =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  16107: 
1.286     matthew  16108: =back
1.297     matthew  16109: 
                   16110: =item *
                   16111: 
                   16112: modify_student_enrollment
                   16113: 
1.1235    raeburn  16114: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  16115: 'role.request.course' must be defined for this function to proceed.
                   16116: 
                   16117: Inputs:
                   16118: 
                   16119: =over 4
                   16120: 
1.1235    raeburn  16121: =item $udom, student's domain
1.297     matthew  16122: 
1.1235    raeburn  16123: =item $uname, student's name
1.297     matthew  16124: 
1.1235    raeburn  16125: =item $uid, student's user id
1.297     matthew  16126: 
1.1235    raeburn  16127: =item $first, student's first name
1.297     matthew  16128: 
                   16129: =item $middle
                   16130: 
                   16131: =item $last
                   16132: 
                   16133: =item $gene
                   16134: 
                   16135: =item $usec
                   16136: 
                   16137: =item $end
                   16138: 
                   16139: =item $start
                   16140: 
1.957     raeburn  16141: =item $type
                   16142: 
                   16143: =item $locktype
                   16144: 
                   16145: =item $cid
                   16146: 
                   16147: =item $selfenroll
                   16148: 
                   16149: =item $context
                   16150: 
1.1216    raeburn  16151: =item $credits, number of credits student will earn from this class
                   16152: 
1.1314    raeburn  16153: =item $instsec, institutional course section code for student
                   16154: 
1.297     matthew  16155: =back
                   16156: 
1.191     harris41 16157: 
                   16158: =item *
                   16159: 
1.243     albertel 16160: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   16161: custom role; give a custom role to a user for the level given by URL.  Specify
                   16162: name and domain of role author, and role name
1.191     harris41 16163: 
                   16164: =item *
                   16165: 
1.243     albertel 16166: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 16167: 
                   16168: =item *
                   16169: 
1.243     albertel 16170: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   16171: 
                   16172: =back
                   16173: 
                   16174: =head2 Course Infomation
                   16175: 
                   16176: =over 4
1.191     harris41 16177: 
                   16178: =item *
                   16179: 
1.1118    foxr     16180: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 16181: specified course id, including all environment settings for the
                   16182: course, the description of the course will be in the hash under the
                   16183: key 'description'
1.191     harris41 16184: 
1.1118    foxr     16185: $options is an optional parameter that if supplied is a hash reference that controls
                   16186: what how this function works.  It has the following key/values:
                   16187: 
                   16188: =over 4
                   16189: 
                   16190: =item freshen_cache
                   16191: 
                   16192: If defined, and the environment cache for the course is valid, it is 
                   16193: returned in the returned hash.
                   16194: 
                   16195: =item one_time
                   16196: 
                   16197: If defined, the last cache time is set to _now_
                   16198: 
                   16199: =item user
                   16200: 
                   16201: If defined, the supplied username is used instead of the current user.
                   16202: 
                   16203: 
                   16204: =back
                   16205: 
1.191     harris41 16206: =item *
                   16207: 
1.624     albertel 16208: resdata($name,$domain,$type,@which) : request for current parameter
                   16209: setting for a specific $type, where $type is either 'course' or 'user',
                   16210: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  16211: answers for 10 minutes.
1.243     albertel 16212: 
1.877     foxr     16213: =item *
                   16214: 
                   16215: get_courseresdata($courseid, $domain) : dump the entire course resource
                   16216: data base, returning a hash that is keyed by the resource name and has
                   16217: values that are the resource value.  I believe that the timestamps and
                   16218: versions are also returned.
                   16219: 
1.1236    raeburn  16220: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   16221: supplemental content area. This routine caches the number of files for 
                   16222: 10 minutes.
                   16223: 
1.243     albertel 16224: =back
                   16225: 
                   16226: =head2 Course Modification
                   16227: 
                   16228: =over 4
1.191     harris41 16229: 
                   16230: =item *
                   16231: 
1.243     albertel 16232: writecoursepref($courseid,%prefs) : write preferences (environment
                   16233: database) for a course
1.191     harris41 16234: 
                   16235: =item *
                   16236: 
1.1011    raeburn  16237: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   16238: 
                   16239: =item *
                   16240: 
1.1038    raeburn  16241: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 16242: 
1.1167    droeschl 16243: =item *
                   16244: 
                   16245: is_course($courseid), is_course($cdom, $cnum)
                   16246: 
                   16247: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   16248: two component version $cdom, $cnum. It checks if the specified course exists.
                   16249: 
                   16250: Returns:
                   16251:     undef if the course doesn't exist, otherwise
                   16252:     in scalar context the combined courseid.
                   16253:     in list context the two components of the course identifier, domain and 
                   16254:     courseid.    
                   16255: 
1.243     albertel 16256: =back
                   16257: 
1.1401    raeburn  16258: =head2 Bubblesheet Configuration
                   16259: 
                   16260: =over 4
                   16261: 
                   16262: =item *
                   16263: 
                   16264: get_scantron_config($which)
                   16265: 
                   16266: $which - the name of the configuration to parse from the file.
                   16267: 
                   16268: Parses and returns the bubblesheet configuration line selected as a
                   16269: hash of configuration file fields.
                   16270: 
                   16271: 
                   16272: Returns:
                   16273:     If the named configuration is not in the file, an empty
                   16274:     hash is returned.
                   16275: 
                   16276:     a hash with the fields
                   16277:       name         - internal name for the this configuration setup
                   16278:       description  - text to display to operator that describes this config
                   16279:       CODElocation - if 0 or the string 'none'
                   16280:                           - no CODE exists for this config
                   16281:                      if -1 || the string 'letter'
                   16282:                           - a CODE exists for this config and is
                   16283:                             a string of letters
                   16284:                      Unsupported value (but planned for future support)
                   16285:                           if a positive integer
                   16286:                                - The CODE exists as the first n items from
                   16287:                                  the question section of the form
                   16288:                           if the string 'number'
                   16289:                                - The CODE exists for this config and is
                   16290:                                  a string of numbers
                   16291:       CODEstart   - (only matter if a CODE exists) column in the line where
                   16292:                      the CODE starts
                   16293:       CODElength  - length of the CODE
                   16294:       IDstart     - column where the student/employee ID starts
                   16295:       IDlength    - length of the student/employee ID info
                   16296:       Qstart      - column where the information from the bubbled
                   16297:                     'questions' start
                   16298:       Qlength     - number of columns comprising a single bubble line from
                   16299:                     the sheet. (usually either 1 or 10)
                   16300:       Qon         - either a single character representing the character used
                   16301:                     to signal a bubble was chosen in the positional setup, or
                   16302:                     the string 'letter' if the letter of the chosen bubble is
                   16303:                     in the final, or 'number' if a number representing the
                   16304:                     chosen bubble is in the file (1->A 0->J)
                   16305:       Qoff        - the character used to represent that a bubble was
                   16306:                     left blank
                   16307:       PaperID     - if the scanning process generates a unique number for each
                   16308:                     sheet scanned the column that this ID number starts in
                   16309:       PaperIDlength - number of columns that comprise the unique ID number
                   16310:                       for the sheet of paper
                   16311:       FirstName   - column that the first name starts in
                   16312:       FirstNameLength - number of columns that the first name spans
                   16313:       LastName    - column that the last name starts in
                   16314:       LastNameLength - number of columns that the last name spans
                   16315:       BubblesPerRow - number of bubbles available in each row used to
                   16316:                       bubble an answer. (If not specified, 10 assumed).
                   16317: 
                   16318: 
                   16319: =item *
                   16320: 
                   16321: get_scantronformat_file($cdom)
                   16322: 
                   16323: $cdom - the course's domain (optional); if not supplied, uses
                   16324: domain for current $env{'request.course.id'}.
                   16325: 
                   16326: Returns an array containing lines from the scantron format file for
                   16327: the domain of the course.
                   16328: 
                   16329: If a url for a custom.tab file is listed in domain's configuration.db,
                   16330: lines are from this file.
                   16331: 
                   16332: Otherwise, if a default.tab has been published in RES space by the
                   16333: domainconfig user, lines are from this file.
                   16334: 
                   16335: Otherwise, fall back to getting lines from the legacy file on the
                   16336: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   16337: 
                   16338: =back
                   16339: 
1.243     albertel 16340: =head2 Resource Subroutines
                   16341: 
                   16342: =over 4
1.191     harris41 16343: 
                   16344: =item *
                   16345: 
1.243     albertel 16346: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 16347: 
                   16348: =item *
                   16349: 
1.243     albertel 16350: repcopy($filename) : subscribes to the requested file, and attempts to
                   16351: replicate from the owning library server, Might return
1.607     raeburn  16352: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   16353: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 16354: resource. Expects the local filesystem pathname
                   16355: (/home/httpd/html/res/....)
                   16356: 
                   16357: =back
                   16358: 
                   16359: =head2 Resource Information
                   16360: 
                   16361: =over 4
1.191     harris41 16362: 
                   16363: =item *
                   16364: 
1.1228    raeburn  16365: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   16366: and returns the value of a variety of different possible values,
                   16367: $varname should be a request string, and the other parameters can be
                   16368: used to specify who and what one is asking about. Ordinarily, $cid 
                   16369: does not need to be specified, as it is retrived from 
                   16370: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   16371: within lonuserstate::loadmap() when initializing a course, before
                   16372: $env{'request.course.id'} has been set, so it needs to be provided
                   16373: in that one case.
1.243     albertel 16374: 
                   16375: Possible values for $varname are environment.lastname (or other item
                   16376: from the envirnment hash), user.name (or someother aspect about the
                   16377: user), resource.0.maxtries (or some other part and parameter of a
                   16378: resource)
1.204     albertel 16379: 
                   16380: =item *
                   16381: 
1.243     albertel 16382: directcondval($number) : get current value of a condition; reads from a state
                   16383: string
1.204     albertel 16384: 
                   16385: =item *
                   16386: 
1.243     albertel 16387: condval($condidx) : value of condition index based on state
1.204     albertel 16388: 
                   16389: =item *
                   16390: 
1.1362    raeburn  16391: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 16392: resource's metadata, $what should be either a specific key, or either
                   16393: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  16394: packages that this resource currently uses, the last 3 arguments are 
                   16395: only used internally for recursive metadata.
                   16396: 
                   16397: the toolsymb is only used where the uri is for an external tool (for which
                   16398: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 16399: 
1.1371    raeburn  16400: this function automatically caches all requests except any made recursively
                   16401: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   16402: defined).
1.191     harris41 16403: 
                   16404: =item *
                   16405: 
1.243     albertel 16406: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   16407: network of library servers; returns file handle of where SQL and regex results
                   16408: will be stored for query
1.191     harris41 16409: 
                   16410: =item *
                   16411: 
1.1282    raeburn  16412: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   16413: return symbolic list entry (all arguments optional). 
                   16414: 
                   16415: Args: filename is the filename (including path) for the file for which a symb 
                   16416: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   16417: to check access status if more than one resource was found in the bighash 
                   16418: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   16419: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   16420: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   16421: cause possible symbs to be checked to determine if they are subject to content
                   16422: blocking, if so they will not be included as possible symbs; possibles is a
                   16423: ref to a hash, which, as a side effect, will be populated with all possible 
                   16424: symbs (content blocking not tested).
                   16425:  
1.243     albertel 16426: returns the data handle
1.191     harris41 16427: 
                   16428: =item *
                   16429: 
1.1190    raeburn  16430: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   16431: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 16432: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  16433: on failure, user must be in a course, as it assumes the existence of
                   16434: the course initial hash, and uses $env('request.course.id'}.  The third
                   16435: arg is an optional reference to a scalar.  If this arg is passed in the 
                   16436: call to symbverify, it will be set to 1 if the symb has been set to be 
                   16437: encrypted; otherwise it will be null.  
1.191     harris41 16438: 
                   16439: =item *
                   16440: 
1.243     albertel 16441: symbclean($symb) : removes versions numbers from a symb, returns the
                   16442: cleaned symb
1.191     harris41 16443: 
                   16444: =item *
                   16445: 
1.243     albertel 16446: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16447: course map, user must be in a course for it to work.
1.191     harris41 16448: 
                   16449: =item *
                   16450: 
1.243     albertel 16451: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16452: 
                   16453: =item *
                   16454: 
1.243     albertel 16455: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16456: a random seed, all arguments are optional, if they aren't sent it uses the
                   16457: environment to derive them. Note: if symb isn't sent and it can't get one
                   16458: from &symbread it will use the current time as its return value
1.191     harris41 16459: 
                   16460: =item *
                   16461: 
1.243     albertel 16462: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16463: unfakeable, receipt
1.191     harris41 16464: 
                   16465: =item *
                   16466: 
1.620     albertel 16467: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16468: 
                   16469: =item *
                   16470: 
1.243     albertel 16471: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16472: 
                   16473: =item *
                   16474: 
1.243     albertel 16475: 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 16476: 
                   16477: =item *
                   16478: 
1.243     albertel 16479: 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 16480: 
                   16481: =item *
                   16482: 
1.243     albertel 16483: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16484: 
                   16485: =item *
                   16486: 
1.243     albertel 16487: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16488: forcing spreadsheet to reevaluate the resource scores next time.
                   16489: 
1.1195    raeburn  16490: =item * 
                   16491: 
1.1196    raeburn  16492: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16493: when viewing in course context.
1.1195    raeburn  16494: 
1.1196    raeburn  16495:  input: six args -- filename (decluttered), course number, course domain,
                   16496:                     url, symb (if registered) and group (if this is a 
                   16497:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  16498: 
1.1196    raeburn  16499:  output: array of five scalars --
1.1195    raeburn  16500:          $cfile -- url for file editing if editable on current server
                   16501:          $home -- homeserver of resource (i.e., for author if published,
                   16502:                                           or course if uploaded.).
                   16503:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  16504:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   16505:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  16506: 
                   16507: =item *
                   16508: 
                   16509: is_course_upload($file,$cnum,$cdom)
                   16510: 
                   16511: Used in course context to determine if current file was uploaded to 
                   16512: the course (i.e., would be found in /userfiles/docs on the course's 
                   16513: homeserver.
                   16514: 
                   16515:   input: 3 args -- filename (decluttered), course number and course domain.
                   16516:   output: boolean -- 1 if file was uploaded.
                   16517: 
1.243     albertel 16518: =back
                   16519: 
                   16520: =head2 Storing/Retreiving Data
                   16521: 
                   16522: =over 4
1.191     harris41 16523: 
                   16524: =item *
                   16525: 
1.1269    raeburn  16526: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   16527: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16528: the remaining args aren't required and if they aren't passed or are '' they will
                   16529: be derived from the env (with the exception of $laststore, which is an 
                   16530: optional arg used when a user's submission is stored in grading).
                   16531: $laststore is $version=$timestamp, where $version is the most recent version
                   16532: number retrieved for the corresponding $symb in the $namespace db file, and
                   16533: $timestamp is the timestamp for that transaction (UNIX time).
                   16534: $laststore is currently only passed when cstore() is called by 
                   16535: structuretags::finalize_storage().
1.191     harris41 16536: 
                   16537: =item *
                   16538: 
1.1269    raeburn  16539: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   16540: but uses critical subroutine
1.191     harris41 16541: 
                   16542: =item *
                   16543: 
1.243     albertel 16544: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16545: all args are optional
1.191     harris41 16546: 
                   16547: =item *
                   16548: 
1.717     albertel 16549: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16550: dumps the complete (or key matching regexp) namespace into a hash
                   16551: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16552: normally &store()ed into
                   16553: 
                   16554: $range should be either an integer '100' (give me the first 100
                   16555:                                            matching records)
                   16556:               or be  two integers sperated by a - with no spaces
                   16557:                  '30-50' (give me the 30th through the 50th matching
                   16558:                           records)
                   16559: 
                   16560: 
                   16561: =item *
                   16562: 
1.1269    raeburn  16563: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16564: replaces a &store() version of data with a replacement set of data
                   16565: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  16566: reference. If $tolog is true, the transaction is logged in the courselog
                   16567: with an action=PUTSTORE.
1.717     albertel 16568: 
                   16569: =item *
                   16570: 
1.243     albertel 16571: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16572: works very similar to store/cstore, but all data is stored in a
                   16573: temporary location and can be reset using tmpreset, $storehash should
                   16574: be a hash reference, returns nothing on success
1.191     harris41 16575: 
                   16576: =item *
                   16577: 
1.243     albertel 16578: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16579: similar to restore, but all data is stored in a temporary location and
                   16580: can be reset using tmpreset. Returns a hash of values on success,
                   16581: error string otherwise.
1.191     harris41 16582: 
                   16583: =item *
                   16584: 
1.243     albertel 16585: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16586: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16587: 
                   16588: =item *
                   16589: 
1.243     albertel 16590: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16591: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16592: 
                   16593: =item *
                   16594: 
1.243     albertel 16595: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16596: namesp ($udom and $uname are optional)
1.191     harris41 16597: 
                   16598: =item *
                   16599: 
1.702     albertel 16600: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16601: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16602: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16603: 
1.702     albertel 16604: $range should be either an integer '100' (give me the first 100
                   16605:                                            matching records)
                   16606:               or be  two integers sperated by a - with no spaces
                   16607:                  '30-50' (give me the 30th through the 50th matching
                   16608:                           records)
1.449     matthew  16609: =item *
                   16610: 
                   16611: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16612: $store can be a scalar, an array reference, or if the amount to be 
                   16613: incremented is > 1, a hash reference.
                   16614: 
                   16615: ($udom and $uname are optional)
1.191     harris41 16616: 
                   16617: =item *
                   16618: 
1.243     albertel 16619: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16620: ($udom and $uname are optional)
1.191     harris41 16621: 
                   16622: =item *
                   16623: 
1.243     albertel 16624: cput($namespace,$storehash,$udom,$uname) : critical put
                   16625: ($udom and $uname are optional)
1.191     harris41 16626: 
                   16627: =item *
                   16628: 
1.748     albertel 16629: newput($namespace,$storehash,$udom,$uname) :
                   16630: 
                   16631: Attempts to store the items in the $storehash, but only if they don't
                   16632: currently exist, if this succeeds you can be certain that you have 
                   16633: successfully created a new key value pair in the $namespace db.
                   16634: 
                   16635: 
                   16636: Args:
                   16637:  $namespace: name of database to store values to
                   16638:  $storehash: hashref to store to the db
                   16639:  $udom: (optional) domain of user containing the db
                   16640:  $uname: (optional) name of user caontaining the db
                   16641: 
                   16642: Returns:
                   16643:  'ok' -> succeeded in storing all keys of $storehash
                   16644:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16645:                         least <key> already existed in the db (other
                   16646:                         requested keys may also already exist)
1.967     bisitz   16647:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16648:  'con_lost' -> unable to contact request server
                   16649:  'refused' -> action was not allowed by remote machine
                   16650: 
                   16651: 
                   16652: =item *
                   16653: 
1.243     albertel 16654: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16655: reference filled in from namesp (encrypts the return communication)
                   16656: ($udom and $uname are optional)
1.191     harris41 16657: 
                   16658: =item *
                   16659: 
1.243     albertel 16660: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16661: critical subroutine
                   16662: 
1.806     raeburn  16663: =item *
                   16664: 
1.860     raeburn  16665: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16666: array reference filled in from namespace found in domain level on either
                   16667: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16668: 
                   16669: =item *
                   16670: 
1.860     raeburn  16671: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16672: domain level either on specified domain server ($uhome) or primary domain 
                   16673: server ($udom and $uhome are optional)
1.806     raeburn  16674: 
1.943     raeburn  16675: =item * 
                   16676: 
1.1240    raeburn  16677: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   16678: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16679: the target domain.
                   16680: 
                   16681: May also include additional key => value pairs for the following groups:
                   16682: 
                   16683: =over
                   16684: 
                   16685: =item
                   16686: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16687: 
                   16688: =over
                   16689: 
                   16690: =item defaultquota, authorquota
                   16691: 
                   16692: =back
                   16693: 
                   16694: =item
                   16695: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16696: portfolio for users).
                   16697: 
                   16698: =over
                   16699: 
                   16700: =item
                   16701: aboutme, blog, webdav, portfolio
                   16702: 
                   16703: =back
                   16704: 
                   16705: =item
                   16706: requestcourses: ability to request courses, and how requests are processed.
                   16707: 
                   16708: =over
                   16709: 
                   16710: =item
1.1305    raeburn  16711: official, unofficial, community, textbook, placement
1.1240    raeburn  16712: 
                   16713: =back
                   16714: 
                   16715: =item
                   16716: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16717: 
                   16718: =over
                   16719: 
                   16720: =item
1.1256    raeburn  16721: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  16722: 
                   16723: =back
                   16724: 
                   16725: =item
                   16726: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16727: for course's uploaded content.
                   16728: 
                   16729: =over
                   16730: 
                   16731: =item
1.1246    raeburn  16732: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  16733: communityquota, textbookquota, placementquota
1.1240    raeburn  16734: 
                   16735: =back
                   16736: 
                   16737: =item
                   16738: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16739: on your servers.
                   16740: 
                   16741: =over
                   16742: 
                   16743: =item 
                   16744: remotesessions, hostedsessions
                   16745: 
                   16746: =back
                   16747: 
                   16748: =back
                   16749: 
                   16750: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16751: utility to create a configuration.db file on a domain's primary library server 
                   16752: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16753: -- corresponding values are authentication type (internal, krb4, krb5,
                   16754: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   16755: will be available. Values are retrieved from cache (if current), unless the
                   16756: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16757: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16758: 
                   16759: Typical usage:
1.943     raeburn  16760: 
1.1240    raeburn  16761: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16762: 
1.243     albertel 16763: =back
                   16764: 
                   16765: =head2 Network Status Functions
                   16766: 
                   16767: =over 4
1.191     harris41 16768: 
                   16769: =item *
                   16770: 
1.1137    raeburn  16771: dirlist() : return directory list based on URI (first arg).
                   16772: 
                   16773: Inputs: 1 required, 5 optional.
                   16774: 
                   16775: =over
                   16776: 
                   16777: =item 
                   16778: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16779: 
                   16780: =item
                   16781: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16782: 
                   16783: =item
                   16784: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16785: 
                   16786: =item
                   16787: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16788: 
                   16789: =item
                   16790: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16791: 
                   16792: =item 
                   16793: $alternateRoot - path to prepend in place of path from $uri.
                   16794: 
                   16795: =back
                   16796: 
                   16797: Returns: Array of up to two items.
                   16798: 
                   16799: =over
                   16800: 
                   16801: a reference to an array of files/subdirectories
                   16802: 
                   16803: =over
                   16804: 
                   16805: Each element in the array of files/subdirectories is a & separated list of
                   16806: item name and the result of running stat on the item.  If dirlist was requested
                   16807: for a file instead of a directory, the item name will be ''. For a directory 
                   16808: listing, if the item is a metadata file, the element will end &N&M 
                   16809: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16810: default copyright set (1).  
                   16811: 
                   16812: =back
                   16813: 
                   16814: a scalar containing error condition (if encountered).
                   16815: 
                   16816: =over
                   16817: 
                   16818: =item 
                   16819: no_host (no homeserver identified for $username:$domain).
                   16820: 
                   16821: =item 
                   16822: no_such_host (server contacted for listing not identified as valid host).
                   16823: 
                   16824: =item 
                   16825: con_lost (connection to remote server failed).
                   16826: 
                   16827: =item 
                   16828: refused (invalid $username:$domain received on lond side).
                   16829: 
                   16830: =item 
                   16831: no_such_dir (directory at specified path on lond side does not exist). 
                   16832: 
                   16833: =item 
                   16834: empty (directory at specified path on lond side is empty).
                   16835: 
                   16836: =over
                   16837: 
                   16838: This is currently not encountered because the &ls3, &ls2, 
                   16839: &ls (_handler) routines on the lond side do not filter out
                   16840: . and .. from a directory listing. 
                   16841: 
                   16842: =back
                   16843: 
                   16844: =back
                   16845: 
                   16846: =back
1.191     harris41 16847: 
                   16848: =item *
                   16849: 
1.243     albertel 16850: spareserver() : find server with least workload from spare.tab
                   16851: 
1.986     foxr     16852: 
                   16853: =item *
                   16854: 
                   16855: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16856: if there is no corresponding loncapa host.
                   16857: 
1.243     albertel 16858: =back
                   16859: 
1.986     foxr     16860: 
1.243     albertel 16861: =head2 Apache Request
                   16862: 
                   16863: =over 4
1.191     harris41 16864: 
                   16865: =item *
                   16866: 
1.243     albertel 16867: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16868: localhost, posts hash
                   16869: 
                   16870: =back
                   16871: 
                   16872: =head2 Data to String to Data
                   16873: 
                   16874: =over 4
1.191     harris41 16875: 
                   16876: =item *
                   16877: 
1.243     albertel 16878: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16879: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16880: 
                   16881: =item *
                   16882: 
1.243     albertel 16883: hashref2str($hashref) : convert a hashref into a string complete with
                   16884: escaping and '=' and '&' separators, supports elements that are
                   16885: arrayrefs and hashrefs
1.191     harris41 16886: 
                   16887: =item *
                   16888: 
1.243     albertel 16889: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16890: with escaping and '&' separators, supports elements that are arrayrefs
                   16891: and hashrefs
1.191     harris41 16892: 
                   16893: =item *
                   16894: 
1.243     albertel 16895: str2hash($string) : convert string to hash using unescaping and
                   16896: splitting on '=' and '&', supports elements that are arrayrefs and
                   16897: hashrefs
1.191     harris41 16898: 
                   16899: =item *
                   16900: 
1.243     albertel 16901: str2array($string) : convert string to hash using unescaping and
                   16902: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16903: 
                   16904: =back
                   16905: 
                   16906: =head2 Logging Routines
                   16907: 
                   16908: 
                   16909: These routines allow one to make log messages in the lonnet.log and
                   16910: lonnet.perm logfiles.
1.191     harris41 16911: 
1.1119    foxr     16912: =over 4
                   16913: 
1.191     harris41 16914: =item *
                   16915: 
1.243     albertel 16916: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16917: 
                   16918: =item *
                   16919: 
1.243     albertel 16920: logthis() : append message to the normal lonnet.log file, it gets
                   16921: preiodically rolled over and deleted.
1.191     harris41 16922: 
                   16923: =item *
                   16924: 
1.243     albertel 16925: logperm() : append a permanent message to lonnet.perm.log, this log
                   16926: file never gets deleted by any automated portion of the system, only
                   16927: messages of critical importance should go in here.
                   16928: 
1.1119    foxr     16929: 
1.243     albertel 16930: =back
                   16931: 
                   16932: =head2 General File Helper Routines
                   16933: 
                   16934: =over 4
1.191     harris41 16935: 
                   16936: =item *
                   16937: 
1.481     raeburn  16938: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16939: (a) files in /uploaded
                   16940:   (i) If a local copy of the file exists - 
                   16941:       compares modification date of local copy with last-modified date for 
                   16942:       definitive version stored on home server for course. If local copy is 
                   16943:       stale, requests a new version from the home server and stores it. 
                   16944:       If the original has been removed from the home server, then local copy 
                   16945:       is unlinked.
                   16946:   (ii) If local copy does not exist -
                   16947:       requests the file from the home server and stores it. 
                   16948:   
                   16949:   If $caller is 'uploadrep':  
                   16950:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16951:     for request for files originally uploaded via DOCS. 
                   16952:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16953:   
                   16954:   Otherwise:
                   16955:      This indicates a call from the content generation phase of the request.
                   16956:      -  returns the entire contents of the file or -1.
                   16957:      
                   16958: (b) files in /res
                   16959:    - returns the entire contents of a file or -1; 
                   16960:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16961: 
1.712     albertel 16962: 
                   16963: =item *
                   16964: 
                   16965: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16966:                   reference
                   16967: 
                   16968: returns either a stat() list of data about the file or an empty list
                   16969: if the file doesn't exist or couldn't find out about it (connection
                   16970: problems or user unknown)
                   16971: 
1.191     harris41 16972: =item *
                   16973: 
1.243     albertel 16974: filelocation($dir,$file) : returns file system location of a file
                   16975: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16976: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16977: and a file of ../bob will become /a/bob)
1.191     harris41 16978: 
                   16979: =item *
                   16980: 
                   16981: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16982: filelocation except for hrefs
                   16983: 
                   16984: =item *
                   16985: 
1.1261    raeburn  16986: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16987: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16988: 
1.243     albertel 16989: =back
                   16990: 
1.608     albertel 16991: =head2 Usererfile file routines (/uploaded*)
                   16992: 
                   16993: =over 4
                   16994: 
                   16995: =item *
                   16996: 
                   16997: userfileupload(): main rotine for putting a file in a user or course's
                   16998:                   filespace, arguments are,
                   16999: 
1.620     albertel 17000:  formname - required - this is the name of the element in $env where the
1.608     albertel 17001:            filename, and the contents of the file to create/modifed exist
1.620     albertel 17002:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   17003:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  17004:  context - if coursedoc, store the file in the course of the active role
                   17005:              of the current user; 
                   17006:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   17007:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 17008:  subdir - required - subdirectory to put the file in under ../userfiles/
                   17009:          if undefined, it will be placed in "unknown"
                   17010: 
                   17011:  (This routine calls clean_filename() to remove any dangerous
                   17012:  characters from the filename, and then calls finuserfileupload() to
                   17013:  complete the transaction)
                   17014: 
                   17015:  returns either the url of the uploaded file (/uploaded/....) if successful
                   17016:  and /adm/notfound.html if unsuccessful
                   17017: 
                   17018: =item *
                   17019: 
                   17020: clean_filename(): routine for cleaing a filename up for storage in
                   17021:                  userfile space, argument is:
                   17022: 
                   17023:  filename - proposed filename
                   17024: 
                   17025: returns: the new clean filename
                   17026: 
                   17027: =item *
                   17028: 
1.1090    raeburn  17029: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 17030: userspace, probably shouldn't be called directly
                   17031: 
                   17032:   docuname: username or courseid of destination for the file
                   17033:   docudom: domain of user/course of destination for the file
                   17034:   formname: same as for userfileupload()
1.1090    raeburn  17035:   fname: filename (including subdirectories) for the file
                   17036:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  17037:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  17038:   allfiles: reference to hash used to store objects found by parser
                   17039:   codebase: reference to hash used for codebases of java objects found by parser
                   17040:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   17041:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   17042:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   17043:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   17044:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   17045:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  17046:   mimetype: reference to scalar to accommodate mime type determined
                   17047:             from File::MMagic if $parser = parse.
1.608     albertel 17048: 
                   17049:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  17050:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   17051:  was 'overwrite').
                   17052:  
1.608     albertel 17053: 
                   17054: =item *
                   17055: 
                   17056: renameuserfile(): renames an existing userfile to a new name
                   17057: 
                   17058:   Args:
                   17059:    docuname: username or courseid of destination for the file
                   17060:    docudom: domain of user/course of destination for the file
                   17061:    old: current file name (including any subdirs under userfiles)
                   17062:    new: desired file name (including any subdirs under userfiles)
                   17063: 
                   17064: =item *
                   17065: 
                   17066: mkdiruserfile(): creates a directory is a userfiles dir
                   17067: 
                   17068:   Args:
                   17069:    docuname: username or courseid of destination for the file
                   17070:    docudom: domain of user/course of destination for the file
                   17071:    dir: dir to create (including any subdirs under userfiles)
                   17072: 
                   17073: =item *
                   17074: 
                   17075: removeuserfile(): removes a file that exists in userfiles
                   17076: 
                   17077:   Args:
                   17078:    docuname: username or courseid of destination for the file
                   17079:    docudom: domain of user/course of destination for the file
                   17080:    fname: filname to delete (including any subdirs under userfiles)
                   17081: 
                   17082: =item *
                   17083: 
                   17084: removeuploadedurl(): convience function for removeuserfile()
                   17085: 
                   17086:   Args:
                   17087:    url:  a full /uploaded/... url to delete
                   17088: 
1.747     albertel 17089: =item * 
                   17090: 
                   17091: get_portfile_permissions():
                   17092:   Args:
                   17093:     domain: domain of user or course contain the portfolio files
                   17094:     user: name of user or num of course contain the portfolio files
                   17095:   Returns:
                   17096:     hashref of a dump of the proper file_permissions.db
                   17097:    
                   17098: 
                   17099: =item * 
                   17100: 
                   17101: get_access_controls():
                   17102: 
                   17103: Args:
                   17104:   current_permissions: the hash ref returned from get_portfile_permissions()
                   17105:   group: (optional) the group you want the files associated with
                   17106:   file: (optional) the file you want access info on
                   17107: 
                   17108: Returns:
1.749     raeburn  17109:     a hash (keys are file names) of hashes containing
                   17110:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   17111:         values are XML containing access control settings (see below) 
1.747     albertel 17112: 
                   17113: Internal notes:
                   17114: 
1.749     raeburn  17115:  access controls are stored in file_permissions.db as key=value pairs.
                   17116:     key -> path to file/file_name\0uniqueID:scope_end_start
                   17117:         where scope -> public,guest,course,group,domains or users.
                   17118:               end -> UNIX time for end of access (0 -> no end date)
                   17119:               start -> UNIX time for start of access
                   17120: 
                   17121:     value -> XML description of access control
                   17122:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   17123:             <start></start>
                   17124:             <end></end>
                   17125: 
                   17126:             <password></password>  for scope type = guest
                   17127: 
                   17128:             <domain></domain>     for scope type = course or group
                   17129:             <number></number>
                   17130:             <roles id="">
                   17131:              <role></role>
                   17132:              <access></access>
                   17133:              <section></section>
                   17134:              <group></group>
                   17135:             </roles>
                   17136: 
                   17137:             <dom></dom>         for scope type = domains
                   17138: 
                   17139:             <users>             for scope type = users
                   17140:              <user>
                   17141:               <uname></uname>
                   17142:               <udom></udom>
                   17143:              </user>
                   17144:             </users>
                   17145:            </scope> 
                   17146:               
                   17147:  Access data is also aggregated for each file in an additional key=value pair:
                   17148:  key -> path to file/file_name\0accesscontrol 
                   17149:  value -> reference to hash
                   17150:           hash contains key = value pairs
                   17151:           where key = uniqueID:scope_end_start
                   17152:                 value = UNIX time record was last updated
                   17153: 
                   17154:           Used to improve speed of look-ups of access controls for each file.  
                   17155:  
                   17156:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   17157: 
1.1198    raeburn  17158: =item *
                   17159: 
1.749     raeburn  17160: modify_access_controls():
                   17161: 
                   17162: Modifies access controls for a portfolio file
                   17163: Args
                   17164: 1. file name
                   17165: 2. reference to hash of required changes,
                   17166: 3. domain
                   17167: 4. username
                   17168:   where domain,username are the domain of the portfolio owner 
                   17169:   (either a user or a course) 
                   17170: 
                   17171: Returns:
                   17172: 1. result of additions or updates ('ok' or 'error', with error message). 
                   17173: 2. result of deletions ('ok' or 'error', with error message).
                   17174: 3. reference to hash of any new or updated access controls.
                   17175: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   17176:    key = integer (inbound ID)
1.1198    raeburn  17177:    value = uniqueID
                   17178: 
                   17179: =item *
                   17180: 
                   17181: get_timebased_id():
                   17182: 
                   17183: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   17184: course via the Course Editor (e.g., folders, composite pages, 
                   17185: group bulletin boards).
                   17186: 
                   17187: Args: (first three required; six others optional)
                   17188: 
                   17189: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   17190:    docssequence, or name of group
                   17191: 
                   17192: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   17193:    e.g., num, boardids
                   17194: 
                   17195: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   17196:    file will be named nohist_namespace.db
                   17197: 
                   17198: 4. cdom: domain of course; default is current course domain from %env
                   17199: 
                   17200: 5. cnum: course number; default is current course number from %env
                   17201: 
                   17202: 6. idtype: set to concat if an additional digit is to be appended to the 
                   17203:    unix timestamp to form the suffix, if the plain timestamp is already
                   17204:    in use.  Default is to not do this, but simply increment the unix 
                   17205:    timestamp by 1 until a unique key is obtained.
                   17206: 
                   17207: 7. who: holder of locking key; defaults to user:domain for user.
                   17208: 
                   17209: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   17210:    retrying); default is 3.
                   17211: 
                   17212: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   17213: 
                   17214: Returns:
                   17215: 
                   17216: 1. suffix obtained (numeric)
                   17217: 
                   17218: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   17219: 
                   17220: 3. error: contains (localized) error message if an error occurred.
                   17221: 
1.747     albertel 17222: 
1.608     albertel 17223: =back
                   17224: 
1.243     albertel 17225: =head2 HTTP Helper Routines
                   17226: 
                   17227: =over 4
                   17228: 
1.191     harris41 17229: =item *
                   17230: 
                   17231: escape() : unpack non-word characters into CGI-compatible hex codes
                   17232: 
                   17233: =item *
                   17234: 
                   17235: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   17236: 
1.243     albertel 17237: =back
                   17238: 
                   17239: =head1 PRIVATE SUBROUTINES
                   17240: 
                   17241: =head2 Underlying communication routines (Shouldn't call)
                   17242: 
                   17243: =over 4
                   17244: 
                   17245: =item *
                   17246: 
                   17247: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   17248: 
                   17249: =item *
                   17250: 
                   17251: reply() : uses subreply to send a message to remote machine, logs all failures
                   17252: 
                   17253: =item *
                   17254: 
                   17255: critical() : passes a critical message to another server; if cannot
                   17256: get through then place message in connection buffer directory and
                   17257: returns con_delayed, if incapable of saving message, returns
                   17258: con_failed
                   17259: 
                   17260: =item *
                   17261: 
                   17262: reconlonc() : tries to reconnect lonc client processes.
                   17263: 
                   17264: =back
                   17265: 
                   17266: =head2 Resource Access Logging
                   17267: 
                   17268: =over 4
                   17269: 
                   17270: =item *
                   17271: 
                   17272: flushcourselogs() : flush (save) buffer logs and access logs
                   17273: 
                   17274: =item *
                   17275: 
                   17276: courselog($what) : save message for course in hash
                   17277: 
                   17278: =item *
                   17279: 
                   17280: courseacclog($what) : save message for course using &courselog().  Perform
                   17281: special processing for specific resource types (problems, exams, quizzes, etc).
                   17282: 
1.191     harris41 17283: =item *
                   17284: 
                   17285: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   17286: as a PerlChildExitHandler
1.243     albertel 17287: 
                   17288: =back
                   17289: 
                   17290: =head2 Other
                   17291: 
                   17292: =over 4
                   17293: 
                   17294: =item *
                   17295: 
                   17296: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 17297: 
                   17298: =back
                   17299: 
                   17300: =cut
1.877     foxr     17301: 

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