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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.58! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.57 2014/10/26 13:02:42 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1172.2.36  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   100: use LONCAPA::Lond;
1.1117    foxr      101: 
1.1090    raeburn   102: use File::Copy;
1.676     albertel  103: 
1.195     www       104: my $readit;
1.550     foxr      105: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  106: 
1.619     albertel  107: require Exporter;
                    108: 
                    109: our @ISA = qw (Exporter);
                    110: our @EXPORT = qw(%env);
                    111: 
1.1172.2.9  raeburn   112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       113: {
                    114:     my $logid;
1.1172.2.9  raeburn   115:     sub write_log {
                    116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    117:         if ($context eq 'course') {
                    118:             if (($cnum eq '') || ($cdom eq '')) {
                    119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    121:             }
1.957     raeburn   122:         }
1.1172.2.13  raeburn   123: 	$logid ++;
1.957     raeburn   124:         my $now = time();
                    125: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   126:         my $logentry = {
                    127:                          $id => {
                    128:                                   'exe_uname' => $env{'user.name'},
                    129:                                   'exe_udom'  => $env{'user.domain'},
                    130:                                   'exe_time'  => $now,
                    131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    132:                                   'delflag'   => $delflag,
                    133:                                   'logentry'  => $storehash,
                    134:                                   'uname'     => $uname,
                    135:                                   'udom'      => $udom,
                    136:                                 }
                    137:                        };
                    138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       139:     }
                    140: }
1.1       albertel  141: 
1.163     harris41  142: sub logtouch {
                    143:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  144:     unless (-e "$execdir/logs/lonnet.log") {	
                    145: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  146: 	close $fh;
                    147:     }
                    148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    150: }
                    151: 
1.1       albertel  152: sub logthis {
                    153:     my $message=shift;
                    154:     my $execdir=$perlvar{'lonDaemons'};
                    155:     my $now=time;
                    156:     my $local=localtime($now);
1.448     albertel  157:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    159: 	print $fh $logstring;
1.448     albertel  160: 	close($fh);
                    161:     }
1.1       albertel  162:     return 1;
                    163: }
                    164: 
                    165: sub logperm {
                    166:     my $message=shift;
                    167:     my $execdir=$perlvar{'lonDaemons'};
                    168:     my $now=time;
                    169:     my $local=localtime($now);
1.448     albertel  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    171: 	print $fh "$now:$message:$local\n";
                    172: 	close($fh);
                    173:     }
1.1       albertel  174:     return 1;
                    175: }
                    176: 
1.850     albertel  177: sub create_connection {
1.853     albertel  178:     my ($hostname,$lonid) = @_;
1.851     albertel  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  180: 				     Type    => SOCK_STREAM,
                    181: 				     Timeout => 10);
                    182:     return 0 if (!$client);
1.890     albertel  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  184:     my $result = <$client>;
                    185:     chomp($result);
                    186:     return 1 if ($result eq 'done');
                    187:     return 0;
                    188: }
                    189: 
1.983     raeburn   190: sub get_server_timezone {
                    191:     my ($cnum,$cdom) = @_;
                    192:     my $home=&homeserver($cnum,$cdom);
                    193:     if ($home ne 'no_host') {
                    194:         my $cachetime = 24*3600;
                    195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    196:         if (defined($cached)) {
                    197:             return $timezone;
                    198:         } else {
                    199:             my $timezone = &reply('servertimezone',$home);
                    200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    201:         }
                    202:     }
                    203: }
1.850     albertel  204: 
1.1106    raeburn   205: sub get_server_distarch {
                    206:     my ($lonhost,$ignore_cache) = @_;
                    207:     if (defined($lonhost)) {
                    208:         if (!defined(&hostname($lonhost))) {
                    209:             return;
                    210:         }
                    211:         my $cachetime = 12*3600;
                    212:         if (!$ignore_cache) {
                    213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    214:             if (defined($cached)) {
                    215:                 return $distarch;
                    216:             }
                    217:         }
                    218:         my $rep = &reply('serverdistarch',$lonhost);
                    219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    221:                 $rep eq '') {
                    222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    223:         }
                    224:     }
                    225:     return;
                    226: }
                    227: 
1.993     raeburn   228: sub get_server_loncaparev {
1.1073    raeburn   229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   230:     if (defined($lonhost)) {
                    231:         if (!defined(&hostname($lonhost))) {
                    232:             undef($lonhost);
                    233:         }
                    234:     }
                    235:     if (!defined($lonhost)) {
                    236:         if (defined(&domain($dom,'primary'))) {
                    237:             $lonhost=&domain($dom,'primary');
                    238:             if ($lonhost eq 'no_host') {
                    239:                 undef($lonhost);
                    240:             }
                    241:         }
                    242:     }
                    243:     if (defined($lonhost)) {
1.1073    raeburn   244:         my $cachetime = 12*3600;
                    245:         if (!$ignore_cache) {
                    246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    247:             if (defined($cached)) {
                    248:                 return $loncaparev;
                    249:             }
                    250:         }
                    251:         my ($answer,$loncaparev);
                    252:         my @ids=&current_machine_ids();
                    253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    254:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   256:                 $loncaparev = $1;
                    257:             }
                    258:         } else {
                    259:             $answer = &reply('serverloncaparev',$lonhost);
                    260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    261:                 if ($caller eq 'loncron') {
                    262:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   263:                     $ua->timeout(4);
1.1073    raeburn   264:                     my $protocol = $protocol{$lonhost};
                    265:                     $protocol = 'http' if ($protocol ne 'https');
                    266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    267:                     my $request=new HTTP::Request('GET',$url);
                    268:                     my $response=$ua->request($request);
                    269:                     unless ($response->is_error()) {
                    270:                         my $content = $response->content;
1.1081    raeburn   271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   272:                             $loncaparev = $1;
                    273:                         }
                    274:                     }
                    275:                 } else {
                    276:                     $loncaparev = $loncaparevs{$lonhost};
                    277:                 }
1.1081    raeburn   278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   279:                 $loncaparev = $1;
                    280:             }
1.993     raeburn   281:         }
1.1073    raeburn   282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   283:     }
                    284: }
                    285: 
1.1074    raeburn   286: sub get_server_homeID {
                    287:     my ($hostname,$ignore_cache,$caller) = @_;
                    288:     unless ($ignore_cache) {
                    289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    290:         if (defined($cached)) {
                    291:             return $serverhomeID;
                    292:         }
                    293:     }
                    294:     my $cachetime = 12*3600;
                    295:     my $serverhomeID;
                    296:     if ($caller eq 'loncron') { 
                    297:         my @machine_ids = &machine_ids($hostname);
                    298:         foreach my $id (@machine_ids) {
                    299:             my $response = &reply('serverhomeID',$id);
                    300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    301:                 $serverhomeID = $response;
                    302:                 last;
                    303:             }
                    304:         }
                    305:         if ($serverhomeID eq '') {
                    306:             $serverhomeID = $machine_ids[-1];
                    307:         }
                    308:     } else {
                    309:         $serverhomeID = $serverhomeIDs{$hostname};
                    310:     }
                    311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    312: }
                    313: 
1.1121    raeburn   314: sub get_remote_globals {
                    315:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   316:     my ($result,%returnhash,%whatneeded);
                    317:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   318:         foreach my $what (sort(keys(%{$whathash}))) {
                    319:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   320:             my ($response,$cached);
1.1121    raeburn   321:             unless ($ignore_cache) {
1.1125    raeburn   322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   323:             }
                    324:             if (defined($cached)) {
1.1125    raeburn   325:                 $returnhash{$what} = $response;
1.1121    raeburn   326:             } else {
1.1125    raeburn   327:                 $whatneeded{$what} = 1;
1.1121    raeburn   328:             }
                    329:         }
1.1125    raeburn   330:         if (keys(%whatneeded) == 0) {
                    331:             $result = 'ok';
                    332:         } else {
1.1121    raeburn   333:             my $requested = &freeze_escape(\%whatneeded);
                    334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    336:                 ($rep eq 'unknown_cmd')) {
                    337:                 $result = $rep;
                    338:             } else {
                    339:                 $result = 'ok';
1.1121    raeburn   340:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   341:                 foreach my $item (@pairs) {
                    342:                     my ($key,$value)=split(/=/,$item,2);
                    343:                     my $what = &unescape($key);
                    344:                     my $hashid = $lonhost.'-'.$what;
                    345:                     $returnhash{$what}=&thaw_unescape($value);
                    346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   347:                 }
                    348:             }
                    349:         }
                    350:     }
1.1125    raeburn   351:     return ($result,\%returnhash);
1.1121    raeburn   352: }
                    353: 
1.1124    raeburn   354: sub remote_devalidate_cache {
1.1172.2.35  raeburn   355:     my ($lonhost,$cachekeys) = @_;
                    356:     my $items;
                    357:     return unless (ref($cachekeys) eq 'ARRAY');
                    358:     my $cachestr = join('&',@{$cachekeys});
                    359:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   360: }
                    361: 
1.1       albertel  362: # -------------------------------------------------- Non-critical communication
                    363: sub subreply {
                    364:     my ($cmd,$server)=@_;
1.838     albertel  365:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      366:     #
                    367:     #  With loncnew process trimming, there's a timing hole between lonc server
                    368:     #  process exit and the master server picking up the listen on the AF_UNIX
                    369:     #  socket.  In that time interval, a lock file will exist:
                    370: 
                    371:     my $lockfile=$peerfile.".lock";
                    372:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    373: 	sleep(1);
                    374:     }
                    375:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      376:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      377:     #
1.550     foxr      378:     #   We'll give the connection a few tries before abandoning it.  If
                    379:     #   connection is not possible, we'll con_lost back to the client.
                    380:     #   
                    381:     my $client;
                    382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    384: 				      Type    => SOCK_STREAM,
                    385: 				      Timeout => 10);
1.869     albertel  386: 	if ($client) {
1.550     foxr      387: 	    last;		# Connected!
1.850     albertel  388: 	} else {
1.853     albertel  389: 	    &create_connection(&hostname($server),$server);
1.550     foxr      390: 	}
1.850     albertel  391:         sleep(1);		# Try again later if failed connection.
1.550     foxr      392:     }
                    393:     my $answer;
                    394:     if ($client) {
1.704     albertel  395: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      396: 	$answer=<$client>;
                    397: 	if (!$answer) { $answer="con_lost"; }
                    398: 	chomp($answer);
                    399:     } else {
                    400: 	$answer = 'con_lost';	# Failed connection.
                    401:     }
1.1       albertel  402:     return $answer;
                    403: }
                    404: 
                    405: sub reply {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  408:     my $answer=subreply($cmd,$server);
1.65      www       409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  410:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       411:                 " $cmd to $server returned $answer</font>");
                    412:     }
1.1       albertel  413:     return $answer;
                    414: }
                    415: 
                    416: # ----------------------------------------------------------- Send USR1 to lonc
                    417: 
                    418: sub reconlonc {
1.891     albertel  419:     my ($lonid) = @_;
                    420:     my $hostname = &hostname($lonid);
                    421:     if ($lonid) {
                    422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    423: 	if ($hostname && -e $peerfile) {
                    424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    426: 					     Type    => SOCK_STREAM,
                    427: 					     Timeout => 10);
                    428: 	    if ($client) {
                    429: 		print $client ("reset_retries\n");
                    430: 		my $answer=<$client>;
                    431: 		#reset just this one.
                    432: 	    }
                    433: 	}
                    434: 	return;
                    435:     }
                    436: 
1.836     www       437:     &logthis("Trying to reconnect lonc");
1.1       albertel  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  439:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  440: 	my $loncpid=<$fh>;
                    441:         chomp($loncpid);
                    442:         if (kill 0 => $loncpid) {
                    443: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    444:             kill USR1 => $loncpid;
                    445:             sleep 1;
1.836     www       446:          } else {
1.12      www       447: 	    &logthis(
1.672     albertel  448:                "<font color=\"blue\">WARNING:".
1.12      www       449:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  450:         }
                    451:     } else {
1.836     www       452: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  453:     }
                    454: }
                    455: 
                    456: # ------------------------------------------------------ Critical communication
1.12      www       457: 
1.1       albertel  458: sub critical {
                    459:     my ($cmd,$server)=@_;
1.838     albertel  460:     unless (&hostname($server)) {
1.672     albertel  461:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       462:                " Critical message to unknown server ($server)</font>");
                    463:         return 'no_such_host';
                    464:     }
1.1       albertel  465:     my $answer=reply($cmd,$server);
                    466:     if ($answer eq 'con_lost') {
                    467: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  468: 	my $answer=reply($cmd,$server);
1.1       albertel  469:         if ($answer eq 'con_lost') {
                    470:             my $now=time;
                    471:             my $middlename=$cmd;
1.5       www       472:             $middlename=substr($middlename,0,16);
1.1       albertel  473:             $middlename=~s/\W//g;
                    474:             my $dfilename=
1.305     www       475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    476:             $dumpcount++;
1.1       albertel  477:             {
1.448     albertel  478: 		my $dfh;
                    479: 		if (open($dfh,">$dfilename")) {
                    480: 		    print $dfh "$cmd\n"; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
                    484:             sleep 2;
                    485:             my $wcmd='';
                    486:             {
1.448     albertel  487: 		my $dfh;
                    488: 		if (open($dfh,"<$dfilename")) {
                    489: 		    $wcmd=<$dfh>; 
                    490: 		    close($dfh);
                    491: 		}
1.1       albertel  492:             }
                    493:             chomp($wcmd);
1.7       www       494:             if ($wcmd eq $cmd) {
1.672     albertel  495: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       496:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  497:                 &logperm("D:$server:$cmd");
                    498: 	        return 'con_delayed';
                    499:             } else {
1.672     albertel  500:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       501:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  502:                 &logperm("F:$server:$cmd");
                    503:                 return 'con_failed';
                    504:             }
                    505:         }
                    506:     }
                    507:     return $answer;
1.405     albertel  508: }
                    509: 
1.755     albertel  510: # ------------------------------------------- check if return value is an error
                    511: 
                    512: sub error {
                    513:     my ($result) = @_;
1.756     albertel  514:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  515: 	if ($2 == 2) { return undef; }
                    516: 	return $1;
                    517:     }
                    518:     return undef;
                    519: }
                    520: 
1.783     albertel  521: sub convert_and_load_session_env {
                    522:     my ($lonidsdir,$handle)=@_;
                    523:     my @profile;
                    524:     {
1.917     albertel  525: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    526: 	if (!$opened) {
1.915     albertel  527: 	    return 0;
                    528: 	}
1.783     albertel  529: 	flock($idf,LOCK_SH);
                    530: 	@profile=<$idf>;
                    531: 	close($idf);
                    532:     }
                    533:     my %temp_env;
                    534:     foreach my $line (@profile) {
1.786     albertel  535: 	if ($line !~ m/=/) {
                    536: 	    return 0;
                    537: 	}
1.783     albertel  538: 	chomp($line);
                    539: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    540: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    541:     }
                    542:     unlink("$lonidsdir/$handle.id");
                    543:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    544: 	    0640)) {
                    545: 	%disk_env = %temp_env;
                    546: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    547: 	untie(%disk_env);
                    548:     }
1.786     albertel  549:     return 1;
1.783     albertel  550: }
                    551: 
1.374     www       552: # ------------------------------------------- Transfer profile into environment
1.780     albertel  553: my $env_loaded;
                    554: sub transfer_profile_to_env {
1.788     albertel  555:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    556:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       557: 
1.720     albertel  558:     if (!defined($lonidsdir)) {
                    559: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    560:     }
                    561:     if (!defined($handle)) {
                    562:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    563:     }
                    564: 
1.786     albertel  565:     my $convert;
                    566:     {
1.917     albertel  567:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    568: 	if (!$opened) {
1.915     albertel  569: 	    return;
                    570: 	}
1.786     albertel  571: 	flock($idf,LOCK_SH);
                    572: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    573: 		&GDBM_READER(),0640)) {
                    574: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    575: 	    untie(%disk_env);
                    576: 	} else {
                    577: 	    $convert = 1;
                    578: 	}
                    579:     }
                    580:     if ($convert) {
                    581: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    582: 	    &logthis("Failed to load session, or convert session.");
                    583: 	}
1.374     www       584:     }
1.783     albertel  585: 
1.786     albertel  586:     my %remove;
1.783     albertel  587:     while ( my $envname = each(%env) ) {
1.433     matthew   588:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    589:             if ($time < time-300) {
1.783     albertel  590:                 $remove{$key}++;
1.433     matthew   591:             }
                    592:         }
                    593:     }
1.783     albertel  594: 
1.619     albertel  595:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  596:     $env_loaded=1;
1.783     albertel  597:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   598:         &delenv($expired_key);
1.374     www       599:     }
1.1       albertel  600: }
                    601: 
1.916     albertel  602: # ---------------------------------------------------- Check for valid session 
                    603: sub check_for_valid_session {
1.1172.2.36  raeburn   604:     my ($r,$name,$userhashref) = @_;
1.916     albertel  605:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   606:     if ($name eq '') {
                    607:         $name = 'lonID';
                    608:     }
                    609:     my $lonid=$cookies{$name};
1.916     albertel  610:     return undef if (!$lonid);
                    611: 
                    612:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   613:     my $lonidsdir;
                    614:     if ($name eq 'lonDAV') {
                    615:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    616:     } else {
                    617:         $lonidsdir=$r->dir_config('lonIDsDir');
                    618:     }
1.916     albertel  619:     return undef if (!-e "$lonidsdir/$handle.id");
                    620: 
1.917     albertel  621:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    622:     return undef if (!$opened);
1.916     albertel  623: 
                    624:     flock($idf,LOCK_SH);
                    625:     my %disk_env;
                    626:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    627: 	    &GDBM_READER(),0640)) {
                    628: 	return undef;	
                    629:     }
                    630: 
                    631:     if (!defined($disk_env{'user.name'})
                    632: 	|| !defined($disk_env{'user.domain'})) {
                    633: 	return undef;
                    634:     }
1.1172.2.18  raeburn   635: 
1.1172.2.36  raeburn   636:     if (ref($userhashref) eq 'HASH') {
                    637:         $userhashref->{'name'} = $disk_env{'user.name'};
                    638:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   639:     }
                    640: 
1.916     albertel  641:     return $handle;
                    642: }
                    643: 
1.830     albertel  644: sub timed_flock {
                    645:     my ($file,$lock_type) = @_;
                    646:     my $failed=0;
                    647:     eval {
                    648: 	local $SIG{__DIE__}='DEFAULT';
                    649: 	local $SIG{ALRM}=sub {
                    650: 	    $failed=1;
                    651: 	    die("failed lock");
                    652: 	};
                    653: 	alarm(13);
                    654: 	flock($file,$lock_type);
                    655: 	alarm(0);
                    656:     };
                    657:     if ($failed) {
                    658: 	return undef;
                    659:     } else {
                    660: 	return 1;
                    661:     }
                    662: }
                    663: 
1.5       www       664: # ---------------------------------------------------------- Append Environment
                    665: 
                    666: sub appenv {
1.949     raeburn   667:     my ($newenv,$roles) = @_;
                    668:     if (ref($newenv) eq 'HASH') {
                    669:         foreach my $key (keys(%{$newenv})) {
                    670:             my $refused = 0;
                    671: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    672:                 $refused = 1;
                    673:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   674:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   675:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    676:                         $refused = 0;
                    677:                     }
                    678:                 }
                    679:             }
                    680:             if ($refused) {
                    681:                 &logthis("<font color=\"blue\">WARNING: ".
                    682:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    683:                          .'</font>');
                    684: 	        delete($newenv->{$key});
                    685:             } else {
                    686:                 $env{$key}=$newenv->{$key};
                    687:             }
                    688:         }
                    689:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    690:         if ($opened
                    691: 	    && &timed_flock($env_file,LOCK_EX)
                    692: 	    &&
                    693: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    694: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    695: 	    while (my ($key,$value) = each(%{$newenv})) {
                    696: 	        $disk_env{$key} = $value;
                    697: 	    }
                    698: 	    untie(%disk_env);
1.35      www       699:         }
1.191     harris41  700:     }
1.56      www       701:     return 'ok';
                    702: }
                    703: # ----------------------------------------------------- Delete from Environment
                    704: 
                    705: sub delenv {
1.1104    raeburn   706:     my ($delthis,$regexp,$roles) = @_;
                    707:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    708:         my $refused = 1;
                    709:         if (ref($roles) eq 'ARRAY') {
                    710:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    711:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    712:                 $refused = 0;
                    713:             }
                    714:         }
                    715:         if ($refused) {
                    716:             &logthis("<font color=\"blue\">WARNING: ".
                    717:                      "Attempt to delete from environment ".$delthis);
                    718:             return 'error';
                    719:         }
1.56      www       720:     }
1.917     albertel  721:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    722:     if ($opened
1.915     albertel  723: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  724: 	&&
                    725: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    726: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  727: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   728: 	    if ($regexp) {
                    729:                 if ($key=~/^$delthis/) {
                    730:                     delete($env{$key});
                    731:                     delete($disk_env{$key});
                    732:                 } 
                    733:             } else {
                    734:                 if ($key=~/^\Q$delthis\E/) {
                    735: 		    delete($env{$key});
                    736: 		    delete($disk_env{$key});
                    737: 	        }
                    738:             }
1.448     albertel  739: 	}
1.783     albertel  740: 	untie(%disk_env);
1.5       www       741:     }
                    742:     return 'ok';
1.369     albertel  743: }
                    744: 
1.790     albertel  745: sub get_env_multiple {
                    746:     my ($name) = @_;
                    747:     my @values;
                    748:     if (defined($env{$name})) {
                    749:         # exists is it an array
                    750:         if (ref($env{$name})) {
                    751:             @values=@{ $env{$name} };
                    752:         } else {
                    753:             $values[0]=$env{$name};
                    754:         }
                    755:     }
                    756:     return(@values);
                    757: }
                    758: 
1.958     www       759: # ------------------------------------------------------------------- Locking
                    760: 
                    761: sub set_lock {
                    762:     my ($text)=@_;
                    763:     $locknum++;
                    764:     my $id=$$.'-'.$locknum;
                    765:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    766:              'session.lock.'.$id => $text});
                    767:     return $id;
                    768: }
                    769: 
                    770: sub get_locks {
                    771:     my $num=0;
                    772:     my %texts=();
                    773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    774:        if ($lock=~/\w/) {
                    775:           $num++;
                    776:           $texts{$lock}=$env{'session.lock.'.$lock};
                    777:        }
                    778:    }
                    779:    return ($num,%texts);
                    780: }
                    781: 
                    782: sub remove_lock {
                    783:     my ($id)=@_;
                    784:     my $newlocks='';
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if (($lock=~/\w/) && ($lock ne $id)) {
                    787:           $newlocks.=','.$lock;
                    788:        }
                    789:     }
                    790:     &appenv({'session.locks' => $newlocks});
                    791:     &delenv('session.lock.'.$id);
                    792: }
                    793: 
                    794: sub remove_all_locks {
                    795:     my $activelocks=$env{'session.locks'};
                    796:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    797:        if ($lock=~/\w/) {
                    798:           &remove_lock($lock);
                    799:        }
                    800:     }
                    801: }
                    802: 
                    803: 
1.369     albertel  804: # ------------------------------------------ Find out current server userload
                    805: sub userload {
                    806:     my $numusers=0;
                    807:     {
                    808: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    809: 	my $filename;
                    810: 	my $curtime=time;
                    811: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  812: 	    next if ($filename eq '.' || $filename eq '..');
                    813: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  814: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  815: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  816: 	}
                    817: 	closedir(LONIDS);
                    818:     }
                    819:     my $userloadpercent=0;
                    820:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    821:     if ($maxuserload) {
1.371     albertel  822: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  823:     }
1.372     albertel  824:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  825:     return $userloadpercent;
1.283     www       826: }
                    827: 
1.1       albertel  828: # ------------------------------ Find server with least workload from spare.tab
1.11      www       829: 
1.1       albertel  830: sub spareserver {
1.1083    raeburn   831:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  832:     my $spare_server;
1.370     albertel  833:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  834:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    835:                                                      :  $userloadpercent;
1.1083    raeburn   836:     my ($uint_dom,$remotesessions);
                    837:     if (($udom ne '') && (&domain($udom) ne '')) {
                    838:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    839:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    840:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    841:         $remotesessions = $udomdefaults{'remotesessions'};
                    842:     }
1.1123    raeburn   843:     my $spareshash = &this_host_spares($udom);
                    844:     if (ref($spareshash) eq 'HASH') {
                    845:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    846:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    847:                 if ($uint_dom) {
                    848:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    849:                                                  $try_server));
                    850:                 }
                    851: 	        ($spare_server, $lowest_load) =
                    852: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    853:             }
1.1083    raeburn   854:         }
1.784     albertel  855: 
1.1123    raeburn   856:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    857: 
                    858:         if (!$found_server) {
                    859:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    860: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    861:                     if ($uint_dom) {
                    862:                         next unless (&spare_can_host($udom,$uint_dom,
                    863:                                                      $remotesessions,$try_server));
                    864:                     }
                    865: 	            ($spare_server, $lowest_load) =
                    866: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    867:                 }
                    868: 	    }
                    869:         }
1.784     albertel  870:     }
                    871: 
                    872:     if (!$want_server_name) {
1.968     raeburn   873:         my $protocol = 'http';
                    874:         if ($protocol{$spare_server} eq 'https') {
                    875:             $protocol = $protocol{$spare_server};
                    876:         }
1.1001    raeburn   877:         if (defined($spare_server)) {
                    878:             my $hostname = &hostname($spare_server);
1.1083    raeburn   879:             if (defined($hostname)) {
1.1001    raeburn   880: 	        $spare_server = $protocol.'://'.$hostname;
                    881:             }
                    882:         }
1.784     albertel  883:     }
                    884:     return $spare_server;
                    885: }
                    886: 
                    887: sub compare_server_load {
1.1172.2.41  raeburn   888:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    889: 
                    890:     if ($required) {
                    891:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    892:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    893:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    894:         if (($major eq '' && $minor eq '') ||
                    895:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    896:             return ($spare_server,$lowest_load);
                    897:         }
                    898:     }
1.784     albertel  899: 
                    900:     my $loadans     = &reply('load',    $try_server);
                    901:     my $userloadans = &reply('userload',$try_server);
                    902: 
                    903:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   904: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  905:     }
                    906: 
                    907:     my $load;
                    908:     if ($loadans =~ /\d/) {
                    909: 	if ($userloadans =~ /\d/) {
                    910: 	    #both are numbers, pick the bigger one
                    911: 	    $load = ($loadans > $userloadans) ? $loadans 
                    912: 		                              : $userloadans;
1.411     albertel  913: 	} else {
1.784     albertel  914: 	    $load = $loadans;
1.411     albertel  915: 	}
1.784     albertel  916:     } else {
                    917: 	$load = $userloadans;
                    918:     }
                    919: 
                    920:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    921: 	$spare_server = $try_server;
                    922: 	$lowest_load  = $load;
1.370     albertel  923:     }
1.784     albertel  924:     return ($spare_server,$lowest_load);
1.202     matthew   925: }
1.914     albertel  926: 
                    927: # --------------------------- ask offload servers if user already has a session
                    928: sub find_existing_session {
                    929:     my ($udom,$uname) = @_;
1.1123    raeburn   930:     my $spareshash = &this_host_spares($udom);
                    931:     if (ref($spareshash) eq 'HASH') {
                    932:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    933:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    934:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    935:             }
                    936:         }
                    937:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    938:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    939:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    940:             }
                    941:         }
1.914     albertel  942:     }
                    943:     return;
                    944: }
                    945: 
                    946: # -------------------------------- ask if server already has a session for user
                    947: sub has_user_session {
                    948:     my ($lonid,$udom,$uname) = @_;
                    949:     my $result = &reply(join(':','userhassession',
                    950: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    951:     return 1 if ($result eq 'ok');
                    952: 
                    953:     return 0;
                    954: }
                    955: 
1.1076    raeburn   956: # --------- determine least loaded server in a user's domain which allows login
                    957: 
                    958: sub choose_server {
1.1172.2.47  raeburn   959:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   960:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   961:     my %servers = &get_servers($udom);
1.1076    raeburn   962:     my $lowest_load = 30000;
1.1172.2.47  raeburn   963:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    964:     if ($skiploadbal) {
                    965:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    966:         unless (defined($cached)) {
                    967:             my $cachetime = 60*60*24;
                    968:             my %domconfig =
                    969:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    970:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    971:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    972:                                            $cachetime);
                    973:             }
                    974:         }
                    975:     }
1.1076    raeburn   976:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   977:         my $loginvia;
1.1172.2.47  raeburn   978:         if ($skiploadbal) {
                    979:             if (ref($balancers) eq 'HASH') {
                    980:                 next if (exists($balancers->{$lonhost}));
                    981:             }
                    982:         }
1.1115    raeburn   983:         if ($checkloginvia) {
                    984:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   985:             if ($loginvia) {
                    986:                 my ($server,$path) = split(/:/,$loginvia);
                    987:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   988:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   989:                 if ($login_host eq $server) {
                    990:                     $portal_path = $path;
1.1151    raeburn   991:                     $isredirect = 1;
1.1116    raeburn   992:                 }
                    993:             } else {
                    994:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   995:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   996:                 if ($login_host eq $lonhost) {
                    997:                     $portal_path = '';
1.1151    raeburn   998:                     $isredirect = ''; 
1.1116    raeburn   999:                 }
                   1000:             }
                   1001:         } else {
1.1076    raeburn  1002:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1003:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1004:         }
                   1005:     }
                   1006:     if ($login_host ne '') {
1.1116    raeburn  1007:         $hostname = &hostname($login_host);
1.1076    raeburn  1008:     }
1.1151    raeburn  1009:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1010: }
                   1011: 
1.202     matthew  1012: # --------------------------------------------- Try to change a user's password
                   1013: 
                   1014: sub changepass {
1.799     raeburn  1015:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1016:     $currentpass = &escape($currentpass);
                   1017:     $newpass     = &escape($newpass);
1.1030    raeburn  1018:     my $lonhost = $perlvar{'lonHostID'};
                   1019:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1020: 		       $server);
                   1021:     if (! $answer) {
                   1022: 	&logthis("No reply on password change request to $server ".
                   1023: 		 "by $uname in domain $udom.");
                   1024:     } elsif ($answer =~ "^ok") {
                   1025:         &logthis("$uname in $udom successfully changed their password ".
                   1026: 		 "on $server.");
                   1027:     } elsif ($answer =~ "^pwchange_failure") {
                   1028: 	&logthis("$uname in $udom was unable to change their password ".
                   1029: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1030: 		 "or pwchange");
                   1031:     } elsif ($answer =~ "^non_authorized") {
                   1032:         &logthis("$uname in $udom did not get their password correct when ".
                   1033: 		 "attempting to change it on $server.");
                   1034:     } elsif ($answer =~ "^auth_mode_error") {
                   1035:         &logthis("$uname in $udom attempted to change their password despite ".
                   1036: 		 "not being locally or internally authenticated on $server.");
                   1037:     } elsif ($answer =~ "^unknown_user") {
                   1038:         &logthis("$uname in $udom attempted to change their password ".
                   1039: 		 "on $server but were unable to because $server is not ".
                   1040: 		 "their home server.");
                   1041:     } elsif ($answer =~ "^refused") {
                   1042: 	&logthis("$server refused to change $uname in $udom password because ".
                   1043: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1044:     } elsif ($answer =~ "invalid_client") {
                   1045:         &logthis("$server refused to change $uname in $udom password because ".
                   1046:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1047:     }
                   1048:     return $answer;
1.1       albertel 1049: }
                   1050: 
1.169     harris41 1051: # ----------------------- Try to determine user's current authentication scheme
                   1052: 
                   1053: sub queryauthenticate {
                   1054:     my ($uname,$udom)=@_;
1.456     albertel 1055:     my $uhome=&homeserver($uname,$udom);
                   1056:     if (!$uhome) {
                   1057: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1058: 	return 'no_host';
                   1059:     }
                   1060:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1061:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1062: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1063:     }
1.456     albertel 1064:     return $answer;
1.169     harris41 1065: }
                   1066: 
1.1       albertel 1067: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1068: 
1.1       albertel 1069: sub authenticate {
1.1073    raeburn  1070:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1071:     $upass=&escape($upass);
                   1072:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1073:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1074:     my $newhome;
1.836     www      1075:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1076: # Maybe the machine was offline and only re-appeared again recently?
                   1077:         &reconlonc();
                   1078: # One more
1.952     raeburn  1079: 	$uhome=&homeserver($uname,$udom,1);
                   1080:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1081:             if (defined(&domain($udom,'primary'))) {
                   1082:                 $newhome=&domain($udom,'primary');
                   1083:             }
                   1084:             if ($newhome ne '') {
                   1085:                 $uhome = $newhome;
                   1086:             }
                   1087:         }
1.836     www      1088: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1089: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1090: 	    return 'no_host';
                   1091:         }
1.1       albertel 1092:     }
1.1073    raeburn  1093:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1094:     if ($answer eq 'authorized') {
1.952     raeburn  1095:         if ($newhome) {
                   1096:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1097:             return 'no_account_on_host'; 
                   1098:         } else {
                   1099:             &logthis("User $uname at $udom authorized by $uhome");
                   1100:             return $uhome;
                   1101:         }
1.471     albertel 1102:     }
                   1103:     if ($answer eq 'non_authorized') {
                   1104: 	&logthis("User $uname at $udom rejected by $uhome");
                   1105: 	return 'no_host'; 
1.9       www      1106:     }
1.471     albertel 1107:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1108:     return 'no_host';
                   1109: }
                   1110: 
1.1073    raeburn  1111: sub can_host_session {
1.1074    raeburn  1112:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1113:     my $canhost = 1;
1.1074    raeburn  1114:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1115:     if (ref($remotesessions) eq 'HASH') {
                   1116:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1117:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1118:                 $canhost = 0;
                   1119:             } else {
                   1120:                 $canhost = 1;
                   1121:             }
                   1122:         }
                   1123:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1124:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1125:                 $canhost = 1;
                   1126:             } else {
                   1127:                 $canhost = 0;
                   1128:             }
                   1129:         }
                   1130:         if ($canhost) {
                   1131:             if ($remotesessions->{'version'} ne '') {
                   1132:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1133:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1134:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1135:                         my $major = $1;
                   1136:                         my $minor = $2;
                   1137:                         if (($major < $reqmajor ) ||
                   1138:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1139:                             $canhost = 0;
                   1140:                         }
                   1141:                     } else {
                   1142:                         $canhost = 0;
                   1143:                     }
                   1144:                 }
                   1145:             }
                   1146:         }
                   1147:     }
                   1148:     if ($canhost) {
                   1149:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1150:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1151:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1152:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1153:                 if (($uint_dom ne '') && 
                   1154:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1155:                     $canhost = 0;
                   1156:                 } else {
                   1157:                     $canhost = 1;
                   1158:                 }
                   1159:             }
                   1160:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1161:                 if (($uint_dom ne '') && 
                   1162:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1163:                     $canhost = 1;
                   1164:                 } else {
                   1165:                     $canhost = 0;
                   1166:                 }
                   1167:             }
                   1168:         }
                   1169:     }
                   1170:     return $canhost;
                   1171: }
                   1172: 
1.1083    raeburn  1173: sub spare_can_host {
                   1174:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1175:     my $canhost=1;
                   1176:     my @intdoms;
                   1177:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1178:     if (ref($internet_names) eq 'ARRAY') {
                   1179:         @intdoms = @{$internet_names};
                   1180:     }
                   1181:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1182:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1183:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1184:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1185:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1186:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1187:                                      $remotesessions,
                   1188:                                      $defdomdefaults{'hostedsessions'});
                   1189:     }
                   1190:     return $canhost;
                   1191: }
                   1192: 
1.1123    raeburn  1193: sub this_host_spares {
                   1194:     my ($dom) = @_;
1.1126    raeburn  1195:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1196:     my @hosts = &current_machine_ids();
                   1197:     foreach my $lonhost (@hosts) {
                   1198:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1199:             $dom_in_use = $dom;
                   1200:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1201:             last;
                   1202:         }
                   1203:     }
1.1126    raeburn  1204:     if ($dom_in_use ne '') {
                   1205:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1206:     }
                   1207:     if (ref($result) ne 'HASH') {
                   1208:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1209:         $dom_in_use = &host_domain($lonhost_in_use);
                   1210:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1211:         if (ref($result) ne 'HASH') {
                   1212:             $result = \%spareid;
                   1213:         }
                   1214:     }
                   1215:     return $result;
                   1216: }
                   1217: 
                   1218: sub spares_for_offload  {
                   1219:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1220:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1221:     if (defined($cached)) {
                   1222:         return $result;
                   1223:     } else {
1.1126    raeburn  1224:         my $cachetime = 60*60*24;
                   1225:         my %domconfig =
                   1226:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1227:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1228:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1229:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1230:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1231:                 }
                   1232:             }
                   1233:         }
                   1234:     }
1.1126    raeburn  1235:     return;
1.1123    raeburn  1236: }
                   1237: 
1.1129    raeburn  1238: sub get_lonbalancer_config {
                   1239:     my ($servers) = @_;
                   1240:     my ($currbalancer,$currtargets);
                   1241:     if (ref($servers) eq 'HASH') {
                   1242:         foreach my $server (keys(%{$servers})) {
                   1243:             my %what = (
                   1244:                          spareid => 1,
                   1245:                          perlvar => 1,
                   1246:                        );
                   1247:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1248:             if ($result eq 'ok') {
                   1249:                 if (ref($returnhash) eq 'HASH') {
                   1250:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1251:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1252:                             $currbalancer = $server;
                   1253:                             $currtargets = {};
                   1254:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1255:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1256:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1257:                                 }
                   1258:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1259:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1260:                                 }
                   1261:                             }
                   1262:                             last;
                   1263:                         }
                   1264:                     }
                   1265:                 }
                   1266:             }
                   1267:         }
                   1268:     }
                   1269:     return ($currbalancer,$currtargets);
                   1270: }
                   1271: 
                   1272: sub check_loadbalancing {
                   1273:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1274:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1275:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1276:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1277:     my @hosts = &current_machine_ids();
1.1129    raeburn  1278:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1279:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1280:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1281:     my $serverhomedom = &host_domain($lonhost);
                   1282: 
                   1283:     my $cachetime = 60*60*24;
                   1284: 
                   1285:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1286:         $dom_in_use = $udom;
                   1287:         $homeintdom = 1;
                   1288:     } else {
                   1289:         $dom_in_use = $serverhomedom;
                   1290:     }
                   1291:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1292:     unless (defined($cached)) {
                   1293:         my %domconfig =
                   1294:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1295:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1296:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1297:         }
                   1298:     }
                   1299:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1300:         ($is_balancer,$currtargets,$currrules) =
                   1301:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1302:         if ($is_balancer) {
                   1303:             if (ref($currrules) eq 'HASH') {
                   1304:                 if ($homeintdom) {
                   1305:                     if ($uname ne '') {
                   1306:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1307:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1308:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1309:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1310:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1311:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1312:                             }
                   1313:                         }
                   1314:                         if ($rule_in_effect eq '') {
                   1315:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1316:                             if ($userenv{'inststatus'} ne '') {
                   1317:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1318:                                 my ($othertitle,$usertypes,$types) =
                   1319:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1320:                                 if (ref($types) eq 'ARRAY') {
                   1321:                                     foreach my $type (@{$types}) {
                   1322:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1323:                                             if (exists($currrules->{$type})) {
                   1324:                                                 $rule_in_effect = $currrules->{$type};
                   1325:                                             }
                   1326:                                         }
                   1327:                                     }
                   1328:                                 }
                   1329:                             } else {
                   1330:                                 if (exists($currrules->{'default'})) {
                   1331:                                     $rule_in_effect = $currrules->{'default'};
                   1332:                                 }
                   1333:                             }
                   1334:                         }
                   1335:                     } else {
                   1336:                         if (exists($currrules->{'default'})) {
                   1337:                             $rule_in_effect = $currrules->{'default'};
                   1338:                         }
                   1339:                     }
                   1340:                 } else {
                   1341:                     if ($currrules->{'_LC_external'} ne '') {
                   1342:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1343:                     }
                   1344:                 }
                   1345:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1346:                                                        $uname,$udom);
                   1347:             }
                   1348:         }
                   1349:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1350:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1351:         unless (defined($cached)) {
                   1352:             my %domconfig =
                   1353:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1354:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1355:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1356:             }
                   1357:         }
                   1358:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1359:             ($is_balancer,$currtargets,$currrules) =
                   1360:                 &check_balancer_result($result,@hosts);
                   1361:             if ($is_balancer) {
1.1129    raeburn  1362:                 if (ref($currrules) eq 'HASH') {
                   1363:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1364:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1365:                     }
                   1366:                 }
                   1367:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1368:                                                        $uname,$udom);
                   1369:             }
                   1370:         } else {
                   1371:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1372:                 $is_balancer = 1;
                   1373:                 $offloadto = &this_host_spares($dom_in_use);
                   1374:             }
                   1375:         }
                   1376:     } else {
                   1377:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1378:             $is_balancer = 1;
                   1379:             $offloadto = &this_host_spares($dom_in_use);
                   1380:         }
                   1381:     }
1.1172.2.5  raeburn  1382:     if ($is_balancer) {
                   1383:         my $lowest_load = 30000;
                   1384:         if (ref($offloadto) eq 'HASH') {
                   1385:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1386:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1387:                     ($otherserver,$lowest_load) =
                   1388:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1389:                 }
1.1129    raeburn  1390:             }
1.1172.2.5  raeburn  1391:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1392: 
1.1172.2.5  raeburn  1393:             if (!$found_server) {
                   1394:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1395:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1396:                         ($otherserver,$lowest_load) =
                   1397:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1398:                     }
                   1399:                 }
                   1400:             }
                   1401:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1402:             if (@{$offloadto} == 1) {
                   1403:                 $otherserver = $offloadto->[0];
                   1404:             } elsif (@{$offloadto} > 1) {
                   1405:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1406:                     ($otherserver,$lowest_load) =
                   1407:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1408:                 }
                   1409:             }
                   1410:         }
1.1172.2.5  raeburn  1411:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1412:             $is_balancer = 0;
                   1413:             if ($uname ne '' && $udom ne '') {
                   1414:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1415: 
                   1416:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1417:                              'user.loadbalcheck.time' => time});
                   1418:                 }
1.1129    raeburn  1419:             }
                   1420:         }
                   1421:     }
                   1422:     return ($is_balancer,$otherserver);
                   1423: }
                   1424: 
1.1172.2.12  raeburn  1425: sub check_balancer_result {
                   1426:     my ($result,@hosts) = @_;
                   1427:     my ($is_balancer,$currtargets,$currrules);
                   1428:     if (ref($result) eq 'HASH') {
                   1429:         if ($result->{'lonhost'} ne '') {
                   1430:             my $currbalancer = $result->{'lonhost'};
                   1431:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1432:                 $is_balancer = 1;
                   1433:                 $currtargets = $result->{'targets'};
                   1434:                 $currrules = $result->{'rules'};
                   1435:             }
                   1436:         } else {
                   1437:             foreach my $key (keys(%{$result})) {
                   1438:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1439:                     (ref($result->{$key}) eq 'HASH')) {
                   1440:                     $is_balancer = 1;
                   1441:                     $currrules = $result->{$key}{'rules'};
                   1442:                     $currtargets = $result->{$key}{'targets'};
                   1443:                     last;
                   1444:                 }
                   1445:             }
                   1446:         }
                   1447:     }
                   1448:     return ($is_balancer,$currtargets,$currrules);
                   1449: }
                   1450: 
1.1129    raeburn  1451: sub get_loadbalancer_targets {
                   1452:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1453:     my $offloadto;
1.1172.2.4  raeburn  1454:     if ($rule_in_effect eq 'none') {
                   1455:         return [$perlvar{'lonHostID'}];
                   1456:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1457:         $offloadto = $currtargets;
                   1458:     } else {
                   1459:         if ($rule_in_effect eq 'homeserver') {
                   1460:             my $homeserver = &homeserver($uname,$udom);
                   1461:             if ($homeserver ne 'no_host') {
                   1462:                 $offloadto = [$homeserver];
                   1463:             }
                   1464:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1465:             my %domconfig =
                   1466:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1467:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1468:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1469:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1470:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1471:                     }
                   1472:                 }
                   1473:             } else {
1.1172.2.7  raeburn  1474:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1475:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1476:                 if (&hostname($remotebalancer) ne '') {
                   1477:                     $offloadto = [$remotebalancer];
                   1478:                 }
                   1479:             }
                   1480:         } elsif (&hostname($rule_in_effect) ne '') {
                   1481:             $offloadto = [$rule_in_effect];
                   1482:         }
                   1483:     }
                   1484:     return $offloadto;
                   1485: }
                   1486: 
1.1127    raeburn  1487: sub internet_dom_servers {
                   1488:     my ($dom) = @_;
                   1489:     my (%uniqservers,%servers);
                   1490:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1491:     my @machinedoms = &machine_domains($primaryserver);
                   1492:     foreach my $mdom (@machinedoms) {
                   1493:         my %currservers = %servers;
                   1494:         my %server = &get_servers($mdom);
                   1495:         %servers = (%currservers,%server);
                   1496:     }
                   1497:     my %by_hostname;
                   1498:     foreach my $id (keys(%servers)) {
                   1499:         push(@{$by_hostname{$servers{$id}}},$id);
                   1500:     }
                   1501:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1502:         if (@{$by_hostname{$hostname}} > 1) {
                   1503:             my $match = 0;
                   1504:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1505:                 if (&host_domain($id) eq $dom) {
                   1506:                     $uniqservers{$id} = $hostname;
                   1507:                     $match = 1;
                   1508:                 }
                   1509:             }
                   1510:             unless ($match) {
                   1511:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1512:             }
                   1513:         } else {
                   1514:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1515:         }
                   1516:     }
                   1517:     return %uniqservers;
                   1518: }
                   1519: 
1.1       albertel 1520: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1521: 
1.599     albertel 1522: my %homecache;
1.1       albertel 1523: sub homeserver {
1.230     stredwic 1524:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1525:     my $index="$uname:$udom";
1.426     albertel 1526: 
1.599     albertel 1527:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1528: 
                   1529:     my %servers = &get_servers($udom,'library');
                   1530:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1531:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1532: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1533: 
                   1534: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1535: 	if ($answer eq 'found') {
                   1536: 	    delete($badServerCache{$tryserver}); 
                   1537: 	    return $homecache{$index}=$tryserver;
                   1538: 	} elsif ($answer eq 'no_host') {
                   1539: 	    $badServerCache{$tryserver}=1;
                   1540: 	}
1.1       albertel 1541:     }    
                   1542:     return 'no_host';
1.70      www      1543: }
                   1544: 
                   1545: # ------------------------------------- Find the usernames behind a list of IDs
                   1546: 
                   1547: sub idget {
                   1548:     my ($udom,@ids)=@_;
                   1549:     my %returnhash=();
                   1550:     
1.841     albertel 1551:     my %servers = &get_servers($udom,'library');
                   1552:     foreach my $tryserver (keys(%servers)) {
                   1553: 	my $idlist=join('&',@ids);
                   1554: 	$idlist=~tr/A-Z/a-z/; 
                   1555: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1556: 	my @answer=();
                   1557: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1558: 	    @answer=split(/\&/,$reply);
                   1559: 	}                    ;
                   1560: 	my $i;
                   1561: 	for ($i=0;$i<=$#ids;$i++) {
                   1562: 	    if ($answer[$i]) {
                   1563: 		$returnhash{$ids[$i]}=$answer[$i];
                   1564: 	    } 
                   1565: 	}
                   1566:     } 
1.70      www      1567:     return %returnhash;
                   1568: }
                   1569: 
                   1570: # ------------------------------------- Find the IDs behind a list of usernames
                   1571: 
                   1572: sub idrget {
                   1573:     my ($udom,@unames)=@_;
                   1574:     my %returnhash=();
1.800     albertel 1575:     foreach my $uname (@unames) {
                   1576:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1577:     }
1.70      www      1578:     return %returnhash;
                   1579: }
                   1580: 
                   1581: # ------------------------------- Store away a list of names and associated IDs
                   1582: 
                   1583: sub idput {
                   1584:     my ($udom,%ids)=@_;
                   1585:     my %servers=();
1.800     albertel 1586:     foreach my $uname (keys(%ids)) {
                   1587: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1588:         my $uhom=&homeserver($uname,$udom);
1.70      www      1589:         if ($uhom ne 'no_host') {
1.800     albertel 1590:             my $id=&escape($ids{$uname});
1.70      www      1591:             $id=~tr/A-Z/a-z/;
1.800     albertel 1592:             my $esc_unam=&escape($uname);
1.70      www      1593: 	    if ($servers{$uhom}) {
1.800     albertel 1594: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1595:             } else {
1.800     albertel 1596:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1597:             }
                   1598:         }
1.191     harris41 1599:     }
1.800     albertel 1600:     foreach my $server (keys(%servers)) {
                   1601:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1602:     }
1.344     www      1603: }
                   1604: 
1.1172.2.30  raeburn  1605: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1606: 
                   1607: sub iddel {
                   1608:     my ($udom,$idshashref,$uhome)=@_;
                   1609:     my %result=();
                   1610:     unless (ref($idshashref) eq 'HASH') {
                   1611:         return %result;
                   1612:     }
                   1613:     my %servers=();
                   1614:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1615:         my $uhom;
                   1616:         if ($uhome) {
                   1617:             $uhom = $uhome;
                   1618:         } else {
                   1619:             $uhom=&homeserver($uname,$udom);
                   1620:         }
                   1621:         if ($uhom ne 'no_host') {
                   1622:             if ($servers{$uhom}) {
                   1623:                 $servers{$uhom}.='&'.&escape($id);
                   1624:             } else {
                   1625:                 $servers{$uhom}=&escape($id);
                   1626:             }
                   1627:         }
                   1628:     }
                   1629:     foreach my $server (keys(%servers)) {
                   1630:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1631:     }
                   1632:     return %result;
                   1633: }
                   1634: 
1.1023    raeburn  1635: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1636: sub dump_dom {
1.1165    droeschl 1637:     my ($namespace, $udom, $regexp) = @_;
                   1638: 
                   1639:     $udom ||= $env{'user.domain'};
                   1640: 
                   1641:     return () unless $udom;
                   1642: 
                   1643:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1644: }
                   1645: 
1.1023    raeburn  1646: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1647: 
                   1648: sub get_dom {
1.860     raeburn  1649:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1650:     return if ($udom eq 'public');
1.806     raeburn  1651:     my $items='';
                   1652:     foreach my $item (@$storearr) {
                   1653:         $items.=&escape($item).'&';
                   1654:     }
                   1655:     $items=~s/\&$//;
1.860     raeburn  1656:     if (!$udom) {
                   1657:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1658:         return if ($udom eq 'public');
1.860     raeburn  1659:         if (defined(&domain($udom,'primary'))) {
                   1660:             $uhome=&domain($udom,'primary');
                   1661:         } else {
1.874     albertel 1662:             undef($uhome);
1.860     raeburn  1663:         }
                   1664:     } else {
                   1665:         if (!$uhome) {
                   1666:             if (defined(&domain($udom,'primary'))) {
                   1667:                 $uhome=&domain($udom,'primary');
                   1668:             }
                   1669:         }
                   1670:     }
                   1671:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1672:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1673:         my %returnhash;
1.875     albertel 1674:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1675:             return %returnhash;
                   1676:         }
1.806     raeburn  1677:         my @pairs=split(/\&/,$rep);
                   1678:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1679:             return @pairs;
                   1680:         }
                   1681:         my $i=0;
                   1682:         foreach my $item (@$storearr) {
                   1683:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1684:             $i++;
                   1685:         }
                   1686:         return %returnhash;
                   1687:     } else {
1.880     banghart 1688:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1689:     }
                   1690: }
                   1691: 
                   1692: # -------------------------------------------- put items in domain db files 
                   1693: 
                   1694: sub put_dom {
1.860     raeburn  1695:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1696:     if (!$udom) {
                   1697:         $udom=$env{'user.domain'};
                   1698:         if (defined(&domain($udom,'primary'))) {
                   1699:             $uhome=&domain($udom,'primary');
                   1700:         } else {
1.874     albertel 1701:             undef($uhome);
1.860     raeburn  1702:         }
                   1703:     } else {
                   1704:         if (!$uhome) {
                   1705:             if (defined(&domain($udom,'primary'))) {
                   1706:                 $uhome=&domain($udom,'primary');
                   1707:             }
                   1708:         }
                   1709:     } 
                   1710:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1711:         my $items='';
                   1712:         foreach my $item (keys(%$storehash)) {
                   1713:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1714:         }
                   1715:         $items=~s/\&$//;
                   1716:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1717:     } else {
1.860     raeburn  1718:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1719:     }
                   1720: }
                   1721: 
1.1023    raeburn  1722: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1723: sub newput_dom {
1.1023    raeburn  1724:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1725:     my $result;
                   1726:     if (!$udom) {
                   1727:         $udom=$env{'user.domain'};
                   1728:     }
1.1023    raeburn  1729:     if ($udom) {
                   1730:         my $uname = &get_domainconfiguser($udom);
                   1731:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1732:     }
                   1733:     return $result;
                   1734: }
                   1735: 
1.1023    raeburn  1736: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1737: sub del_dom {
1.1023    raeburn  1738:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1739:     if (ref($storearr) eq 'ARRAY') {
                   1740:         if (!$udom) {
                   1741:             $udom=$env{'user.domain'};
                   1742:         }
1.1023    raeburn  1743:         if ($udom) {
                   1744:             my $uname = &get_domainconfiguser($udom); 
                   1745:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1746:         }
                   1747:     }
                   1748: }
                   1749: 
1.1023    raeburn  1750: # ----------------------------------construct domainconfig user for a domain 
                   1751: sub get_domainconfiguser {
                   1752:     my ($udom) = @_;
                   1753:     return $udom.'-domainconfig';
                   1754: }
                   1755: 
1.837     raeburn  1756: sub retrieve_inst_usertypes {
                   1757:     my ($udom) = @_;
                   1758:     my (%returnhash,@order);
1.989     raeburn  1759:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1760:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1761:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1762:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1763:     } else {
                   1764:         if (defined(&domain($udom,'primary'))) {
                   1765:             my $uhome=&domain($udom,'primary');
                   1766:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1767:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1768:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1769:                 return (\%returnhash,\@order);
                   1770:             }
                   1771:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1772:             my @pairs=split(/\&/,$hashitems);
                   1773:             foreach my $item (@pairs) {
                   1774:                 my ($key,$value)=split(/=/,$item,2);
                   1775:                 $key = &unescape($key);
                   1776:                 next if ($key =~ /^error: 2 /);
                   1777:                 $returnhash{$key}=&thaw_unescape($value);
                   1778:             }
                   1779:             my @esc_order = split(/\&/,$orderitems);
                   1780:             foreach my $item (@esc_order) {
                   1781:                 push(@order,&unescape($item));
                   1782:             }
                   1783:         } else {
1.1172.2.44  raeburn  1784:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1785:         }
1.1172.2.44  raeburn  1786:         return (\%returnhash,\@order);
1.837     raeburn  1787:     }
                   1788: }
                   1789: 
1.868     raeburn  1790: sub is_domainimage {
                   1791:     my ($url) = @_;
                   1792:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1793:         if (&domain($1) ne '') {
                   1794:             return '1';
                   1795:         }
                   1796:     }
                   1797:     return;
                   1798: }
                   1799: 
1.899     raeburn  1800: sub inst_directory_query {
                   1801:     my ($srch) = @_;
                   1802:     my $udom = $srch->{'srchdomain'};
                   1803:     my %results;
                   1804:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1805:     my $outcome;
1.899     raeburn  1806:     if ($homeserver ne '') {
1.904     albertel 1807: 	my $queryid=&reply("querysend:instdirsearch:".
                   1808: 			   &escape($srch->{'srchby'}).':'.
                   1809: 			   &escape($srch->{'srchterm'}).':'.
                   1810: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1811: 	my $host=&hostname($homeserver);
                   1812: 	if ($queryid !~/^\Q$host\E\_/) {
                   1813: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1814: 	    return;
                   1815: 	}
                   1816: 	my $response = &get_query_reply($queryid);
                   1817: 	my $maxtries = 5;
                   1818: 	my $tries = 1;
                   1819: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1820: 	    $response = &get_query_reply($queryid);
                   1821: 	    $tries ++;
                   1822: 	}
                   1823: 
                   1824:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1825:             if ($response eq 'unavailable') {
                   1826:                 $outcome = $response;
                   1827:             } else {
                   1828:                 $outcome = 'ok';
                   1829:                 my @matches = split(/\n/,$response);
                   1830:                 foreach my $match (@matches) {
                   1831:                     my ($key,$value) = split(/=/,$match);
                   1832:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1833:                 }
1.899     raeburn  1834:             }
                   1835:         }
                   1836:     }
1.909     raeburn  1837:     return ($outcome,%results);
1.899     raeburn  1838: }
                   1839: 
                   1840: sub usersearch {
                   1841:     my ($srch) = @_;
                   1842:     my $dom = $srch->{'srchdomain'};
                   1843:     my %results;
                   1844:     my %libserv = &all_library();
                   1845:     my $query = 'usersearch';
                   1846:     foreach my $tryserver (keys(%libserv)) {
                   1847:         if (&host_domain($tryserver) eq $dom) {
                   1848:             my $host=&hostname($tryserver);
                   1849:             my $queryid=
1.911     raeburn  1850:                 &reply("querysend:".&escape($query).':'.
                   1851:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1852:                        &escape($srch->{'srchtype'}).':'.
                   1853:                        &escape($srch->{'srchterm'}),$tryserver);
                   1854:             if ($queryid !~/^\Q$host\E\_/) {
                   1855:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1856:                 next;
1.899     raeburn  1857:             }
                   1858:             my $reply = &get_query_reply($queryid);
                   1859:             my $maxtries = 1;
                   1860:             my $tries = 1;
                   1861:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1862:                 $reply = &get_query_reply($queryid);
                   1863:                 $tries ++;
                   1864:             }
                   1865:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1866:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1867:             } else {
1.911     raeburn  1868:                 my @matches;
                   1869:                 if ($reply =~ /\n/) {
                   1870:                     @matches = split(/\n/,$reply);
                   1871:                 } else {
                   1872:                     @matches = split(/\&/,$reply);
                   1873:                 }
1.899     raeburn  1874:                 foreach my $match (@matches) {
                   1875:                     my ($uname,$udom,%userhash);
1.911     raeburn  1876:                     foreach my $entry (split(/:/,$match)) {
                   1877:                         my ($key,$value) =
                   1878:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1879:                         $userhash{$key} = $value;
                   1880:                         if ($key eq 'username') {
                   1881:                             $uname = $value;
                   1882:                         } elsif ($key eq 'domain') {
                   1883:                             $udom = $value;
1.911     raeburn  1884:                         }
1.899     raeburn  1885:                     }
                   1886:                     $results{$uname.':'.$udom} = \%userhash;
                   1887:                 }
                   1888:             }
                   1889:         }
                   1890:     }
                   1891:     return %results;
                   1892: }
                   1893: 
1.912     raeburn  1894: sub get_instuser {
                   1895:     my ($udom,$uname,$id) = @_;
                   1896:     my $homeserver = &domain($udom,'primary');
                   1897:     my ($outcome,%results);
                   1898:     if ($homeserver ne '') {
                   1899:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1900:                            &escape($id).':'.&escape($udom),$homeserver);
                   1901:         my $host=&hostname($homeserver);
                   1902:         if ($queryid !~/^\Q$host\E\_/) {
                   1903:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1904:             return;
                   1905:         }
                   1906:         my $response = &get_query_reply($queryid);
                   1907:         my $maxtries = 5;
                   1908:         my $tries = 1;
                   1909:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1910:             $response = &get_query_reply($queryid);
                   1911:             $tries ++;
                   1912:         }
                   1913:         if (!&error($response) && $response ne 'refused') {
                   1914:             if ($response eq 'unavailable') {
                   1915:                 $outcome = $response;
                   1916:             } else {
                   1917:                 $outcome = 'ok';
                   1918:                 my @matches = split(/\n/,$response);
                   1919:                 foreach my $match (@matches) {
                   1920:                     my ($key,$value) = split(/=/,$match);
                   1921:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1922:                 }
                   1923:             }
                   1924:         }
                   1925:     }
                   1926:     my %userinfo;
                   1927:     if (ref($results{$uname}) eq 'HASH') {
                   1928:         %userinfo = %{$results{$uname}};
                   1929:     } 
                   1930:     return ($outcome,%userinfo);
                   1931: }
                   1932: 
                   1933: sub inst_rulecheck {
1.923     raeburn  1934:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1935:     my %returnhash;
                   1936:     if ($udom ne '') {
                   1937:         if (ref($rules) eq 'ARRAY') {
                   1938:             @{$rules} = map {&escape($_);} (@{$rules});
                   1939:             my $rulestr = join(':',@{$rules});
                   1940:             my $homeserver=&domain($udom,'primary');
                   1941:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1942:                 my $response;
                   1943:                 if ($item eq 'username') {                
                   1944:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1945:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1946:                                               $homeserver));
1.923     raeburn  1947:                 } elsif ($item eq 'id') {
                   1948:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1949:                                               ':'.&escape($id).':'.$rulestr,
                   1950:                                               $homeserver));
1.945     raeburn  1951:                 } elsif ($item eq 'selfcreate') {
                   1952:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1953:                                                &escape($udom).':'.&escape($uname).
                   1954:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1955:                 }
1.912     raeburn  1956:                 if ($response ne 'refused') {
                   1957:                     my @pairs=split(/\&/,$response);
                   1958:                     foreach my $item (@pairs) {
                   1959:                         my ($key,$value)=split(/=/,$item,2);
                   1960:                         $key = &unescape($key);
                   1961:                         next if ($key =~ /^error: 2 /);
                   1962:                         $returnhash{$key}=&thaw_unescape($value);
                   1963:                     }
                   1964:                 }
                   1965:             }
                   1966:         }
                   1967:     }
                   1968:     return %returnhash;
                   1969: }
                   1970: 
                   1971: sub inst_userrules {
1.923     raeburn  1972:     my ($udom,$check) = @_;
1.912     raeburn  1973:     my (%ruleshash,@ruleorder);
                   1974:     if ($udom ne '') {
                   1975:         my $homeserver=&domain($udom,'primary');
                   1976:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1977:             my $response;
                   1978:             if ($check eq 'id') {
                   1979:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1980:                                  $homeserver);
1.943     raeburn  1981:             } elsif ($check eq 'email') {
                   1982:                 $response=&reply('instemailrules:'.&escape($udom),
                   1983:                                  $homeserver);
1.923     raeburn  1984:             } else {
                   1985:                 $response=&reply('instuserrules:'.&escape($udom),
                   1986:                                  $homeserver);
                   1987:             }
1.912     raeburn  1988:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1989:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1990:                 ($response ne 'no_such_host')) {
                   1991:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1992:                 my @pairs=split(/\&/,$hashitems);
                   1993:                 foreach my $item (@pairs) {
                   1994:                     my ($key,$value)=split(/=/,$item,2);
                   1995:                     $key = &unescape($key);
                   1996:                     next if ($key =~ /^error: 2 /);
                   1997:                     $ruleshash{$key}=&thaw_unescape($value);
                   1998:                 }
                   1999:                 my @esc_order = split(/\&/,$orderitems);
                   2000:                 foreach my $item (@esc_order) {
                   2001:                     push(@ruleorder,&unescape($item));
                   2002:                 }
                   2003:             }
                   2004:         }
                   2005:     }
                   2006:     return (\%ruleshash,\@ruleorder);
                   2007: }
                   2008: 
1.976     raeburn  2009: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2010: 
                   2011: sub get_domain_defaults {
1.1172.2.35  raeburn  2012:     my ($domain,$ignore_cache) = @_;
                   2013:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2014:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2015:     unless ($ignore_cache) {
                   2016:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2017:         if (defined($cached)) {
                   2018:             if (ref($result) eq 'HASH') {
                   2019:                 return %{$result};
                   2020:             }
1.943     raeburn  2021:         }
                   2022:     }
                   2023:     my %domdefaults;
                   2024:     my %domconfig =
1.989     raeburn  2025:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2026:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2027:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2028:                                   'requestauthor','selfenrollment',
                   2029:                                   'coursecategories'],$domain);
1.1172.2.41  raeburn  2030:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2031:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2032:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2033:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2034:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2035:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2036:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2037:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2038:     } else {
                   2039:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2040:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2041:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2042:     }
1.976     raeburn  2043:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2044:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2045:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2046:         } else {
                   2047:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2048:         }
1.1172.2.6  raeburn  2049:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2050:         foreach my $item (@usertools) {
                   2051:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2052:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2053:             }
                   2054:         }
1.1172.2.29  raeburn  2055:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2056:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2057:         }
1.976     raeburn  2058:     }
1.985     raeburn  2059:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2060:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2061:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2062:         }
                   2063:     }
1.1172.2.9  raeburn  2064:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2065:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2066:     }
1.989     raeburn  2067:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2068:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2069:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2070:         }
                   2071:     }
1.1047    raeburn  2072:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.41  raeburn  2073:         foreach my $type (@coursetypes) {
                   2074:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2075:                 unless ($type eq 'community') {
                   2076:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2077:                 }
                   2078:             }
                   2079:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2080:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2081:             }
1.1172.2.30  raeburn  2082:         }
1.1047    raeburn  2083:     }
1.1073    raeburn  2084:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2085:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2086:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2087:         }
                   2088:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2089:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2090:         }
                   2091:     }
1.1172.2.41  raeburn  2092:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2093:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2094:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2095:                             'approval','limit');
                   2096:             foreach my $type (@coursetypes) {
                   2097:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2098:                     my @mgrdc = ();
                   2099:                     foreach my $item (@settings) {
                   2100:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2101:                             push(@mgrdc,$item);
                   2102:                         }
                   2103:                     }
                   2104:                     if (@mgrdc) {
                   2105:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2106:                     }
                   2107:                 }
                   2108:             }
                   2109:         }
                   2110:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2111:             foreach my $type (@coursetypes) {
                   2112:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2113:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2114:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2115:                     }
                   2116:                 }
                   2117:             }
                   2118:         }
                   2119:     }
1.1172.2.46  raeburn  2120:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2121:         $domdefaults{'catauth'} = 'std';
                   2122:         $domdefaults{'catunauth'} = 'std';
                   2123:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2124:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2125:         }
                   2126:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2127:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2128:         }
                   2129:     }
1.1172.2.23  raeburn  2130:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2131:     return %domdefaults;
                   2132: }
                   2133: 
1.344     www      2134: # --------------------------------------------------- Assign a key to a student
                   2135: 
                   2136: sub assign_access_key {
1.364     www      2137: #
                   2138: # a valid key looks like uname:udom#comments
                   2139: # comments are being appended
                   2140: #
1.498     www      2141:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2142:     $kdom=
1.620     albertel 2143:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2144:     $knum=
1.620     albertel 2145:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2146:     $cdom=
1.620     albertel 2147:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2148:     $cnum=
1.620     albertel 2149:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2150:     $udom=$env{'user.name'} unless (defined($udom));
                   2151:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2152:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2153:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2154:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2155:                                                   # assigned to this person
                   2156:                                                   # - this should not happen,
1.345     www      2157:                                                   # unless something went wrong
                   2158:                                                   # the first time around
                   2159: # ready to assign
1.364     www      2160:         $logentry=$1.'; '.$logentry;
1.496     www      2161:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2162:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2163: # key now belongs to user
1.346     www      2164: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2165:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2166:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2167:                 return 'ok';
                   2168:             } else {
                   2169:                 return 
                   2170:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2171: 	    }
                   2172:         } else {
                   2173:             return 'error: Could not assign key, try again later.';
                   2174:         }
1.364     www      2175:     } elsif (!$existing{$ckey}) {
1.345     www      2176: # the key does not exist
                   2177: 	return 'error: The key does not exist';
                   2178:     } else {
                   2179: # the key is somebody else's
                   2180: 	return 'error: The key is already in use';
                   2181:     }
1.344     www      2182: }
                   2183: 
1.364     www      2184: # ------------------------------------------ put an additional comment on a key
                   2185: 
                   2186: sub comment_access_key {
                   2187: #
                   2188: # a valid key looks like uname:udom#comments
                   2189: # comments are being appended
                   2190: #
                   2191:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2192:     $cdom=
1.620     albertel 2193:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2194:     $cnum=
1.620     albertel 2195:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2196:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2197:     if ($existing{$ckey}) {
                   2198:         $existing{$ckey}.='; '.$logentry;
                   2199: # ready to assign
1.367     www      2200:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2201:                                                  $cdom,$cnum) eq 'ok') {
                   2202: 	    return 'ok';
                   2203:         } else {
                   2204: 	    return 'error: Count not store comment.';
                   2205:         }
                   2206:     } else {
                   2207: # the key does not exist
                   2208: 	return 'error: The key does not exist';
                   2209:     }
                   2210: }
                   2211: 
1.344     www      2212: # ------------------------------------------------------ Generate a set of keys
                   2213: 
                   2214: sub generate_access_keys {
1.364     www      2215:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2216:     $cdom=
1.620     albertel 2217:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2218:     $cnum=
1.620     albertel 2219:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2220:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2221:     unless (($cdom) && ($cnum)) { return 0; }
                   2222:     if ($number>10000) { return 0; }
                   2223:     sleep(2); # make sure don't get same seed twice
                   2224:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2225:     my $total=0;
                   2226:     for (my $i=1;$i<=$number;$i++) {
                   2227:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2228:                   sprintf("%lx",int(100000*rand)).'-'.
                   2229:                   sprintf("%lx",int(100000*rand));
                   2230:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2231:        $newkey=~s/0/h/g; # and also 0 and O
                   2232:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2233:        if ($existing{$newkey}) {
                   2234:            $i--;
                   2235:        } else {
1.364     www      2236: 	  if (&put('accesskeys',
                   2237:               { $newkey => '# generated '.localtime().
1.620     albertel 2238:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2239:                            '; '.$logentry },
                   2240: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2241:               $total++;
                   2242: 	  }
                   2243:        }
                   2244:     }
1.620     albertel 2245:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2246:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2247:     return $total;
                   2248: }
                   2249: 
                   2250: # ------------------------------------------------------- Validate an accesskey
                   2251: 
                   2252: sub validate_access_key {
                   2253:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2254:     $cdom=
1.620     albertel 2255:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2256:     $cnum=
1.620     albertel 2257:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2258:     $udom=$env{'user.domain'} unless (defined($udom));
                   2259:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2260:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2261:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2262: }
                   2263: 
                   2264: # ------------------------------------- Find the section of student in a course
1.652     albertel 2265: sub devalidate_getsection_cache {
                   2266:     my ($udom,$unam,$courseid)=@_;
                   2267:     my $hashid="$udom:$unam:$courseid";
                   2268:     &devalidate_cache_new('getsection',$hashid);
                   2269: }
1.298     matthew  2270: 
1.815     albertel 2271: sub courseid_to_courseurl {
                   2272:     my ($courseid) = @_;
                   2273:     #already url style courseid
                   2274:     return $courseid if ($courseid =~ m{^/});
                   2275: 
                   2276:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2277: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2278: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2279: 	return "/$cdom/$cnum";
                   2280:     }
                   2281: 
                   2282:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2283:     if (exists($courseinfo{'num'})) {
                   2284: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2285:     }
                   2286: 
                   2287:     return undef;
                   2288: }
                   2289: 
1.298     matthew  2290: sub getsection {
                   2291:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2292:     my $cachetime=1800;
1.551     albertel 2293: 
                   2294:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2295:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2296:     if (defined($cached)) { return $result; }
                   2297: 
1.298     matthew  2298:     my %Pending; 
                   2299:     my %Expired;
                   2300:     #
                   2301:     # Each role can either have not started yet (pending), be active, 
                   2302:     #    or have expired.
                   2303:     #
                   2304:     # If there is an active role, we are done.
                   2305:     #
                   2306:     # If there is more than one role which has not started yet, 
                   2307:     #     choose the one which will start sooner
                   2308:     # If there is one role which has not started yet, return it.
                   2309:     #
                   2310:     # If there is more than one expired role, choose the one which ended last.
                   2311:     # If there is a role which has expired, return it.
                   2312:     #
1.815     albertel 2313:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2314:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2315:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2316:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2317:         my $section=$1;
                   2318:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2319:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2320:         my $now=time;
1.548     albertel 2321:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2322:             $Expired{$end}=$section;
                   2323:             next;
                   2324:         }
1.548     albertel 2325:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2326:             $Pending{$start}=$section;
                   2327:             next;
                   2328:         }
1.599     albertel 2329:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2330:     }
                   2331:     #
                   2332:     # Presumedly there will be few matching roles from the above
                   2333:     # loop and the sorting time will be negligible.
                   2334:     if (scalar(keys(%Pending))) {
                   2335:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2336:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2337:     } 
                   2338:     if (scalar(keys(%Expired))) {
                   2339:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2340:         my $time = pop(@sorted);
1.599     albertel 2341:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2342:     }
1.599     albertel 2343:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2344: }
1.70      www      2345: 
1.599     albertel 2346: sub save_cache {
                   2347:     &purge_remembered();
1.722     albertel 2348:     #&Apache::loncommon::validate_page();
1.620     albertel 2349:     undef(%env);
1.780     albertel 2350:     undef($env_loaded);
1.599     albertel 2351: }
1.452     albertel 2352: 
1.599     albertel 2353: my $to_remember=-1;
                   2354: my %remembered;
                   2355: my %accessed;
                   2356: my $kicks=0;
                   2357: my $hits=0;
1.849     albertel 2358: sub make_key {
                   2359:     my ($name,$id) = @_;
1.872     albertel 2360:     if (length($id) > 65 
                   2361: 	&& length(&escape($id)) > 200) {
                   2362: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2363:     }
1.849     albertel 2364:     return &escape($name.':'.$id);
                   2365: }
                   2366: 
1.599     albertel 2367: sub devalidate_cache_new {
                   2368:     my ($name,$id,$debug) = @_;
                   2369:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2370:     $id=&make_key($name,$id);
1.599     albertel 2371:     $memcache->delete($id);
                   2372:     delete($remembered{$id});
                   2373:     delete($accessed{$id});
                   2374: }
                   2375: 
                   2376: sub is_cached_new {
                   2377:     my ($name,$id,$debug) = @_;
1.849     albertel 2378:     $id=&make_key($name,$id);
1.599     albertel 2379:     if (exists($remembered{$id})) {
1.1133    foxr     2380: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2381: 	$accessed{$id}=[&gettimeofday()];
                   2382: 	$hits++;
                   2383: 	return ($remembered{$id},1);
                   2384:     }
                   2385:     my $value = $memcache->get($id);
                   2386:     if (!(defined($value))) {
                   2387: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2388: 	return (undef,undef);
1.416     albertel 2389:     }
1.599     albertel 2390:     if ($value eq '__undef__') {
                   2391: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2392: 	$value=undef;
                   2393:     }
                   2394:     &make_room($id,$value,$debug);
                   2395:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2396:     return ($value,1);
                   2397: }
                   2398: 
                   2399: sub do_cache_new {
                   2400:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2401:     $id=&make_key($name,$id);
1.599     albertel 2402:     my $setvalue=$value;
                   2403:     if (!defined($setvalue)) {
                   2404: 	$setvalue='__undef__';
                   2405:     }
1.623     albertel 2406:     if (!defined($time) ) {
                   2407: 	$time=600;
                   2408:     }
1.599     albertel 2409:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2410:     my $result = $memcache->set($id,$setvalue,$time);
                   2411:     if (! $result) {
1.872     albertel 2412: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2413: 	$memcache->disconnect_all();
1.872     albertel 2414:     }
1.600     albertel 2415:     # need to make a copy of $value
1.919     albertel 2416:     &make_room($id,$value,$debug);
1.599     albertel 2417:     return $value;
                   2418: }
                   2419: 
                   2420: sub make_room {
                   2421:     my ($id,$value,$debug)=@_;
1.919     albertel 2422: 
                   2423:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2424:                                     : $value;
1.599     albertel 2425:     if ($to_remember<0) { return; }
                   2426:     $accessed{$id}=[&gettimeofday()];
                   2427:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2428:     my $to_kick;
                   2429:     my $max_time=0;
                   2430:     foreach my $other (keys(%accessed)) {
                   2431: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2432: 	    $to_kick=$other;
                   2433: 	    $max_time=&tv_interval($accessed{$other});
                   2434: 	}
                   2435:     }
                   2436:     delete($remembered{$to_kick});
                   2437:     delete($accessed{$to_kick});
                   2438:     $kicks++;
                   2439:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2440:     return;
                   2441: }
                   2442: 
1.599     albertel 2443: sub purge_remembered {
1.604     albertel 2444:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2445:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2446:     undef(%remembered);
                   2447:     undef(%accessed);
1.428     albertel 2448: }
1.70      www      2449: # ------------------------------------- Read an entry from a user's environment
                   2450: 
                   2451: sub userenvironment {
                   2452:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2453:     my $items;
                   2454:     foreach my $item (@what) {
                   2455:         $items.=&escape($item).'&';
                   2456:     }
                   2457:     $items=~s/\&$//;
1.70      www      2458:     my %returnhash=();
1.1009    raeburn  2459:     my $uhome = &homeserver($unam,$udom);
                   2460:     unless ($uhome eq 'no_host') {
                   2461:         my @answer=split(/\&/, 
                   2462:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2463:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2464:             return %returnhash;
                   2465:         }
1.1009    raeburn  2466:         my $i;
                   2467:         for ($i=0;$i<=$#what;$i++) {
                   2468: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2469:         }
1.70      www      2470:     }
                   2471:     return %returnhash;
1.1       albertel 2472: }
                   2473: 
1.617     albertel 2474: # ---------------------------------------------------------- Get a studentphoto
                   2475: sub studentphoto {
                   2476:     my ($udom,$unam,$ext) = @_;
                   2477:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2478:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2479:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2480:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2481:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2482:             } else {
                   2483:                 my ($result,$perm_reqd)=
1.707     albertel 2484: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2485:                 if ($result eq 'ok') {
                   2486:                     if (!($perm_reqd eq 'yes')) {
                   2487:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2488:                     }
                   2489:                 }
                   2490:             }
                   2491:         }
                   2492:     } else {
                   2493:         my ($result,$perm_reqd) = 
1.707     albertel 2494: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2495:         if ($result eq 'ok') {
                   2496:             if (!($perm_reqd eq 'yes')) {
                   2497:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2498:             }
                   2499:         }
                   2500:     }
                   2501:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2502: }
                   2503: 
                   2504: sub retrievestudentphoto {
                   2505:     my ($udom,$unam,$ext,$type) = @_;
                   2506:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2507:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2508:     if ($ret eq 'ok') {
                   2509:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2510:         if ($type eq 'thumbnail') {
                   2511:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2512:         }
                   2513:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2514:         return $tokenurl;
                   2515:     } else {
                   2516:         if ($type eq 'thumbnail') {
                   2517:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2518:         } else { 
                   2519:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2520:         }
1.617     albertel 2521:     }
                   2522: }
                   2523: 
1.263     www      2524: # -------------------------------------------------------------------- New chat
                   2525: 
                   2526: sub chatsend {
1.724     raeburn  2527:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2528:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2529:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2530:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2531:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2532: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2533: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2534: }
                   2535: 
                   2536: # ------------------------------------------ Find current version of a resource
                   2537: 
                   2538: sub getversion {
                   2539:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2540:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2541:     return &currentversion(&filelocation('',$fname));
                   2542: }
                   2543: 
                   2544: sub currentversion {
                   2545:     my $fname=shift;
                   2546:     my $author=$fname;
                   2547:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2548:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2549:     my $home=&homeserver($uname,$udom);
1.292     www      2550:     if ($home eq 'no_host') { 
                   2551:         return -1; 
                   2552:     }
1.1112    www      2553:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2554:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2555: 	return -1;
                   2556:     }
1.1112    www      2557:     return $answer;
1.263     www      2558: }
                   2559: 
1.1111    www      2560: #
                   2561: # Return special version number of resource if set by override, empty otherwise
                   2562: #
                   2563: sub usedversion {
                   2564:     my $fname=shift;
                   2565:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2566:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2567:     if ($urlversion) { return $urlversion; }
                   2568:     return '';
                   2569: }
                   2570: 
1.1       albertel 2571: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2572: 
1.1       albertel 2573: sub subscribe {
                   2574:     my $fname=shift;
1.761     raeburn  2575:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2576:     $fname=~s/[\n\r]//g;
1.1       albertel 2577:     my $author=$fname;
                   2578:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2579:     my ($udom,$uname)=split(/\//,$author);
                   2580:     my $home=homeserver($uname,$udom);
1.335     albertel 2581:     if ($home eq 'no_host') {
                   2582:         return 'not_found';
1.1       albertel 2583:     }
                   2584:     my $answer=reply("sub:$fname",$home);
1.64      www      2585:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2586: 	$answer.=' by '.$home;
                   2587:     }
1.1       albertel 2588:     return $answer;
                   2589: }
                   2590:     
1.8       www      2591: # -------------------------------------------------------------- Replicate file
                   2592: 
                   2593: sub repcopy {
                   2594:     my $filename=shift;
1.23      www      2595:     $filename=~s/\/+/\//g;
1.1142    raeburn  2596:     my $londocroot = $perlvar{'lonDocRoot'};
                   2597:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2598:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2599:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2600: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2601: 	return &repcopy_userfile($filename);
                   2602:     }
1.532     albertel 2603:     $filename=~s/[\n\r]//g;
1.8       www      2604:     my $transname="$filename.in.transfer";
1.828     www      2605: # FIXME: this should flock
1.607     raeburn  2606:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2607:     my $remoteurl=subscribe($filename);
1.64      www      2608:     if ($remoteurl =~ /^con_lost by/) {
                   2609: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2610:            return 'unavailable';
1.8       www      2611:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2612: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2613: 	   return 'not_found';
1.64      www      2614:     } elsif ($remoteurl =~ /^rejected by/) {
                   2615: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2616:            return 'forbidden';
1.20      www      2617:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2618:            return 'ok';
1.8       www      2619:     } else {
1.290     www      2620:         my $author=$filename;
                   2621:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2622:         my ($udom,$uname)=split(/\//,$author);
                   2623:         my $home=homeserver($uname,$udom);
                   2624:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2625:            my @parts=split(/\//,$filename);
                   2626:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2627:            if ($path ne "$londocroot/res") {
1.8       www      2628:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2629: 	       return 'bad_request';
1.8       www      2630:            }
                   2631:            my $count;
                   2632:            for ($count=5;$count<$#parts;$count++) {
                   2633:                $path.="/$parts[$count]";
                   2634:                if ((-e $path)!=1) {
                   2635: 		   mkdir($path,0777);
                   2636:                }
                   2637:            }
                   2638:            my $ua=new LWP::UserAgent;
                   2639:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2640:            my $response=$ua->request($request,$transname);
                   2641:            if ($response->is_error()) {
                   2642: 	       unlink($transname);
                   2643:                my $message=$response->status_line;
1.672     albertel 2644:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2645:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2646:                return 'unavailable';
1.8       www      2647:            } else {
1.16      www      2648: 	       if ($remoteurl!~/\.meta$/) {
                   2649:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2650:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2651:                   if ($mresponse->is_error()) {
                   2652: 		      unlink($filename.'.meta');
                   2653:                       &logthis(
1.672     albertel 2654:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2655:                   }
                   2656: 	       }
1.8       www      2657:                rename($transname,$filename);
1.607     raeburn  2658:                return 'ok';
1.8       www      2659:            }
1.290     www      2660:        }
1.8       www      2661:     }
1.330     www      2662: }
                   2663: 
                   2664: # ------------------------------------------------ Get server side include body
                   2665: sub ssi_body {
1.381     albertel 2666:     my ($filelink,%form)=@_;
1.606     matthew  2667:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2668:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2669:     }
1.953     www      2670:     my $output='';
                   2671:     my $response;
1.980     raeburn  2672:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2673:        ($output,$response)=&externalssi($filelink);
1.953     www      2674:     } else {
1.1004    droeschl 2675:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2676:        $filelink .= 'inhibitmenu=yes';
1.953     www      2677:        ($output,$response)=&ssi($filelink,%form);
                   2678:     }
1.778     albertel 2679:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2680:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2681:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2682:     if (wantarray) {
                   2683:         return ($output, $response);
                   2684:     } else {
                   2685:         return $output;
                   2686:     }
1.8       www      2687: }
                   2688: 
1.15      www      2689: # --------------------------------------------------------- Server Side Include
                   2690: 
1.782     albertel 2691: sub absolute_url {
                   2692:     my ($host_name) = @_;
                   2693:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2694:     if ($host_name eq '') {
                   2695: 	$host_name = $ENV{'SERVER_NAME'};
                   2696:     }
                   2697:     return $protocol.$host_name;
                   2698: }
                   2699: 
1.942     foxr     2700: #
                   2701: #   Server side include.
                   2702: # Parameters:
                   2703: #  fn     Possibly encrypted resource name/id.
                   2704: #  form   Hash that describes how the rendering should be done
                   2705: #         and other things.
1.944     foxr     2706: # Returns:
1.950     raeburn  2707: #   Scalar context: The content of the response.
                   2708: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2709: #     
1.15      www      2710: sub ssi {
                   2711: 
1.944     foxr     2712:     my ($fn,%form)=@_;
1.15      www      2713:     my $ua=new LWP::UserAgent;
1.23      www      2714:     my $request;
1.711     albertel 2715: 
                   2716:     $form{'no_update_last_known'}=1;
1.895     albertel 2717:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2718:     if (%form) {
1.782     albertel 2719:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58! raeburn  2720:       $request->content(join('&',map {
        !          2721:             my $name = escape($_);
        !          2722:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
        !          2723:             ? join("&$name=", map {escape($_) } @{$form{$_}})
        !          2724:             : &escape($form{$_}) );
        !          2725:         } keys(%form)));
1.23      www      2726:     } else {
1.782     albertel 2727:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2728:     }
                   2729: 
1.15      www      2730:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2731:     my $response= $ua->request($request);
1.944     foxr     2732:     if (wantarray) {
1.1172.2.3  raeburn  2733: 	return ($response->content, $response);
1.944     foxr     2734:     } else {
1.1172.2.3  raeburn  2735: 	return $response->content;
1.942     foxr     2736:     }
1.324     www      2737: }
                   2738: 
                   2739: sub externalssi {
                   2740:     my ($url)=@_;
                   2741:     my $ua=new LWP::UserAgent;
                   2742:     my $request=new HTTP::Request('GET',$url);
                   2743:     my $response=$ua->request($request);
1.954     raeburn  2744:     if (wantarray) {
                   2745:         return ($response->content, $response);
                   2746:     } else {
                   2747:         return $response->content;
                   2748:     }
1.15      www      2749: }
1.254     www      2750: 
1.492     albertel 2751: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2752: 
                   2753: sub allowuploaded {
                   2754:     my ($srcurl,$url)=@_;
                   2755:     $url=&clutter(&declutter($url));
                   2756:     my $dir=$url;
                   2757:     $dir=~s/\/[^\/]+$//;
                   2758:     my %httpref=();
                   2759:     my $httpurl=&hreflocation('',$url);
                   2760:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2761:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2762: }
1.477     raeburn  2763: 
1.1172.2.13  raeburn  2764: #
                   2765: # Determine if the current user should be able to edit a particular resource,
                   2766: # when viewing in course context.
                   2767: # (a) When viewing resource used to determine if "Edit" item is included in
                   2768: #     Functions.
                   2769: # (b) When displaying folder contents in course editor, used to determine if
                   2770: #     "Edit" link will be displayed alongside resource.
                   2771: #
                   2772: #  input: six args -- filename (decluttered), course number, course domain,
                   2773: #                   url, symb (if registered) and group (if this is a group
                   2774: #                   item -- e.g., bulletin board, group page etc.).
                   2775: #  output: array of five scalars --
                   2776: #          $cfile -- url for file editing if editable on current server
                   2777: #          $home -- homeserver of resource (i.e., for author if published,
                   2778: #                                           or course if uploaded.).
                   2779: #          $switchserver --  1 if server switch will be needed.
                   2780: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2781: #          $forceview -- 1 if icon/link should be to go to view mode
                   2782: #
                   2783: 
                   2784: sub can_edit_resource {
                   2785:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2786:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2787: #
                   2788: # For aboutme pages user can only edit his/her own.
                   2789: #
                   2790:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2791:         my ($sdom,$sname) = ($1,$2);
                   2792:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2793:             $home = $env{'user.home'};
                   2794:             $cfile = $resurl;
                   2795:             if ($env{'form.forceedit'}) {
                   2796:                 $forceview = 1;
                   2797:             } else {
                   2798:                 $forceedit = 1;
                   2799:             }
                   2800:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2801:         } else {
                   2802:             return;
                   2803:         }
                   2804:     }
                   2805: 
                   2806:     if ($env{'request.course.id'}) {
                   2807:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2808:         if ($group ne '') {
                   2809: # if this is a group homepage or group bulletin board, check group privs
                   2810:             my $allowed = 0;
                   2811:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2812:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2813:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2814:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2815:                     $allowed = 1;
                   2816:                 }
                   2817:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2818:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2819:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2820:                     $allowed = 1;
                   2821:                 }
                   2822:             }
                   2823:             if ($allowed) {
                   2824:                 $home=&homeserver($cnum,$cdom);
                   2825:                 if ($env{'form.forceedit'}) {
                   2826:                     $forceview = 1;
                   2827:                 } else {
                   2828:                     $forceedit = 1;
                   2829:                 }
                   2830:                 $cfile = $resurl;
                   2831:             } else {
                   2832:                 return;
                   2833:             }
                   2834:         } else {
1.1172.2.15  raeburn  2835:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2836:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2837:                     return;
                   2838:                 }
                   2839:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2840: #
                   2841: # No edit allowed where CC has switched to student role.
                   2842: #
                   2843:                 return;
                   2844:             }
                   2845:         }
                   2846:     }
                   2847: 
                   2848:     if ($file ne '') {
                   2849:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2850:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2851:                 $uploaded = 1;
                   2852:                 $incourse = 1;
                   2853:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2854:                     $cfile = &hreflocation('',$file);
                   2855:                     if ($env{'form.forceedit'}) {
                   2856:                         $forceview = 1;
                   2857:                     } else {
                   2858:                         $forceedit = 1;
                   2859:                     }
                   2860:                 }
                   2861:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2862:                 $incourse = 1;
                   2863:                 if ($env{'form.forceedit'}) {
                   2864:                     $forceview = 1;
                   2865:                 } else {
                   2866:                     $forceedit = 1;
                   2867:                 }
                   2868:                 $cfile = $resurl;
                   2869:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2870:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2871:                     $incourse = 1;
                   2872:                     if ($env{'form.forceedit'}) {
                   2873:                         $forceview = 1;
                   2874:                     } else {
                   2875:                         $forceedit = 1;
                   2876:                     }
                   2877:                     $cfile = $resurl;
                   2878:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2879:                     $incourse = 1;
                   2880:                     $cfile = $resurl.'/smpedit';
                   2881:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2882:                     $incourse = 1;
                   2883:                     if ($env{'form.forceedit'}) {
                   2884:                         $forceview = 1;
                   2885:                     } else {
                   2886:                         $forceedit = 1;
                   2887:                     }
                   2888:                     $cfile = $resurl;
1.1172.2.15  raeburn  2889:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2890:                     $incourse = 1;
                   2891:                     if ($env{'form.forceedit'}) {
                   2892:                         $forceview = 1;
                   2893:                     } else {
                   2894:                         $forceedit = 1;
                   2895:                     }
                   2896:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2897:                 }
                   2898:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2899:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2900:                 if (&is_on_map($template)) {
                   2901:                     $incourse = 1;
                   2902:                     $forceview = 1;
                   2903:                     $cfile = $template;
                   2904:                 }
                   2905:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2906:                     $incourse = 1;
                   2907:                     if ($env{'form.forceedit'}) {
                   2908:                         $forceview = 1;
                   2909:                     } else {
                   2910:                         $forceedit = 1;
                   2911:                     }
                   2912:                     $cfile = $resurl;
                   2913:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2914:                 $incourse = 1;
                   2915:                 $forceview = 1;
                   2916:                 if ($symb) {
                   2917:                     my ($map,$id,$res)=&decode_symb($symb);
                   2918:                     $env{'request.symb'} = $symb;
                   2919:                     $cfile = &clutter($res);
                   2920:                 } else {
                   2921:                     $cfile = $env{'form.suppurl'};
                   2922:                     $cfile =~ s{^http://}{};
                   2923:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2924:                 }
1.1172.2.31  raeburn  2925:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2926:                 if ($env{'form.forceedit'}) {
                   2927:                     $forceview = 1;
                   2928:                 } else {
                   2929:                     $forceedit = 1;
                   2930:                 }
                   2931:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2932:             }
                   2933:         }
                   2934:         if ($uploaded || $incourse) {
                   2935:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2936:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2937:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2938:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2939:             # Check that the user has permission to edit this resource
                   2940:             my $setpriv = 1;
                   2941:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2942:             if (defined($cfudom)) {
                   2943:                 $home=&homeserver($cfuname,$cfudom);
                   2944:                 $cfile=$file;
                   2945:             }
                   2946:         }
                   2947:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2948:             (($home ne '') && ($home ne 'no_host'))) {
                   2949:             my @ids=&current_machine_ids();
                   2950:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2951:                 $switchserver=1;
                   2952:             }
                   2953:         }
                   2954:     }
                   2955:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2956: }
                   2957: 
                   2958: sub is_course_upload {
                   2959:     my ($file,$cnum,$cdom) = @_;
                   2960:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2961:     $uploadpath =~ s{^\/}{};
                   2962:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2963:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2964:         return 1;
                   2965:     }
                   2966:     return;
                   2967: }
                   2968: 
                   2969: sub in_course {
                   2970:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2971:     if ($hideprivileged) {
                   2972:         my $skipuser;
1.1172.2.23  raeburn  2973:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2974:         my @possdoms = ($cdom);
                   2975:         if ($coursehash{'checkforpriv'}) {
                   2976:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   2977:         }
                   2978:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  2979:             $skipuser = 1;
                   2980:             if ($coursehash{'nothideprivileged'}) {
                   2981:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2982:                     my $user;
                   2983:                     if ($item =~ /:/) {
                   2984:                         $user = $item;
                   2985:                     } else {
                   2986:                         $user = join(':',split(/[\@]/,$item));
                   2987:                     }
                   2988:                     if ($user eq $uname.':'.$udom) {
                   2989:                         undef($skipuser);
                   2990:                         last;
                   2991:                     }
                   2992:                 }
                   2993:             }
                   2994:             if ($skipuser) {
                   2995:                 return 0;
                   2996:             }
                   2997:         }
                   2998:     }
                   2999:     $type ||= 'any';
                   3000:     if (!defined($cdom) || !defined($cnum)) {
                   3001:         my $cid  = $env{'request.course.id'};
                   3002:         $cdom = $env{'course.'.$cid.'.domain'};
                   3003:         $cnum = $env{'course.'.$cid.'.num'};
                   3004:     }
                   3005:     my $typesref;
                   3006:     if (($type eq 'any') || ($type eq 'all')) {
                   3007:         $typesref = ['active','previous','future'];
                   3008:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3009:         $typesref = [$type];
                   3010:     }
                   3011:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3012:                               $typesref,undef,[$cdom]);
                   3013:     my ($tmp) = keys(%roles);
                   3014:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3015:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3016:     if (@course_roles > 0) {
                   3017:         return 1;
                   3018:     }
                   3019:     return 0;
                   3020: }
                   3021: 
1.478     albertel 3022: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3023: # input: action, courseID, current domain, intended
1.637     raeburn  3024: #        path to file, source of file, instruction to parse file for objects,
                   3025: #        ref to hash for embedded objects,
                   3026: #        ref to hash for codebase of java objects.
1.1095    raeburn  3027: #        reference to scalar to accommodate mime type determined
                   3028: #          from File::MMagic if $parser = parse.
1.637     raeburn  3029: #
1.485     raeburn  3030: # output: url to file (if action was uploaddoc), 
                   3031: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3032: #
1.478     albertel 3033: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3034: # course.
1.477     raeburn  3035: #
1.478     albertel 3036: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3037: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3038: #          course's home server.
1.477     raeburn  3039: #
1.478     albertel 3040: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3041: #          be copied from $source (current location) to 
                   3042: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3043: #         and will then be copied to
                   3044: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3045: #         course's home server.
1.485     raeburn  3046: #
1.481     raeburn  3047: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3048: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3049: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3050: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3051: #         in course's home server.
1.637     raeburn  3052: #
1.477     raeburn  3053: 
                   3054: sub process_coursefile {
1.1095    raeburn  3055:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3056:         $mimetype)=@_;
1.477     raeburn  3057:     my $fetchresult;
1.638     albertel 3058:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3059:     if ($action eq 'propagate') {
1.638     albertel 3060:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3061: 			     $home);
1.481     raeburn  3062:     } else {
1.477     raeburn  3063:         my $fpath = '';
                   3064:         my $fname = $file;
1.478     albertel 3065:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3066:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3067:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3068:         if ($action eq 'copy') {
                   3069:             if ($source eq '') {
                   3070:                 $fetchresult = 'no source file';
                   3071:                 return $fetchresult;
                   3072:             } else {
                   3073:                 my $destination = $filepath.'/'.$fname;
                   3074:                 rename($source,$destination);
                   3075:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3076:                                  $home);
1.481     raeburn  3077:             }
                   3078:         } elsif ($action eq 'uploaddoc') {
                   3079:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3080:             print $fh $env{'form.'.$source};
1.481     raeburn  3081:             close($fh);
1.637     raeburn  3082:             if ($parser eq 'parse') {
1.1024    raeburn  3083:                 my $mm = new File::MMagic;
1.1095    raeburn  3084:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3085:                 if ($type eq 'text/html') {
1.1024    raeburn  3086:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3087:                     unless ($parse_result eq 'ok') {
                   3088:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3089:                     }
1.637     raeburn  3090:                 }
1.1095    raeburn  3091:                 if (ref($mimetype)) {
                   3092:                     $$mimetype = $type;
                   3093:                 } 
1.637     raeburn  3094:             }
1.477     raeburn  3095:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3096:                                  $home);
1.481     raeburn  3097:             if ($fetchresult eq 'ok') {
                   3098:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3099:             } else {
                   3100:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3101:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3102:                 return '/adm/notfound.html';
                   3103:             }
1.477     raeburn  3104:         }
                   3105:     }
1.485     raeburn  3106:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3107:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3108:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3109:     }
                   3110:     return $fetchresult;
                   3111: }
                   3112: 
1.637     raeburn  3113: sub build_filepath {
                   3114:     my ($fpath) = @_;
                   3115:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3116:     unless ($fpath eq '') {
                   3117:         my @parts=split('/',$fpath);
                   3118:         foreach my $part (@parts) {
                   3119:             $filepath.= '/'.$part;
                   3120:             if ((-e $filepath)!=1) {
                   3121:                 mkdir($filepath,0777);
                   3122:             }
                   3123:         }
                   3124:     }
                   3125:     return $filepath;
                   3126: }
                   3127: 
                   3128: sub store_edited_file {
1.638     albertel 3129:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3130:     my $file = $primary_url;
                   3131:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3132:     my $fpath = '';
                   3133:     my $fname = $file;
                   3134:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3135:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3136:     my $filepath = &build_filepath($fpath);
                   3137:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3138:     print $fh $content;
                   3139:     close($fh);
1.638     albertel 3140:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3141:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3142: 			  $home);
1.637     raeburn  3143:     if ($$fetchresult eq 'ok') {
                   3144:         return '/uploaded/'.$fpath.'/'.$fname;
                   3145:     } else {
1.638     albertel 3146:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3147: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3148:         return '/adm/notfound.html';
                   3149:     }
                   3150: }
                   3151: 
1.531     albertel 3152: sub clean_filename {
1.831     albertel 3153:     my ($fname,$args)=@_;
1.315     www      3154: # Replace Windows backslashes by forward slashes
1.257     www      3155:     $fname=~s/\\/\//g;
1.831     albertel 3156:     if (!$args->{'keep_path'}) {
                   3157:         # Get rid of everything but the actual filename
                   3158: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3159:     }
1.315     www      3160: # Replace spaces by underscores
                   3161:     $fname=~s/\s+/\_/g;
                   3162: # Replace all other weird characters by nothing
1.831     albertel 3163:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3164: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3165: # numbers
                   3166:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3167:     return $fname;
                   3168: }
1.1051    raeburn  3169: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3170: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3171: # image with the same aspect ratio as the original, but with dimensions which do 
                   3172: # not exceed $resizewidth and $resizeheight.
                   3173:  
1.984     neumanie 3174: sub resizeImage {
1.1051    raeburn  3175:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3176:     my $ima = Image::Magick->new;
                   3177:     my $resized;
                   3178:     if (-e $img_path) {
                   3179:         $ima->Read($img_path);
                   3180:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3181:             my $width = $ima->Get('width');
                   3182:             my $height = $ima->Get('height');
                   3183:             if ($width > $resizewidth) {
                   3184: 	        my $factor = $width/$resizewidth;
                   3185:                 my $newheight = $height/$factor;
                   3186:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3187:                 $resized = 1;
                   3188:             }
                   3189:         }
                   3190:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3191:             my $width = $ima->Get('width');
                   3192:             my $height = $ima->Get('height');
                   3193:             if ($height > $resizeheight) {
                   3194:                 my $factor = $height/$resizeheight;
                   3195:                 my $newwidth = $width/$factor;
                   3196:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3197:                 $resized = 1;
                   3198:             }
                   3199:         }
                   3200:         if ($resized) {
                   3201:             $ima->Write($img_path);
                   3202:         }
                   3203:     }
                   3204:     return;
1.977     amueller 3205: }
                   3206: 
1.608     albertel 3207: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3208: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3209: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3210: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3211: #                                    canceloverwrite, or ''. 
                   3212: #                   if 'coursedoc': upload to the current course
                   3213: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3214: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3215: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3216: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3217: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3218: #        $allfiles - reference to hash for embedded objects
                   3219: #        $codebase - reference to hash for codebase of java objects
                   3220: #        $desuname - username for permanent storage of uploaded file
                   3221: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3222: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3223: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3224: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3225: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3226: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3227: #                    from File::MMagic.
1.858     raeburn  3228: # 
1.686     albertel 3229: # output: url of file in userspace, or error: <message> 
                   3230: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3231: 
1.531     albertel 3232: sub userfileupload {
1.1090    raeburn  3233:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3234:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3235:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3236:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3237:     $fname=&clean_filename($fname);
1.1090    raeburn  3238:     # See if there is anything left
1.257     www      3239:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3240:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3241:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3242:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3243:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3244:         my $now = time;
1.1090    raeburn  3245:         my $filepath;
1.1095    raeburn  3246:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3247:              $filepath = 'tmp/helprequests/'.$now;
                   3248:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3249:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3250:                          '_'.$env{'user.domain'}.'/pending';
                   3251:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3252:             my ($docuname,$docudom);
                   3253:             if ($destudom) {
                   3254:                 $docudom = $destudom;
                   3255:             } else {
                   3256:                 $docudom = $env{'user.domain'};
                   3257:             }
                   3258:             if ($destuname) {
                   3259:                 $docuname = $destuname;
                   3260:             } else {
                   3261:                 $docuname = $env{'user.name'};
                   3262:             }
                   3263:             if (exists($env{'form.group'})) {
                   3264:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3265:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3266:             }
                   3267:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3268:             if ($context eq 'canceloverwrite') {
                   3269:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3270:                 if (-e  $tempfile) {
                   3271:                     my @info = stat($tempfile);
                   3272:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3273:                         unlink($tempfile);
                   3274:                     }
                   3275:                 }
                   3276:                 return;
1.523     raeburn  3277:             }
                   3278:         }
1.1090    raeburn  3279:         # Create the directory if not present
1.741     raeburn  3280:         my @parts=split(/\//,$filepath);
                   3281:         my $fullpath = $perlvar{'lonDaemons'};
                   3282:         for (my $i=0;$i<@parts;$i++) {
                   3283:             $fullpath .= '/'.$parts[$i];
                   3284:             if ((-e $fullpath)!=1) {
                   3285:                 mkdir($fullpath,0777);
                   3286:             }
                   3287:         }
                   3288:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3289:         print $fh $env{'form.'.$formname};
                   3290:         close($fh);
1.1090    raeburn  3291:         if ($context eq 'existingfile') {
                   3292:             my @info = stat($fullpath.'/'.$fname);
                   3293:             return ($fullpath.'/'.$fname,$info[9]);
                   3294:         } else {
                   3295:             return $fullpath.'/'.$fname;
                   3296:         }
1.523     raeburn  3297:     }
1.995     raeburn  3298:     if ($subdir eq 'scantron') {
                   3299:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3300:     } else {
1.995     raeburn  3301:         $fname="$subdir/$fname";
                   3302:     }
1.1090    raeburn  3303:     if ($context eq 'coursedoc') {
1.638     albertel 3304: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3305: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3306:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3307:             return &finishuserfileupload($docuname,$docudom,
                   3308: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3309: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3310:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3311:         } else {
1.1172.2.21  raeburn  3312:             if ($env{'form.folder'}) {
                   3313:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3314:             }
1.638     albertel 3315:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3316: 				       $fname,$formname,$parser,
1.1095    raeburn  3317: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3318:         }
1.719     banghart 3319:     } elsif (defined($destuname)) {
                   3320:         my $docuname=$destuname;
                   3321:         my $docudom=$destudom;
1.860     raeburn  3322: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3323: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3324:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3325:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3326:     } else {
1.638     albertel 3327:         my $docuname=$env{'user.name'};
                   3328:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3329:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3330:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3331:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3332:         }
1.860     raeburn  3333: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3334: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3335:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3336:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3337:     }
1.271     www      3338: }
                   3339: 
                   3340: sub finishuserfileupload {
1.860     raeburn  3341:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3342:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3343:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3344:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3345:   
1.860     raeburn  3346:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3347:     $file=$fname;
                   3348:     if ($fname=~m|/|) {
                   3349:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3350: 	$path.=$fnamepath.'/';
                   3351:     }
1.259     www      3352:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3353:     my $count;
                   3354:     for ($count=4;$count<=$#parts;$count++) {
                   3355:         $filepath.="/$parts[$count]";
                   3356:         if ((-e $filepath)!=1) {
                   3357: 	    mkdir($filepath,0777);
                   3358:         }
                   3359:     }
1.984     neumanie 3360: 
1.258     www      3361: # Save the file
                   3362:     {
1.701     albertel 3363: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3364: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3365: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3366: 	    return '/adm/notfound.html';
                   3367: 	}
1.1090    raeburn  3368:         if ($context eq 'overwrite') {
1.1117    foxr     3369:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3370:             my $target = $filepath.'/'.$file;
                   3371:             if (-e $source) {
                   3372:                 my @info = stat($source);
                   3373:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3374:                     unless (&File::Copy::move($source,$target)) {
                   3375:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3376:                         return "Moving from $source failed";
                   3377:                     }
                   3378:                 } else {
                   3379:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3380:                 }
                   3381:             } else {
                   3382:                 return "Temporary file: $source missing";
                   3383:             }
                   3384:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3385: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3386: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3387: 	    return '/adm/notfound.html';
                   3388: 	}
1.570     albertel 3389: 	close(FH);
1.1051    raeburn  3390:         if ($resizewidth && $resizeheight) {
                   3391:             my $mm = new File::MMagic;
                   3392:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3393:             if ($mime_type =~ m{^image/}) {
                   3394: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3395:             }  
1.977     amueller 3396: 	}
1.258     www      3397:     }
1.1152    raeburn  3398:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3399:         if (ref($mimetype)) {
                   3400:             if ($$mimetype eq '') {
                   3401:                 my $mm = new File::MMagic;
                   3402:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3403:                 $$mimetype = $type;
                   3404:             }
                   3405:         }
                   3406:     }
1.637     raeburn  3407:     if ($parser eq 'parse') {
1.1152    raeburn  3408:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3409:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3410:                                                        $allfiles,$codebase);
                   3411:             unless ($parse_result eq 'ok') {
                   3412:                 &logthis('Failed to parse '.$filepath.$file.
                   3413: 	   	         ' for embedded media: '.$parse_result); 
                   3414:             }
1.637     raeburn  3415:         }
                   3416:     }
1.860     raeburn  3417:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3418:         my $input = $filepath.'/'.$file;
                   3419:         my $output = $filepath.'/'.'tn-'.$file;
                   3420:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3421:         system("convert -sample $thumbsize $input $output");
                   3422:         if (-e $filepath.'/'.'tn-'.$file) {
                   3423:             $fetchthumb  = 1; 
                   3424:         }
                   3425:     }
1.858     raeburn  3426:  
1.259     www      3427: # Notify homeserver to grep it
                   3428: #
1.984     neumanie 3429:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3430:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3431:     if ($fetchresult eq 'ok') {
1.860     raeburn  3432:         if ($fetchthumb) {
                   3433:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3434:             if ($thumbresult ne 'ok') {
                   3435:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3436:                          $docuhome.': '.$thumbresult);
                   3437:             }
                   3438:         }
1.259     www      3439: #
1.258     www      3440: # Return the URL to it
1.494     albertel 3441:         return '/uploaded/'.$path.$file;
1.263     www      3442:     } else {
1.494     albertel 3443:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3444: 		 ': '.$fetchresult);
1.263     www      3445:         return '/adm/notfound.html';
1.858     raeburn  3446:     }
1.493     albertel 3447: }
                   3448: 
1.637     raeburn  3449: sub extract_embedded_items {
1.961     raeburn  3450:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3451:     my @state = ();
1.1164    raeburn  3452:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3453:     my %javafiles = (
                   3454:                       codebase => '',
                   3455:                       code => '',
                   3456:                       archive => ''
                   3457:                     );
                   3458:     my %mediafiles = (
                   3459:                       src => '',
                   3460:                       movie => '',
                   3461:                      );
1.648     raeburn  3462:     my $p;
                   3463:     if ($content) {
                   3464:         $p = HTML::LCParser->new($content);
                   3465:     } else {
1.961     raeburn  3466:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3467:     }
1.641     albertel 3468:     while (my $t=$p->get_token()) {
1.640     albertel 3469: 	if ($t->[0] eq 'S') {
                   3470: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3471: 	    push(@state, $tagname);
1.648     raeburn  3472:             if (lc($tagname) eq 'allow') {
                   3473:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3474:             }
1.640     albertel 3475: 	    if (lc($tagname) eq 'img') {
                   3476: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3477: 	    }
1.886     albertel 3478: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3479:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3480: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3481:                 }
1.886     albertel 3482: 	    }
1.645     raeburn  3483:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3484:                 my $src;
1.645     raeburn  3485:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3486:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3487:                 } else {
1.1164    raeburn  3488:                     if ($attr->{'src'} ne '') {
                   3489:                         $src = $attr->{'src'};
                   3490:                         &add_filetype($allfiles,$src,'src');
                   3491:                     }
                   3492:                 }
                   3493:                 my $text = $p->get_trimmed_text();
                   3494:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3495:                     my @swfargs = split(/,/,$1);
                   3496:                     foreach my $item (@swfargs) {
                   3497:                         $item =~ s/["']//g;
                   3498:                         $item =~ s/^\s+//;
                   3499:                         $item =~ s/\s+$//;
                   3500:                     }
                   3501:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3502:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3503:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3504:                         } else {
                   3505:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3506:                         }
                   3507:                     }
1.645     raeburn  3508:                 }
                   3509:             }
                   3510:             if (lc($tagname) eq 'link') {
                   3511:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3512:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3513:                 }
                   3514:             }
1.640     albertel 3515: 	    if (lc($tagname) eq 'object' ||
                   3516: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3517: 		foreach my $item (keys(%javafiles)) {
                   3518: 		    $javafiles{$item} = '';
                   3519: 		}
1.1164    raeburn  3520:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3521:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3522:                 }
1.640     albertel 3523: 	    }
                   3524: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3525: 		my $name = lc($attr->{'name'});
                   3526: 		foreach my $item (keys(%javafiles)) {
                   3527: 		    if ($name eq $item) {
                   3528: 			$javafiles{$item} = $attr->{'value'};
                   3529: 			last;
                   3530: 		    }
                   3531: 		}
1.1164    raeburn  3532:                 my $pathfrom;
1.640     albertel 3533: 		foreach my $item (keys(%mediafiles)) {
                   3534: 		    if ($name eq $item) {
1.1164    raeburn  3535:                         $pathfrom = $attr->{'value'};
                   3536:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3537: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3538: 			last;
                   3539: 		    }
                   3540: 		}
1.1164    raeburn  3541:                 if ($name eq 'flashvars') {
                   3542:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3543:                 }
                   3544:                 if ($pathfrom ne '') {
                   3545:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3546:                                          $pathfrom);
                   3547:                 }
1.640     albertel 3548: 	    }
                   3549: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3550: 		foreach my $item (keys(%javafiles)) {
                   3551: 		    if ($attr->{$item}) {
                   3552: 			$javafiles{$item} = $attr->{$item};
                   3553: 			last;
                   3554: 		    }
                   3555: 		}
                   3556: 		foreach my $item (keys(%mediafiles)) {
                   3557: 		    if ($attr->{$item}) {
                   3558: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3559: 			last;
                   3560: 		    }
                   3561: 		}
1.1164    raeburn  3562:                 if (lc($tagname) eq 'embed') {
                   3563:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3564:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3565:                                              $attr->{'src'});
                   3566:                     }
                   3567:                 }
1.640     albertel 3568: 	    }
1.1172.2.35  raeburn  3569:             if (lc($tagname) eq 'iframe') {
                   3570:                 my $src = $attr->{'src'} ;
                   3571:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3572:                     &add_filetype($allfiles,$src,'src');
                   3573:                 } elsif ($src =~ m{^/}) {
                   3574:                     if ($env{'request.course.id'}) {
                   3575:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3576:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3577:                         my $url = &hreflocation('',$fullpath);
                   3578:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3579:                             my $relpath = $1;
                   3580:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3581:                                 &add_filetype($allfiles,$1,'src');
                   3582:                             }
                   3583:                         }
                   3584:                     }
                   3585:                 }
                   3586:             }
1.1164    raeburn  3587:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3588:                 pop(@state);
1.1164    raeburn  3589:             }
1.640     albertel 3590: 	} elsif ($t->[0] eq 'E') {
                   3591: 	    my ($tagname) = ($t->[1]);
                   3592: 	    if ($javafiles{'codebase'} ne '') {
                   3593: 		$javafiles{'codebase'} .= '/';
                   3594: 	    }  
                   3595: 	    if (lc($tagname) eq 'applet' ||
                   3596: 		lc($tagname) eq 'object' ||
                   3597: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3598: 		) {
                   3599: 		foreach my $item (keys(%javafiles)) {
                   3600: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3601: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3602: 			&add_filetype($allfiles,$file,$item);
                   3603: 		    }
                   3604: 		}
                   3605: 	    } 
                   3606: 	    pop @state;
                   3607: 	}
                   3608:     }
1.1164    raeburn  3609:     foreach my $id (sort(keys(%flashvars))) {
                   3610:         if ($shockwave{$id} ne '') {
                   3611:             my @pairs = split(/\&/,$flashvars{$id});
                   3612:             foreach my $pair (@pairs) {
                   3613:                 my ($key,$value) = split(/\=/,$pair);
                   3614:                 if ($key eq 'thumb') {
                   3615:                     &add_filetype($allfiles,$value,$key);
                   3616:                 } elsif ($key eq 'content') {
                   3617:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3618:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3619:                     if ($ext ne '') {
                   3620:                         &add_filetype($allfiles,$path.$value,$ext);
                   3621:                     }
                   3622:                 }
                   3623:             }
                   3624:         }
                   3625:     }
1.637     raeburn  3626:     return 'ok';
                   3627: }
                   3628: 
1.639     albertel 3629: sub add_filetype {
                   3630:     my ($allfiles,$file,$type)=@_;
                   3631:     if (exists($allfiles->{$file})) {
                   3632: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3633: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3634: 	}
                   3635:     } else {
                   3636: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3637:     }
                   3638: }
                   3639: 
1.1164    raeburn  3640: sub embedded_dependency {
                   3641:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3642:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3643:         if (($identifier ne '') &&
                   3644:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3645:             ($pathfrom ne '')) {
                   3646:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3647:             foreach my $dep (@{$related->{$identifier}}) {
                   3648:                 &add_filetype($allfiles,$path.$dep,'object');
                   3649:             }
                   3650:         }
                   3651:     }
                   3652:     return;
                   3653: }
                   3654: 
1.493     albertel 3655: sub removeuploadedurl {
1.984     neumanie 3656:     my ($url)=@_;	
                   3657:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3658:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3659: }
                   3660: 
                   3661: sub removeuserfile {
                   3662:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3663:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3664:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3665:     if ($result eq 'ok') {	
1.798     raeburn  3666:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3667:             my $metafile = $fname.'.meta';
                   3668:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3669: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3670:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3671:             my $sqlresult = 
1.823     albertel 3672:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3673:                                         'portfolio_metadata',$group,
                   3674:                                         'delete');
1.798     raeburn  3675:         }
                   3676:     }
                   3677:     return $result;
1.257     www      3678: }
1.15      www      3679: 
1.530     albertel 3680: sub mkdiruserfile {
                   3681:     my ($docuname,$docudom,$dir)=@_;
                   3682:     my $home=&homeserver($docuname,$docudom);
                   3683:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3684: }
                   3685: 
1.531     albertel 3686: sub renameuserfile {
                   3687:     my ($docuname,$docudom,$old,$new)=@_;
                   3688:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3689:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3690:                         &escape("$old").':'.&escape("$new"),$home);
                   3691:     if ($result eq 'ok') {
                   3692:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3693:             my $oldmeta = $old.'.meta';
                   3694:             my $newmeta = $new.'.meta';
                   3695:             my $metaresult = 
                   3696:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3697: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3698:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3699:             my $sqlresult = 
1.823     albertel 3700:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3701:                                         'portfolio_metadata',$group,
                   3702:                                         'delete');
1.798     raeburn  3703:         }
                   3704:     }
                   3705:     return $result;
1.531     albertel 3706: }
                   3707: 
1.14      www      3708: # ------------------------------------------------------------------------- Log
                   3709: 
                   3710: sub log {
                   3711:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3712:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3713: }
                   3714: 
                   3715: # ------------------------------------------------------------------ Course Log
1.352     www      3716: #
                   3717: # This routine flushes several buffers of non-mission-critical nature
                   3718: #
1.157     www      3719: 
                   3720: sub flushcourselogs {
1.352     www      3721:     &logthis('Flushing log buffers');
                   3722: #
                   3723: # course logs
                   3724: # This is a log of all transactions in a course, which can be used
                   3725: # for data mining purposes
                   3726: #
                   3727: # It also collects the courseid database, which lists last transaction
                   3728: # times and course titles for all courseids
                   3729: #
                   3730:     my %courseidbuffer=();
1.921     raeburn  3731:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3732:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3733: 		          &escape($courselogs{$crsid}),
                   3734: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3735: 	    delete $courselogs{$crsid};
                   3736:         } else {
                   3737:             &logthis('Failed to flush log buffer for '.$crsid);
                   3738:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3739:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3740:                         " exceeded maximum size, deleting.</font>");
                   3741:                delete $courselogs{$crsid};
                   3742:             }
1.352     www      3743:         }
1.920     raeburn  3744:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3745:             'description' => $coursedescrbuf{$crsid},
                   3746:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3747:             'type'        => $coursetypebuf{$crsid},
                   3748:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3749:         };
1.191     harris41 3750:     }
1.352     www      3751: #
                   3752: # Write course id database (reverse lookup) to homeserver of courses 
                   3753: # Is used in pickcourse
                   3754: #
1.840     albertel 3755:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3756:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3757:                                     $courseidbuffer{$crs_home},
                   3758:                                     $crs_home,'timeonly');
1.352     www      3759:     }
                   3760: #
                   3761: # File accesses
                   3762: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3763: #
1.449     matthew  3764:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3765:         if ($entry =~ /___count$/) {
                   3766:             my ($dom,$name);
1.807     albertel 3767:             ($dom,$name,undef)=
1.811     albertel 3768: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3769:             if (! defined($dom) || $dom eq '' || 
                   3770:                 ! defined($name) || $name eq '') {
1.620     albertel 3771:                 my $cid = $env{'request.course.id'};
                   3772:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3773:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3774:             }
1.450     matthew  3775:             my $value = $accesshash{$entry};
                   3776:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3777:             my %temphash=($url => $value);
1.449     matthew  3778:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3779:             if ($result eq 'ok') {
                   3780:                 delete $accesshash{$entry};
                   3781:             }
                   3782:         } else {
1.811     albertel 3783:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3784:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3785:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3786:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3787:                 delete $accesshash{$entry};
                   3788:             }
1.185     www      3789:         }
1.191     harris41 3790:     }
1.352     www      3791: #
                   3792: # Roles
                   3793: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3794: #
1.800     albertel 3795:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3796:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3797: 	    split(/\:/,$entry);
                   3798:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3799:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3800:                 $rudom,$runame) eq 'ok') {
                   3801: 	    delete $userrolehash{$entry};
                   3802:         }
                   3803:     }
1.662     raeburn  3804: #
                   3805: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3806: #
                   3807:     my %domrolebuffer = ();
1.1000    raeburn  3808:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3809:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3810:         if ($domrolebuffer{$rudom}) {
                   3811:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3812:                       '='.&escape($domainrolehash{$entry});
                   3813:         } else {
                   3814:             $domrolebuffer{$rudom}.=&escape($entry).
                   3815:                       '='.&escape($domainrolehash{$entry});
                   3816:         }
                   3817:         delete $domainrolehash{$entry};
                   3818:     }
                   3819:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3820: 	my %servers = &get_servers($dom,'library');
                   3821: 	foreach my $tryserver (keys(%servers)) {
                   3822: 	    unless (&reply('domroleput:'.$dom.':'.
                   3823: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3824: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3825: 	    }
1.662     raeburn  3826:         }
                   3827:     }
1.186     www      3828:     $dumpcount++;
1.157     www      3829: }
                   3830: 
                   3831: sub courselog {
                   3832:     my $what=shift;
1.158     www      3833:     $what=time.':'.$what;
1.620     albertel 3834:     unless ($env{'request.course.id'}) { return ''; }
                   3835:     $coursedombuf{$env{'request.course.id'}}=
                   3836:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3837:     $coursenumbuf{$env{'request.course.id'}}=
                   3838:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3839:     $coursehombuf{$env{'request.course.id'}}=
                   3840:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3841:     $coursedescrbuf{$env{'request.course.id'}}=
                   3842:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3843:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3844:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3845:     $courseownerbuf{$env{'request.course.id'}}=
                   3846:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3847:     $coursetypebuf{$env{'request.course.id'}}=
                   3848:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3849:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3850: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3851:     } else {
1.620     albertel 3852: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3853:     }
1.620     albertel 3854:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3855: 	&flushcourselogs();
                   3856:     }
1.158     www      3857: }
                   3858: 
                   3859: sub courseacclog {
                   3860:     my $fnsymb=shift;
1.620     albertel 3861:     unless ($env{'request.course.id'}) { return ''; }
                   3862:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3863:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3864:         $what.=':POST';
1.583     matthew  3865:         # FIXME: Probably ought to escape things....
1.800     albertel 3866: 	foreach my $key (keys(%env)) {
                   3867:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3868:                 my $formitem = $1;
                   3869:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3870:                     $what.=':'.$formitem.'='.$env{$key};
                   3871:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3872:                     $what.=':'.$formitem.'='.$env{$key};
                   3873:                 }
1.158     www      3874:             }
1.191     harris41 3875:         }
1.583     matthew  3876:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3877:         # FIXME: We should not be depending on a form parameter that someone
                   3878:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3879:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3880:             $what.= ':POST';
                   3881:             # FIXME: Probably ought to escape things....
                   3882:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3883:                                  'crsdiscuss') {
1.620     albertel 3884:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3885:             }
                   3886:         }
1.158     www      3887:     }
                   3888:     &courselog($what);
1.149     www      3889: }
                   3890: 
1.185     www      3891: sub countacc {
                   3892:     my $url=&declutter(shift);
1.458     matthew  3893:     return if (! defined($url) || $url eq '');
1.620     albertel 3894:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3895: #
                   3896: # Mark that this url was used in this course
                   3897: #
1.620     albertel 3898:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3899: #
                   3900: # Increase the access count for this resource in this child process
                   3901: #
1.281     www      3902:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3903:     $accesshash{$key}++;
1.185     www      3904: }
1.349     www      3905: 
1.361     www      3906: sub linklog {
                   3907:     my ($from,$to)=@_;
                   3908:     $from=&declutter($from);
                   3909:     $to=&declutter($to);
                   3910:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3911:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3912: }
1.1160    www      3913: 
                   3914: sub statslog {
                   3915:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3916:     if ($users<2) { return; }
                   3917:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3918:             'course'       => $env{'request.course.id'},
                   3919:             'sections'     => '"all"',
                   3920:             'num_students' => $users,
                   3921:             'part'         => $part,
                   3922:             'symb'         => $symb,
                   3923:             'mean_tries'   => $av_attempts,
                   3924:             'deg_of_diff'  => $degdiff});
                   3925:     foreach my $key (keys(%dynstore)) {
                   3926:         $accesshash{$key}=$dynstore{$key};
                   3927:     }
                   3928: }
1.361     www      3929:   
1.349     www      3930: sub userrolelog {
                   3931:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3932:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3933:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3934:        $userrolehash
                   3935:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3936:                     =$tend.':'.$tstart;
1.662     raeburn  3937:     }
1.1169    droeschl 3938:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3939:        $userrolehash
                   3940:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3941:                     =$tend.':'.$tstart;
                   3942:     }
1.1169    droeschl 3943:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3944:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3945:        $domainrolehash
                   3946:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3947:                     = $tend.':'.$tstart;
                   3948:     }
1.351     www      3949: }
                   3950: 
1.957     raeburn  3951: sub courserolelog {
                   3952:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3953:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3954:         my $cdom = $1;
                   3955:         my $cnum = $2;
                   3956:         my $sec = $3;
                   3957:         my $namespace = 'rolelog';
                   3958:         my %storehash = (
                   3959:                            role    => $trole,
                   3960:                            start   => $tstart,
                   3961:                            end     => $tend,
                   3962:                            selfenroll => $selfenroll,
                   3963:                            context    => $context,
                   3964:                         );
                   3965:         if ($trole eq 'gr') {
                   3966:             $namespace = 'groupslog';
                   3967:             $storehash{'group'} = $sec;
                   3968:         } else {
                   3969:             $storehash{'section'} = $sec;
                   3970:         }
                   3971:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3972:                    $domain,$cnum,$cdom);
                   3973:         if (($trole ne 'st') || ($sec ne '')) {
                   3974:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3975:         }
                   3976:     }
                   3977:     return;
                   3978: }
                   3979: 
1.1172.2.9  raeburn  3980: sub domainrolelog {
                   3981:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3982:     if ($area =~ m{^/($match_domain)/$}) {
                   3983:         my $cdom = $1;
                   3984:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3985:         my $namespace = 'rolelog';
                   3986:         my %storehash = (
                   3987:                            role    => $trole,
                   3988:                            start   => $tstart,
                   3989:                            end     => $tend,
                   3990:                            context => $context,
                   3991:                         );
                   3992:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3993:                    $domain,$domconfiguser,$cdom);
                   3994:     }
                   3995:     return;
                   3996: 
                   3997: }
                   3998: 
                   3999: sub coauthorrolelog {
                   4000:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4001:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4002:         my $audom = $1;
                   4003:         my $auname = $2;
                   4004:         my $namespace = 'rolelog';
                   4005:         my %storehash = (
                   4006:                            role    => $trole,
                   4007:                            start   => $tstart,
                   4008:                            end     => $tend,
                   4009:                            context => $context,
                   4010:                         );
                   4011:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4012:                    $domain,$auname,$audom);
                   4013:     }
                   4014:     return;
                   4015: }
                   4016: 
1.351     www      4017: sub get_course_adv_roles {
1.948     raeburn  4018:     my ($cid,$codes) = @_;
1.620     albertel 4019:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4020:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4021:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4022:     my %nothide=();
1.800     albertel 4023:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4024:         if ($user !~ /:/) {
                   4025: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4026:         } else {
                   4027:             $nothide{$user}=1;
                   4028:         }
1.470     www      4029:     }
1.1172.2.23  raeburn  4030:     my @possdoms = ($coursehash{'domain'});
                   4031:     if ($coursehash{'checkforpriv'}) {
                   4032:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4033:     }
1.351     www      4034:     my %returnhash=();
                   4035:     my %dumphash=
                   4036:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4037:     my $now=time;
1.997     raeburn  4038:     my %privileged;
1.1000    raeburn  4039:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4040: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4041:         if (($tstart) && ($tstart<0)) { next; }
                   4042:         if (($tend) && ($tend<$now)) { next; }
                   4043:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4044:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4045: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4046:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4047:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4048: 	if ($role eq 'cr') { next; }
1.948     raeburn  4049:         if ($codes) {
                   4050:             if ($section) { $role .= ':'.$section; }
                   4051:             if ($returnhash{$role}) {
                   4052:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4053:             } else {
                   4054:                 $returnhash{$role}=$username.':'.$domain;
                   4055:             }
1.351     www      4056:         } else {
1.988     raeburn  4057:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4058:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4059:             if ($returnhash{$key}) {
                   4060: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4061:             } else {
                   4062:                 $returnhash{$key}=$username.':'.$domain;
                   4063:             }
1.351     www      4064:         }
1.948     raeburn  4065:     }
1.400     www      4066:     return %returnhash;
                   4067: }
                   4068: 
                   4069: sub get_my_roles {
1.937     raeburn  4070:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4071:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4072:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4073:     my (%dumphash,%nothide);
1.1086    raeburn  4074:     if ($context eq 'userroles') {
1.1166    raeburn  4075:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4076:     } else {
1.1172.2.23  raeburn  4077:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4078:         if ($hidepriv) {
                   4079:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4080:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4081:                 if ($user !~ /:/) {
                   4082:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4083:                 } else {
                   4084:                     $nothide{$user} = 1;
                   4085:                 }
                   4086:             }
                   4087:         }
1.858     raeburn  4088:     }
1.400     www      4089:     my %returnhash=();
                   4090:     my $now=time;
1.999     raeburn  4091:     my %privileged;
1.800     albertel 4092:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4093:         my ($role,$tend,$tstart);
                   4094:         if ($context eq 'userroles') {
1.1149    raeburn  4095:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4096: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4097:         } else {
                   4098:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4099:         }
1.400     www      4100:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4101:         my $status = 'active';
1.939     raeburn  4102:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4103:             $status = 'previous';
                   4104:         } 
                   4105:         if (($tstart) && ($now<$tstart)) {
                   4106:             $status = 'future';
                   4107:         }
                   4108:         if (ref($types) eq 'ARRAY') {
                   4109:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4110:                 next;
                   4111:             } 
                   4112:         } else {
                   4113:             if ($status ne 'active') {
                   4114:                 next;
                   4115:             }
                   4116:         }
1.867     raeburn  4117:         my ($rolecode,$username,$domain,$section,$area);
                   4118:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4119:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4120:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4121:         } else {
                   4122:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4123:         }
1.832     raeburn  4124:         if (ref($roledoms) eq 'ARRAY') {
                   4125:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4126:                 next;
                   4127:             }
                   4128:         }
                   4129:         if (ref($roles) eq 'ARRAY') {
                   4130:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4131:                 if ($role =~ /^cr\//) {
                   4132:                     if (!grep(/^cr$/,@{$roles})) {
                   4133:                         next;
                   4134:                     }
1.1104    raeburn  4135:                 } elsif ($role =~ /^gr\//) {
                   4136:                     if (!grep(/^gr$/,@{$roles})) {
                   4137:                         next;
                   4138:                     }
1.922     raeburn  4139:                 } else {
                   4140:                     next;
                   4141:                 }
1.832     raeburn  4142:             }
1.867     raeburn  4143:         }
1.937     raeburn  4144:         if ($hidepriv) {
1.1172.2.23  raeburn  4145:             my @privroles = ('dc','su');
1.999     raeburn  4146:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4147:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4148:             } else {
1.1172.2.23  raeburn  4149:                 my $possdoms = [$domain];
                   4150:                 if (ref($roledoms) eq 'ARRAY') {
                   4151:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4152:                 }
1.1172.2.23  raeburn  4153:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4154:                     if (!$nothide{$username.':'.$domain}) {
                   4155:                         next;
                   4156:                     }
                   4157:                 }
1.937     raeburn  4158:             }
                   4159:         }
1.933     raeburn  4160:         if ($withsec) {
                   4161:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4162:                 $tstart.':'.$tend;
                   4163:         } else {
                   4164:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4165:         }
1.832     raeburn  4166:     }
1.373     www      4167:     return %returnhash;
1.399     www      4168: }
                   4169: 
                   4170: # ----------------------------------------------------- Frontpage Announcements
                   4171: #
                   4172: #
                   4173: 
                   4174: sub postannounce {
                   4175:     my ($server,$text)=@_;
1.844     albertel 4176:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4177:     unless ($text=~/\w/) { $text=''; }
                   4178:     return &reply('setannounce:'.&escape($text),$server);
                   4179: }
                   4180: 
                   4181: sub getannounce {
1.448     albertel 4182: 
                   4183:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4184: 	my $announcement='';
1.800     albertel 4185: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4186: 	close($fh);
1.399     www      4187: 	if ($announcement=~/\w/) { 
                   4188: 	    return 
                   4189:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4190:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4191: 	} else {
                   4192: 	    return '';
                   4193: 	}
                   4194:     } else {
                   4195: 	return '';
                   4196:     }
1.351     www      4197: }
1.353     www      4198: 
                   4199: # ---------------------------------------------------------- Course ID routines
                   4200: # Deal with domain's nohist_courseid.db files
                   4201: #
                   4202: 
                   4203: sub courseidput {
1.921     raeburn  4204:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4205:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4206:     my $outcome;
                   4207:     if ($caller eq 'timeonly') {
                   4208:         my $cids = '';
                   4209:         foreach my $item (keys(%$storehash)) {
                   4210:             $cids.=&escape($item).'&';
                   4211:         }
                   4212:         $cids=~s/\&$//;
                   4213:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4214:                           $coursehome);       
                   4215:     } else {
                   4216:         my $items = '';
                   4217:         foreach my $item (keys(%$storehash)) {
                   4218:             $items.= &escape($item).'='.
                   4219:                      &freeze_escape($$storehash{$item}).'&';
                   4220:         }
                   4221:         $items=~s/\&$//;
                   4222:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4223:                           $coursehome);
1.918     raeburn  4224:     }
                   4225:     if ($outcome eq 'unknown_cmd') {
                   4226:         my $what;
                   4227:         foreach my $cid (keys(%$storehash)) {
                   4228:             $what .= &escape($cid).'=';
1.921     raeburn  4229:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4230:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4231:             }
                   4232:             $what =~ s/\:$/&/;
                   4233:         }
                   4234:         $what =~ s/\&$//;  
                   4235:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4236:     } else {
                   4237:         return $outcome;
                   4238:     }
1.353     www      4239: }
                   4240: 
                   4241: sub courseiddump {
1.921     raeburn  4242:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4243:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4244:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4245:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
                   4246:         $hasuniquecode)=@_;
1.918     raeburn  4247:     my $as_hash = 1;
                   4248:     my %returnhash;
                   4249:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4250:     my %libserv = &all_library();
                   4251:     foreach my $tryserver (keys(%libserv)) {
                   4252:         if ( (  $hostidflag == 1 
                   4253: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4254: 	     || (!defined($hostidflag)) ) {
                   4255: 
1.918     raeburn  4256: 	    if (($domfilter eq '') ||
                   4257: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4258:                 my $rep;
                   4259:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4260:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4261:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4262:                                 &escape($descfilter), &escape($instcodefilter),
                   4263:                                 &escape($ownerfilter), &escape($coursefilter),
                   4264:                                 &escape($typefilter), &escape($regexp_ok),
                   4265:                                 $as_hash, &escape($selfenrollonly),
                   4266:                                 &escape($catfilter), $showhidden, $caller,
                   4267:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4268:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.38  raeburn  4269:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22  raeburn  4270:                 } else {
                   4271:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4272:                              $sincefilter.':'.&escape($descfilter).':'.
                   4273:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4274:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4275:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4276:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4277:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4278:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4279:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38  raeburn  4280:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22  raeburn  4281:                              $tryserver);
                   4282:                 }
                   4283: 
1.918     raeburn  4284:                 my @pairs=split(/\&/,$rep);
                   4285:                 foreach my $item (@pairs) {
                   4286:                     my ($key,$value)=split(/\=/,$item,2);
                   4287:                     $key = &unescape($key);
                   4288:                     next if ($key =~ /^error: 2 /);
                   4289:                     my $result = &thaw_unescape($value);
                   4290:                     if (ref($result) eq 'HASH') {
                   4291:                         $returnhash{$key}=$result;
                   4292:                     } else {
1.921     raeburn  4293:                         my @responses = split(/:/,$value);
                   4294:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4295:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4296:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4297:                         }
1.1008    raeburn  4298:                     }
1.353     www      4299:                 }
                   4300:             }
                   4301:         }
                   4302:     }
                   4303:     return %returnhash;
                   4304: }
                   4305: 
1.1055    raeburn  4306: sub courselastaccess {
                   4307:     my ($cdom,$cnum,$hostidref) = @_;
                   4308:     my %returnhash;
                   4309:     if ($cdom && $cnum) {
                   4310:         my $chome = &homeserver($cnum,$cdom);
                   4311:         if ($chome ne 'no_host') {
                   4312:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4313:             &extract_lastaccess(\%returnhash,$rep);
                   4314:         }
                   4315:     } else {
                   4316:         if (!$cdom) { $cdom=''; }
                   4317:         my %libserv = &all_library();
                   4318:         foreach my $tryserver (keys(%libserv)) {
                   4319:             if (ref($hostidref) eq 'ARRAY') {
                   4320:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4321:             } 
                   4322:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4323:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4324:                 &extract_lastaccess(\%returnhash,$rep);
                   4325:             }
                   4326:         }
                   4327:     }
                   4328:     return %returnhash;
                   4329: }
                   4330: 
                   4331: sub extract_lastaccess {
                   4332:     my ($returnhash,$rep) = @_;
                   4333:     if (ref($returnhash) eq 'HASH') {
                   4334:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4335:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4336:                  $rep eq '') {
                   4337:             my @pairs=split(/\&/,$rep);
                   4338:             foreach my $item (@pairs) {
                   4339:                 my ($key,$value)=split(/\=/,$item,2);
                   4340:                 $key = &unescape($key);
                   4341:                 next if ($key =~ /^error: 2 /);
                   4342:                 $returnhash->{$key} = &thaw_unescape($value);
                   4343:             }
                   4344:         }
                   4345:     }
                   4346:     return;
                   4347: }
                   4348: 
1.658     raeburn  4349: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4350: 
                   4351: sub dcmailput {
1.685     raeburn  4352:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4353:     my $status = &Apache::lonnet::critical(
1.740     www      4354:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4355:        &escape($message),$server);
1.662     raeburn  4356:     return $status;
                   4357: }
                   4358: 
1.658     raeburn  4359: sub dcmaildump {
                   4360:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4361:     my %returnhash=();
1.846     albertel 4362: 
                   4363:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4364:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4365:                                                          &escape($enddate).':';
                   4366: 	my @esc_senders=map { &escape($_)} @$senders;
                   4367: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4368: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4369:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4370:             if (($key) && ($value)) {
                   4371:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4372:             }
                   4373:         }
                   4374:     }
                   4375:     return %returnhash;
                   4376: }
1.662     raeburn  4377: # ---------------------------------------------------------- Domain roles
                   4378: 
                   4379: sub get_domain_roles {
                   4380:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4381:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4382:         $startdate = '.';
                   4383:     }
1.1018    raeburn  4384:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4385:         $enddate = '.';
                   4386:     }
1.922     raeburn  4387:     my $rolelist;
                   4388:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4389:         $rolelist = join('&',@{$roles});
1.922     raeburn  4390:     }
1.662     raeburn  4391:     my %personnel = ();
1.841     albertel 4392: 
                   4393:     my %servers = &get_servers($dom,'library');
                   4394:     foreach my $tryserver (keys(%servers)) {
                   4395: 	%{$personnel{$tryserver}}=();
                   4396: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4397: 					    &escape($startdate).':'.
                   4398: 					    &escape($enddate).':'.
                   4399: 					    &escape($rolelist), $tryserver))) {
                   4400: 	    my ($key,$value) = split(/\=/,$line,2);
                   4401: 	    if (($key) && ($value)) {
                   4402: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4403: 	    }
                   4404: 	}
1.662     raeburn  4405:     }
                   4406:     return %personnel;
                   4407: }
1.658     raeburn  4408: 
1.1057    www      4409: # ----------------------------------------------------------- Interval timing 
1.149     www      4410: 
1.1153    www      4411: {
                   4412: # Caches needed for speedup of navmaps
                   4413: # We don't want to cache this for very long at all (5 seconds at most)
                   4414: # 
                   4415: # The user for whom we cache
                   4416: my $cachedkey='';
                   4417: # The cached times for this user
                   4418: my %cachedtimes=();
                   4419: # When this was last done
                   4420: my $cachedtime=();
                   4421: 
                   4422: sub load_all_first_access {
1.1154    raeburn  4423:     my ($uname,$udom)=@_;
1.1156    www      4424:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4425:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4426:         return;
                   4427:     }
                   4428:     $cachedtime=time;
                   4429:     $cachedkey=$uname.':'.$udom;
                   4430:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4431: }
                   4432: 
1.504     albertel 4433: sub get_first_access {
1.1162    raeburn  4434:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4435:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4436:     if ($argsymb) { $symb=$argsymb; }
                   4437:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4438:     if ($argmap) { $map = $argmap; }
1.926     albertel 4439:     if ($type eq 'course') {
                   4440: 	$res='course';
                   4441:     } elsif ($type eq 'map') {
1.588     albertel 4442: 	$res=&symbread($map);
                   4443:     } else {
                   4444: 	$res=$symb;
                   4445:     }
1.1153    www      4446:     &load_all_first_access($uname,$udom);
                   4447:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4448: }
                   4449: 
                   4450: sub set_first_access {
1.1162    raeburn  4451:     my ($type,$interval)=@_;
1.790     albertel 4452:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4453:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4454:     if ($type eq 'course') {
                   4455: 	$res='course';
                   4456:     } elsif ($type eq 'map') {
1.588     albertel 4457: 	$res=&symbread($map);
                   4458:     } else {
                   4459: 	$res=$symb;
                   4460:     }
1.1153    www      4461:     $cachedkey='';
1.1162    raeburn  4462:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4463:     if (!$firstaccess) {
1.1162    raeburn  4464:         my $start = time;
                   4465: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4466:                           $udom,$uname);
                   4467:         if ($putres eq 'ok') {
                   4468:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4469:                  $udom,$uname); 
                   4470:             &appenv(
                   4471:                      {
                   4472:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4473:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4474:                      }
                   4475:                   );
                   4476:         }
                   4477:         return $putres;
1.505     albertel 4478:     }
                   4479:     return 'already_set';
1.504     albertel 4480: }
1.1153    www      4481: }
1.1172.2.32  raeburn  4482: 
                   4483: sub checkout {
                   4484:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4485:     my $now=time;
                   4486:     my $lonhost=$perlvar{'lonHostID'};
                   4487:     my $infostr=&escape(
                   4488:                  'CHECKOUTTOKEN&'.
                   4489:                  $tuname.'&'.
                   4490:                  $tudom.'&'.
                   4491:                  $tcrsid.'&'.
                   4492:                  $symb.'&'.
                   4493:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4494:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4495:     if ($token=~/^error\:/) {
                   4496:         &logthis("<font color=\"blue\">WARNING: ".
                   4497:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4498:                  "</font>");
                   4499:         return '';
                   4500:     }
                   4501: 
                   4502:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4503:     $token=~tr/a-z/A-Z/;
                   4504: 
                   4505:     my %infohash=('resource.0.outtoken' => $token,
                   4506:                   'resource.0.checkouttime' => $now,
                   4507:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4508: 
                   4509:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4510:        return '';
                   4511:     } else {
                   4512:         &logthis("<font color=\"blue\">WARNING: ".
                   4513:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4514:                  "</font>");
                   4515:     }
                   4516: 
                   4517:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4518:                          &escape('Checkout '.$infostr.' - '.
                   4519:                                                  $token)) ne 'ok') {
                   4520:         return '';
                   4521:     } else {
                   4522:         &logthis("<font color=\"blue\">WARNING: ".
                   4523:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4524:                  "</font>");
                   4525:     }
                   4526:     return $token;
                   4527: }
                   4528: 
                   4529: # ------------------------------------------------------------ Check in an item
                   4530: 
                   4531: sub checkin {
                   4532:     my $token=shift;
                   4533:     my $now=time;
                   4534:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4535:     $lonhost=~tr/A-Z/a-z/;
                   4536:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4537:     $dtoken=~s/\W/\_/g;
                   4538:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4539:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4540: 
                   4541:     unless (($tuname) && ($tudom)) {
                   4542:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4543:         return '';
                   4544:     }
                   4545: 
                   4546:     unless (&allowed('mgr',$tcrsid)) {
                   4547:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4548:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4549:         return '';
                   4550:     }
                   4551: 
                   4552:     my %infohash=('resource.0.intoken' => $token,
                   4553:                   'resource.0.checkintime' => $now,
                   4554:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4555: 
                   4556:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4557:        return '';
                   4558:     }
                   4559: 
                   4560:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4561:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4562:         return '';
                   4563:     }
                   4564: 
                   4565:     return ($symb,$tuname,$tudom,$tcrsid);
                   4566: }
                   4567: 
1.110     www      4568: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4569: 
                   4570: sub expirespread {
                   4571:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4572:     my $cid=$env{'request.course.id'}; 
1.110     www      4573:     if ($cid) {
                   4574:        my $now=time;
                   4575:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4576:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4577:                             $env{'course.'.$cid.'.num'}.
1.110     www      4578: 	        	    ':nohist_expirationdates:'.
                   4579:                             &escape($key).'='.$now,
1.620     albertel 4580:                             $env{'course.'.$cid.'.home'})
1.110     www      4581:     }
                   4582:     return 'ok';
1.14      www      4583: }
                   4584: 
1.109     www      4585: # ----------------------------------------------------- Devalidate Spreadsheets
                   4586: 
                   4587: sub devalidate {
1.325     www      4588:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4589:     my $cid=$env{'request.course.id'}; 
1.109     www      4590:     if ($cid) {
1.391     matthew  4591:         # delete the stored spreadsheets for
                   4592:         # - the student level sheet of this user in course's homespace
                   4593:         # - the assessment level sheet for this resource 
                   4594:         #   for this user in user's homespace
1.553     albertel 4595: 	# - current conditional state info
1.325     www      4596: 	my $key=$uname.':'.$udom.':';
1.109     www      4597:         my $status=
1.299     matthew  4598: 	    &del('nohist_calculatedsheets',
1.391     matthew  4599: 		 [$key.'studentcalc:'],
1.620     albertel 4600: 		 $env{'course.'.$cid.'.domain'},
                   4601: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4602: 		.' '.
                   4603: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4604: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4605:         unless ($status eq 'ok ok') {
                   4606:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4607:                     $uname.' at '.$udom.' for '.
1.109     www      4608: 		    $symb.': '.$status);
1.133     albertel 4609:         }
1.553     albertel 4610: 	&delenv('user.state.'.$cid);
1.109     www      4611:     }
                   4612: }
                   4613: 
1.265     albertel 4614: sub get_scalar {
                   4615:     my ($string,$end) = @_;
                   4616:     my $value;
                   4617:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4618: 	$value = $1;
                   4619:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4620: 	$value = $1;
                   4621:     }
                   4622:     return &unescape($value);
                   4623: }
                   4624: 
                   4625: sub array2str {
                   4626:   my (@array) = @_;
                   4627:   my $result=&arrayref2str(\@array);
                   4628:   $result=~s/^__ARRAY_REF__//;
                   4629:   $result=~s/__END_ARRAY_REF__$//;
                   4630:   return $result;
                   4631: }
                   4632: 
1.204     albertel 4633: sub arrayref2str {
                   4634:   my ($arrayref) = @_;
1.265     albertel 4635:   my $result='__ARRAY_REF__';
1.204     albertel 4636:   foreach my $elem (@$arrayref) {
1.265     albertel 4637:     if(ref($elem) eq 'ARRAY') {
                   4638:       $result.=&arrayref2str($elem).'&';
                   4639:     } elsif(ref($elem) eq 'HASH') {
                   4640:       $result.=&hashref2str($elem).'&';
                   4641:     } elsif(ref($elem)) {
                   4642:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4643:     } else {
                   4644:       $result.=&escape($elem).'&';
                   4645:     }
                   4646:   }
                   4647:   $result=~s/\&$//;
1.265     albertel 4648:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4649:   return $result;
                   4650: }
                   4651: 
1.168     albertel 4652: sub hash2str {
1.204     albertel 4653:   my (%hash) = @_;
                   4654:   my $result=&hashref2str(\%hash);
1.265     albertel 4655:   $result=~s/^__HASH_REF__//;
                   4656:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4657:   return $result;
                   4658: }
                   4659: 
                   4660: sub hashref2str {
                   4661:   my ($hashref)=@_;
1.265     albertel 4662:   my $result='__HASH_REF__';
1.800     albertel 4663:   foreach my $key (sort(keys(%$hashref))) {
                   4664:     if (ref($key) eq 'ARRAY') {
                   4665:       $result.=&arrayref2str($key).'=';
                   4666:     } elsif (ref($key) eq 'HASH') {
                   4667:       $result.=&hashref2str($key).'=';
                   4668:     } elsif (ref($key)) {
1.265     albertel 4669:       $result.='=';
1.800     albertel 4670:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4671:     } else {
1.1132    raeburn  4672: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4673:     }
                   4674: 
1.800     albertel 4675:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4676:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4677:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4678:       $result.=&hashref2str($hashref->{$key}).'&';
                   4679:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4680:        $result.='&';
1.800     albertel 4681:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4682:     } else {
1.800     albertel 4683:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4684:     }
                   4685:   }
1.168     albertel 4686:   $result=~s/\&$//;
1.265     albertel 4687:   $result .= '__END_HASH_REF__';
1.168     albertel 4688:   return $result;
                   4689: }
                   4690: 
                   4691: sub str2hash {
1.265     albertel 4692:     my ($string)=@_;
                   4693:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4694:     return %$hash;
                   4695: }
                   4696: 
                   4697: sub str2hashref {
1.168     albertel 4698:   my ($string) = @_;
1.265     albertel 4699: 
                   4700:   my %hash;
                   4701: 
                   4702:   if($string !~ /^__HASH_REF__/) {
                   4703:       if (! ($string eq '' || !defined($string))) {
                   4704: 	  $hash{'error'}='Not hash reference';
                   4705:       }
                   4706:       return (\%hash, $string);
                   4707:   }
                   4708: 
                   4709:   $string =~ s/^__HASH_REF__//;
                   4710: 
                   4711:   while($string !~ /^__END_HASH_REF__/) {
                   4712:       #key
                   4713:       my $key='';
                   4714:       if($string =~ /^__HASH_REF__/) {
                   4715:           ($key, $string)=&str2hashref($string);
                   4716:           if(defined($key->{'error'})) {
                   4717:               $hash{'error'}='Bad data';
                   4718:               return (\%hash, $string);
                   4719:           }
                   4720:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4721:           ($key, $string)=&str2arrayref($string);
                   4722:           if($key->[0] eq 'Array reference error') {
                   4723:               $hash{'error'}='Bad data';
                   4724:               return (\%hash, $string);
                   4725:           }
                   4726:       } else {
                   4727:           $string =~ s/^(.*?)=//;
1.267     albertel 4728: 	  $key=&unescape($1);
1.265     albertel 4729:       }
                   4730:       $string =~ s/^=//;
                   4731: 
                   4732:       #value
                   4733:       my $value='';
                   4734:       if($string =~ /^__HASH_REF__/) {
                   4735:           ($value, $string)=&str2hashref($string);
                   4736:           if(defined($value->{'error'})) {
                   4737:               $hash{'error'}='Bad data';
                   4738:               return (\%hash, $string);
                   4739:           }
                   4740:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4741:           ($value, $string)=&str2arrayref($string);
                   4742:           if($value->[0] eq 'Array reference error') {
                   4743:               $hash{'error'}='Bad data';
                   4744:               return (\%hash, $string);
                   4745:           }
                   4746:       } else {
                   4747: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4748:       }
                   4749:       $string =~ s/^&//;
                   4750: 
                   4751:       $hash{$key}=$value;
1.204     albertel 4752:   }
1.265     albertel 4753: 
                   4754:   $string =~ s/^__END_HASH_REF__//;
                   4755: 
                   4756:   return (\%hash, $string);
1.204     albertel 4757: }
                   4758: 
                   4759: sub str2array {
1.265     albertel 4760:     my ($string)=@_;
                   4761:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4762:     return @$array;
                   4763: }
                   4764: 
                   4765: sub str2arrayref {
1.204     albertel 4766:   my ($string) = @_;
1.265     albertel 4767:   my @array;
                   4768: 
                   4769:   if($string !~ /^__ARRAY_REF__/) {
                   4770:       if (! ($string eq '' || !defined($string))) {
                   4771: 	  $array[0]='Array reference error';
                   4772:       }
                   4773:       return (\@array, $string);
                   4774:   }
                   4775: 
                   4776:   $string =~ s/^__ARRAY_REF__//;
                   4777: 
                   4778:   while($string !~ /^__END_ARRAY_REF__/) {
                   4779:       my $value='';
                   4780:       if($string =~ /^__HASH_REF__/) {
                   4781:           ($value, $string)=&str2hashref($string);
                   4782:           if(defined($value->{'error'})) {
                   4783:               $array[0] ='Array reference error';
                   4784:               return (\@array, $string);
                   4785:           }
                   4786:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4787:           ($value, $string)=&str2arrayref($string);
                   4788:           if($value->[0] eq 'Array reference error') {
                   4789:               $array[0] ='Array reference error';
                   4790:               return (\@array, $string);
                   4791:           }
                   4792:       } else {
                   4793: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4794:       }
                   4795:       $string =~ s/^&//;
                   4796: 
                   4797:       push(@array, $value);
1.191     harris41 4798:   }
1.265     albertel 4799: 
                   4800:   $string =~ s/^__END_ARRAY_REF__//;
                   4801: 
                   4802:   return (\@array, $string);
1.168     albertel 4803: }
                   4804: 
1.167     albertel 4805: # -------------------------------------------------------------------Temp Store
                   4806: 
1.168     albertel 4807: sub tmpreset {
                   4808:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4809:   if (!$symb) {
                   4810:     $symb=&symbread();
1.620     albertel 4811:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4812:   }
                   4813:   $symb=escape($symb);
                   4814: 
1.620     albertel 4815:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4816:   $namespace=~s/\//\_/g;
                   4817:   $namespace=~s/\W//g;
                   4818: 
1.620     albertel 4819:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4820:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4821:   if ($domain eq 'public' && $stuname eq 'public') {
                   4822:       $stuname=$ENV{'REMOTE_ADDR'};
                   4823:   }
1.1117    foxr     4824:   my $path=LONCAPA::tempdir();
1.168     albertel 4825:   my %hash;
                   4826:   if (tie(%hash,'GDBM_File',
                   4827: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4828: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4829:     foreach my $key (keys(%hash)) {
1.180     albertel 4830:       if ($key=~ /:$symb/) {
1.168     albertel 4831: 	delete($hash{$key});
                   4832:       }
                   4833:     }
                   4834:   }
                   4835: }
                   4836: 
1.167     albertel 4837: sub tmpstore {
1.168     albertel 4838:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4839: 
                   4840:   if (!$symb) {
                   4841:     $symb=&symbread();
1.620     albertel 4842:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4843:   }
                   4844:   $symb=escape($symb);
                   4845: 
                   4846:   if (!$namespace) {
                   4847:     # I don't think we would ever want to store this for a course.
                   4848:     # it seems this will only be used if we don't have a course.
1.620     albertel 4849:     #$namespace=$env{'request.course.id'};
1.168     albertel 4850:     #if (!$namespace) {
1.620     albertel 4851:       $namespace=$env{'request.state'};
1.168     albertel 4852:     #}
                   4853:   }
                   4854:   $namespace=~s/\//\_/g;
                   4855:   $namespace=~s/\W//g;
1.620     albertel 4856:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4857:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4858:   if ($domain eq 'public' && $stuname eq 'public') {
                   4859:       $stuname=$ENV{'REMOTE_ADDR'};
                   4860:   }
1.168     albertel 4861:   my $now=time;
                   4862:   my %hash;
1.1117    foxr     4863:   my $path=LONCAPA::tempdir();
1.168     albertel 4864:   if (tie(%hash,'GDBM_File',
                   4865: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4866: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4867:     $hash{"version:$symb"}++;
                   4868:     my $version=$hash{"version:$symb"};
                   4869:     my $allkeys=''; 
                   4870:     foreach my $key (keys(%$storehash)) {
                   4871:       $allkeys.=$key.':';
1.591     albertel 4872:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4873:     }
                   4874:     $hash{"$version:$symb:timestamp"}=$now;
                   4875:     $allkeys.='timestamp';
                   4876:     $hash{"$version:keys:$symb"}=$allkeys;
                   4877:     if (untie(%hash)) {
                   4878:       return 'ok';
                   4879:     } else {
                   4880:       return "error:$!";
                   4881:     }
                   4882:   } else {
                   4883:     return "error:$!";
                   4884:   }
                   4885: }
1.167     albertel 4886: 
1.168     albertel 4887: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4888: 
1.168     albertel 4889: sub tmprestore {
                   4890:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4891: 
1.168     albertel 4892:   if (!$symb) {
                   4893:     $symb=&symbread();
1.620     albertel 4894:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4895:   }
                   4896:   $symb=escape($symb);
                   4897: 
1.620     albertel 4898:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4899: 
1.620     albertel 4900:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4901:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4902:   if ($domain eq 'public' && $stuname eq 'public') {
                   4903:       $stuname=$ENV{'REMOTE_ADDR'};
                   4904:   }
1.168     albertel 4905:   my %returnhash;
                   4906:   $namespace=~s/\//\_/g;
                   4907:   $namespace=~s/\W//g;
                   4908:   my %hash;
1.1117    foxr     4909:   my $path=LONCAPA::tempdir();
1.168     albertel 4910:   if (tie(%hash,'GDBM_File',
                   4911: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4912: 	  &GDBM_READER(),0640)) {
1.168     albertel 4913:     my $version=$hash{"version:$symb"};
                   4914:     $returnhash{'version'}=$version;
                   4915:     my $scope;
                   4916:     for ($scope=1;$scope<=$version;$scope++) {
                   4917:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4918:       my @keys=split(/:/,$vkeys);
                   4919:       my $key;
                   4920:       $returnhash{"$scope:keys"}=$vkeys;
                   4921:       foreach $key (@keys) {
1.591     albertel 4922: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4923: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4924:       }
                   4925:     }
1.168     albertel 4926:     if (!(untie(%hash))) {
                   4927:       return "error:$!";
                   4928:     }
                   4929:   } else {
                   4930:     return "error:$!";
                   4931:   }
                   4932:   return %returnhash;
1.167     albertel 4933: }
                   4934: 
1.9       www      4935: # ----------------------------------------------------------------------- Store
                   4936: 
                   4937: sub store {
1.124     www      4938:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4939:     my $home='';
                   4940: 
1.168     albertel 4941:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4942: 
1.213     www      4943:     $symb=&symbclean($symb);
1.122     albertel 4944:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4945: 
1.620     albertel 4946:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4947:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4948: 
                   4949:     &devalidate($symb,$stuname,$domain);
1.109     www      4950: 
                   4951:     $symb=escape($symb);
1.187     www      4952:     if (!$namespace) { 
1.620     albertel 4953:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4954:           return ''; 
                   4955:        } 
                   4956:     }
1.620     albertel 4957:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4958: 
                   4959:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4960:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4961: 
1.12      www      4962:     my $namevalue='';
1.800     albertel 4963:     foreach my $key (keys(%$storehash)) {
                   4964:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4965:     }
1.12      www      4966:     $namevalue=~s/\&$//;
1.187     www      4967:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4968:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4969: }
                   4970: 
1.47      www      4971: # -------------------------------------------------------------- Critical Store
                   4972: 
                   4973: sub cstore {
1.124     www      4974:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4975:     my $home='';
                   4976: 
1.168     albertel 4977:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4978: 
1.213     www      4979:     $symb=&symbclean($symb);
1.122     albertel 4980:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4981: 
1.620     albertel 4982:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4983:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4984: 
                   4985:     &devalidate($symb,$stuname,$domain);
1.109     www      4986: 
                   4987:     $symb=escape($symb);
1.187     www      4988:     if (!$namespace) { 
1.620     albertel 4989:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4990:           return ''; 
                   4991:        } 
                   4992:     }
1.620     albertel 4993:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4994: 
                   4995:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4996:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4997: 
1.47      www      4998:     my $namevalue='';
1.800     albertel 4999:     foreach my $key (keys(%$storehash)) {
                   5000:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5001:     }
1.47      www      5002:     $namevalue=~s/\&$//;
1.187     www      5003:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5004:     return critical
                   5005:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      5006: }
                   5007: 
1.9       www      5008: # --------------------------------------------------------------------- Restore
                   5009: 
                   5010: sub restore {
1.124     www      5011:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5012:     my $home='';
                   5013: 
1.168     albertel 5014:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5015: 
1.122     albertel 5016:     if (!$symb) {
1.1172.2.26  raeburn  5017:         return if ($namespace eq 'courserequests');
                   5018:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5019:     } else {
1.1172.2.26  raeburn  5020:         unless ($namespace eq 'courserequests') {
                   5021:             $symb=&escape(&symbclean($symb));
                   5022:         }
1.122     albertel 5023:     }
1.188     www      5024:     if (!$namespace) { 
1.620     albertel 5025:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5026:           return ''; 
                   5027:        } 
                   5028:     }
1.620     albertel 5029:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5030:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5031:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5032:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5033: 
1.12      www      5034:     my %returnhash=();
1.800     albertel 5035:     foreach my $line (split(/\&/,$answer)) {
                   5036: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5037:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5038:     }
1.75      www      5039:     my $version;
                   5040:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5041:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5042:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5043:        }
1.75      www      5044:     }
1.13      www      5045:     return %returnhash;
1.34      www      5046: }
                   5047: 
                   5048: # ---------------------------------------------------------- Course Description
1.1118    foxr     5049: #
                   5050: #  
1.34      www      5051: 
                   5052: sub coursedescription {
1.731     albertel 5053:     my ($courseid,$args)=@_;
1.34      www      5054:     $courseid=~s/^\///;
1.49      www      5055:     $courseid=~s/\_/\//g;
1.34      www      5056:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5057:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5058:     my $normalid=$cdomain.'_'.$cnum;
                   5059:     # need to always cache even if we get errors otherwise we keep 
                   5060:     # trying and trying and trying to get the course description.
                   5061:     my %envhash=();
                   5062:     my %returnhash=();
1.731     albertel 5063:     
                   5064:     my $expiretime=600;
                   5065:     if ($env{'request.course.id'} eq $normalid) {
                   5066: 	$expiretime=120;
                   5067:     }
                   5068: 
                   5069:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5070:     if (!$args->{'freshen_cache'}
                   5071: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5072: 	foreach my $key (keys(%env)) {
                   5073: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5074: 	    my ($setting) = $1;
                   5075: 	    $returnhash{$setting} = $env{$key};
                   5076: 	}
                   5077: 	return %returnhash;
                   5078:     }
                   5079: 
1.1118    foxr     5080:     # get the data again
                   5081: 
1.731     albertel 5082:     if (!$args->{'one_time'}) {
                   5083: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5084:     }
1.811     albertel 5085: 
1.34      www      5086:     if ($chome ne 'no_host') {
1.302     albertel 5087:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5088:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5089: 	   my $username = $env{'user.name'}; # Defult username
                   5090: 	   if(defined $args->{'user'}) {
                   5091: 	       $username = $args->{'user'};
                   5092: 	   }
1.129     albertel 5093:            $returnhash{'home'}= $chome;
                   5094: 	   $returnhash{'domain'} = $cdomain;
                   5095: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5096:            if (!defined($returnhash{'type'})) {
                   5097:                $returnhash{'type'} = 'Course';
                   5098:            }
1.130     albertel 5099:            while (my ($name,$value) = each %returnhash) {
1.53      www      5100:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5101:            }
1.270     www      5102:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5103:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5104: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5105:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5106:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5107:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5108:        }
                   5109:     }
1.731     albertel 5110:     if (!$args->{'one_time'}) {
1.949     raeburn  5111: 	&appenv(\%envhash);
1.731     albertel 5112:     }
1.302     albertel 5113:     return %returnhash;
1.461     www      5114: }
                   5115: 
1.1080    raeburn  5116: sub update_released_required {
                   5117:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5118:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5119:         $cid = $env{'request.course.id'};
                   5120:         $cdom = $env{'course.'.$cid.'.domain'};
                   5121:         $cnum = $env{'course.'.$cid.'.num'};
                   5122:         $chome = $env{'course.'.$cid.'.home'};
                   5123:     }
                   5124:     if ($needsrelease) {
                   5125:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5126:         my $needsupdate;
                   5127:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5128:             $needsupdate = 1;
                   5129:         } else {
                   5130:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5131:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5132:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5133:                 $needsupdate = 1;
                   5134:             }
                   5135:         }
                   5136:         if ($needsupdate) {
                   5137:             my %needshash = (
                   5138:                              'internal.releaserequired' => $needsrelease,
                   5139:                             );
                   5140:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5141:             if ($putresult eq 'ok') {
                   5142:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5143:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5144:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5145:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5146:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5147:                 }
                   5148:             }
                   5149:         }
                   5150:     }
                   5151:     return;
                   5152: }
                   5153: 
1.461     www      5154: # -------------------------------------------------See if a user is privileged
                   5155: 
                   5156: sub privileged {
1.1172.2.23  raeburn  5157:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5158:     my $now = time;
1.1172.2.23  raeburn  5159:     my $roles;
                   5160:     if (ref($possroles) eq 'ARRAY') {
                   5161:         $roles = $possroles;
                   5162:     } else {
                   5163:         $roles = ['dc','su'];
                   5164:     }
                   5165:     if (ref($possdomains) eq 'ARRAY') {
                   5166:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5167:         foreach my $dom (@{$possdomains}) {
                   5168:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5169:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5170:                 foreach my $role (@{$roles}) {
                   5171:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5172:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5173:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5174:                             return 1 unless (($end && $end < $now) ||
                   5175:                                              ($start && $start > $now));
                   5176:                         }
                   5177:                     }
                   5178:                 }
                   5179:             }
                   5180:         }
                   5181:     } else {
                   5182:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5183:         my $now = time;
1.1170    droeschl 5184: 
1.1172.2.58! raeburn  5185:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5186:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5187:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5188:                 return 1 unless ($tend && $tend < $now)
                   5189:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5190:             }
1.1172.2.23  raeburn  5191:         }
                   5192:     }
1.461     www      5193:     return 0;
1.9       www      5194: }
1.1       albertel 5195: 
1.1172.2.23  raeburn  5196: sub privileged_by_domain {
                   5197:     my ($domains,$roles) = @_;
                   5198:     my %privileged = ();
                   5199:     my $cachetime = 60*60*24;
                   5200:     my $now = time;
                   5201:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5202:         return %privileged;
                   5203:     }
                   5204:     foreach my $dom (@{$domains}) {
                   5205:         next if (ref($privileged{$dom}) eq 'HASH');
                   5206:         my $needroles;
                   5207:         foreach my $role (@{$roles}) {
                   5208:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5209:             if (defined($cached)) {
                   5210:                 if (ref($result) eq 'HASH') {
                   5211:                     $privileged{$dom}{$role} = $result;
                   5212:                 }
                   5213:             } else {
                   5214:                 $needroles = 1;
                   5215:             }
                   5216:         }
                   5217:         if ($needroles) {
                   5218:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5219:             $privileged{$dom} = {};
                   5220:             foreach my $server (keys(%dompersonnel)) {
                   5221:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5222:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5223:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5224:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5225:                         next if ($end && $end < $now);
                   5226:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5227:                             $dompersonnel{$server}{$item};
                   5228:                     }
                   5229:                 }
                   5230:             }
                   5231:             if (ref($privileged{$dom}) eq 'HASH') {
                   5232:                 foreach my $role (@{$roles}) {
                   5233:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5234:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5235:                     } else {
                   5236:                         my %hash = ();
                   5237:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5238:                     }
                   5239:                 }
                   5240:             }
                   5241:         }
                   5242:     }
                   5243:     return %privileged;
                   5244: }
                   5245: 
1.103     harris41 5246: # -------------------------------------------------------- Get user privileges
1.11      www      5247: 
                   5248: sub rolesinit {
1.1169    droeschl 5249:     my ($domain, $username) = @_;
                   5250:     my %userroles = ('user.login.time' => time);
                   5251:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5252: 
                   5253:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5254:     # also, blocking can be triggered by an activating timer
                   5255:     # it's saved in the user's %env.
                   5256:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5257:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5258:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5259:         %timerintchk, %timerintenv);
                   5260: 
1.1162    raeburn  5261:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5262:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5263:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5264:     }
1.1169    droeschl 5265: 
1.1162    raeburn  5266:     foreach my $key (keys(%timerinterval)) {
                   5267:         my ($cid,$rest) = split(/\0/,$key);
                   5268:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5269:     }
1.1169    droeschl 5270: 
1.11      www      5271:     my %allroles=();
1.1162    raeburn  5272:     my %allgroups=();
1.11      www      5273: 
1.1172.2.58! raeburn  5274:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5275:         my $role = $rolesdump{$area};
                   5276:         $area =~ s/\_\w\w$//;
                   5277: 
                   5278:         my ($trole, $tend, $tstart, $group_privs);
                   5279: 
                   5280:         if ($role =~ /^cr/) {
                   5281:         # Custom role, defined by a user 
                   5282:         # e.g., user.role.cr/msu/smith/mynewrole
                   5283:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5284:                 $trole = $1;
                   5285:                 ($tend, $tstart) = split('_', $2);
                   5286:             } else {
                   5287:                 $trole = $role;
                   5288:             }
                   5289:         } elsif ($role =~ m|^gr/|) {
                   5290:         # Role of member in a group, defined within a course/community
                   5291:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5292:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5293:             next if $tstart eq '-1';
                   5294:             ($trole, $group_privs) = split(/\//, $trole);
                   5295:             $group_privs = &unescape($group_privs);
                   5296:         } else {
                   5297:         # Just a normal role, defined in roles.tab
                   5298:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5299:         }
                   5300: 
                   5301:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5302:                  $username);
                   5303:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5304: 
                   5305:         # role expired or not available yet?
                   5306:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5307:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5308: 
                   5309:         next if $area eq '' or $trole eq '';
                   5310: 
                   5311:         my $spec = "$trole.$area";
                   5312:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5313: 
                   5314:         if ($trole =~ /^cr\//) {
                   5315:         # Custom role, defined by a user
                   5316:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5317:         } elsif ($trole eq 'gr') {
                   5318:         # Role of a member in a group, defined within a course/community
                   5319:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5320:             next;
                   5321:         } else {
                   5322:         # Normal role, defined in roles.tab
                   5323:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5324:         }
                   5325: 
                   5326:         my $cid = $tdomain.'_'.$trest;
                   5327:         unless ($firstaccchk{$cid}) {
                   5328:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5329:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5330:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5331:                         $coursetimerstarts{$cid}{$item}; 
                   5332:                 }
                   5333:             }
                   5334:             $firstaccchk{$cid} = 1;
                   5335:         }
                   5336:         unless ($timerintchk{$cid}) {
                   5337:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5338:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5339:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5340:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5341:                 }
1.12      www      5342:             }
1.1169    droeschl 5343:             $timerintchk{$cid} = 1;
1.191     harris41 5344:         }
1.11      www      5345:     }
1.1169    droeschl 5346: 
                   5347:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5348:         \%allroles, \%allgroups);
                   5349:     $env{'user.adv'} = $userroles{'user.adv'};
                   5350: 
1.1162    raeburn  5351:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5352: }
                   5353: 
1.567     raeburn  5354: sub set_arearole {
1.1172.2.19  raeburn  5355:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5356:     unless ($nolog) {
1.567     raeburn  5357: # log the associated role with the area
1.1172.2.19  raeburn  5358:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5359:     }
1.743     albertel 5360:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5361: }
                   5362: 
                   5363: sub custom_roleprivs {
                   5364:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5365:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5366:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5367:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5368:         my ($rdummy,$roledef)=
                   5369:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5370:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5371:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5372:             if (defined($syspriv)) {
1.1043    raeburn  5373:                 if ($trest =~ /^$match_community$/) {
                   5374:                     $syspriv =~ s/bre\&S//; 
                   5375:                 }
1.567     raeburn  5376:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5377:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5378:             }
                   5379:             if ($tdomain ne '') {
                   5380:                 if (defined($dompriv)) {
                   5381:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5382:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5383:                 }
                   5384:                 if (($trest ne '') && (defined($coursepriv))) {
                   5385:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5386:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5387:                 }
                   5388:             }
                   5389:         }
                   5390:     }
                   5391: }
                   5392: 
1.678     raeburn  5393: sub group_roleprivs {
                   5394:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5395:     my $access = 1;
                   5396:     my $now = time;
                   5397:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5398:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5399:     if ($access) {
1.811     albertel 5400:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5401:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5402:     }
                   5403: }
1.567     raeburn  5404: 
                   5405: sub standard_roleprivs {
                   5406:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5407:     if (defined($pr{$trole.':s'})) {
                   5408:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5409:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5410:     }
                   5411:     if ($tdomain ne '') {
                   5412:         if (defined($pr{$trole.':d'})) {
                   5413:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5414:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5415:         }
                   5416:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5417:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5418:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5419:         }
                   5420:     }
                   5421: }
                   5422: 
                   5423: sub set_userprivs {
1.1064    raeburn  5424:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5425:     my $author=0;
                   5426:     my $adv=0;
1.678     raeburn  5427:     my %grouproles = ();
                   5428:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5429:         my @groupkeys; 
1.1000    raeburn  5430:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5431:             push(@groupkeys,$role);
                   5432:         }
                   5433:         if (ref($groups_roles) eq 'HASH') {
                   5434:             foreach my $key (keys(%{$groups_roles})) {
                   5435:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5436:                     push(@groupkeys,$key);
                   5437:                 }
                   5438:             }
                   5439:         }
                   5440:         if (@groupkeys > 0) {
                   5441:             foreach my $role (@groupkeys) {
                   5442:                 my ($trole,$area,$sec,$extendedarea);
                   5443:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5444:                     $trole = $1;
                   5445:                     $area = $2;
                   5446:                     $sec = $3;
                   5447:                     $extendedarea = $area.$sec;
                   5448:                     if (exists($$allgroups{$area})) {
                   5449:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5450:                             my $spec = $trole.'.'.$extendedarea;
                   5451:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5452:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5453:                         }
1.678     raeburn  5454:                     }
                   5455:                 }
                   5456:             }
                   5457:         }
                   5458:     }
1.800     albertel 5459:     foreach my $group (keys(%grouproles)) {
                   5460:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5461:     }
1.800     albertel 5462:     foreach my $role (keys(%{$allroles})) {
                   5463:         my %thesepriv;
1.941     raeburn  5464:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5465:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5466:             if ($item ne '') {
                   5467:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5468:                 if ($restrictions eq '') {
                   5469:                     $thesepriv{$privilege}='F';
                   5470:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5471:                     $thesepriv{$privilege}.=$restrictions;
                   5472:                 }
                   5473:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5474:             }
                   5475:         }
                   5476:         my $thesestr='';
1.1104    raeburn  5477:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5478: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5479: 	}
                   5480:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5481:     }
                   5482:     return ($author,$adv);
                   5483: }
                   5484: 
1.994     raeburn  5485: sub role_status {
1.1104    raeburn  5486:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5487:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5488:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5489:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5490:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5491:             $$where = '/'.$two;
1.994     raeburn  5492:             $$trolecode=$$role.'.'.$$where;
                   5493:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5494:             $$tstatus='is';
1.1104    raeburn  5495:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5496:                 $$tstatus='future';
1.1034    raeburn  5497:                 if ($$tstart<$now) {
                   5498:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5499:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5500:                             my (%allroles,%allgroups,$group_privs,
                   5501:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5502:                             my %userroles = (
                   5503:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5504:                             );
1.1064    raeburn  5505:                             @rolecodes = ('cm'); 
1.1002    raeburn  5506:                             my $spec=$$role.'.'.$$where;
                   5507:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5508:                             if ($$role =~ /^cr\//) {
                   5509:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5510:                                 push(@rolecodes,'cr');
1.1002    raeburn  5511:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5512:                                 push(@rolecodes,$$role);
1.1002    raeburn  5513:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5514:                                                     $env{'user.name'});
1.1064    raeburn  5515:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5516:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5517:                                 $group_privs = &unescape($group_privs);
                   5518:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5519:                                 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  5520:                                 &get_groups_roles($tdomain,$trest,
                   5521:                                                   \%course_roles,\@rolecodes,
                   5522:                                                   \%groups_roles);
1.1002    raeburn  5523:                             } else {
1.1064    raeburn  5524:                                 push(@rolecodes,$$role);
1.1002    raeburn  5525:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5526:                             }
1.1064    raeburn  5527:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5528:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5529:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5530:                         }
                   5531:                     }
1.1034    raeburn  5532:                     $$tstatus = 'is';
1.1002    raeburn  5533:                 }
1.994     raeburn  5534:             }
                   5535:             if ($$tend) {
1.1104    raeburn  5536:                 if ($$tend<$update) {
1.994     raeburn  5537:                     $$tstatus='expired';
                   5538:                 } elsif ($$tend<$now) {
                   5539:                     $$tstatus='will_not';
                   5540:                 }
                   5541:             }
                   5542:         }
                   5543:     }
                   5544: }
                   5545: 
1.1104    raeburn  5546: sub get_groups_roles {
                   5547:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5548:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5549:                   (ref($rolecodes) eq 'ARRAY') && 
                   5550:                   (ref($groups_roles) eq 'HASH')); 
                   5551:     if (keys(%{$cdom_courseroles}) > 0) {
                   5552:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5553:         if ($cdom ne '' && $cnum ne '') {
                   5554:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5555:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5556:                     my $crsrole = $1;
                   5557:                     my $crssec = $2;
                   5558:                     if ($crsrole =~ /^cr/) {
                   5559:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5560:                             push(@{$rolecodes},'cr');
                   5561:                         }
                   5562:                     } else {
                   5563:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5564:                             push(@{$rolecodes},$crsrole);
                   5565:                         }
                   5566:                     }
                   5567:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5568:                     if ($crssec ne '') {
                   5569:                         $rolekey .= "/$crssec";
                   5570:                     }
                   5571:                     $rolekey .= './';
                   5572:                     $groups_roles->{$rolekey} = $rolecodes;
                   5573:                 }
                   5574:             }
                   5575:         }
                   5576:     }
                   5577:     return;
                   5578: }
                   5579: 
                   5580: sub delete_env_groupprivs {
                   5581:     my ($where,$courseroles,$possroles) = @_;
                   5582:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5583:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5584:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5585:         %{$courseroles->{$udom}} =
                   5586:             &get_my_roles('','','userroles',['active'],
                   5587:                           $possroles,[$udom],1);
                   5588:     }
                   5589:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5590:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5591:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5592:             my $area = '/'.$cdom.'/'.$cnum;
                   5593:             my $privkey = "user.priv.$crsrole.$area";
                   5594:             if ($crssec ne '') {
                   5595:                 $privkey .= '/'.$crssec;
                   5596:             }
                   5597:             $privkey .= ".$area/$group";
                   5598:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5599:         }
                   5600:     }
                   5601:     return;
                   5602: }
                   5603: 
1.994     raeburn  5604: sub check_adhoc_privs {
1.1104    raeburn  5605:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5606:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5607:     my $setprivs;
1.994     raeburn  5608:     if ($env{$cckey}) {
                   5609:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5610:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5611:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5612:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5613:             $setprivs = 1;
1.994     raeburn  5614:         }
                   5615:     } else {
1.1088    raeburn  5616:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5617:         $setprivs = 1;
1.994     raeburn  5618:     }
1.1172.2.9  raeburn  5619:     return $setprivs;
1.994     raeburn  5620: }
                   5621: 
                   5622: sub set_adhoc_privileges {
                   5623: # role can be cc or ca
1.1088    raeburn  5624:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5625:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5626:     my $spec = $role.'.'.$area;
                   5627:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5628:                                   $env{'user.name'},1);
1.994     raeburn  5629:     my %ccrole = ();
                   5630:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5631:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5632:     &appenv(\%userroles,[$role,'cm']);
                   5633:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5634:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5635:         &appenv( {'request.role'        => $spec,
                   5636:                   'request.role.domain' => $dcdom,
                   5637:                   'request.course.sec'  => ''
                   5638:                  }
                   5639:                );
                   5640:         my $tadv=0;
                   5641:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5642:         &appenv({'request.role.adv'    => $tadv});
                   5643:     }
1.994     raeburn  5644: }
                   5645: 
1.12      www      5646: # --------------------------------------------------------------- get interface
                   5647: 
                   5648: sub get {
1.131     albertel 5649:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5650:    my $items='';
1.800     albertel 5651:    foreach my $item (@$storearr) {
                   5652:        $items.=&escape($item).'&';
1.191     harris41 5653:    }
1.12      www      5654:    $items=~s/\&$//;
1.620     albertel 5655:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5656:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5657:    my $uhome=&homeserver($uname,$udomain);
                   5658: 
1.133     albertel 5659:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5660:    my @pairs=split(/\&/,$rep);
1.273     albertel 5661:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5662:      return @pairs;
                   5663:    }
1.15      www      5664:    my %returnhash=();
1.42      www      5665:    my $i=0;
1.800     albertel 5666:    foreach my $item (@$storearr) {
                   5667:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5668:       $i++;
1.191     harris41 5669:    }
1.15      www      5670:    return %returnhash;
1.27      www      5671: }
                   5672: 
                   5673: # --------------------------------------------------------------- del interface
                   5674: 
                   5675: sub del {
1.133     albertel 5676:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5677:    my $items='';
1.800     albertel 5678:    foreach my $item (@$storearr) {
                   5679:        $items.=&escape($item).'&';
1.191     harris41 5680:    }
1.984     neumanie 5681: 
1.27      www      5682:    $items=~s/\&$//;
1.620     albertel 5683:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5684:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5685:    my $uhome=&homeserver($uname,$udomain);
                   5686:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5687: }
                   5688: 
                   5689: # -------------------------------------------------------------- dump interface
                   5690: 
1.1172.2.22  raeburn  5691: sub unserialize {
                   5692:     my ($rep, $escapedkeys) = @_;
                   5693: 
                   5694:     return {} if $rep =~ /^error/;
                   5695: 
                   5696:     my %returnhash=();
                   5697:     foreach my $item (split(/\&/,$rep)) {
                   5698:         my ($key, $value) = split(/=/, $item, 2);
                   5699:         $key = unescape($key) unless $escapedkeys;
                   5700:         next if $key =~ /^error: 2 /;
                   5701:         $returnhash{$key} = &thaw_unescape($value);
                   5702:     }
                   5703:     return \%returnhash;
                   5704: }
                   5705: 
                   5706: # see Lond::dump_with_regexp
                   5707: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5708: sub dump {
1.1172.2.22  raeburn  5709:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5710:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5711:     if (!$uname) { $uname=$env{'user.name'}; }
                   5712:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5713: 
1.1172.2.55  raeburn  5714:     if ($regexp) {
                   5715:         $regexp=&escape($regexp);
                   5716:     } else {
                   5717:         $regexp='.';
                   5718:     }
1.1172.2.22  raeburn  5719:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5720:         # user is hosted on this machine
1.1172.2.55  raeburn  5721:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5722:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5723:         return %{&unserialize($reply, $escapedkeys)};
                   5724:     }
1.1166    raeburn  5725:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5726:     my @pairs=split(/\&/,$rep);
                   5727:     my %returnhash=();
1.1098    foxr     5728:     if (!($rep =~ /^error/ )) {
                   5729: 	foreach my $item (@pairs) {
                   5730: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5731:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5732: 	    next if ($key =~ /^error: 2 /);
                   5733: 	    $returnhash{$key}=&thaw_unescape($value);
                   5734: 	}
1.755     albertel 5735:     }
                   5736:     return %returnhash;
1.407     www      5737: }
                   5738: 
1.1098    foxr     5739: 
1.717     albertel 5740: # --------------------------------------------------------- dumpstore interface
                   5741: 
                   5742: sub dumpstore {
                   5743:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5744:    # same as dump but keys must be escaped. They may contain colon separated
                   5745:    # lists of values that may themself contain colons (e.g. symbs).
                   5746:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5747: }
                   5748: 
1.407     www      5749: # -------------------------------------------------------------- keys interface
                   5750: 
                   5751: sub getkeys {
                   5752:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5753:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5754:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5755:    my $uhome=&homeserver($uname,$udomain);
                   5756:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5757:    my @keyarray=();
1.800     albertel 5758:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5759:       next if ($key =~ /^error: 2 /);
1.800     albertel 5760:       push(@keyarray,&unescape($key));
1.407     www      5761:    }
                   5762:    return @keyarray;
1.318     matthew  5763: }
                   5764: 
1.319     matthew  5765: # --------------------------------------------------------------- currentdump
                   5766: sub currentdump {
1.328     matthew  5767:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5768:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5769:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5770:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5771:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  5772:    my $rep;
                   5773: 
                   5774:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5775:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   5776:                    $courseid)));
                   5777:    } else {
                   5778:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5779:    }
                   5780: 
1.318     matthew  5781:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5782:    #
1.318     matthew  5783:    my %returnhash=();
1.319     matthew  5784:    #
                   5785:    if ($rep eq "unknown_cmd") { 
                   5786:        # an old lond will not know currentdump
                   5787:        # Do a dump and make it look like a currentdump
1.822     albertel 5788:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5789:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5790:        my %hash = @tmp;
                   5791:        @tmp=();
1.424     matthew  5792:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5793:    } else {
                   5794:        my @pairs=split(/\&/,$rep);
1.800     albertel 5795:        foreach my $pair (@pairs) {
                   5796:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5797:            my ($symb,$param) = split(/:/,$key);
                   5798:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5799:                                                         &thaw_unescape($value);
1.319     matthew  5800:        }
1.191     harris41 5801:    }
1.12      www      5802:    return %returnhash;
1.424     matthew  5803: }
                   5804: 
                   5805: sub convert_dump_to_currentdump{
                   5806:     my %hash = %{shift()};
                   5807:     my %returnhash;
                   5808:     # Code ripped from lond, essentially.  The only difference
                   5809:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5810:     # we might run in to problems with parameter names =~ /^v\./
                   5811:     while (my ($key,$value) = each(%hash)) {
                   5812:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5813: 	$symb  = &unescape($symb);
                   5814: 	$param = &unescape($param);
1.424     matthew  5815:         next if ($v eq 'version' || $symb eq 'keys');
                   5816:         next if (exists($returnhash{$symb}) &&
                   5817:                  exists($returnhash{$symb}->{$param}) &&
                   5818:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5819:         $returnhash{$symb}->{$param}=$value;
                   5820:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5821:     }
                   5822:     #
                   5823:     # Remove all of the keys in the hashes which keep track of
                   5824:     # the version of the parameter.
                   5825:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5826:         # use a foreach because we are going to delete from the hash.
                   5827:         foreach my $key (keys(%$param_hash)) {
                   5828:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5829:         }
                   5830:     }
                   5831:     return \%returnhash;
1.12      www      5832: }
                   5833: 
1.627     albertel 5834: # ------------------------------------------------------ critical inc interface
                   5835: 
                   5836: sub cinc {
                   5837:     return &inc(@_,'critical');
                   5838: }
                   5839: 
1.449     matthew  5840: # --------------------------------------------------------------- inc interface
                   5841: 
                   5842: sub inc {
1.627     albertel 5843:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5844:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5845:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5846:     my $uhome=&homeserver($uname,$udomain);
                   5847:     my $items='';
                   5848:     if (! ref($store)) {
                   5849:         # got a single value, so use that instead
                   5850:         $items = &escape($store).'=&';
                   5851:     } elsif (ref($store) eq 'SCALAR') {
                   5852:         $items = &escape($$store).'=&';        
                   5853:     } elsif (ref($store) eq 'ARRAY') {
                   5854:         $items = join('=&',map {&escape($_);} @{$store});
                   5855:     } elsif (ref($store) eq 'HASH') {
                   5856:         while (my($key,$value) = each(%{$store})) {
                   5857:             $items.= &escape($key).'='.&escape($value).'&';
                   5858:         }
                   5859:     }
                   5860:     $items=~s/\&$//;
1.627     albertel 5861:     if ($critical) {
                   5862: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5863:     } else {
                   5864: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5865:     }
1.449     matthew  5866: }
                   5867: 
1.12      www      5868: # --------------------------------------------------------------- put interface
                   5869: 
                   5870: sub put {
1.134     albertel 5871:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5872:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5873:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5874:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5875:    my $items='';
1.800     albertel 5876:    foreach my $item (keys(%$storehash)) {
                   5877:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5878:    }
1.12      www      5879:    $items=~s/\&$//;
1.134     albertel 5880:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5881: }
                   5882: 
1.631     albertel 5883: # ------------------------------------------------------------ newput interface
                   5884: 
                   5885: sub newput {
                   5886:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5887:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5888:    if (!$uname) { $uname=$env{'user.name'}; }
                   5889:    my $uhome=&homeserver($uname,$udomain);
                   5890:    my $items='';
                   5891:    foreach my $key (keys(%$storehash)) {
                   5892:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5893:    }
                   5894:    $items=~s/\&$//;
                   5895:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5896: }
                   5897: 
                   5898: # ---------------------------------------------------------  putstore interface
                   5899: 
1.524     raeburn  5900: sub putstore {
1.715     albertel 5901:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5902:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5903:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5904:    my $uhome=&homeserver($uname,$udomain);
                   5905:    my $items='';
1.715     albertel 5906:    foreach my $key (keys(%$storehash)) {
                   5907:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5908:    }
1.715     albertel 5909:    $items=~s/\&$//;
1.716     albertel 5910:    my $esc_symb=&escape($symb);
                   5911:    my $esc_v=&escape($version);
1.715     albertel 5912:    my $reply =
1.716     albertel 5913:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5914: 	      $uhome);
                   5915:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5916:        # gfall back to way things use to be done
1.715     albertel 5917:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5918: 			    $uname);
1.524     raeburn  5919:    }
1.715     albertel 5920:    return $reply;
                   5921: }
                   5922: 
                   5923: sub old_putstore {
1.716     albertel 5924:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5925:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5926:     if (!$uname) { $uname=$env{'user.name'}; }
                   5927:     my $uhome=&homeserver($uname,$udomain);
                   5928:     my %newstorehash;
1.800     albertel 5929:     foreach my $item (keys(%$storehash)) {
                   5930: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5931: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5932:     }
                   5933:     my $items='';
                   5934:     my %allitems = ();
1.800     albertel 5935:     foreach my $item (keys(%newstorehash)) {
                   5936: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5937: 	    my $key = $1.':keys:'.$2;
                   5938: 	    $allitems{$key} .= $3.':';
                   5939: 	}
1.800     albertel 5940: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5941:     }
1.800     albertel 5942:     foreach my $item (keys(%allitems)) {
                   5943: 	$allitems{$item} =~ s/\:$//;
                   5944: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5945:     }
                   5946:     $items=~s/\&$//;
                   5947:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5948: }
                   5949: 
1.47      www      5950: # ------------------------------------------------------ critical put interface
                   5951: 
                   5952: sub cput {
1.134     albertel 5953:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5954:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5955:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5956:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5957:    my $items='';
1.800     albertel 5958:    foreach my $item (keys(%$storehash)) {
                   5959:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5960:    }
1.47      www      5961:    $items=~s/\&$//;
1.134     albertel 5962:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5963: }
                   5964: 
                   5965: # -------------------------------------------------------------- eget interface
                   5966: 
                   5967: sub eget {
1.133     albertel 5968:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5969:    my $items='';
1.800     albertel 5970:    foreach my $item (@$storearr) {
                   5971:        $items.=&escape($item).'&';
1.191     harris41 5972:    }
1.12      www      5973:    $items=~s/\&$//;
1.620     albertel 5974:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5975:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5976:    my $uhome=&homeserver($uname,$udomain);
                   5977:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5978:    my @pairs=split(/\&/,$rep);
                   5979:    my %returnhash=();
1.42      www      5980:    my $i=0;
1.800     albertel 5981:    foreach my $item (@$storearr) {
                   5982:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5983:       $i++;
1.191     harris41 5984:    }
1.12      www      5985:    return %returnhash;
                   5986: }
                   5987: 
1.667     albertel 5988: # ------------------------------------------------------------ tmpput interface
                   5989: sub tmpput {
1.802     raeburn  5990:     my ($storehash,$server,$context)=@_;
1.667     albertel 5991:     my $items='';
1.800     albertel 5992:     foreach my $item (keys(%$storehash)) {
                   5993: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5994:     }
                   5995:     $items=~s/\&$//;
1.802     raeburn  5996:     if (defined($context)) {
                   5997:         $items .= ':'.&escape($context);
                   5998:     }
1.667     albertel 5999:     return &reply("tmpput:$items",$server);
                   6000: }
                   6001: 
                   6002: # ------------------------------------------------------------ tmpget interface
                   6003: sub tmpget {
1.688     albertel 6004:     my ($token,$server)=@_;
                   6005:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6006:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6007:     my %returnhash;
                   6008:     foreach my $item (split(/\&/,$rep)) {
                   6009: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6010:         next if ($key =~ /^error: 2 /);
1.667     albertel 6011: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6012:     }
                   6013:     return %returnhash;
                   6014: }
                   6015: 
1.1113    raeburn  6016: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6017: sub tmpdel {
                   6018:     my ($token,$server)=@_;
                   6019:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6020:     return &reply("tmpdel:$token",$server);
                   6021: }
                   6022: 
1.1172.2.13  raeburn  6023: # ------------------------------------------------------------ get_timebased_id
                   6024: 
                   6025: sub get_timebased_id {
                   6026:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6027:         $maxtries) = @_;
                   6028:     my ($newid,$error,$dellock);
                   6029:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6030:         return ('','ok','invalid call to get suffix');
                   6031:     }
                   6032: 
                   6033: # set defaults for any optional args for which values were not supplied
                   6034:     if ($who eq '') {
                   6035:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6036:     }
                   6037:     if (!$locktries) {
                   6038:         $locktries = 3;
                   6039:     }
                   6040:     if (!$maxtries) {
                   6041:         $maxtries = 10;
                   6042:     }
                   6043: 
                   6044:     if (($cdom eq '') || ($cnum eq '')) {
                   6045:         if ($env{'request.course.id'}) {
                   6046:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6047:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6048:         }
                   6049:         if (($cdom eq '') || ($cnum eq '')) {
                   6050:             return ('','ok','call to get suffix not in course context');
                   6051:         }
                   6052:     }
                   6053: 
                   6054: # construct locking item
                   6055:     my $lockhash = {
                   6056:                       $prefix."\0".'locked_'.$keyid => $who,
                   6057:                    };
                   6058:     my $tries = 0;
                   6059: 
                   6060: # attempt to get lock on nohist_$namespace file
                   6061:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6062:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6063:         $tries ++;
                   6064:         sleep 1;
                   6065:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6066:     }
                   6067: 
                   6068: # attempt to get unique identifier, based on current timestamp
                   6069:     if ($gotlock eq 'ok') {
                   6070:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6071:         my $id = time;
                   6072:         $newid = $id;
1.1172.2.56  raeburn  6073:         if ($idtype eq 'addcode') {
                   6074:             $newid .= &sixnum_code();
                   6075:         }
1.1172.2.13  raeburn  6076:         my $idtries = 0;
                   6077:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6078:             if ($idtype eq 'concat') {
                   6079:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6080:             } elsif ($idtype eq 'addcode') {
                   6081:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6082:             } else {
                   6083:                 $newid ++;
                   6084:             }
                   6085:             $idtries ++;
                   6086:         }
                   6087:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6088:             my %new_item =  (
                   6089:                               $prefix."\0".$newid => $who,
                   6090:                             );
                   6091:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6092:                                                  $cdom,$cnum);
                   6093:             if ($putresult ne 'ok') {
                   6094:                 undef($newid);
                   6095:                 $error = 'error saving new item: '.$putresult;
                   6096:             }
                   6097:         } else {
1.1172.2.56  raeburn  6098:              undef($newid);
1.1172.2.13  raeburn  6099:              $error = ('error: no unique suffix available for the new item ');
                   6100:         }
                   6101: #  remove lock
                   6102:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6103:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6104:     } else {
                   6105:         $error = "error: could not obtain lockfile\n";
                   6106:         $dellock = 'ok';
1.1172.2.58! raeburn  6107:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
        !          6108:             $dellock = 'nolock';
        !          6109:         }
1.1172.2.13  raeburn  6110:     }
                   6111:     return ($newid,$dellock,$error);
                   6112: }
                   6113: 
1.1172.2.56  raeburn  6114: sub sixnum_code {
                   6115:     my $code;
                   6116:     for (0..6) {
                   6117:         $code .= int( rand(9) );
                   6118:     }
                   6119:     return $code;
                   6120: }
                   6121: 
1.765     albertel 6122: # -------------------------------------------------- portfolio access checking
                   6123: 
                   6124: sub portfolio_access {
1.766     albertel 6125:     my ($requrl) = @_;
1.765     albertel 6126:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   6127:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  6128:     if ($result) {
                   6129:         my %setters;
                   6130:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6131:             my ($startblock,$endblock) =
                   6132:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6133:             if ($startblock && $endblock) {
                   6134:                 return 'B';
                   6135:             }
                   6136:         } else {
                   6137:             my ($startblock,$endblock) =
                   6138:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6139:             if ($startblock && $endblock) {
                   6140:                 return 'B';
                   6141:             }
                   6142:         }
                   6143:     }
1.765     albertel 6144:     if ($result eq 'ok') {
1.766     albertel 6145:        return 'F';
1.765     albertel 6146:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6147:        return 'A';
1.765     albertel 6148:     }
1.766     albertel 6149:     return '';
1.765     albertel 6150: }
                   6151: 
                   6152: sub get_portfolio_access {
1.767     albertel 6153:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   6154: 
                   6155:     if (!ref($access_hash)) {
                   6156: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6157: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6158: 						   $file_name);
                   6159: 	$access_hash = $access_controls{$file_name};
                   6160:     }
                   6161: 
1.765     albertel 6162:     my ($public,$guest,@domains,@users,@courses,@groups);
                   6163:     my $now = time;
                   6164:     if (ref($access_hash) eq 'HASH') {
                   6165:         foreach my $key (keys(%{$access_hash})) {
                   6166:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6167:             if ($start > $now) {
                   6168:                 next;
                   6169:             }
                   6170:             if ($end && $end<$now) {
                   6171:                 next;
                   6172:             }
                   6173:             if ($scope eq 'public') {
                   6174:                 $public = $key;
                   6175:                 last;
                   6176:             } elsif ($scope eq 'guest') {
                   6177:                 $guest = $key;
                   6178:             } elsif ($scope eq 'domains') {
                   6179:                 push(@domains,$key);
                   6180:             } elsif ($scope eq 'users') {
                   6181:                 push(@users,$key);
                   6182:             } elsif ($scope eq 'course') {
                   6183:                 push(@courses,$key);
                   6184:             } elsif ($scope eq 'group') {
                   6185:                 push(@groups,$key);
                   6186:             }
                   6187:         }
                   6188:         if ($public) {
                   6189:             return 'ok';
                   6190:         }
                   6191:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6192:             if ($guest) {
                   6193:                 return $guest;
                   6194:             }
                   6195:         } else {
                   6196:             if (@domains > 0) {
                   6197:                 foreach my $domkey (@domains) {
                   6198:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6199:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6200:                             return 'ok';
                   6201:                         }
                   6202:                     }
                   6203:                 }
                   6204:             }
                   6205:             if (@users > 0) {
                   6206:                 foreach my $userkey (@users) {
1.865     raeburn  6207:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6208:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6209:                             if (ref($item) eq 'HASH') {
                   6210:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6211:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6212:                                     return 'ok';
                   6213:                                 }
                   6214:                             }
                   6215:                         }
                   6216:                     } 
1.765     albertel 6217:                 }
                   6218:             }
                   6219:             my %roleshash;
                   6220:             my @courses_and_groups = @courses;
                   6221:             push(@courses_and_groups,@groups); 
                   6222:             if (@courses_and_groups > 0) {
                   6223:                 my (%allgroups,%allroles); 
                   6224:                 my ($start,$end,$role,$sec,$group);
                   6225:                 foreach my $envkey (%env) {
1.1060    raeburn  6226:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6227:                         my $cid = $2.'_'.$3; 
                   6228:                         if ($1 eq 'gr') {
                   6229:                             $group = $4;
                   6230:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6231:                         } else {
                   6232:                             if ($4 eq '') {
                   6233:                                 $sec = 'none';
                   6234:                             } else {
                   6235:                                 $sec = $4;
                   6236:                             }
                   6237:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6238:                         }
1.811     albertel 6239:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6240:                         my $cid = $2.'_'.$3;
                   6241:                         if ($4 eq '') {
                   6242:                             $sec = 'none';
                   6243:                         } else {
                   6244:                             $sec = $4;
                   6245:                         }
                   6246:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6247:                     }
                   6248:                 }
                   6249:                 if (keys(%allroles) == 0) {
                   6250:                     return;
                   6251:                 }
                   6252:                 foreach my $key (@courses_and_groups) {
                   6253:                     my %content = %{$$access_hash{$key}};
                   6254:                     my $cnum = $content{'number'};
                   6255:                     my $cdom = $content{'domain'};
                   6256:                     my $cid = $cdom.'_'.$cnum;
                   6257:                     if (!exists($allroles{$cid})) {
                   6258:                         next;
                   6259:                     }    
                   6260:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6261:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6262:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6263:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6264:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6265:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6266:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6267:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6268:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6269:                                         if (grep/^all$/,@sections) {
                   6270:                                             return 'ok';
                   6271:                                         } else {
                   6272:                                             if (grep/^$sec$/,@sections) {
                   6273:                                                 return 'ok';
                   6274:                                             }
                   6275:                                         }
                   6276:                                     }
                   6277:                                 }
                   6278:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6279:                                     if (grep/^none$/,@groups) {
                   6280:                                         return 'ok';
                   6281:                                     }
                   6282:                                 } else {
                   6283:                                     if (grep/^all$/,@groups) {
                   6284:                                         return 'ok';
                   6285:                                     } 
                   6286:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6287:                                         if (grep/^$group$/,@groups) {
                   6288:                                             return 'ok';
                   6289:                                         }
                   6290:                                     }
                   6291:                                 } 
                   6292:                             }
                   6293:                         }
                   6294:                     }
                   6295:                 }
                   6296:             }
                   6297:             if ($guest) {
                   6298:                 return $guest;
                   6299:             }
                   6300:         }
                   6301:     }
                   6302:     return;
                   6303: }
                   6304: 
                   6305: sub course_group_datechecker {
                   6306:     my ($dates,$now,$status) = @_;
                   6307:     my ($start,$end) = split(/\./,$dates);
                   6308:     if (!$start && !$end) {
                   6309:         return 'ok';
                   6310:     }
                   6311:     if (grep/^active$/,@{$status}) {
                   6312:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6313:             return 'ok';
                   6314:         }
                   6315:     }
                   6316:     if (grep/^previous$/,@{$status}) {
                   6317:         if ($end > $now ) {
                   6318:             return 'ok';
                   6319:         }
                   6320:     }
                   6321:     if (grep/^future$/,@{$status}) {
                   6322:         if ($start > $now) {
                   6323:             return 'ok';
                   6324:         }
                   6325:     }
                   6326:     return; 
                   6327: }
                   6328: 
                   6329: sub parse_portfolio_url {
                   6330:     my ($url) = @_;
                   6331: 
                   6332:     my ($type,$udom,$unum,$group,$file_name);
                   6333:     
1.823     albertel 6334:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6335: 	$type = 1;
                   6336:         $udom = $1;
                   6337:         $unum = $2;
                   6338:         $file_name = $3;
1.823     albertel 6339:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6340: 	$type = 2;
                   6341:         $udom = $1;
                   6342:         $unum = $2;
                   6343:         $group = $3;
                   6344:         $file_name = $3.'/'.$4;
                   6345:     }
                   6346:     if (wantarray) {
                   6347: 	return ($type,$udom,$unum,$file_name,$group);
                   6348:     }
                   6349:     return $type;
                   6350: }
                   6351: 
                   6352: sub is_portfolio_url {
                   6353:     my ($url) = @_;
                   6354:     return scalar(&parse_portfolio_url($url));
                   6355: }
                   6356: 
1.798     raeburn  6357: sub is_portfolio_file {
                   6358:     my ($file) = @_;
1.820     raeburn  6359:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6360:         return 1;
                   6361:     }
                   6362:     return;
                   6363: }
                   6364: 
1.976     raeburn  6365: sub usertools_access {
1.1084    raeburn  6366:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6367:     my ($access,%tools);
                   6368:     if ($context eq '') {
                   6369:         $context = 'tools';
                   6370:     }
                   6371:     if ($context eq 'requestcourses') {
                   6372:         %tools = (
                   6373:                       official   => 1,
                   6374:                       unofficial => 1,
1.1006    raeburn  6375:                       community  => 1,
1.1172.2.37  raeburn  6376:                       textbook   => 1,
1.985     raeburn  6377:                  );
1.1172.2.9  raeburn  6378:     } elsif ($context eq 'requestauthor') {
                   6379:         %tools = (
                   6380:                       requestauthor => 1,
                   6381:                  );
1.985     raeburn  6382:     } else {
                   6383:         %tools = (
                   6384:                       aboutme   => 1,
                   6385:                       blog      => 1,
1.1172.2.6  raeburn  6386:                       webdav    => 1,
1.985     raeburn  6387:                       portfolio => 1,
                   6388:                  );
                   6389:     }
1.976     raeburn  6390:     return if (!defined($tools{$tool}));
                   6391: 
1.1172.2.35  raeburn  6392:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6393:         $udom = $env{'user.domain'};
                   6394:         $uname = $env{'user.name'};
                   6395:     }
                   6396: 
1.978     raeburn  6397:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6398:         if ($action ne 'reload') {
1.985     raeburn  6399:             if ($context eq 'requestcourses') {
                   6400:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6401:             } elsif ($context eq 'requestauthor') {
                   6402:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6403:             } else {
                   6404:                 return $env{'environment.availabletools.'.$tool};
                   6405:             }
                   6406:         }
1.976     raeburn  6407:     }
                   6408: 
1.1172.2.9  raeburn  6409:     my ($toolstatus,$inststatus,$envkey);
                   6410:     if ($context eq 'requestauthor') {
                   6411:         $envkey = $context;
                   6412:     } else {
                   6413:         $envkey = $context.'.'.$tool;
                   6414:     }
1.976     raeburn  6415: 
1.985     raeburn  6416:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6417:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6418:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6419:         $inststatus = $env{'environment.inststatus'};
                   6420:     } else {
1.1084    raeburn  6421:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6422:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6423:             $inststatus = $userenvref->{'inststatus'};
                   6424:         } else {
1.1172.2.9  raeburn  6425:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6426:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6427:             $inststatus = $userenv{'inststatus'};
                   6428:         }
1.976     raeburn  6429:     }
                   6430: 
                   6431:     if ($toolstatus ne '') {
                   6432:         if ($toolstatus) {
                   6433:             $access = 1;
                   6434:         } else {
                   6435:             $access = 0;
                   6436:         }
                   6437:         return $access;
                   6438:     }
                   6439: 
1.1084    raeburn  6440:     my ($is_adv,%domdef);
                   6441:     if (ref($is_advref) eq 'HASH') {
                   6442:         $is_adv = $is_advref->{'is_adv'};
                   6443:     } else {
                   6444:         $is_adv = &is_advanced_user($udom,$uname);
                   6445:     }
                   6446:     if (ref($domdefref) eq 'HASH') {
                   6447:         %domdef = %{$domdefref};
                   6448:     } else {
                   6449:         %domdef = &get_domain_defaults($udom);
                   6450:     }
1.976     raeburn  6451:     if (ref($domdef{$tool}) eq 'HASH') {
                   6452:         if ($is_adv) {
                   6453:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6454:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6455:                     $access = 1;
                   6456:                 } else {
                   6457:                     $access = 0;
                   6458:                 }
                   6459:                 return $access;
                   6460:             }
                   6461:         }
                   6462:         if ($inststatus ne '') {
                   6463:             my ($hasaccess,$hasnoaccess);
                   6464:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6465:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6466:                     if ($domdef{$tool}{$affiliation}) {
                   6467:                         $hasaccess = 1;
                   6468:                     } else {
                   6469:                         $hasnoaccess = 1;
                   6470:                     }
                   6471:                 }
                   6472:             }
                   6473:             if ($hasaccess || $hasnoaccess) {
                   6474:                 if ($hasaccess) {
                   6475:                     $access = 1;
                   6476:                 } elsif ($hasnoaccess) {
                   6477:                     $access = 0; 
                   6478:                 }
                   6479:                 return $access;
                   6480:             }
                   6481:         } else {
                   6482:             if ($domdef{$tool}{'default'} ne '') {
                   6483:                 if ($domdef{$tool}{'default'}) {
                   6484:                     $access = 1;
                   6485:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6486:                     $access = 0;
                   6487:                 }
                   6488:                 return $access;
                   6489:             }
                   6490:         }
                   6491:     } else {
1.1172.2.6  raeburn  6492:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6493:             $access = 1;
                   6494:         } else {
                   6495:             $access = 0;
                   6496:         }
1.976     raeburn  6497:         return $access;
                   6498:     }
                   6499: }
                   6500: 
1.1050    raeburn  6501: sub is_course_owner {
                   6502:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6503:     if (($udom eq '') || ($uname eq '')) {
                   6504:         $udom = $env{'user.domain'};
                   6505:         $uname = $env{'user.name'};
                   6506:     }
                   6507:     unless (($udom eq '') || ($uname eq '')) {
                   6508:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6509:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6510:                 return 1;
                   6511:             } else {
                   6512:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6513:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6514:                     return 1;
                   6515:                 }
                   6516:             }
                   6517:         }
                   6518:     }
                   6519:     return;
                   6520: }
                   6521: 
1.976     raeburn  6522: sub is_advanced_user {
                   6523:     my ($udom,$uname) = @_;
1.1085    raeburn  6524:     if ($udom ne '' && $uname ne '') {
                   6525:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6526:             if (wantarray) {
                   6527:                 return ($env{'user.adv'},$env{'user.author'});
                   6528:             } else {
                   6529:                 return $env{'user.adv'};
                   6530:             }
1.1085    raeburn  6531:         }
                   6532:     }
1.976     raeburn  6533:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6534:     my %allroles;
1.1128    raeburn  6535:     my ($is_adv,$is_author);
1.976     raeburn  6536:     foreach my $role (keys(%roleshash)) {
                   6537:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6538:         my $area = '/'.$tdomain.'/'.$trest;
                   6539:         if ($sec ne '') {
                   6540:             $area .= '/'.$sec;
                   6541:         }
                   6542:         if (($area ne '') && ($trole ne '')) {
                   6543:             my $spec=$trole.'.'.$area;
                   6544:             if ($trole =~ /^cr\//) {
                   6545:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6546:             } elsif ($trole ne 'gr') {
                   6547:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6548:             }
1.1128    raeburn  6549:             if ($trole eq 'au') {
                   6550:                 $is_author = 1;
                   6551:             }
1.976     raeburn  6552:         }
                   6553:     }
                   6554:     foreach my $role (keys(%allroles)) {
                   6555:         last if ($is_adv);
                   6556:         foreach my $item (split(/:/,$allroles{$role})) {
                   6557:             if ($item ne '') {
                   6558:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6559:                 if ($privilege eq 'adv') {
                   6560:                     $is_adv = 1;
                   6561:                     last;
                   6562:                 }
                   6563:             }
                   6564:         }
                   6565:     }
1.1128    raeburn  6566:     if (wantarray) {
                   6567:         return ($is_adv,$is_author);
                   6568:     }
1.976     raeburn  6569:     return $is_adv;
                   6570: }
1.798     raeburn  6571: 
1.1035    raeburn  6572: sub check_can_request {
1.1036    raeburn  6573:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6574:     my $canreq = 0;
                   6575:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6576:     my @options = ('approval','validate','autolimit');
                   6577:     my $optregex = join('|',@options);
                   6578:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6579:         foreach my $type (@{$types}) {
                   6580:             if (&usertools_access($env{'user.name'},
                   6581:                                   $env{'user.domain'},
                   6582:                                   $type,undef,'requestcourses')) {
                   6583:                 $canreq ++;
1.1036    raeburn  6584:                 if (ref($request_domains) eq 'HASH') {
                   6585:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6586:                 }
1.1035    raeburn  6587:                 if ($dom eq $env{'user.domain'}) {
                   6588:                     $can_request->{$type} = 1;
                   6589:                 }
                   6590:             }
                   6591:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6592:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6593:                 if (@curr > 0) {
1.1036    raeburn  6594:                     foreach my $item (@curr) {
                   6595:                         if (ref($request_domains) eq 'HASH') {
                   6596:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6597:                             if ($otherdom ne '') {
                   6598:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6599:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6600:                                         push(@{$request_domains->{$type}},$otherdom);
                   6601:                                     }
                   6602:                                 } else {
                   6603:                                     push(@{$request_domains->{$type}},$otherdom);
                   6604:                                 }
                   6605:                             }
                   6606:                         }
                   6607:                     }
                   6608:                     unless($dom eq $env{'user.domain'}) {
                   6609:                         $canreq ++;
1.1035    raeburn  6610:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6611:                             $can_request->{$type} = 1;
                   6612:                         }
                   6613:                     }
                   6614:                 }
                   6615:             }
                   6616:         }
                   6617:     }
                   6618:     return $canreq;
                   6619: }
                   6620: 
1.341     www      6621: # ---------------------------------------------- Custom access rule evaluation
                   6622: 
                   6623: sub customaccess {
                   6624:     my ($priv,$uri)=@_;
1.807     albertel 6625:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6626:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6627:     $udom = &LONCAPA::clean_domain($udom);
                   6628:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6629:     my $access=0;
1.800     albertel 6630:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6631: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6632: 	if ($type eq 'user') {
                   6633: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6634: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6635: 		if ($tdom) {
                   6636: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6637: 		}
1.896     albertel 6638: 		if ($tuname) {
                   6639: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6640: 		}
                   6641: 		$access=($effect eq 'allow');
                   6642: 		last;
                   6643: 	    }
                   6644: 	} else {
                   6645: 	    if ($role) {
                   6646: 		if ($role ne $urole) { next; }
                   6647: 	    }
                   6648: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6649: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6650: 		if ($tdom) {
                   6651: 		    if ($tdom ne $udom) { next; }
                   6652: 		}
                   6653: 		if ($tcrs) {
                   6654: 		    if ($tcrs ne $ucrs) { next; }
                   6655: 		}
                   6656: 		if ($tsec) {
                   6657: 		    if ($tsec ne $usec) { next; }
                   6658: 		}
                   6659: 		$access=($effect eq 'allow');
                   6660: 		last;
                   6661: 	    }
                   6662: 	    if ($realm eq '' && $role eq '') {
                   6663: 		$access=($effect eq 'allow');
                   6664: 	    }
1.402     bowersj2 6665: 	}
1.341     www      6666:     }
                   6667:     return $access;
                   6668: }
                   6669: 
1.103     harris41 6670: # ------------------------------------------------- Check for a user privilege
1.12      www      6671: 
                   6672: sub allowed {
1.810     raeburn  6673:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6674:     my $ver_orguri=$uri;
1.439     www      6675:     $uri=&deversion($uri);
1.152     www      6676:     my $orguri=$uri;
1.52      www      6677:     $uri=&declutter($uri);
1.809     raeburn  6678: 
1.810     raeburn  6679:     if ($priv eq 'evb') {
                   6680: # Evade communication block restrictions for specified role in a course
                   6681:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6682:             return $1;
                   6683:         } else {
                   6684:             return;
                   6685:         }
                   6686:     }
                   6687: 
1.620     albertel 6688:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6689: # Free bre access to adm and meta resources
1.775     albertel 6690:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6691: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6692: 	&& ($priv eq 'bre')) {
1.14      www      6693: 	return 'F';
1.159     www      6694:     }
                   6695: 
1.545     banghart 6696: # Free bre access to user's own portfolio contents
1.714     raeburn  6697:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6698:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6699: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6700:         my %setters;
                   6701:         my ($startblock,$endblock) = 
                   6702:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6703:         if ($startblock && $endblock) {
                   6704:             return 'B';
                   6705:         } else {
                   6706:             return 'F';
                   6707:         }
1.545     banghart 6708:     }
                   6709: 
1.762     raeburn  6710: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6711:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6712:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6713:         if (exists($env{'request.course.id'})) {
                   6714:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6715:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6716:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6717:                 my $courseprivid=$env{'request.course.id'};
                   6718:                 $courseprivid=~s/\_/\//;
                   6719:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6720:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6721:                     return $1; 
1.762     raeburn  6722:                 } else {
                   6723:                     if ($env{'request.course.sec'}) {
                   6724:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6725:                     }
                   6726:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6727:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6728:                         return $2;
                   6729:                     }
1.714     raeburn  6730:                 }
                   6731:             }
                   6732:         }
                   6733:     }
                   6734: 
1.159     www      6735: # Free bre to public access
                   6736: 
                   6737:     if ($priv eq 'bre') {
1.238     www      6738:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6739: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6740:            return 'F'; 
                   6741:         }
1.238     www      6742:         if ($copyright eq 'priv') {
                   6743:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6744: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6745: 		return '';
                   6746:             }
                   6747:         }
                   6748:         if ($copyright eq 'domain') {
                   6749:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6750: 	    unless (($env{'user.domain'} eq $1) ||
                   6751:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6752: 		return '';
                   6753:             }
1.262     matthew  6754:         }
1.620     albertel 6755:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6756:             # Library role, so allow browsing of resources in this domain.
                   6757:             return 'F';
1.238     www      6758:         }
1.341     www      6759:         if ($copyright eq 'custom') {
                   6760: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6761:         }
1.14      www      6762:     }
1.264     matthew  6763:     # Domain coordinator is trying to create a course
1.620     albertel 6764:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6765:         # uri is the requested domain in this case.
                   6766:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6767:         # a role of dc for the domain in question.
1.620     albertel 6768:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6769:     }
1.29      www      6770: 
1.52      www      6771:     my $thisallowed='';
                   6772:     my $statecond=0;
                   6773:     my $courseprivid='';
                   6774: 
1.1039    raeburn  6775:     my $ownaccess;
1.1043    raeburn  6776:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6777:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6778:         if ($uri eq '') {
                   6779:             $ownaccess = 1;
                   6780:         } else {
                   6781:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6782:                 my $udom = $env{'user.domain'};
                   6783:                 my $uname = $env{'user.name'};
                   6784:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6785:                     $ownaccess = 1;
1.1040    raeburn  6786:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6787:                     unless ($uri =~ m{\.\./}) {
                   6788:                         $ownaccess = 1;
                   6789:                     }
                   6790:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6791:                     my $now = time;
                   6792:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6793:                         my $adom = $1;
                   6794:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6795:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6796:                                 my ($start,$end) = split('.',$env{$key});
                   6797:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6798:                                     $ownaccess = 1;
                   6799:                                     last;
                   6800:                                 }
                   6801:                             }
                   6802:                         }
                   6803:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6804:                         my $adom = $1;
                   6805:                         my $aname = $2;
1.1042    raeburn  6806:                         foreach my $role ('ca','aa') { 
                   6807:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6808:                                 my ($start,$end) =
                   6809:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6810:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6811:                                     $ownaccess = 1;
                   6812:                                     last;
                   6813:                                 }
1.1039    raeburn  6814:                             }
                   6815:                         }
                   6816:                     }
                   6817:                 }
                   6818:             }
                   6819:         }
                   6820:     }
                   6821: 
1.52      www      6822: # Course
                   6823: 
1.620     albertel 6824:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6825:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6826:             $thisallowed.=$1;
                   6827:         }
1.52      www      6828:     }
1.29      www      6829: 
1.52      www      6830: # Domain
                   6831: 
1.620     albertel 6832:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6833:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6834:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6835:             $thisallowed.=$1;
                   6836:         }
1.12      www      6837:     }
1.52      www      6838: 
1.1141    raeburn  6839: # User who is not author or co-author might still be able to edit
                   6840: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6841:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6842:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6843:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6844:             $thisallowed.=$1;
                   6845:         }
                   6846:     }
                   6847: 
1.52      www      6848: # Course: uri itself is a course
1.66      www      6849:     my $courseuri=$uri;
                   6850:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6851:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6852: 
1.620     albertel 6853:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6854:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6855:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6856:             $thisallowed.=$1;
                   6857:         }
1.12      www      6858:     }
1.29      www      6859: 
1.665     albertel 6860: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6861: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6862:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6863: 	$thisallowed='';
1.671     raeburn  6864:         my ($match)=&is_on_map($uri);
                   6865:         if ($match) {
                   6866:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6867:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6868:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6869:                 if (@blockers > 0) {
                   6870:                     $thisallowed = 'B';
                   6871:                 } else {
                   6872:                     $thisallowed.=$1;
                   6873:                 }
1.671     raeburn  6874:             }
                   6875:         } else {
1.705     albertel 6876:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6877:             if ($refuri) {
                   6878:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6879:                     $thisallowed='F';
1.671     raeburn  6880:                 } else {
                   6881:                     $refuri=&declutter($refuri);
                   6882:                     my ($match) = &is_on_map($refuri);
                   6883:                     if ($match) {
1.1162    raeburn  6884:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6885:                         if (@blockers > 0) {
                   6886:                             $thisallowed = 'B';
                   6887:                         } else {
                   6888:                             $thisallowed='F';
                   6889:                         }
1.671     raeburn  6890:                     }
1.669     raeburn  6891:                 }
1.671     raeburn  6892:             }
                   6893:         }
1.314     www      6894:     }
1.492     albertel 6895: 
1.766     albertel 6896:     if ($priv eq 'bre'
                   6897: 	&& $thisallowed ne 'F' 
                   6898: 	&& $thisallowed ne '2'
                   6899: 	&& &is_portfolio_url($uri)) {
                   6900: 	$thisallowed = &portfolio_access($uri);
                   6901:     }
                   6902:     
1.52      www      6903: # Full access at system, domain or course-wide level? Exit.
1.29      www      6904:     if ($thisallowed=~/F/) {
                   6905: 	return 'F';
                   6906:     }
                   6907: 
1.52      www      6908: # If this is generating or modifying users, exit with special codes
1.29      www      6909: 
1.643     www      6910:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6911: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6912: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6913: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6914: 	    unless ($auname) { return $thisallowed; }
                   6915: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6916: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6917: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6918: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6919: 	}
1.52      www      6920: 	return $thisallowed;
                   6921:     }
                   6922: #
1.103     harris41 6923: # Gathered so far: system, domain and course wide privileges
1.52      www      6924: #
                   6925: # Course: See if uri or referer is an individual resource that is part of 
                   6926: # the course
                   6927: 
1.620     albertel 6928:     if ($env{'request.course.id'}) {
1.232     www      6929: 
1.620     albertel 6930:        $courseprivid=$env{'request.course.id'};
                   6931:        if ($env{'request.course.sec'}) {
                   6932:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6933:        }
                   6934:        $courseprivid=~s/\_/\//;
                   6935:        my $checkreferer=1;
1.232     www      6936:        my ($match,$cond)=&is_on_map($uri);
                   6937:        if ($match) {
                   6938:            $statecond=$cond;
1.620     albertel 6939:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6940:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6941:                my $value = $1;
                   6942:                if ($priv eq 'bre') {
                   6943:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6944:                    if (@blockers > 0) {
                   6945:                        $thisallowed = 'B';
                   6946:                    } else {
                   6947:                        $thisallowed.=$value;
                   6948:                    }
                   6949:                } else {
                   6950:                    $thisallowed.=$value;
                   6951:                }
1.52      www      6952:                $checkreferer=0;
                   6953:            }
1.29      www      6954:        }
1.83      www      6955:        
1.148     www      6956:        if ($checkreferer) {
1.620     albertel 6957: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6958:             unless ($refuri) {
1.800     albertel 6959:                 foreach my $key (keys(%env)) {
                   6960: 		    if ($key=~/^httpref\..*\*/) {
                   6961: 			my $pattern=$key;
1.156     www      6962:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6963:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6964:                         $pattern=~s/\//\\\//g;
1.152     www      6965:                         if ($orguri=~/$pattern/) {
1.800     albertel 6966: 			    $refuri=$env{$key};
1.148     www      6967:                         }
                   6968:                     }
1.191     harris41 6969:                 }
1.148     www      6970:             }
1.232     www      6971: 
1.148     www      6972:          if ($refuri) { 
1.152     www      6973: 	  $refuri=&declutter($refuri);
1.232     www      6974:           my ($match,$cond)=&is_on_map($refuri);
                   6975:             if ($match) {
                   6976:               my $refstatecond=$cond;
1.620     albertel 6977:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6978:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6979:                   my $value = $1;
                   6980:                   if ($priv eq 'bre') {
                   6981:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6982:                       if (@blockers > 0) {
                   6983:                           $thisallowed = 'B';
                   6984:                       } else {
                   6985:                           $thisallowed.=$value;
                   6986:                       }
                   6987:                   } else {
                   6988:                       $thisallowed.=$value;
                   6989:                   }
1.53      www      6990:                   $uri=$refuri;
                   6991:                   $statecond=$refstatecond;
1.52      www      6992:               }
                   6993:           }
1.148     www      6994:         }
1.29      www      6995:        }
1.52      www      6996:    }
1.29      www      6997: 
1.52      www      6998: #
1.103     harris41 6999: # Gathered now: all privileges that could apply, and condition number
1.52      www      7000: # 
                   7001: #
                   7002: # Full or no access?
                   7003: #
1.29      www      7004: 
1.52      www      7005:     if ($thisallowed=~/F/) {
                   7006: 	return 'F';
                   7007:     }
1.29      www      7008: 
1.52      www      7009:     unless ($thisallowed) {
                   7010:         return '';
                   7011:     }
1.29      www      7012: 
1.52      www      7013: # Restrictions exist, deal with them
                   7014: #
                   7015: #   C:according to course preferences
                   7016: #   R:according to resource settings
                   7017: #   L:unless locked
                   7018: #   X:according to user session state
                   7019: #
                   7020: 
                   7021: # Possibly locked functionality, check all courses
1.54      www      7022: # Locks might take effect only after 10 minutes cache expiration for other
                   7023: # courses, and 2 minutes for current course
1.52      www      7024: 
                   7025:     my $envkey;
                   7026:     if ($thisallowed=~/L/) {
1.1000    raeburn  7027:         foreach $envkey (keys(%env)) {
1.54      www      7028:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7029:                my $courseid=$2;
                   7030:                my $roleid=$1.'.'.$2;
1.92      www      7031:                $courseid=~s/^\///;
1.54      www      7032:                my $expiretime=600;
1.620     albertel 7033:                if ($env{'request.role'} eq $roleid) {
1.54      www      7034: 		  $expiretime=120;
                   7035:                }
                   7036: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7037:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7038:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7039: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7040:                }
1.620     albertel 7041:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7042:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7043: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7044:                        &log($env{'user.domain'},$env{'user.name'},
                   7045:                             $env{'user.home'},
1.57      www      7046:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7047:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7048:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7049: 		       return '';
                   7050:                    }
                   7051:                }
1.620     albertel 7052:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7053:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7054: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7055:                        &log($env{'user.domain'},$env{'user.name'},
                   7056:                             $env{'user.home'},
1.57      www      7057:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7058:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7059:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7060: 		       return '';
                   7061:                    }
                   7062:                }
                   7063: 	   }
1.29      www      7064:        }
1.52      www      7065:     }
                   7066:    
                   7067: #
                   7068: # Rest of the restrictions depend on selected course
                   7069: #
                   7070: 
1.620     albertel 7071:     unless ($env{'request.course.id'}) {
1.766     albertel 7072: 	if ($thisallowed eq 'A') {
                   7073: 	    return 'A';
1.814     raeburn  7074:         } elsif ($thisallowed eq 'B') {
                   7075:             return 'B';
1.766     albertel 7076: 	} else {
                   7077: 	    return '1';
                   7078: 	}
1.52      www      7079:     }
1.29      www      7080: 
1.52      www      7081: #
                   7082: # Now user is definitely in a course
                   7083: #
1.53      www      7084: 
                   7085: 
                   7086: # Course preferences
                   7087: 
                   7088:    if ($thisallowed=~/C/) {
1.620     albertel 7089:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7090:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7091:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7092: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7093: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7094: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7095: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7096: 			$env{'request.course.id'});
                   7097: 	   }
1.237     www      7098:            return '';
                   7099:        }
                   7100: 
1.620     albertel 7101:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7102: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7103: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7104: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7105: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7106: 			$env{'request.course.id'});
                   7107: 	   }
1.54      www      7108:            return '';
                   7109:        }
1.53      www      7110:    }
                   7111: 
                   7112: # Resource preferences
                   7113: 
                   7114:    if ($thisallowed=~/R/) {
1.620     albertel 7115:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7116:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7117: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7118: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7119: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7120: 	   }
                   7121: 	   return '';
1.54      www      7122:        }
1.53      www      7123:    }
1.30      www      7124: 
1.246     www      7125: # Restricted by state or randomout?
1.30      www      7126: 
1.52      www      7127:    if ($thisallowed=~/X/) {
1.620     albertel 7128:       if ($env{'acc.randomout'}) {
1.579     albertel 7129: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7130:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7131:             return ''; 
                   7132:          }
1.247     www      7133:       }
                   7134:       if (&condval($statecond)) {
1.52      www      7135: 	 return '2';
                   7136:       } else {
                   7137:          return '';
                   7138:       }
                   7139:    }
1.30      www      7140: 
1.766     albertel 7141:     if ($thisallowed eq 'A') {
                   7142: 	return 'A';
1.814     raeburn  7143:     } elsif ($thisallowed eq 'B') {
                   7144:         return 'B';
1.766     albertel 7145:     }
1.52      www      7146:    return 'F';
1.232     www      7147: }
1.1162    raeburn  7148: 
1.1172.2.13  raeburn  7149: # ------------------------------------------- Check construction space access
                   7150: 
                   7151: sub constructaccess {
                   7152:     my ($url,$setpriv)=@_;
                   7153: 
                   7154: # We do not allow editing of previous versions of files
                   7155:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7156: 
                   7157: # Get username and domain from URL
                   7158:     my ($ownername,$ownerdomain,$ownerhome);
                   7159: 
                   7160:     ($ownerdomain,$ownername) =
                   7161:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7162: 
                   7163: # The URL does not really point to any authorspace, forget it
                   7164:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7165: 
                   7166: # Now we need to see if the user has access to the authorspace of
                   7167: # $ownername at $ownerdomain
                   7168: 
                   7169:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7170: # Real author for this?
                   7171:        $ownerhome = $env{'user.home'};
                   7172:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7173:           return ($ownername,$ownerdomain,$ownerhome);
                   7174:        }
                   7175:     } else {
                   7176: # Co-author for this?
                   7177:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7178:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7179:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7180:             return ($ownername,$ownerdomain,$ownerhome);
                   7181:         }
                   7182:     }
                   7183: 
                   7184: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7185: # we might as well leave
                   7186:    unless ($setpriv) { return ''; }
                   7187: 
                   7188: # Backdoor access?
                   7189:     my $allowed=&allowed('eco',$ownerdomain);
                   7190: # Nope
                   7191:     unless ($allowed) { return ''; }
                   7192: # Looks like we may have access, but could be locked by the owner of the construction space
                   7193:     if ($allowed eq 'U') {
                   7194:         my %blocked=&get('environment',['domcoord.author'],
                   7195:                          $ownerdomain,$ownername);
                   7196: # Is blocked by owner
                   7197:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7198:     }
                   7199:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7200: # Grant temporary access
                   7201:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7202:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7203:         if (!$update) { $update = $then; }
                   7204:         my $refresh=$env{'user.refresh.time'};
                   7205:         if (!$refresh) { $refresh = $update; }
                   7206:         my $now = time;
                   7207:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7208:                            $now,'ca','constructaccess');
                   7209:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7210:         return($ownername,$ownerdomain,$ownerhome);
                   7211:     }
                   7212: # No business here
                   7213:     return '';
                   7214: }
                   7215: 
1.1162    raeburn  7216: sub get_comm_blocks {
                   7217:     my ($cdom,$cnum) = @_;
                   7218:     if ($cdom eq '' || $cnum eq '') {
                   7219:         return unless ($env{'request.course.id'});
                   7220:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7221:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7222:     }
                   7223:     my %commblocks;
                   7224:     my $hashid=$cdom.'_'.$cnum;
                   7225:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7226:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7227:         %commblocks = %{$blocksref};
                   7228:     } else {
                   7229:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7230:         my $cachetime = 600;
                   7231:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7232:     }
                   7233:     return %commblocks;
                   7234: }
                   7235: 
                   7236: sub has_comm_blocking {
                   7237:     my ($priv,$symb,$uri,$blocks) = @_;
                   7238:     return unless ($env{'request.course.id'});
                   7239:     return unless ($priv eq 'bre');
                   7240:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7241:     my %commblocks;
                   7242:     if (ref($blocks) eq 'HASH') {
                   7243:         %commblocks = %{$blocks};
                   7244:     } else {
                   7245:         %commblocks = &get_comm_blocks();
                   7246:     }
                   7247:     return unless (keys(%commblocks) > 0);
                   7248:     if (!$symb) { $symb=&symbread($uri,1); }
                   7249:     my ($map,$resid,undef)=&decode_symb($symb);
                   7250:     my %tocheck = (
                   7251:                     maps      => $map,
                   7252:                     resources => $symb,
                   7253:                   );
                   7254:     my @blockers;
                   7255:     my $now = time;
1.1163    raeburn  7256:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7257:     foreach my $block (keys(%commblocks)) {
                   7258:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7259:             my ($start,$end) = ($1,$2);
                   7260:             if ($start <= $now && $end >= $now) {
                   7261:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7262:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7263:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7264:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7265:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7266:                                     push(@blockers,$block);
                   7267:                                 }
                   7268:                             }
                   7269:                         }
                   7270:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7271:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7272:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7273:                                     push(@blockers,$block);
                   7274:                                 }
                   7275:                             }
                   7276:                         }
                   7277:                     }
                   7278:                 }
                   7279:             }
                   7280:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7281:             my $item = $1;
1.1163    raeburn  7282:             my @to_test;
1.1162    raeburn  7283:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7284:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7285:                     my $check_interval;
                   7286:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7287:                         my @interval;
                   7288:                         my $type = 'map';
                   7289:                         if ($item eq 'course') {
                   7290:                             $type = 'course';
                   7291:                             @interval=&EXT("resource.0.interval");
                   7292:                         } else {
                   7293:                             if ($item =~ /___\d+___/) {
                   7294:                                 $type = 'resource';
                   7295:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7296:                                 if (ref($navmap)) {                        
                   7297:                                     my $res = $navmap->getBySymb($item); 
                   7298:                                     push(@to_test,$res);
                   7299:                                 }
1.1162    raeburn  7300:                             } else {
                   7301:                                 my $mapsymb = &symbread($item,1);
                   7302:                                 if ($mapsymb) {
                   7303:                                     if (ref($navmap)) {
                   7304:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7305:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7306:                                         foreach my $res (@to_test) {
1.1162    raeburn  7307:                                             my $symb = $res->symb();
                   7308:                                             next if ($symb eq $mapsymb);
                   7309:                                             if ($symb ne '') {
                   7310:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7311:                                                 last;
                   7312:                                             }
                   7313:                                         }
                   7314:                                     }
                   7315:                                 }
                   7316:                             }
                   7317:                         }
                   7318:                         if ($interval[0] =~ /\d+/) {
                   7319:                             my $first_access;
                   7320:                             if ($type eq 'resource') {
                   7321:                                 $first_access=&get_first_access($interval[1],$item);
                   7322:                             } elsif ($type eq 'map') {
                   7323:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7324:                             } else {
                   7325:                                 $first_access=&get_first_access($interval[1]);
                   7326:                             }
                   7327:                             if ($first_access) {
                   7328:                                 my $timesup = $first_access+$interval[0];
                   7329:                                 if ($timesup > $now) {
1.1163    raeburn  7330:                                     foreach my $res (@to_test) {
                   7331:                                         if ($res->is_problem()) {
                   7332:                                             if ($res->completable()) {
                   7333:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7334:                                                     push(@blockers,$block);
                   7335:                                                 }
                   7336:                                                 last;
                   7337:                                             }
                   7338:                                         }
1.1162    raeburn  7339:                                     }
                   7340:                                 }
                   7341:                             }
                   7342:                         }
                   7343:                     }
                   7344:                 }
                   7345:             }
                   7346:         }
                   7347:     }
                   7348:     return @blockers;
                   7349: }
                   7350: 
                   7351: sub check_docs_block {
                   7352:     my ($docsblock,$tocheck) =@_;
                   7353:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7354:         return;
                   7355:     }
                   7356:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7357:         if ($tocheck->{'maps'}) {
                   7358:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7359:                 return 1;
                   7360:             }
                   7361:         }
                   7362:     }
                   7363:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7364:         if ($tocheck->{'resources'}) {
                   7365:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7366:                 return 1;
                   7367:             }
                   7368:         }
                   7369:     }
                   7370:     return;
                   7371: }
                   7372: 
1.1133    foxr     7373: #
                   7374: #   Removes the versino from a URI and
                   7375: #   splits it in to its filename and path to the filename.
                   7376: #   Seems like File::Basename could have done this more clearly.
                   7377: #   Parameters:
                   7378: #      $uri   - input URI
                   7379: #   Returns:
                   7380: #     Two element list consisting of 
                   7381: #     $pathname  - the URI up to and excluding the trailing /
                   7382: #     $filename  - The part of the URI following the last /
                   7383: #  NOTE:
                   7384: #    Another realization of this is simply:
                   7385: #    use File::Basename;
                   7386: #    ...
                   7387: #    $uri = shift;
                   7388: #    $filename = basename($uri);
                   7389: #    $path     = dirname($uri);
                   7390: #    return ($filename, $path);
                   7391: #
                   7392: #     The implementation below is probably faster however.
                   7393: #
1.710     albertel 7394: sub split_uri_for_cond {
                   7395:     my $uri=&deversion(&declutter(shift));
                   7396:     my @uriparts=split(/\//,$uri);
                   7397:     my $filename=pop(@uriparts);
                   7398:     my $pathname=join('/',@uriparts);
                   7399:     return ($pathname,$filename);
                   7400: }
1.232     www      7401: # --------------------------------------------------- Is a resource on the map?
                   7402: 
                   7403: sub is_on_map {
1.710     albertel 7404:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7405:     #Trying to find the conditional for the file
1.620     albertel 7406:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7407: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7408:     if ($match) {
1.289     bowersj2 7409: 	return (1,$1);
                   7410:     } else {
1.434     www      7411: 	return (0,0);
1.289     bowersj2 7412:     }
1.12      www      7413: }
                   7414: 
1.427     www      7415: # --------------------------------------------------------- Get symb from alias
                   7416: 
                   7417: sub get_symb_from_alias {
                   7418:     my $symb=shift;
                   7419:     my ($map,$resid,$url)=&decode_symb($symb);
                   7420: # Already is a symb
                   7421:     if ($url) { return $symb; }
                   7422: # Must be an alias
                   7423:     my $aliassymb='';
                   7424:     my %bighash;
1.620     albertel 7425:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7426:                             &GDBM_READER(),0640)) {
                   7427:         my $rid=$bighash{'mapalias_'.$symb};
                   7428: 	if ($rid) {
                   7429: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7430: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7431: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7432: 	}
                   7433:         untie %bighash;
                   7434:     }
                   7435:     return $aliassymb;
                   7436: }
                   7437: 
1.12      www      7438: # ----------------------------------------------------------------- Define Role
                   7439: 
                   7440: sub definerole {
                   7441:   if (allowed('mcr','/')) {
                   7442:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7443:     foreach my $role (split(':',$sysrole)) {
                   7444: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7445:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7446:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7447: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7448:                return "refused:s:$crole&$cqual"; 
                   7449:             }
                   7450:         }
1.191     harris41 7451:     }
1.800     albertel 7452:     foreach my $role (split(':',$domrole)) {
                   7453: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7454:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7455:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7456: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7457:                return "refused:d:$crole&$cqual"; 
                   7458:             }
                   7459:         }
1.191     harris41 7460:     }
1.800     albertel 7461:     foreach my $role (split(':',$courole)) {
                   7462: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7463:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7464:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7465: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7466:                return "refused:c:$crole&$cqual"; 
                   7467:             }
                   7468:         }
1.191     harris41 7469:     }
1.620     albertel 7470:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7471:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7472: 	        "rolesdef_$rolename=".
                   7473:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7474:     return reply($command,$env{'user.home'});
1.12      www      7475:   } else {
                   7476:     return 'refused';
                   7477:   }
1.105     harris41 7478: }
                   7479: 
                   7480: # ---------------- Make a metadata query against the network of library servers
                   7481: 
                   7482: sub metadata_query {
1.1172.2.33  raeburn  7483:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7484:     my %rhash;
1.845     albertel 7485:     my %libserv = &all_library();
1.244     matthew  7486:     my @server_list = (defined($server_array) ? @$server_array
                   7487:                                               : keys(%libserv) );
                   7488:     for my $server (@server_list) {
1.1172.2.33  raeburn  7489:         my $domains = '';
                   7490:         if (ref($domains_hash) eq 'HASH') {
                   7491:             $domains = $domains_hash->{$server};    
                   7492:         }
1.118     harris41 7493: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  7494: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7495: 	    $rhash{$server}=$reply;
                   7496: 	}
                   7497: 	else {
                   7498: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  7499: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7500: 			     $server);
                   7501: 	    $rhash{$server}=$reply;
                   7502: 	}
1.112     harris41 7503:     }
1.118     harris41 7504:     return \%rhash;
1.240     www      7505: }
                   7506: 
                   7507: # ----------------------------------------- Send log queries and wait for reply
                   7508: 
                   7509: sub log_query {
                   7510:     my ($uname,$udom,$query,%filters)=@_;
                   7511:     my $uhome=&homeserver($uname,$udom);
                   7512:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7513:     my $uhost=&hostname($uhome);
1.800     albertel 7514:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7515:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7516:                        $uhome);
1.479     albertel 7517:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7518:     return get_query_reply($queryid);
                   7519: }
                   7520: 
1.818     raeburn  7521: # -------------------------- Update MySQL table for portfolio file
                   7522: 
                   7523: sub update_portfolio_table {
1.821     raeburn  7524:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7525:     if ($group ne '') {
                   7526:         $file_name =~s /^\Q$group\E//;
                   7527:     }
1.818     raeburn  7528:     my $homeserver = &homeserver($uname,$udom);
                   7529:     my $queryid=
1.821     raeburn  7530:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7531:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7532:     my $reply = &get_query_reply($queryid);
                   7533:     return $reply;
                   7534: }
                   7535: 
1.899     raeburn  7536: # -------------------------- Update MySQL allusers table
                   7537: 
                   7538: sub update_allusers_table {
                   7539:     my ($uname,$udom,$names) = @_;
                   7540:     my $homeserver = &homeserver($uname,$udom);
                   7541:     my $queryid=
                   7542:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7543:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7544:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7545:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7546:                'generation='.&escape($names->{'generation'}).'%%'.
                   7547:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7548:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7549:     return;
1.899     raeburn  7550: }
                   7551: 
1.508     raeburn  7552: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7553: 
                   7554: sub fetch_enrollment_query {
1.511     raeburn  7555:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7556:     my $homeserver;
1.547     raeburn  7557:     my $maxtries = 1;
1.508     raeburn  7558:     if ($context eq 'automated') {
                   7559:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7560:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7561:     } else {
                   7562:         $homeserver = &homeserver($cnum,$dom);
                   7563:     }
1.838     albertel 7564:     my $host=&hostname($homeserver);
1.506     raeburn  7565:     my $cmd = '';
1.1000    raeburn  7566:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7567:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7568:     }
                   7569:     $cmd =~ s/%%$//;
                   7570:     $cmd = &escape($cmd);
                   7571:     my $query = 'fetchenrollment';
1.620     albertel 7572:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7573:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7574:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7575:         return 'error: '.$queryid;
                   7576:     }
1.506     raeburn  7577:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7578:     my $tries = 1;
                   7579:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7580:         $reply = &get_query_reply($queryid);
                   7581:         $tries ++;
                   7582:     }
1.526     raeburn  7583:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7584:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7585:     } else {
1.901     albertel 7586:         my @responses = split(/:/,$reply);
1.515     raeburn  7587:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7588:             foreach my $line (@responses) {
                   7589:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7590:                 $$replyref{$key} = $value;
                   7591:             }
                   7592:         } else {
1.1117    foxr     7593:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7594:             foreach my $line (@responses) {
                   7595:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7596:                 $$replyref{$key} = $value;
                   7597:                 if ($value > 0) {
1.800     albertel 7598:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7599:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7600:                         my $destname = $pathname.'/'.$filename;
                   7601:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7602:                         if ($xml_classlist =~ /^error/) {
                   7603:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7604:                         } else {
1.506     raeburn  7605:                             if ( open(FILE,">$destname") ) {
                   7606:                                 print FILE &unescape($xml_classlist);
                   7607:                                 close(FILE);
1.526     raeburn  7608:                             } else {
                   7609:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7610:                             }
                   7611:                         }
                   7612:                     }
                   7613:                 }
                   7614:             }
                   7615:         }
                   7616:         return 'ok';
                   7617:     }
                   7618:     return 'error';
                   7619: }
                   7620: 
1.242     www      7621: sub get_query_reply {
                   7622:     my $queryid=shift;
1.1117    foxr     7623:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7624:     my $reply='';
                   7625:     for (1..100) {
                   7626: 	sleep 2;
                   7627:         if (-e $replyfile.'.end') {
1.448     albertel 7628: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7629: 		$reply = join('',<$fh>);
                   7630: 		close($fh);
1.240     www      7631: 	   } else { return 'error: reply_file_error'; }
1.242     www      7632:            return &unescape($reply);
                   7633: 	}
1.240     www      7634:     }
1.242     www      7635:     return 'timeout:'.$queryid;
1.240     www      7636: }
                   7637: 
                   7638: sub courselog_query {
1.241     www      7639: #
                   7640: # possible filters:
                   7641: # url: url or symb
                   7642: # username
                   7643: # domain
                   7644: # action: view, submit, grade
                   7645: # start: timestamp
                   7646: # end: timestamp
                   7647: #
1.240     www      7648:     my (%filters)=@_;
1.620     albertel 7649:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7650:     if ($filters{'url'}) {
                   7651: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7652:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7653:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7654:     }
1.620     albertel 7655:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7656:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7657:     return &log_query($cname,$cdom,'courselog',%filters);
                   7658: }
                   7659: 
                   7660: sub userlog_query {
1.858     raeburn  7661: #
                   7662: # possible filters:
                   7663: # action: log check role
                   7664: # start: timestamp
                   7665: # end: timestamp
                   7666: #
1.240     www      7667:     my ($uname,$udom,%filters)=@_;
                   7668:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7669: }
                   7670: 
1.506     raeburn  7671: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7672: 
                   7673: sub auto_run {
1.508     raeburn  7674:     my ($cnum,$cdom) = @_;
1.876     raeburn  7675:     my $response = 0;
                   7676:     my $settings;
                   7677:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7678:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7679:         $settings = $domconfig{'autoenroll'};
                   7680:         if ($settings->{'run'} eq '1') {
                   7681:             $response = 1;
                   7682:         }
                   7683:     } else {
1.934     raeburn  7684:         my $homeserver;
                   7685:         if (&is_course($cdom,$cnum)) {
                   7686:             $homeserver = &homeserver($cnum,$cdom);
                   7687:         } else {
                   7688:             $homeserver = &domain($cdom,'primary');
                   7689:         }
                   7690:         if ($homeserver ne 'no_host') {
                   7691:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7692:         }
1.876     raeburn  7693:     }
1.506     raeburn  7694:     return $response;
                   7695: }
1.776     albertel 7696: 
1.506     raeburn  7697: sub auto_get_sections {
1.508     raeburn  7698:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7699:     my $homeserver;
                   7700:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7701:         $homeserver = &homeserver($cnum,$cdom);
                   7702:     }
                   7703:     if (!defined($homeserver)) { 
                   7704:         if ($cdom =~ /^$match_domain$/) {
                   7705:             $homeserver = &domain($cdom,'primary');
                   7706:         }
                   7707:     }
                   7708:     my @secs;
                   7709:     if (defined($homeserver)) {
                   7710:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7711:         unless ($response eq 'refused') {
                   7712:             @secs = split(/:/,$response);
                   7713:         }
1.506     raeburn  7714:     }
                   7715:     return @secs;
                   7716: }
1.776     albertel 7717: 
1.506     raeburn  7718: sub auto_new_course {
1.1099    raeburn  7719:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7720:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7721:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7722:     return $response;
                   7723: }
1.776     albertel 7724: 
1.506     raeburn  7725: sub auto_validate_courseID {
1.508     raeburn  7726:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7727:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7728:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7729:     return $response;
                   7730: }
1.776     albertel 7731: 
1.1007    raeburn  7732: sub auto_validate_instcode {
1.1020    raeburn  7733:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7734:     my ($homeserver,$response);
                   7735:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7736:         $homeserver = &homeserver($cnum,$cdom);
                   7737:     }
                   7738:     if (!defined($homeserver)) {
                   7739:         if ($cdom =~ /^$match_domain$/) {
                   7740:             $homeserver = &domain($cdom,'primary');
                   7741:         }
                   7742:     }
1.1065    raeburn  7743:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7744:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7745:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7746:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7747: }
                   7748: 
1.506     raeburn  7749: sub auto_create_password {
1.873     raeburn  7750:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7751:     my ($homeserver,$response);
1.506     raeburn  7752:     my $create_passwd = 0;
                   7753:     my $authchk = '';
1.873     raeburn  7754:     if ($udom =~ /^$match_domain$/) {
                   7755:         $homeserver = &domain($udom,'primary');
                   7756:     }
                   7757:     if ($homeserver eq '') {
                   7758:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7759:             $homeserver = &homeserver($cnum,$cdom);
                   7760:         }
                   7761:     }
                   7762:     if ($homeserver eq '') {
                   7763:         $authchk = 'nodomain';
1.506     raeburn  7764:     } else {
1.873     raeburn  7765:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7766:         if ($response eq 'refused') {
                   7767:             $authchk = 'refused';
                   7768:         } else {
1.901     albertel 7769:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7770:         }
1.506     raeburn  7771:     }
                   7772:     return ($authparam,$create_passwd,$authchk);
                   7773: }
                   7774: 
1.706     raeburn  7775: sub auto_photo_permission {
                   7776:     my ($cnum,$cdom,$students) = @_;
                   7777:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7778:     my ($outcome,$perm_reqd,$conditions) = 
                   7779: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7780:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7781: 	return (undef,undef);
                   7782:     }
1.706     raeburn  7783:     return ($outcome,$perm_reqd,$conditions);
                   7784: }
                   7785: 
                   7786: sub auto_checkphotos {
                   7787:     my ($uname,$udom,$pid) = @_;
                   7788:     my $homeserver = &homeserver($uname,$udom);
                   7789:     my ($result,$resulttype);
                   7790:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7791: 				   &escape($uname).':'.&escape($pid),
                   7792: 				   $homeserver));
1.709     albertel 7793:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7794: 	return (undef,undef);
                   7795:     }
1.706     raeburn  7796:     if ($outcome) {
                   7797:         ($result,$resulttype) = split(/:/,$outcome);
                   7798:     } 
                   7799:     return ($result,$resulttype);
                   7800: }
                   7801: 
                   7802: sub auto_photochoice {
                   7803:     my ($cnum,$cdom) = @_;
                   7804:     my $homeserver = &homeserver($cnum,$cdom);
                   7805:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7806: 						       &escape($cdom),
                   7807: 						       $homeserver)));
1.709     albertel 7808:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7809: 	return (undef,undef);
                   7810:     }
1.706     raeburn  7811:     return ($update,$comment);
                   7812: }
                   7813: 
                   7814: sub auto_photoupdate {
                   7815:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7816:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7817:     my $host=&hostname($homeserver);
1.706     raeburn  7818:     my $cmd = '';
                   7819:     my $maxtries = 1;
1.800     albertel 7820:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7821:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7822:     }
                   7823:     $cmd =~ s/%%$//;
                   7824:     $cmd = &escape($cmd);
                   7825:     my $query = 'institutionalphotos';
                   7826:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7827:     unless ($queryid=~/^\Q$host\E\_/) {
                   7828:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7829:         return 'error: '.$queryid;
                   7830:     }
                   7831:     my $reply = &get_query_reply($queryid);
                   7832:     my $tries = 1;
                   7833:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7834:         $reply = &get_query_reply($queryid);
                   7835:         $tries ++;
                   7836:     }
                   7837:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7838:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7839:     } else {
                   7840:         my @responses = split(/:/,$reply);
                   7841:         my $outcome = shift(@responses); 
                   7842:         foreach my $item (@responses) {
                   7843:             my ($key,$value) = split(/=/,$item);
                   7844:             $$photo{$key} = $value;
                   7845:         }
                   7846:         return $outcome;
                   7847:     }
                   7848:     return 'error';
                   7849: }
                   7850: 
1.521     raeburn  7851: sub auto_instcode_format {
1.793     albertel 7852:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7853: 	$cat_order) = @_;
1.521     raeburn  7854:     my $courses = '';
1.772     raeburn  7855:     my @homeservers;
1.521     raeburn  7856:     if ($caller eq 'global') {
1.841     albertel 7857: 	my %servers = &get_servers($codedom,'library');
                   7858: 	foreach my $tryserver (keys(%servers)) {
                   7859: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7860: 		push(@homeservers,$tryserver);
                   7861: 	    }
1.584     raeburn  7862:         }
1.1022    raeburn  7863:     } elsif ($caller eq 'requests') {
                   7864:         if ($codedom =~ /^$match_domain$/) {
                   7865:             my $chome = &domain($codedom,'primary');
                   7866:             unless ($chome eq 'no_host') {
                   7867:                 push(@homeservers,$chome);
                   7868:             }
                   7869:         }
1.521     raeburn  7870:     } else {
1.772     raeburn  7871:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7872:     }
1.793     albertel 7873:     foreach my $code (keys(%{$instcodes})) {
                   7874:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7875:     }
                   7876:     chop($courses);
1.772     raeburn  7877:     my $ok_response = 0;
                   7878:     my $response;
                   7879:     while (@homeservers > 0 && $ok_response == 0) {
                   7880:         my $server = shift(@homeservers); 
                   7881:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7882:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7883:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7884: 		split(/:/,$response);
1.772     raeburn  7885:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7886:             push(@{$codetitles},&str2array($codetitles_str));
                   7887:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7888:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7889:             $ok_response = 1;
                   7890:         }
                   7891:     }
                   7892:     if ($ok_response) {
1.521     raeburn  7893:         return 'ok';
1.772     raeburn  7894:     } else {
                   7895:         return $response;
1.521     raeburn  7896:     }
                   7897: }
                   7898: 
1.792     raeburn  7899: sub auto_instcode_defaults {
                   7900:     my ($domain,$returnhash,$code_order) = @_;
                   7901:     my @homeservers;
1.841     albertel 7902: 
                   7903:     my %servers = &get_servers($domain,'library');
                   7904:     foreach my $tryserver (keys(%servers)) {
                   7905: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7906: 	    push(@homeservers,$tryserver);
                   7907: 	}
1.792     raeburn  7908:     }
1.841     albertel 7909: 
1.792     raeburn  7910:     my $response;
1.841     albertel 7911:     foreach my $server (@homeservers) {
1.792     raeburn  7912:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7913:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7914: 	
                   7915: 	foreach my $pair (split(/\&/,$response)) {
                   7916: 	    my ($name,$value)=split(/\=/,$pair);
                   7917: 	    if ($name eq 'code_order') {
                   7918: 		@{$code_order} = split(/\&/,&unescape($value));
                   7919: 	    } else {
                   7920: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7921: 	    }
                   7922: 	}
                   7923: 	return 'ok';
1.792     raeburn  7924:     }
1.841     albertel 7925: 
                   7926:     return $response;
1.1003    raeburn  7927: }
                   7928: 
                   7929: sub auto_possible_instcodes {
1.1007    raeburn  7930:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7931:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7932:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7933:         return;
                   7934:     }
1.1003    raeburn  7935:     my (@homeservers,$uhome);
                   7936:     if (defined(&domain($domain,'primary'))) {
                   7937:         $uhome=&domain($domain,'primary');
                   7938:         push(@homeservers,&domain($domain,'primary'));
                   7939:     } else {
                   7940:         my %servers = &get_servers($domain,'library');
                   7941:         foreach my $tryserver (keys(%servers)) {
                   7942:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7943:                 push(@homeservers,$tryserver);
                   7944:             }
                   7945:         }
                   7946:     }
                   7947:     my $response;
                   7948:     foreach my $server (@homeservers) {
                   7949:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7950:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7951:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7952:             split(':',$response);
                   7953:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7954:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7955:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7956:             my ($name,$value)=split('=',$item);
                   7957:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7958:         }
                   7959:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7960:             my ($name,$value)=split('=',$item);
                   7961:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7962:         }
                   7963:         return 'ok';
                   7964:     }
                   7965:     return $response;
                   7966: }
1.792     raeburn  7967: 
1.1010    raeburn  7968: sub auto_courserequest_checks {
                   7969:     my ($dom) = @_;
1.1020    raeburn  7970:     my ($homeserver,%validations);
                   7971:     if ($dom =~ /^$match_domain$/) {
                   7972:         $homeserver = &domain($dom,'primary');
                   7973:     }
                   7974:     unless ($homeserver eq 'no_host') {
                   7975:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7976:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7977:             my @items = split(/&/,$response);
                   7978:             foreach my $item (@items) {
                   7979:                 my ($key,$value) = split('=',$item);
                   7980:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7981:             }
                   7982:         }
                   7983:     }
1.1010    raeburn  7984:     return %validations; 
                   7985: }
                   7986: 
1.1020    raeburn  7987: sub auto_courserequest_validation {
1.1172.2.43  raeburn  7988:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  7989:     my ($homeserver,$response);
                   7990:     if ($dom =~ /^$match_domain$/) {
                   7991:         $homeserver = &domain($dom,'primary');
                   7992:     }
1.1172.2.43  raeburn  7993:     unless ($homeserver eq 'no_host') {
                   7994:         my $customdata;
                   7995:         if (ref($custominfo) eq 'HASH') {
                   7996:             $customdata = &freeze_escape($custominfo);
                   7997:         }
1.1020    raeburn  7998:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7999:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8000:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8001:                                     $customdata,$homeserver));
1.1020    raeburn  8002:     }
                   8003:     return $response;
                   8004: }
                   8005: 
1.777     albertel 8006: sub auto_validate_class_sec {
1.918     raeburn  8007:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8008:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8009:     my $ownerlist;
                   8010:     if (ref($owners) eq 'ARRAY') {
                   8011:         $ownerlist = join(',',@{$owners});
                   8012:     } else {
                   8013:         $ownerlist = $owners;
                   8014:     }
1.773     raeburn  8015:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8016:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8017:     return $response;
                   8018: }
                   8019: 
1.1172.2.38  raeburn  8020: sub auto_crsreq_update {
                   8021:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8022:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8023:     my ($homeserver,%crsreqresponse);
                   8024:     if ($cdom =~ /^$match_domain$/) {
                   8025:         $homeserver = &domain($cdom,'primary');
                   8026:     }
                   8027:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8028:         my $info;
                   8029:         if (ref($inbound) eq 'HASH') {
                   8030:             $info = &freeze_escape($inbound);
                   8031:         }
                   8032:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8033:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8034:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8035:                             &escape($title).':'.&escape($code).':'.
                   8036:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8037:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8038:             my @items = split(/&/,$response);
                   8039:             foreach my $item (@items) {
                   8040:                 my ($key,$value) = split('=',$item);
                   8041:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8042:             }
                   8043:         }
                   8044:     }
                   8045:     return \%crsreqresponse;
                   8046: }
                   8047: 
1.679     raeburn  8048: # ------------------------------------------------------- Course Group routines
                   8049: 
                   8050: sub get_coursegroups {
1.809     raeburn  8051:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8052:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8053: }
                   8054: 
1.679     raeburn  8055: sub modify_coursegroup {
                   8056:     my ($cdom,$cnum,$groupsettings) = @_;
                   8057:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8058: }
                   8059: 
1.809     raeburn  8060: sub toggle_coursegroup_status {
                   8061:     my ($cdom,$cnum,$group,$action) = @_;
                   8062:     my ($from_namespace,$to_namespace);
                   8063:     if ($action eq 'delete') {
                   8064:         $from_namespace = 'coursegroups';
                   8065:         $to_namespace = 'deleted_groups';
                   8066:     } else {
                   8067:         $from_namespace = 'deleted_groups';
                   8068:         $to_namespace = 'coursegroups';
                   8069:     }
                   8070:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8071:     if (my $tmp = &error(%curr_group)) {
                   8072:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8073:         return ('read error',$tmp);
                   8074:     } else {
                   8075:         my %savedsettings = %curr_group; 
1.809     raeburn  8076:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8077:         my $deloutcome;
                   8078:         if ($result eq 'ok') {
1.809     raeburn  8079:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8080:         } else {
                   8081:             return ('write error',$result);
                   8082:         }
                   8083:         if ($deloutcome eq 'ok') {
                   8084:             return 'ok';
                   8085:         } else {
                   8086:             return ('delete error',$deloutcome);
                   8087:         }
                   8088:     }
                   8089: }
                   8090: 
1.679     raeburn  8091: sub modify_group_roles {
1.957     raeburn  8092:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8093:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8094:     my $role = 'gr/'.&escape($userprivs);
                   8095:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8096:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8097:     if ($result eq 'ok') {
                   8098:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8099:     }
1.679     raeburn  8100:     return $result;
                   8101: }
                   8102: 
                   8103: sub modify_coursegroup_membership {
                   8104:     my ($cdom,$cnum,$membership) = @_;
                   8105:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8106:     return $result;
                   8107: }
                   8108: 
1.682     raeburn  8109: sub get_active_groups {
                   8110:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8111:     my $now = time;
                   8112:     my %groups = ();
                   8113:     foreach my $key (keys(%env)) {
1.811     albertel 8114:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8115:             my ($start,$end) = split(/\./,$env{$key});
                   8116:             if (($end!=0) && ($end<$now)) { next; }
                   8117:             if (($start!=0) && ($start>$now)) { next; }
                   8118:             if ($1 eq $cdom && $2 eq $cnum) {
                   8119:                 $groups{$3} = $env{$key} ;
                   8120:             }
                   8121:         }
                   8122:     }
                   8123:     return %groups;
                   8124: }
                   8125: 
1.683     raeburn  8126: sub get_group_membership {
                   8127:     my ($cdom,$cnum,$group) = @_;
                   8128:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8129: }
                   8130: 
                   8131: sub get_users_groups {
                   8132:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8133:     my @usersgroups;
1.683     raeburn  8134:     my $cachetime=1800;
                   8135: 
                   8136:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8137:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8138:     if (defined($cached)) {
1.734     albertel 8139:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8140:     } else {  
                   8141:         $grouplist = '';
1.816     raeburn  8142:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8143:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8144:         my $access_end = $env{'course.'.$courseid.
                   8145:                               '.default_enrollment_end_date'};
                   8146:         my $now = time;
                   8147:         foreach my $key (keys(%roleshash)) {
                   8148:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8149:                 my $group = $1;
                   8150:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8151:                     my $start = $2;
                   8152:                     my $end = $1;
                   8153:                     if ($start == -1) { next; } # deleted from group
                   8154:                     if (($start!=0) && ($start>$now)) { next; }
                   8155:                     if (($end!=0) && ($end<$now)) {
                   8156:                         if ($access_end && $access_end < $now) {
                   8157:                             if ($access_end - $end < 86400) {
                   8158:                                 push(@usersgroups,$group);
1.733     raeburn  8159:                             }
                   8160:                         }
1.817     raeburn  8161:                         next;
1.733     raeburn  8162:                     }
1.817     raeburn  8163:                     push(@usersgroups,$group);
1.683     raeburn  8164:                 }
                   8165:             }
                   8166:         }
1.817     raeburn  8167:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8168:         $grouplist = join(':',@usersgroups);
                   8169:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8170:     }
1.733     raeburn  8171:     return @usersgroups;
1.683     raeburn  8172: }
                   8173: 
                   8174: sub devalidate_getgroups_cache {
                   8175:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8176:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8177: 
1.683     raeburn  8178:     my $hashid="$udom:$uname:$courseid";
                   8179:     &devalidate_cache_new('getgroups',$hashid);
                   8180: }
                   8181: 
1.12      www      8182: # ------------------------------------------------------------------ Plain Text
                   8183: 
                   8184: sub plaintext {
1.988     raeburn  8185:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8186:     if ($short =~ m{^cr/}) {
1.758     albertel 8187: 	return (split('/',$short))[-1];
                   8188:     }
1.742     raeburn  8189:     if (!defined($cid)) {
                   8190:         $cid = $env{'request.course.id'};
                   8191:     }
                   8192:     my %rolenames = (
1.1008    raeburn  8193:                       Course    => 'std',
                   8194:                       Community => 'alt1',
1.742     raeburn  8195:                     );
1.1037    raeburn  8196:     if ($cid ne '') {
                   8197:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8198:             unless ($forcedefault) {
                   8199:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8200:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8201:                 return &Apache::lonlocal::mt($roletext);
                   8202:             }
                   8203:         }
                   8204:     }
                   8205:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8206:         (defined($rolenames{$type})) && 
                   8207:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8208:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8209:     } elsif ($cid ne '') {
                   8210:         my $crstype = $env{'course.'.$cid.'.type'};
                   8211:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8212:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8213:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8214:         }
1.742     raeburn  8215:     }
1.1037    raeburn  8216:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8217: }
                   8218: 
                   8219: # ----------------------------------------------------------------- Assign Role
                   8220: 
                   8221: sub assignrole {
1.957     raeburn  8222:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8223:         $context)=@_;
1.21      www      8224:     my $mrole;
                   8225:     if ($role =~ /^cr\//) {
1.393     www      8226:         my $cwosec=$url;
1.811     albertel 8227:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8228: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8229:            my $refused = 1;
                   8230:            if ($context eq 'requestcourses') {
                   8231:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8232:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8233:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8234:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8235:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8236:                            if ($crsenv{'internal.courseowner'} eq
                   8237:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8238:                                $refused = '';
                   8239:                            }
                   8240:                        }
                   8241:                    }
                   8242:                }
                   8243:            }
                   8244:            if ($refused) {
                   8245:                &logthis('Refused custom assignrole: '.
                   8246:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8247:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8248:                return 'refused';
                   8249:            }
1.104     www      8250:         }
1.21      www      8251:         $mrole='cr';
1.678     raeburn  8252:     } elsif ($role =~ /^gr\//) {
                   8253:         my $cwogrp=$url;
1.811     albertel 8254:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8255:         unless (&allowed('mdg',$cwogrp)) {
                   8256:             &logthis('Refused group assignrole: '.
                   8257:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8258:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8259:             return 'refused';
                   8260:         }
                   8261:         $mrole='gr';
1.21      www      8262:     } else {
1.82      www      8263:         my $cwosec=$url;
1.811     albertel 8264:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8265:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8266:             my $refused;
                   8267:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8268:                 if (!(&allowed('c'.$role,$url))) {
                   8269:                     $refused = 1;
                   8270:                 }
                   8271:             } else {
                   8272:                 $refused = 1;
                   8273:             }
1.947     raeburn  8274:             if ($refused) {
1.1045    raeburn  8275:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8276:                 if (!$selfenroll && $context eq 'course') {
                   8277:                     my %crsenv;
                   8278:                     if ($role eq 'cc' || $role eq 'co') {
                   8279:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8280:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8281:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8282:                                 if ($crsenv{'internal.courseowner'} eq 
                   8283:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8284:                                     $refused = '';
                   8285:                                 }
                   8286:                             }
                   8287:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8288:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8289:                                 if ($crsenv{'internal.courseowner'} eq 
                   8290:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8291:                                     $refused = '';
                   8292:                                 }
                   8293:                             }
                   8294:                         }
                   8295:                     }
                   8296:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8297:                     $refused = '';
1.1017    raeburn  8298:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8299:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8300:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8301:                         my $wrongcc;
                   8302:                         if ($cnum =~ /^$match_community$/) {
                   8303:                             $wrongcc = 1 if ($role eq 'cc');
                   8304:                         } else {
                   8305:                             $wrongcc = 1 if ($role eq 'co');
                   8306:                         }
                   8307:                         unless ($wrongcc) {
                   8308:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8309:                             if ($crsenv{'internal.courseowner'} eq 
                   8310:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8311:                                 $refused = '';
                   8312:                             }
1.1017    raeburn  8313:                         }
                   8314:                     }
1.1172.2.9  raeburn  8315:                 } elsif ($context eq 'requestauthor') {
                   8316:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8317:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8318:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8319:                             $refused = '';
                   8320:                         } else {
                   8321:                             my %domdefaults = &get_domain_defaults($udom);
                   8322:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8323:                                 my $checkbystatus;
                   8324:                                 if ($env{'user.adv'}) {
                   8325:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8326:                                     if ($disposition eq 'automatic') {
                   8327:                                         $refused = '';
                   8328:                                     } elsif ($disposition eq '') {
                   8329:                                         $checkbystatus = 1;
                   8330:                                     }
                   8331:                                 } else {
                   8332:                                     $checkbystatus = 1;
                   8333:                                 }
                   8334:                                 if ($checkbystatus) {
                   8335:                                     if ($env{'environment.inststatus'}) {
                   8336:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8337:                                         foreach my $type (@inststatuses) {
                   8338:                                             if (($type ne '') &&
                   8339:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8340:                                                 $refused = '';
                   8341:                                             }
                   8342:                                         }
                   8343:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8344:                                         $refused = '';
                   8345:                                     }
                   8346:                                 }
                   8347:                             }
                   8348:                         }
                   8349:                     }
1.1017    raeburn  8350:                 }
                   8351:                 if ($refused) {
1.947     raeburn  8352:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8353:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8354: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8355:                     return 'refused';
                   8356:                 }
1.932     raeburn  8357:             }
1.1131    raeburn  8358:         } elsif ($role eq 'au') {
                   8359:             if ($url ne '/'.$udom.'/') {
                   8360:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8361:                          ' to assign author role for '.$uname.':'.$udom.
                   8362:                          ' in domain: '.$url.' refused (wrong domain).');
                   8363:                 return 'refused';
                   8364:             }
1.104     www      8365:         }
1.21      www      8366:         $mrole=$role;
                   8367:     }
1.620     albertel 8368:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8369:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8370:     if ($end) { $command.='_'.$end; }
1.21      www      8371:     if ($start) {
                   8372: 	if ($end) { 
1.81      www      8373:            $command.='_'.$start; 
1.21      www      8374:         } else {
1.81      www      8375:            $command.='_0_'.$start;
1.21      www      8376:         }
                   8377:     }
1.739     raeburn  8378:     my $origstart = $start;
                   8379:     my $origend = $end;
1.957     raeburn  8380:     my $delflag;
1.357     www      8381: # actually delete
                   8382:     if ($deleteflag) {
1.373     www      8383: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8384: # modify command to delete the role
1.620     albertel 8385:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8386:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8387: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8388: # set start and finish to negative values for userrolelog
                   8389:            $start=-1;
                   8390:            $end=-1;
1.957     raeburn  8391:            $delflag = 1;
1.357     www      8392:         }
                   8393:     }
                   8394: # send command
1.349     www      8395:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8396: # log new user role if status is ok
1.349     www      8397:     if ($answer eq 'ok') {
1.663     raeburn  8398: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8399:         if (($role eq 'cc') || ($role eq 'in') ||
                   8400:             ($role eq 'ep') || ($role eq 'ad') ||
                   8401:             ($role eq 'ta') || ($role eq 'st') ||
                   8402:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8403:             ($role eq 'co')) {
1.1172.2.13  raeburn  8404: # for course roles, perform group memberships changes triggered by role change.
                   8405:             unless ($role =~ /^gr/) {
                   8406:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8407:                                                  $origstart,$selfenroll,$context);
                   8408:             }
1.1172.2.9  raeburn  8409:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8410:                            $selfenroll,$context);
                   8411:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8412:                  ($role eq 'au') || ($role eq 'dc')) {
                   8413:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8414:                            $context);
                   8415:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8416:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8417:                              $context);
                   8418:         }
1.1053    raeburn  8419:         if ($role eq 'cc') {
                   8420:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8421:         }
1.349     www      8422:     }
                   8423:     return $answer;
1.169     harris41 8424: }
                   8425: 
1.1053    raeburn  8426: sub autoupdate_coowners {
                   8427:     my ($url,$end,$start,$uname,$udom) = @_;
                   8428:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8429:     if (($cdom ne '') && ($cnum ne '')) {
                   8430:         my $now = time;
                   8431:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8432:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8433:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8434:             my $instcode = $coursehash{'internal.coursecode'};
                   8435:             if ($instcode ne '') {
1.1056    raeburn  8436:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8437:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8438:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8439:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8440:                         if ($result eq 'valid') {
                   8441:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8442:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8443:                                     push(@newcoowners,$coowner);
                   8444:                                 }
                   8445:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8446:                                     push(@newcoowners,$uname.':'.$udom);
                   8447:                                 }
                   8448:                                 @newcoowners = sort(@newcoowners);
                   8449:                             } else {
                   8450:                                 push(@newcoowners,$uname.':'.$udom);
                   8451:                             }
                   8452:                         } else {
                   8453:                             if ($coursehash{'internal.co-owners'}) {
                   8454:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8455:                                     unless ($coowner eq $uname.':'.$udom) {
                   8456:                                         push(@newcoowners,$coowner);
                   8457:                                     }
                   8458:                                 }
                   8459:                                 unless (@newcoowners > 0) {
                   8460:                                     $delcoowners = 1;
                   8461:                                     $coowners = '';
                   8462:                                 }
                   8463:                             }
                   8464:                         }
                   8465:                         if (@newcoowners || $delcoowners) {
                   8466:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8467:                                             $delcoowners,@newcoowners);
                   8468:                         }
                   8469:                     }
                   8470:                 }
                   8471:             }
                   8472:         }
                   8473:     }
                   8474: }
                   8475: 
                   8476: sub store_coowners {
                   8477:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8478:     my $cid = $cdom.'_'.$cnum;
                   8479:     my ($coowners,$delresult,$putresult);
                   8480:     if (@newcoowners) {
                   8481:         $coowners = join(',',@newcoowners);
                   8482:         my %coownershash = (
                   8483:                             'internal.co-owners' => $coowners,
                   8484:                            );
                   8485:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8486:         if ($putresult eq 'ok') {
                   8487:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8488:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8489:             }
                   8490:         }
                   8491:     }
                   8492:     if ($delcoowners) {
                   8493:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8494:         if ($delresult eq 'ok') {
                   8495:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8496:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8497:             }
                   8498:         }
                   8499:     }
                   8500:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8501:         my %crsinfo =
                   8502:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8503:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8504:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8505:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8506:         }
                   8507:     }
                   8508: }
                   8509: 
1.169     harris41 8510: # -------------------------------------------------- Modify user authentication
1.197     www      8511: # Overrides without validation
                   8512: 
1.169     harris41 8513: sub modifyuserauth {
                   8514:     my ($udom,$uname,$umode,$upass)=@_;
                   8515:     my $uhome=&homeserver($uname,$udom);
1.197     www      8516:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8517:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8518:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8519:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8520:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8521: 		     &escape($upass),$uhome);
1.620     albertel 8522:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8523:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8524:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8525:     &log($udom,,$uname,$uhome,
1.620     albertel 8526:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8527:                                      $env{'user.name'}.', '.$umode.
1.197     www      8528:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8529:     unless ($reply eq 'ok') {
1.197     www      8530:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8531: 	return 'error: '.$reply;
                   8532:     }   
1.170     harris41 8533:     return 'ok';
1.80      www      8534: }
                   8535: 
1.81      www      8536: # --------------------------------------------------------------- Modify a user
1.80      www      8537: 
1.81      www      8538: sub modifyuser {
1.206     matthew  8539:     my ($udom,    $uname, $uid,
                   8540:         $umode,   $upass, $first,
                   8541:         $middle,  $last,  $gene,
1.1058    raeburn  8542:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8543:     $udom= &LONCAPA::clean_domain($udom);
                   8544:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8545:     my $showcandelete = 'none';
                   8546:     if (ref($candelete) eq 'ARRAY') {
                   8547:         if (@{$candelete} > 0) {
                   8548:             $showcandelete = join(', ',@{$candelete});
                   8549:         }
                   8550:     }
1.81      www      8551:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8552:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8553: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8554:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8555:                                      ' desiredhome not specified'). 
1.620     albertel 8556:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8557:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8558:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8559:     my $newuser;
                   8560:     if ($uhome eq 'no_host') {
                   8561:         $newuser = 1;
                   8562:     }
1.80      www      8563: # ----------------------------------------------------------------- Create User
1.406     albertel 8564:     if (($uhome eq 'no_host') && 
                   8565: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8566:         my $unhome='';
1.844     albertel 8567:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8568:             $unhome = $desiredhome;
1.620     albertel 8569: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8570: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8571:         } else { # load balancing routine for determining $unhome
1.81      www      8572:             my $loadm=10000000;
1.841     albertel 8573: 	    my %servers = &get_servers($udom,'library');
                   8574: 	    foreach my $tryserver (keys(%servers)) {
                   8575: 		my $answer=reply('load',$tryserver);
                   8576: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8577: 		    $loadm=$answer;
                   8578: 		    $unhome=$tryserver;
                   8579: 		}
1.80      www      8580: 	    }
                   8581:         }
                   8582:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8583: 	    return 'error: unable to find a home server for '.$uname.
                   8584:                    ' in domain '.$udom;
1.80      www      8585:         }
                   8586:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8587:                          &escape($upass),$unhome);
                   8588: 	unless ($reply eq 'ok') {
                   8589:             return 'error: '.$reply;
                   8590:         }   
1.230     stredwic 8591:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8592:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8593: 	    return 'error: unable verify users home machine.';
1.80      www      8594:         }
1.209     matthew  8595:     }   # End of creation of new user
1.80      www      8596: # ---------------------------------------------------------------------- Add ID
                   8597:     if ($uid) {
                   8598:        $uid=~tr/A-Z/a-z/;
                   8599:        my %uidhash=&idrget($udom,$uname);
1.196     www      8600:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8601:          && (!$forceid)) {
1.80      www      8602: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8603: 	      return 'error: user id "'.$uid.'" does not match '.
                   8604:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8605:           }
                   8606:        } else {
                   8607: 	  &idput($udom,($uname => $uid));
                   8608:        }
                   8609:     }
                   8610: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8611:     my @tmp=&get('environment',
1.899     raeburn  8612: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8613:                     'permanentemail','inststatus'],
1.134     albertel 8614: 		   $udom,$uname);
1.1075    raeburn  8615:     my (%names,%oldnames);
1.313     matthew  8616:     if ($tmp[0] =~ m/^error:.*/) { 
                   8617:         %names=(); 
                   8618:     } else {
                   8619:         %names = @tmp;
1.1075    raeburn  8620:         %oldnames = %names;
1.313     matthew  8621:     }
1.388     www      8622: #
1.1058    raeburn  8623: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8624: # of users did not contain them), do not overwrite existing values
                   8625: # unless field is in $candelete array ref.  
                   8626: #
                   8627: 
                   8628:     my @fields = ('firstname','middlename','lastname','generation',
                   8629:                   'permanentemail','id');
                   8630:     my %newvalues;
                   8631:     if (ref($candelete) eq 'ARRAY') {
                   8632:         foreach my $field (@fields) {
                   8633:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8634:                 if ($field eq 'firstname') {
                   8635:                     $names{$field} = $first;
                   8636:                 } elsif ($field eq 'middlename') {
                   8637:                     $names{$field} = $middle;
                   8638:                 } elsif ($field eq 'lastname') {
                   8639:                     $names{$field} = $last;
                   8640:                 } elsif ($field eq 'generation') { 
                   8641:                     $names{$field} = $gene;
                   8642:                 } elsif ($field eq 'permanentemail') {
                   8643:                     $names{$field} = $email;
                   8644:                 } elsif ($field eq 'id') {
                   8645:                     $names{$field}  = $uid;
                   8646:                 }
                   8647:             }
                   8648:         }
                   8649:     }
1.388     www      8650:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8651:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8652:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8653:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8654:     if ($email) {
                   8655:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8656:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8657:     }
1.899     raeburn  8658:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8659:     if (defined($inststatus)) {
                   8660:         $names{'inststatus'} = '';
                   8661:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8662:         if (ref($usertypes) eq 'HASH') {
                   8663:             my @okstatuses; 
                   8664:             foreach my $item (split(/:/,$inststatus)) {
                   8665:                 if (defined($usertypes->{$item})) {
                   8666:                     push(@okstatuses,$item);  
                   8667:                 }
                   8668:             }
                   8669:             if (@okstatuses) {
                   8670:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8671:             }
                   8672:         }
                   8673:     }
1.1075    raeburn  8674:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8675:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8676:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8677:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8678:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8679:     } else {
                   8680:         $logmsg .= ' during self creation';
                   8681:     }
1.1075    raeburn  8682:     my $changed;
                   8683:     if ($newuser) {
                   8684:         $changed = 1;
                   8685:     } else {
                   8686:         foreach my $field (@fields) {
                   8687:             if ($names{$field} ne $oldnames{$field}) {
                   8688:                 $changed = 1;
                   8689:                 last;
                   8690:             }
                   8691:         }
                   8692:     }
                   8693:     unless ($changed) {
                   8694:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8695:         &logthis($logmsg);
                   8696:         return 'ok';
                   8697:     }
                   8698:     my $reply = &put('environment', \%names, $udom,$uname);
                   8699:     if ($reply ne 'ok') { 
                   8700:         return 'error: '.$reply;
                   8701:     }
1.1087    raeburn  8702:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8703:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8704:     }
1.1075    raeburn  8705:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8706:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8707:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8708:     &logthis($logmsg);
1.134     albertel 8709:     return 'ok';
1.80      www      8710: }
                   8711: 
1.81      www      8712: # -------------------------------------------------------------- Modify student
1.80      www      8713: 
1.81      www      8714: sub modifystudent {
                   8715:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8716:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8717:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8718:     if (!$cid) {
1.620     albertel 8719: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8720: 	    return 'not_in_class';
                   8721: 	}
1.80      www      8722:     }
                   8723: # --------------------------------------------------------------- Make the user
1.81      www      8724:     my $reply=&modifyuser
1.209     matthew  8725: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8726:          $desiredhome,$email,$inststatus);
1.80      www      8727:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8728:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  8729:     # student's environment
1.297     matthew  8730:     $uid = undef if (!$forceid);
1.455     albertel 8731:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8732: 					$gene,$usec,$end,$start,$type,$locktype,
                   8733:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8734:     return $reply;
                   8735: }
                   8736: 
                   8737: sub modify_student_enrollment {
1.1172.2.23  raeburn  8738:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8739:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8740:     my ($cdom,$cnum,$chome);
                   8741:     if (!$cid) {
1.620     albertel 8742: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8743: 	    return 'not_in_class';
                   8744: 	}
1.620     albertel 8745: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8746: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8747:     } else {
                   8748: 	($cdom,$cnum)=split(/_/,$cid);
                   8749:     }
1.620     albertel 8750:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8751:     if (!$chome) {
1.457     raeburn  8752: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8753:     }
1.455     albertel 8754:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8755:     # Make sure the user exists
1.81      www      8756:     my $uhome=&homeserver($uname,$udom);
                   8757:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8758: 	return 'error: no such user';
                   8759:     }
1.297     matthew  8760:     # Get student data if we were not given enough information
                   8761:     if (!defined($first)  || $first  eq '' || 
                   8762:         !defined($last)   || $last   eq '' || 
                   8763:         !defined($uid)    || $uid    eq '' || 
                   8764:         !defined($middle) || $middle eq '' || 
                   8765:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8766:         # They did not supply us with enough data to enroll the student, so
                   8767:         # we need to pick up more information.
1.297     matthew  8768:         my %tmp = &get('environment',
1.294     matthew  8769:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8770:                        ,$udom,$uname);
                   8771: 
1.800     albertel 8772:         #foreach my $key (keys(%tmp)) {
                   8773:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8774:         #}
1.294     matthew  8775:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8776:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8777:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8778:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8779:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8780:     }
1.556     albertel 8781:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8782:     my $user = "$uname:$udom";
                   8783:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8784:     my $reply=cput('classlist',
1.1148    raeburn  8785: 		   {$user => 
1.1172.2.19  raeburn  8786: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8787: 		   $cdom,$cnum);
1.1148    raeburn  8788:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8789:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8790:     } else { 
1.81      www      8791: 	return 'error: '.$reply;
                   8792:     }
1.297     matthew  8793:     # Add student role to user
1.83      www      8794:     my $uurl='/'.$cid;
1.81      www      8795:     $uurl=~s/\_/\//g;
                   8796:     if ($usec) {
                   8797: 	$uurl.='/'.$usec;
                   8798:     }
1.1148    raeburn  8799:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8800:                              $selfenroll,$context);
                   8801:     if ($result ne 'ok') {
                   8802:         if ($old_entry{$user} ne '') {
                   8803:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8804:         } else {
                   8805:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8806:         }
                   8807:     }
                   8808:     return $result; 
1.21      www      8809: }
                   8810: 
1.556     albertel 8811: sub format_name {
                   8812:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8813:     my $name;
                   8814:     if ($first ne 'lastname') {
                   8815: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8816:     } else {
                   8817: 	if ($lastname=~/\S/) {
                   8818: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8819: 	    $name=~s/\s+,/,/;
                   8820: 	} else {
                   8821: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8822: 	}
                   8823:     }
                   8824:     $name=~s/^\s+//;
                   8825:     $name=~s/\s+$//;
                   8826:     $name=~s/\s+/ /g;
                   8827:     return $name;
                   8828: }
                   8829: 
1.84      www      8830: # ------------------------------------------------- Write to course preferences
                   8831: 
                   8832: sub writecoursepref {
                   8833:     my ($courseid,%prefs)=@_;
                   8834:     $courseid=~s/^\///;
                   8835:     $courseid=~s/\_/\//g;
                   8836:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8837:     my $chome=homeserver($cnum,$cdomain);
                   8838:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8839: 	return 'error: no such course';
                   8840:     }
                   8841:     my $cstring='';
1.800     albertel 8842:     foreach my $pref (keys(%prefs)) {
                   8843: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8844:     }
1.84      www      8845:     $cstring=~s/\&$//;
                   8846:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8847: }
                   8848: 
                   8849: # ---------------------------------------------------------- Make/modify course
                   8850: 
                   8851: sub createcourse {
1.741     raeburn  8852:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8853:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8854:     $url=&declutter($url);
                   8855:     my $cid='';
1.1028    raeburn  8856:     if ($context eq 'requestcourses') {
                   8857:         my $can_create = 0;
                   8858:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8859:         if ($udom eq $ownerdom) {
                   8860:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8861:                                   $context)) {
                   8862:                 $can_create = 1;
                   8863:             }
                   8864:         } else {
                   8865:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8866:                                            $category);
                   8867:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8868:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8869:                 if (@curr > 0) {
                   8870:                     my @options = qw(approval validate autolimit);
                   8871:                     my $optregex = join('|',@options);
                   8872:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8873:                         $can_create = 1;
                   8874:                     }
                   8875:                 }
                   8876:             }
                   8877:         }
                   8878:         if ($can_create) {
                   8879:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8880:                 unless (&allowed('ccc',$udom)) {
                   8881:                     return 'refused'; 
                   8882:                 }
1.1017    raeburn  8883:             }
                   8884:         } else {
                   8885:             return 'refused';
                   8886:         }
1.1028    raeburn  8887:     } elsif (!&allowed('ccc',$udom)) {
                   8888:         return 'refused';
1.84      www      8889:     }
1.1011    raeburn  8890: # --------------------------------------------------------------- Get Unique ID
                   8891:     my $uname;
                   8892:     if ($cnum =~ /^$match_courseid$/) {
                   8893:         my $chome=&homeserver($cnum,$udom,'true');
                   8894:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8895:             $uname = $cnum;
                   8896:         } else {
1.1038    raeburn  8897:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8898:         }
                   8899:     } else {
1.1038    raeburn  8900:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8901:     }
                   8902:     return $uname if ($uname =~ /^error/);
                   8903: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8904:     if (!defined($course_server)) {
                   8905:         if (defined(&domain($udom,'primary'))) {
                   8906:             $course_server = &domain($udom,'primary');
                   8907:         } else {
                   8908:             $course_server = $env{'user.home'}; 
                   8909:         }
                   8910:     }
                   8911:     my %host_servers =
                   8912:         &Apache::lonnet::get_servers($udom,'library');
                   8913:     unless ($host_servers{$course_server}) {
                   8914:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8915:     }
1.84      www      8916: # ------------------------------------------------------------- Make the course
                   8917:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8918:                       $course_server);
1.84      www      8919:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8920:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8921:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8922: 	return 'error: no such course';
                   8923:     }
1.271     www      8924: # ----------------------------------------------------------------- Course made
1.516     raeburn  8925: # log existence
1.1029    raeburn  8926:     my $now = time;
1.918     raeburn  8927:     my $newcourse = {
                   8928:                     $udom.'_'.$uname => {
1.921     raeburn  8929:                                      description => $description,
                   8930:                                      inst_code   => $inst_code,
                   8931:                                      owner       => $course_owner,
                   8932:                                      type        => $crstype,
1.1029    raeburn  8933:                                      creator     => $env{'user.name'}.':'.
                   8934:                                                     $env{'user.domain'},
                   8935:                                      created     => $now,
                   8936:                                      context     => $context,
1.918     raeburn  8937:                                                 },
                   8938:                     };
1.921     raeburn  8939:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8940: # set toplevel url
1.271     www      8941:     my $topurl=$url;
                   8942:     unless ($nonstandard) {
                   8943: # ------------------------------------------ For standard courses, make top url
                   8944:         my $mapurl=&clutter($url);
1.278     www      8945:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8946:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8947: <map>
                   8948: <resource id="1" type="start"></resource>
                   8949: <resource id="2" src="$mapurl"></resource>
                   8950: <resource id="3" type="finish"></resource>
                   8951: <link index="1" from="1" to="2"></link>
                   8952: <link index="2" from="2" to="3"></link>
                   8953: </map>
                   8954: ENDINITMAP
                   8955:         $topurl=&declutter(
1.638     albertel 8956:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8957:                           );
                   8958:     }
                   8959: # ----------------------------------------------------------- Write preferences
1.84      www      8960:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8961:                      ('description'              => $description,
                   8962:                       'url'                      => $topurl,
                   8963:                       'internal.creator'         => $env{'user.name'}.':'.
                   8964:                                                     $env{'user.domain'},
                   8965:                       'internal.created'         => $now,
                   8966:                       'internal.creationcontext' => $context)
                   8967:                     );
1.84      www      8968:     return '/'.$udom.'/'.$uname;
                   8969: }
                   8970: 
1.1011    raeburn  8971: # ------------------------------------------------------------------- Create ID
                   8972: sub generate_coursenum {
1.1038    raeburn  8973:     my ($udom,$crstype) = @_;
1.1011    raeburn  8974:     my $domdesc = &domain($udom);
                   8975:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8976:     my $first;
                   8977:     if ($crstype eq 'Community') {
                   8978:         $first = '0';
                   8979:     } else {
                   8980:         $first = int(1+rand(9)); 
                   8981:     } 
                   8982:     my $uname=$first.
1.1011    raeburn  8983:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8984:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8985:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8986: # ----------------------------------------------- Make sure that does not exist
                   8987:     my $uhome=&homeserver($uname,$udom,'true');
                   8988:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8989:         if ($crstype eq 'Community') {
                   8990:             $first = '0';
                   8991:         } else {
                   8992:             $first = int(1+rand(9));
                   8993:         }
                   8994:         $uname=$first.
1.1011    raeburn  8995:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8996:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8997:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8998:         $uhome=&homeserver($uname,$udom,'true');
                   8999:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9000:             return 'error: unable to generate unique course-ID';
                   9001:         }
                   9002:     }
                   9003:     return $uname;
                   9004: }
                   9005: 
1.813     albertel 9006: sub is_course {
1.1167    droeschl 9007:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9008:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9009: 
                   9010:     return unless $cdom and $cnum;
                   9011: 
                   9012:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9013:         '.');
                   9014: 
1.1172.2.23  raeburn  9015:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9016:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9017: }
                   9018: 
1.1015    raeburn  9019: sub store_userdata {
                   9020:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9021:     my $result;
1.1016    raeburn  9022:     if ($datakey ne '') {
1.1013    raeburn  9023:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9024:             if ($udom eq '' || $uname eq '') {
                   9025:                 $udom = $env{'user.domain'};
                   9026:                 $uname = $env{'user.name'};
                   9027:             }
                   9028:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9029:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9030:                 $result = 'error: no_host';
                   9031:             } else {
                   9032:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9033:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9034: 
                   9035:                 my $namevalue='';
                   9036:                 foreach my $key (keys(%{$storehash})) {
                   9037:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9038:                 }
                   9039:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9040:                 unless ($namespace eq 'courserequests') {
                   9041:                     $datakey = &escape($datakey);
                   9042:                 }
1.1105    raeburn  9043:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9044:                                   $namevalue,$uhome);
1.1013    raeburn  9045:             }
                   9046:         } else {
                   9047:             $result = 'error: data to store was not a hash reference'; 
                   9048:         }
                   9049:     } else {
                   9050:         $result= 'error: invalid requestkey'; 
                   9051:     }
                   9052:     return $result;
                   9053: }
                   9054: 
1.21      www      9055: # ---------------------------------------------------------- Assign Custom Role
                   9056: 
                   9057: sub assigncustomrole {
1.957     raeburn  9058:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9059:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9060:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9061: }
                   9062: 
                   9063: # ----------------------------------------------------------------- Revoke Role
                   9064: 
                   9065: sub revokerole {
1.957     raeburn  9066:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9067:     my $now=time;
1.965     raeburn  9068:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9069: }
                   9070: 
                   9071: # ---------------------------------------------------------- Revoke Custom Role
                   9072: 
                   9073: sub revokecustomrole {
1.957     raeburn  9074:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9075:     my $now=time;
1.357     www      9076:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9077:            $deleteflag,$selfenroll,$context);
1.17      www      9078: }
                   9079: 
1.533     banghart 9080: # ------------------------------------------------------------ Disk usage
1.535     albertel 9081: sub diskusage {
1.955     raeburn  9082:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9083:     $directorypath =~ s/\/$//;
                   9084:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9085:                        .&escape($getpropath).':'.&escape($uname).':'
                   9086:                        .&escape($udom),homeserver($uname,$udom));
                   9087:     if ($listing eq 'unknown_cmd') {
                   9088:         if ($getpropath) {
                   9089:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9090:         }
                   9091:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9092:     }
1.514     albertel 9093:     return $listing;
1.512     banghart 9094: }
                   9095: 
1.566     banghart 9096: sub is_locked {
1.1096    raeburn  9097:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9098:     my @check;
                   9099:     my $is_locked;
1.1093    raeburn  9100:     push (@check,$file_name);
1.613     albertel 9101:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9102: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9103:     my ($tmp)=keys(%locked);
                   9104:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9105:     
1.566     banghart 9106:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9107:         $is_locked = 'false';
                   9108:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9109:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9110:                $is_locked = 'true';
1.1096    raeburn  9111:                if (ref($which) eq 'ARRAY') {
                   9112:                    push(@{$which},$entry);
                   9113:                } else {
                   9114:                    last;
                   9115:                }
1.745     raeburn  9116:            }
                   9117:        }
1.566     banghart 9118:     } else {
                   9119:         $is_locked = 'false';
                   9120:     }
1.1093    raeburn  9121:     return $is_locked;
1.566     banghart 9122: }
                   9123: 
1.759     albertel 9124: sub declutter_portfile {
                   9125:     my ($file) = @_;
1.833     albertel 9126:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9127:     return $file;
                   9128: }
                   9129: 
1.559     banghart 9130: # ------------------------------------------------------------- Mark as Read Only
                   9131: 
                   9132: sub mark_as_readonly {
                   9133:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9134:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9135:     my ($tmp)=keys(%current_permissions);
                   9136:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9137:     foreach my $file (@{$files}) {
1.759     albertel 9138: 	$file = &declutter_portfile($file);
1.561     banghart 9139:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9140:     }
1.613     albertel 9141:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9142:     return;
                   9143: }
                   9144: 
1.572     banghart 9145: # ------------------------------------------------------------Save Selected Files
                   9146: 
                   9147: sub save_selected_files {
                   9148:     my ($user, $path, @files) = @_;
                   9149:     my $filename = $user."savedfiles";
1.573     banghart 9150:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9151:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9152:     foreach my $file (@files) {
1.620     albertel 9153:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9154:     }
                   9155:     foreach my $file (@other_files) {
1.574     banghart 9156:         print (OUT $file."\n");
1.572     banghart 9157:     }
1.574     banghart 9158:     close (OUT);
1.572     banghart 9159:     return 'ok';
                   9160: }
                   9161: 
1.574     banghart 9162: sub clear_selected_files {
                   9163:     my ($user) = @_;
                   9164:     my $filename = $user."savedfiles";
1.1117    foxr     9165:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9166:     print (OUT undef);
                   9167:     close (OUT);
                   9168:     return ("ok");    
                   9169: }
                   9170: 
1.572     banghart 9171: sub files_in_path {
                   9172:     my ($user, $path) = @_;
                   9173:     my $filename = $user."savedfiles";
                   9174:     my %return_files;
1.1117    foxr     9175:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9176:     while (my $line_in = <IN>) {
1.574     banghart 9177:         chomp ($line_in);
                   9178:         my @paths_and_file = split (m!/!, $line_in);
                   9179:         my $file_part = pop (@paths_and_file);
                   9180:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9181:         $path_part.='/';
                   9182:         my $path_and_file = $path_part.$file_part;
                   9183:         if ($path_part eq $path) {
                   9184:             $return_files{$file_part}= 'selected';
                   9185:         }
                   9186:     }
1.574     banghart 9187:     close (IN);
                   9188:     return (\%return_files);
1.572     banghart 9189: }
                   9190: 
                   9191: # called in portfolio select mode, to show files selected NOT in current directory
                   9192: sub files_not_in_path {
                   9193:     my ($user, $path) = @_;
                   9194:     my $filename = $user."savedfiles";
                   9195:     my @return_files;
                   9196:     my $path_part;
1.1117    foxr     9197:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9198:     while (my $line = <IN>) {
1.572     banghart 9199:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9200:         my @paths_and_file = split(m|/|, $line);
                   9201:         my $file_part = pop(@paths_and_file);
                   9202:         chomp($file_part);
                   9203:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9204:         $path_part .= '/';
                   9205:         my $path_and_file = $path_part.$file_part;
                   9206:         if ($path_part ne $path) {
1.800     albertel 9207:             push(@return_files, ($path_and_file));
1.572     banghart 9208:         }
                   9209:     }
1.800     albertel 9210:     close(OUT);
1.574     banghart 9211:     return (@return_files);
1.572     banghart 9212: }
                   9213: 
1.745     raeburn  9214: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9215: 
1.745     raeburn  9216: sub get_portfile_permissions {
                   9217:     my ($domain,$user) = @_;
1.613     albertel 9218:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9219:     my ($tmp)=keys(%current_permissions);
                   9220:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9221:     return \%current_permissions;
                   9222: }
                   9223: 
                   9224: #---------------------------------------------Get portfolio file access controls
                   9225: 
1.749     raeburn  9226: sub get_access_controls {
1.745     raeburn  9227:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9228:     my %access;
                   9229:     my $real_file = $file;
                   9230:     $file =~ s/\.meta$//;
1.745     raeburn  9231:     if (defined($file)) {
1.749     raeburn  9232:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9233:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9234:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9235:             }
                   9236:         }
1.745     raeburn  9237:     } else {
1.749     raeburn  9238:         foreach my $key (keys(%{$current_permissions})) {
                   9239:             if ($key =~ /\0accesscontrol$/) {
                   9240:                 if (defined($group)) {
                   9241:                     if ($key !~ m-^\Q$group\E/-) {
                   9242:                         next;
                   9243:                     }
                   9244:                 }
                   9245:                 my ($fullpath) = split(/\0/,$key);
                   9246:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9247:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9248:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9249:                     }
                   9250:                 }
                   9251:             }
                   9252:         }
                   9253:     }
                   9254:     return %access;
                   9255: }
                   9256: 
                   9257: sub modify_access_controls {
                   9258:     my ($file_name,$changes,$domain,$user)=@_;
                   9259:     my ($outcome,$deloutcome);
                   9260:     my %store_permissions;
                   9261:     my %new_values;
                   9262:     my %new_control;
                   9263:     my %translation;
                   9264:     my @deletions = ();
                   9265:     my $now = time;
                   9266:     if (exists($$changes{'activate'})) {
                   9267:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9268:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9269:             my $numnew = scalar(@newitems);
                   9270:             for (my $i=0; $i<$numnew; $i++) {
                   9271:                 my $newkey = $newitems[$i];
                   9272:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9273:                 if ($newkey =~ /^\d+:/) { 
                   9274:                     $newkey =~ s/^(\d+)/$newid/;
                   9275:                     $translation{$1} = $newid;
                   9276:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9277:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9278:                     $translation{$1} = $newid;
                   9279:                 }
1.749     raeburn  9280:                 $new_values{$file_name."\0".$newkey} = 
                   9281:                                           $$changes{'activate'}{$newitems[$i]};
                   9282:                 $new_control{$newkey} = $now;
                   9283:             }
                   9284:         }
                   9285:     }
                   9286:     my %todelete;
                   9287:     my %changed_items;
                   9288:     foreach my $action ('delete','update') {
                   9289:         if (exists($$changes{$action})) {
                   9290:             if (ref($$changes{$action}) eq 'HASH') {
                   9291:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9292:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9293:                     if ($action eq 'delete') { 
                   9294:                         $todelete{$itemnum} = 1;
                   9295:                     } else {
                   9296:                         $changed_items{$itemnum} = $key;
                   9297:                     }
                   9298:                 }
1.745     raeburn  9299:             }
                   9300:         }
1.749     raeburn  9301:     }
                   9302:     # get lock on access controls for file.
                   9303:     my $lockhash = {
                   9304:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9305:                                                        ':'.$env{'user.domain'},
                   9306:                    }; 
                   9307:     my $tries = 0;
                   9308:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9309:    
                   9310:     while (($gotlock ne 'ok') && $tries <3) {
                   9311:         $tries ++;
                   9312:         sleep 1;
                   9313:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9314:     }
                   9315:     if ($gotlock eq 'ok') {
                   9316:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9317:         my ($tmp)=keys(%curr_permissions);
                   9318:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9319:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9320:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9321:             if (ref($curr_controls) eq 'HASH') {
                   9322:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9323:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9324:                     if (defined($todelete{$itemnum})) {
                   9325:                         push(@deletions,$file_name."\0".$control_item);
                   9326:                     } else {
                   9327:                         if (defined($changed_items{$itemnum})) {
                   9328:                             $new_control{$changed_items{$itemnum}} = $now;
                   9329:                             push(@deletions,$file_name."\0".$control_item);
                   9330:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9331:                         } else {
                   9332:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9333:                         }
                   9334:                     }
1.745     raeburn  9335:                 }
                   9336:             }
                   9337:         }
1.970     raeburn  9338:         my ($group);
                   9339:         if (&is_course($domain,$user)) {
                   9340:             ($group,my $file) = split(/\//,$file_name,2);
                   9341:         }
1.749     raeburn  9342:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9343:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9344:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9345:         #  remove lock
                   9346:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9347:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9348:         my $sqlresult =
1.970     raeburn  9349:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9350:                                     $group);
1.749     raeburn  9351:     } else {
                   9352:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9353:     }
1.749     raeburn  9354:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9355: }
                   9356: 
1.827     raeburn  9357: sub make_public_indefinitely {
                   9358:     my ($requrl) = @_;
                   9359:     my $now = time;
                   9360:     my $action = 'activate';
                   9361:     my $aclnum = 0;
                   9362:     if (&is_portfolio_url($requrl)) {
                   9363:         my (undef,$udom,$unum,$file_name,$group) =
                   9364:             &parse_portfolio_url($requrl);
                   9365:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9366:         my %access_controls = &get_access_controls($current_perms,
                   9367:                                                    $group,$file_name);
                   9368:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9369:             my ($num,$scope,$end,$start) = 
                   9370:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9371:             if ($scope eq 'public') {
                   9372:                 if ($start <= $now && $end == 0) {
                   9373:                     $action = 'none';
                   9374:                 } else {
                   9375:                     $action = 'update';
                   9376:                     $aclnum = $num;
                   9377:                 }
                   9378:                 last;
                   9379:             }
                   9380:         }
                   9381:         if ($action eq 'none') {
                   9382:              return 'ok';
                   9383:         } else {
                   9384:             my %changes;
                   9385:             my $newend = 0;
                   9386:             my $newstart = $now;
                   9387:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9388:             $changes{$action}{$newkey} = {
                   9389:                 type => 'public',
                   9390:                 time => {
                   9391:                     start => $newstart,
                   9392:                     end   => $newend,
                   9393:                 },
                   9394:             };
                   9395:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9396:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9397:             return $outcome;
                   9398:         }
                   9399:     } else {
                   9400:         return 'invalid';
                   9401:     }
                   9402: }
                   9403: 
1.745     raeburn  9404: #------------------------------------------------------Get Marked as Read Only
                   9405: 
                   9406: sub get_marked_as_readonly {
                   9407:     my ($domain,$user,$what,$group) = @_;
                   9408:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9409:     my @readonly_files;
1.629     banghart 9410:     my $cmp1=$what;
                   9411:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9412:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9413:         if (defined($group)) {
                   9414:             if ($file_name !~ m-^\Q$group\E/-) {
                   9415:                 next;
                   9416:             }
                   9417:         }
1.561     banghart 9418:         if (ref($value) eq "ARRAY"){
                   9419:             foreach my $stored_what (@{$value}) {
1.629     banghart 9420:                 my $cmp2=$stored_what;
1.759     albertel 9421:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9422:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9423:                 }
1.629     banghart 9424:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9425:                     push(@readonly_files, $file_name);
1.745     raeburn  9426:                     last;
1.563     banghart 9427:                 } elsif (!defined($what)) {
                   9428:                     push(@readonly_files, $file_name);
1.745     raeburn  9429:                     last;
1.561     banghart 9430:                 }
                   9431:             }
1.745     raeburn  9432:         }
1.561     banghart 9433:     }
                   9434:     return @readonly_files;
                   9435: }
1.577     banghart 9436: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9437: 
1.577     banghart 9438: sub get_marked_as_readonly_hash {
1.745     raeburn  9439:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9440:     my %readonly_files;
1.745     raeburn  9441:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9442:         if (defined($group)) {
                   9443:             if ($file_name !~ m-^\Q$group\E/-) {
                   9444:                 next;
                   9445:             }
                   9446:         }
1.577     banghart 9447:         if (ref($value) eq "ARRAY"){
                   9448:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9449:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9450:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9451:                         if ($lock_descriptor eq 'graded') {
                   9452:                             $readonly_files{$file_name} = 'graded';
                   9453:                         } elsif ($lock_descriptor eq 'handback') {
                   9454:                             $readonly_files{$file_name} = 'handback';
                   9455:                         } else {
                   9456:                             if (!exists($readonly_files{$file_name})) {
                   9457:                                 $readonly_files{$file_name} = 'locked';
                   9458:                             }
                   9459:                         }
1.745     raeburn  9460:                     }
1.750     banghart 9461:                 } 
1.577     banghart 9462:             }
                   9463:         } 
                   9464:     }
                   9465:     return %readonly_files;
                   9466: }
1.559     banghart 9467: # ------------------------------------------------------------ Unmark as Read Only
                   9468: 
                   9469: sub unmark_as_readonly {
1.629     banghart 9470:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9471:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9472:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9473:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9474:     my $symb_crs = $what;
                   9475:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9476:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9477:     my ($tmp)=keys(%current_permissions);
                   9478:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9479:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9480:     foreach my $file (@readonly_files) {
1.759     albertel 9481: 	my $clean_file = &declutter_portfile($file);
                   9482: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9483: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9484:         my @new_locks;
                   9485:         my @del_keys;
                   9486:         if (ref($current_locks) eq "ARRAY"){
                   9487:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9488:                 my $compare=$locker;
1.749     raeburn  9489:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9490:                     $compare=join('',@{$locker});
1.746     raeburn  9491:                     if ($compare ne $symb_crs) {
                   9492:                         push(@new_locks, $locker);
                   9493:                     }
1.563     banghart 9494:                 }
                   9495:             }
1.650     albertel 9496:             if (scalar(@new_locks) > 0) {
1.563     banghart 9497:                 $current_permissions{$file} = \@new_locks;
                   9498:             } else {
                   9499:                 push(@del_keys, $file);
1.613     albertel 9500:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9501:                 delete($current_permissions{$file});
1.563     banghart 9502:             }
                   9503:         }
1.561     banghart 9504:     }
1.613     albertel 9505:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9506:     return;
                   9507: }
1.512     banghart 9508: 
1.17      www      9509: # ------------------------------------------------------------ Directory lister
                   9510: 
                   9511: sub dirlist {
1.955     raeburn  9512:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9513:     $uri=~s/^\///;
                   9514:     $uri=~s/\/$//;
1.253     stredwic 9515:     my ($udom, $uname);
1.955     raeburn  9516:     if ($getuserdir) {
1.253     stredwic 9517:         $udom = $userdomain;
                   9518:         $uname = $username;
1.955     raeburn  9519:     } else {
                   9520:         (undef,$udom,$uname)=split(/\//,$uri);
                   9521:         if(defined($userdomain)) {
                   9522:             $udom = $userdomain;
                   9523:         }
                   9524:         if(defined($username)) {
                   9525:             $uname = $username;
                   9526:         }
1.253     stredwic 9527:     }
1.955     raeburn  9528:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9529: 
1.955     raeburn  9530:     $dirRoot = $perlvar{'lonDocRoot'};
                   9531:     if (defined($getpropath)) {
                   9532:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9533:         $dirRoot =~ s/\/$//;
1.955     raeburn  9534:     } elsif (defined($getuserdir)) {
                   9535:         my $subdir=$uname.'__';
                   9536:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9537:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9538:                    ."/$udom/$subdir/$uname";
                   9539:     } elsif (defined($alternateRoot)) {
                   9540:         $dirRoot = $alternateRoot;
1.751     banghart 9541:     }
1.253     stredwic 9542: 
                   9543:     if($udom) {
                   9544:         if($uname) {
1.1135    raeburn  9545:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9546:             if ($uhome eq 'no_host') {
                   9547:                 return ([],'no_host');
                   9548:             }
1.955     raeburn  9549:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9550:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9551:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9552:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9553:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9554:             } else {
                   9555:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9556:             }
1.605     matthew  9557:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9558:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9559:                 @listing_results = split(/:/,$listing);
                   9560:             } else {
                   9561:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9562:             }
1.1135    raeburn  9563:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9564:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9565:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9566:                 return ([],$listing);
                   9567:             } else {
                   9568:                 return (\@listing_results);
1.1135    raeburn  9569:             }
1.955     raeburn  9570:         } elsif(!$alternateRoot) {
1.1136    raeburn  9571:             my (%allusers,%listerror);
1.841     albertel 9572: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9573:  	    foreach my $tryserver (keys(%servers)) {
                   9574:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9575:                                   &escape($udom),$tryserver);
                   9576:                 if ($listing eq 'unknown_cmd') {
                   9577: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9578: 				      $udom, $tryserver);
                   9579:                 } else {
                   9580:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9581:                 }
1.841     albertel 9582: 		if ($listing eq 'unknown_cmd') {
                   9583: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9584: 				      $udom, $tryserver);
                   9585: 		    @listing_results = split(/:/,$listing);
                   9586: 		} else {
                   9587: 		    @listing_results =
                   9588: 			map { &unescape($_); } split(/:/,$listing);
                   9589: 		}
1.1136    raeburn  9590:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9591:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9592:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9593:                     $listerror{$tryserver} = $listing;
                   9594:                 } else {
1.841     albertel 9595: 		    foreach my $line (@listing_results) {
                   9596: 			my ($entry) = split(/&/,$line,2);
                   9597: 			$allusers{$entry} = 1;
                   9598: 		    }
                   9599: 		}
1.253     stredwic 9600:             }
1.1136    raeburn  9601:             my @alluserslist=();
1.800     albertel 9602:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9603:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9604:             }
1.1136    raeburn  9605:             return (\@alluserslist);
1.253     stredwic 9606:         } else {
1.1136    raeburn  9607:             return ([],'missing username');
1.253     stredwic 9608:         }
1.955     raeburn  9609:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9610:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9611:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9612:         return (\@all_domains);
1.955     raeburn  9613:     } else {
1.1136    raeburn  9614:         return ([],'missing domain');
1.275     stredwic 9615:     }
                   9616: }
                   9617: 
                   9618: # --------------------------------------------- GetFileTimestamp
                   9619: # This function utilizes dirlist and returns the date stamp for
                   9620: # when it was last modified.  It will also return an error of -1
                   9621: # if an error occurs
                   9622: 
                   9623: sub GetFileTimestamp {
1.955     raeburn  9624:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9625:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9626:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9627:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9628:                                     undef,$getuserdir);
                   9629:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9630:         return -1;
                   9631:     }
                   9632:     if (ref($fileref) eq 'ARRAY') {
                   9633:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9634:         # @stats contains first the filename, then the stat output
                   9635:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9636:     } else {
                   9637:         return -1;
1.253     stredwic 9638:     }
1.26      www      9639: }
                   9640: 
1.712     albertel 9641: sub stat_file {
                   9642:     my ($uri) = @_;
1.787     albertel 9643:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9644: 
1.955     raeburn  9645:     my ($udom,$uname,$file);
1.712     albertel 9646:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9647: 	($udom,$uname,$file) =
1.811     albertel 9648: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9649: 	$file = 'userfiles/'.$file;
                   9650:     }
                   9651:     if ($uri =~ m-^/res/-) {
                   9652: 	($udom,$uname) = 
1.807     albertel 9653: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9654: 	$file = $uri;
                   9655:     }
                   9656: 
                   9657:     if (!$udom || !$uname || !$file) {
                   9658: 	# unable to handle the uri
                   9659: 	return ();
                   9660:     }
1.956     raeburn  9661:     my $getpropath;
                   9662:     if ($file =~ /^userfiles\//) {
                   9663:         $getpropath = 1;
                   9664:     }
1.1136    raeburn  9665:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9666:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9667:         return ();
                   9668:     } else {
                   9669:         if (ref($listref) eq 'ARRAY') {
                   9670:             my @stats = split('&',$listref->[0]);
                   9671: 	    shift(@stats); #filename is first
                   9672: 	    return @stats;
                   9673:         }
1.712     albertel 9674:     }
                   9675:     return ();
                   9676: }
                   9677: 
1.26      www      9678: # -------------------------------------------------------- Value of a Condition
                   9679: 
1.713     albertel 9680: # gets the value of a specific preevaluated condition
                   9681: #    stored in the string  $env{user.state.<cid>}
                   9682: # or looks up a condition reference in the bighash and if if hasn't
                   9683: # already been evaluated recurses into docondval to get the value of
                   9684: # the condition, then memoizing it to 
                   9685: #   $env{user.state.<cid>.<condition>}
1.40      www      9686: sub directcondval {
                   9687:     my $number=shift;
1.620     albertel 9688:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9689: 	&Apache::lonuserstate::evalstate();
                   9690:     }
1.713     albertel 9691:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9692: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9693:     } elsif ($number =~ /^_/) {
                   9694: 	my $sub_condition;
                   9695: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9696: 		&GDBM_READER(),0640)) {
                   9697: 	    $sub_condition=$bighash{'conditions'.$number};
                   9698: 	    untie(%bighash);
                   9699: 	}
                   9700: 	my $value = &docondval($sub_condition);
1.949     raeburn  9701: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9702: 	return $value;
                   9703:     }
1.620     albertel 9704:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9705:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9706:     } else {
                   9707:        return 2;
                   9708:     }
                   9709: }
                   9710: 
1.713     albertel 9711: # get the collection of conditions for this resource
1.26      www      9712: sub condval {
                   9713:     my $condidx=shift;
1.54      www      9714:     my $allpathcond='';
1.713     albertel 9715:     foreach my $cond (split(/\|/,$condidx)) {
                   9716: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9717: 	    $allpathcond.=
                   9718: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9719: 	}
1.191     harris41 9720:     }
1.54      www      9721:     $allpathcond=~s/\|$//;
1.713     albertel 9722:     return &docondval($allpathcond);
                   9723: }
                   9724: 
                   9725: #evaluates an expression of conditions
                   9726: sub docondval {
                   9727:     my ($allpathcond) = @_;
                   9728:     my $result=0;
                   9729:     if ($env{'request.course.id'}
                   9730: 	&& defined($allpathcond)) {
                   9731: 	my $operand='|';
                   9732: 	my @stack;
                   9733: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9734: 	    if ($chunk eq '(') {
                   9735: 		push @stack,($operand,$result);
                   9736: 	    } elsif ($chunk eq ')') {
                   9737: 		my $before=pop @stack;
                   9738: 		if (pop @stack eq '&') {
                   9739: 		    $result=$result>$before?$before:$result;
                   9740: 		} else {
                   9741: 		    $result=$result>$before?$result:$before;
                   9742: 		}
                   9743: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9744: 		$operand=$chunk;
                   9745: 	    } else {
                   9746: 		my $new=directcondval($chunk);
                   9747: 		if ($operand eq '&') {
                   9748: 		    $result=$result>$new?$new:$result;
                   9749: 		} else {
                   9750: 		    $result=$result>$new?$result:$new;
                   9751: 		}
                   9752: 	    }
                   9753: 	}
1.26      www      9754:     }
                   9755:     return $result;
1.421     albertel 9756: }
                   9757: 
                   9758: # ---------------------------------------------------- Devalidate courseresdata
                   9759: 
                   9760: sub devalidatecourseresdata {
                   9761:     my ($coursenum,$coursedomain)=@_;
                   9762:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9763:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9764: }
                   9765: 
1.763     www      9766: 
1.200     www      9767: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9768: #
                   9769: #  Parameters:
                   9770: #      $coursenum    - Number of the course.
                   9771: #      $coursedomain - Domain at which the course was created.
                   9772: #  Returns:
                   9773: #     A hash of the course parameters along (I think) with timestamps
                   9774: #     and version info.
1.877     foxr     9775: 
1.624     albertel 9776: sub get_courseresdata {
                   9777:     my ($coursenum,$coursedomain)=@_;
1.200     www      9778:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9779:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9780:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9781:     my %dumpreply;
1.417     albertel 9782:     unless (defined($cached)) {
1.624     albertel 9783: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9784: 	$result=\%dumpreply;
1.251     albertel 9785: 	my ($tmp) = keys(%dumpreply);
                   9786: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9787: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9788: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9789: 	    return $tmp;
1.416     albertel 9790: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9791: 	    $result=undef;
1.599     albertel 9792: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9793: 	}
                   9794:     }
1.624     albertel 9795:     return $result;
                   9796: }
                   9797: 
1.633     albertel 9798: sub devalidateuserresdata {
                   9799:     my ($uname,$udom)=@_;
                   9800:     my $hashid="$udom:$uname";
                   9801:     &devalidate_cache_new('userres',$hashid);
                   9802: }
                   9803: 
1.624     albertel 9804: sub get_userresdata {
                   9805:     my ($uname,$udom)=@_;
                   9806:     #most student don\'t have any data set, check if there is some data
                   9807:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9808: 
                   9809:     my $hashid="$udom:$uname";
                   9810:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9811:     if (!defined($cached)) {
                   9812: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9813: 	$result=\%resourcedata;
                   9814: 	&do_cache_new('userres',$hashid,$result,600);
                   9815:     }
                   9816:     my ($tmp)=keys(%$result);
                   9817:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9818: 	return $result;
                   9819:     }
                   9820:     #error 2 occurs when the .db doesn't exist
                   9821:     if ($tmp!~/error: 2 /) {
1.672     albertel 9822: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9823: 		 " Trying to get resource data for ".
                   9824: 		 $uname." at ".$udom.": ".
                   9825: 		 $tmp."</font>");
                   9826:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9827: 	#&EXT_cache_set($udom,$uname);
                   9828: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9829: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9830:     }
                   9831:     return $tmp;
                   9832: }
1.879     foxr     9833: #----------------------------------------------- resdata - return resource data
                   9834: #  Purpose:
                   9835: #    Return resource data for either users or for a course.
                   9836: #  Parameters:
                   9837: #     $name      - Course/user name.
                   9838: #     $domain    - Name of the domain the user/course is registered on.
                   9839: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9840: #     @which     - Array of names of resources desired.
                   9841: #  Returns:
                   9842: #     The value of the first reasource in @which that is found in the
                   9843: #     resource hash.
                   9844: #  Exceptional Conditions:
                   9845: #     If the $type passed in is not valid (not the string 'course' or 
                   9846: #     'user', an undefined  reference is returned.
                   9847: #     If none of the resources are found, an undef is returned
1.624     albertel 9848: sub resdata {
                   9849:     my ($name,$domain,$type,@which)=@_;
                   9850:     my $result;
                   9851:     if ($type eq 'course') {
                   9852: 	$result=&get_courseresdata($name,$domain);
                   9853:     } elsif ($type eq 'user') {
                   9854: 	$result=&get_userresdata($name,$domain);
                   9855:     }
                   9856:     if (!ref($result)) { return $result; }    
1.251     albertel 9857:     foreach my $item (@which) {
1.927     albertel 9858: 	if (defined($result->{$item->[0]})) {
                   9859: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9860: 	}
1.250     albertel 9861:     }
1.291     albertel 9862:     return undef;
1.200     www      9863: }
                   9864: 
1.1172.2.31  raeburn  9865: sub get_numsuppfiles {
                   9866:     my ($cnum,$cdom,$ignorecache)=@_;
                   9867:     my $hashid=$cnum.':'.$cdom;
                   9868:     my ($suppcount,$cached);
                   9869:     unless ($ignorecache) {
                   9870:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9871:     }
                   9872:     unless (defined($cached)) {
                   9873:         my $chome=&homeserver($cnum,$cdom);
                   9874:         unless ($chome eq 'no_host') {
                   9875:             ($suppcount,my $errors) = (0,0);
                   9876:             my $suppmap = 'supplemental.sequence';
                   9877:             ($suppcount,$errors) =
                   9878:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9879:         }
                   9880:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9881:     }
                   9882:     return $suppcount;
                   9883: }
                   9884: 
1.379     matthew  9885: #
                   9886: # EXT resource caching routines
                   9887: #
                   9888: 
                   9889: sub clear_EXT_cache_status {
1.383     albertel 9890:     &delenv('cache.EXT.');
1.379     matthew  9891: }
                   9892: 
                   9893: sub EXT_cache_status {
                   9894:     my ($target_domain,$target_user) = @_;
1.383     albertel 9895:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9896:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9897:         # We know already the user has no data
                   9898:         return 1;
                   9899:     } else {
                   9900:         return 0;
                   9901:     }
                   9902: }
                   9903: 
                   9904: sub EXT_cache_set {
                   9905:     my ($target_domain,$target_user) = @_;
1.383     albertel 9906:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9907:     #&appenv({$cachename => time});
1.379     matthew  9908: }
                   9909: 
1.28      www      9910: # --------------------------------------------------------- Value of a Variable
1.58      www      9911: sub EXT {
1.715     albertel 9912: 
1.1172.2.28  raeburn  9913:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9914:     unless ($varname) { return ''; }
1.218     albertel 9915:     #get real user name/domain, courseid and symb
                   9916:     my $courseid;
1.359     albertel 9917:     my $publicuser;
1.427     www      9918:     if ($symbparm) {
                   9919: 	$symbparm=&get_symb_from_alias($symbparm);
                   9920:     }
1.218     albertel 9921:     if (!($uname && $udom)) {
1.790     albertel 9922:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9923:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9924:     } else {
1.620     albertel 9925: 	$courseid=$env{'request.course.id'};
1.218     albertel 9926:     }
1.48      www      9927:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9928:     my $rest;
1.320     albertel 9929:     if (defined($therest[0])) {
1.48      www      9930:        $rest=join('.',@therest);
                   9931:     } else {
                   9932:        $rest='';
                   9933:     }
1.320     albertel 9934: 
1.57      www      9935:     my $qualifierrest=$qualifier;
                   9936:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9937:     my $spacequalifierrest=$space;
                   9938:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9939:     if ($realm eq 'user') {
1.48      www      9940: # --------------------------------------------------------------- user.resource
                   9941: 	if ($space eq 'resource') {
1.651     albertel 9942: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9943: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9944: 		 &&
1.744     albertel 9945: 		 ($symbparm eq &symbread()) ) {	
                   9946: 		# if we are in the middle of processing the resource the
                   9947: 		# get the value we are planning on committing
                   9948:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9949:                     return $Apache::lonhomework::results{$qualifierrest};
                   9950:                 } else {
                   9951:                     return $Apache::lonhomework::history{$qualifierrest};
                   9952:                 }
1.335     albertel 9953: 	    } else {
1.359     albertel 9954: 		my %restored;
1.620     albertel 9955: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9956: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9957: 		} else {
                   9958: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9959: 		}
1.335     albertel 9960: 		return $restored{$qualifierrest};
                   9961: 	    }
1.48      www      9962: # ----------------------------------------------------------------- user.access
                   9963:         } elsif ($space eq 'access') {
1.218     albertel 9964: 	    # FIXME - not supporting calls for a specific user
1.48      www      9965:             return &allowed($qualifier,$rest);
                   9966: # ------------------------------------------ user.preferences, user.environment
                   9967:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9968: 	    if (($uname eq $env{'user.name'}) &&
                   9969: 		($udom eq $env{'user.domain'})) {
                   9970: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9971: 	    } else {
1.359     albertel 9972: 		my %returnhash;
                   9973: 		if (!$publicuser) {
                   9974: 		    %returnhash=&userenvironment($udom,$uname,
                   9975: 						 $qualifierrest);
                   9976: 		}
1.218     albertel 9977: 		return $returnhash{$qualifierrest};
                   9978: 	    }
1.48      www      9979: # ----------------------------------------------------------------- user.course
                   9980:         } elsif ($space eq 'course') {
1.218     albertel 9981: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9982:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9983: # ------------------------------------------------------------------- user.role
                   9984:         } elsif ($space eq 'role') {
1.218     albertel 9985: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9986:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9987:             if ($qualifier eq 'value') {
                   9988: 		return $role;
                   9989:             } elsif ($qualifier eq 'extent') {
                   9990:                 return $where;
                   9991:             }
                   9992: # ----------------------------------------------------------------- user.domain
                   9993:         } elsif ($space eq 'domain') {
1.218     albertel 9994:             return $udom;
1.48      www      9995: # ------------------------------------------------------------------- user.name
                   9996:         } elsif ($space eq 'name') {
1.218     albertel 9997:             return $uname;
1.48      www      9998: # ---------------------------------------------------- Any other user namespace
1.29      www      9999:         } else {
1.359     albertel 10000: 	    my %reply;
                   10001: 	    if (!$publicuser) {
                   10002: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10003: 	    }
                   10004: 	    return $reply{$qualifierrest};
1.48      www      10005:         }
1.236     www      10006:     } elsif ($realm eq 'query') {
                   10007: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10008:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10009: 						[$spacequalifierrest]);
1.620     albertel 10010: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10011:    } elsif ($realm eq 'request') {
1.48      www      10012: # ------------------------------------------------------------- request.browser
                   10013:         if ($space eq 'browser') {
1.1145    bisitz   10014:             return $env{'browser.'.$qualifier};
1.57      www      10015: # ------------------------------------------------------------ request.filename
                   10016:         } else {
1.620     albertel 10017:             return $env{'request.'.$spacequalifierrest};
1.29      www      10018:         }
1.28      www      10019:     } elsif ($realm eq 'course') {
1.48      www      10020: # ---------------------------------------------------------- course.description
1.620     albertel 10021:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10022:     } elsif ($realm eq 'resource') {
1.165     www      10023: 
1.620     albertel 10024: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10025: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10026: 	}
1.693     albertel 10027: 
1.1172.2.30  raeburn  10028:         if ($qualifier eq '') {
                   10029: 	    if ($space eq 'title') {
                   10030: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10031: 	        return &gettitle($symbparm);
                   10032: 	    }
1.693     albertel 10033: 	
1.1172.2.30  raeburn  10034: 	    if ($space eq 'map') {
                   10035: 	        my ($map) = &decode_symb($symbparm);
                   10036: 	        return &symbread($map);
                   10037: 	    }
                   10038:             if ($space eq 'maptitle') {
                   10039:                 my ($map) = &decode_symb($symbparm);
                   10040:                 return &gettitle($map);
                   10041:             }
                   10042: 	    if ($space eq 'filename') {
                   10043: 	        if ($symbparm) {
                   10044: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10045: 	        }
                   10046: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10047: 	    }
1.1172.2.30  raeburn  10048: 
                   10049:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10050:                 if ($space eq 'visibleparts') {
                   10051:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10052:                     my $item;
                   10053:                     if (ref($navmap)) {
                   10054:                         my $res = $navmap->getBySymb($symbparm);
                   10055:                         my $parts = $res->parts();
                   10056:                         if (ref($parts) eq 'ARRAY') {
                   10057:                             $item = join(',',@{$parts});
                   10058:                         }
                   10059:                         undef($navmap);
                   10060:                     }
                   10061:                     return $item;
                   10062:                 }
                   10063:             }
                   10064:         }
1.693     albertel 10065: 
                   10066: 	my ($section, $group, @groups);
1.593     albertel 10067: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10068:         if (($courseid eq '') && ($cid)) {
                   10069:             $courseid = $cid;
                   10070:         }
                   10071: 	if (($symbparm && $courseid) && 
                   10072: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10073: 
1.218     albertel 10074: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10075: 
1.60      www      10076: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10077: 	    my $symbp=$symbparm;
1.735     albertel 10078: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10079: 
                   10080: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10081: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10082: 
1.620     albertel 10083: 	    if (($env{'user.name'} eq $uname) &&
                   10084: 		($env{'user.domain'} eq $udom)) {
                   10085: 		$section=$env{'request.course.sec'};
1.733     raeburn  10086:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10087:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10088: 	    } else {
1.539     albertel 10089: 		if (! defined($usection)) {
1.551     albertel 10090: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10091: 		} else {
                   10092: 		    $section = $usection;
                   10093: 		}
1.733     raeburn  10094:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10095: 	    }
                   10096: 
                   10097: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10098: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10099: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10100: 
1.593     albertel 10101: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10102: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10103: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10104: 
1.60      www      10105: # ----------------------------------------------------------- first, check user
1.624     albertel 10106: 
                   10107: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10108: 				       ([$courselevelr,'resource'],
                   10109: 					[$courselevelm,'map'     ],
                   10110: 					[$courselevel, 'course'  ]));
1.931     albertel 10111: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10112: 
1.594     albertel 10113: # ------------------------------------------------ second, check some of course
1.684     raeburn  10114:             my $coursereply;
1.691     raeburn  10115:             if (@groups > 0) {
                   10116:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10117:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10118:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10119:             }
1.96      www      10120: 
1.684     raeburn  10121: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10122: 				  $env{'course.'.$courseid.'.domain'},
                   10123: 				  'course',
                   10124: 				  ([$seclevelr,   'resource'],
                   10125: 				   [$seclevelm,   'map'     ],
                   10126: 				   [$seclevel,    'course'  ],
                   10127: 				   [$courselevelr,'resource']));
                   10128: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10129: 
1.60      www      10130: # ------------------------------------------------------ third, check map parms
1.218     albertel 10131: 	    my %parmhash=();
                   10132: 	    my $thisparm='';
                   10133: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10134: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10135: 		    &GDBM_READER(),0640)) {
1.218     albertel 10136: 		$thisparm=$parmhash{$symbparm};
                   10137: 		untie(%parmhash);
                   10138: 	    }
1.927     albertel 10139: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10140: 	}
1.594     albertel 10141: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10142: 
1.218     albertel 10143: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10144: 	my $filename;
                   10145: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10146: 	if ($symbparm) {
1.409     www      10147: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10148: 	} else {
1.620     albertel 10149: 	    $filename=$env{'request.filename'};
1.282     albertel 10150: 	}
                   10151: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10152: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10153: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10154: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10155: 
1.927     albertel 10156: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10157: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10158: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10159: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10160: 				     $env{'course.'.$courseid.'.domain'},
                   10161: 				     'course',
1.927     albertel 10162: 				     ([$courselevelm,'map'   ],
                   10163: 				      [$courselevel, 'course']));
                   10164: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10165: 	}
1.145     www      10166: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10167: 	unless ($space eq '0') {
1.336     albertel 10168: 	    my @parts=split(/_/,$space);
                   10169: 	    my $id=pop(@parts);
                   10170: 	    my $part=join('_',@parts);
                   10171: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10172: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10173: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10174: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10175: 	}
1.395     albertel 10176: 	if ($recurse) { return undef; }
                   10177: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10178: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10179: # ---------------------------------------------------- Any other user namespace
                   10180:     } elsif ($realm eq 'environment') {
                   10181: # ----------------------------------------------------------------- environment
1.620     albertel 10182: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10183: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10184: 	} else {
1.770     albertel 10185: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10186: 		return '';
                   10187: 	    }
1.219     albertel 10188: 	    my %returnhash=&userenvironment($udom,$uname,
                   10189: 					    $spacequalifierrest);
                   10190: 	    return $returnhash{$spacequalifierrest};
                   10191: 	}
1.28      www      10192:     } elsif ($realm eq 'system') {
1.48      www      10193: # ----------------------------------------------------------------- system.time
                   10194: 	if ($space eq 'time') {
                   10195: 	    return time;
                   10196:         }
1.696     albertel 10197:     } elsif ($realm eq 'server') {
                   10198: # ----------------------------------------------------------------- system.time
                   10199: 	if ($space eq 'name') {
                   10200: 	    return $ENV{'SERVER_NAME'};
                   10201:         }
1.28      www      10202:     }
1.48      www      10203:     return '';
1.61      www      10204: }
                   10205: 
1.927     albertel 10206: sub get_reply {
                   10207:     my ($reply_value) = @_;
1.940     raeburn  10208:     if (ref($reply_value) eq 'ARRAY') {
                   10209:         if (wantarray) {
                   10210: 	    return @$reply_value;
                   10211:         }
                   10212:         return $reply_value->[0];
                   10213:     } else {
                   10214:         return $reply_value;
1.927     albertel 10215:     }
                   10216: }
                   10217: 
1.691     raeburn  10218: sub check_group_parms {
                   10219:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10220:     my @groupitems = ();
                   10221:     my $resultitem;
1.927     albertel 10222:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10223:     foreach my $group (@{$groups}) {
                   10224:         foreach my $level (@levels) {
1.927     albertel 10225:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10226:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10227:         }
                   10228:     }
                   10229:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10230:                             $env{'course.'.$courseid.'.domain'},
                   10231:                                      'course',@groupitems);
                   10232:     return $coursereply;
                   10233: }
                   10234: 
                   10235: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10236:     my ($courseid,@groups) = @_;
                   10237:     @groups = sort(@groups);
1.691     raeburn  10238:     return @groups;
                   10239: }
                   10240: 
1.395     albertel 10241: sub packages_tab_default {
                   10242:     my ($uri,$varname)=@_;
                   10243:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10244: 
                   10245:     my (@extension,@specifics,$do_default);
                   10246:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10247: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10248: 	if ($pack_type eq 'default') {
                   10249: 	    $do_default=1;
                   10250: 	} elsif ($pack_type eq 'extension') {
                   10251: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10252: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10253: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10254: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10255: 	}
                   10256:     }
                   10257:     # first look for a package that matches the requested part id
                   10258:     foreach my $package (@specifics) {
                   10259: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10260: 	next if ($pack_part ne $part);
                   10261: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10262: 	    return $packagetab{"$pack_type&$name&default"};
                   10263: 	}
                   10264:     }
                   10265:     # look for any possible matching non extension_ package
                   10266:     foreach my $package (@specifics) {
                   10267: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10268: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10269: 	    return $packagetab{"$pack_type&$name&default"};
                   10270: 	}
1.585     albertel 10271: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10272: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10273: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10274: 	}
                   10275:     }
1.738     albertel 10276:     # look for any posible extension_ match
                   10277:     foreach my $package (@extension) {
                   10278: 	my ($package,$pack_type)=@{$package};
                   10279: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10280: 	    return $packagetab{"$pack_type&$name&default"};
                   10281: 	}
                   10282: 	if (defined($packagetab{$package."&$name&default"})) {
                   10283: 	    return $packagetab{$package."&$name&default"};
                   10284: 	}
                   10285:     }
                   10286:     # look for a global default setting
                   10287:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10288: 	return $packagetab{"default&$name&default"};
                   10289:     }
1.395     albertel 10290:     return undef;
                   10291: }
                   10292: 
1.334     albertel 10293: sub add_prefix_and_part {
                   10294:     my ($prefix,$part)=@_;
                   10295:     my $keyroot;
                   10296:     if (defined($prefix) && $prefix !~ /^__/) {
                   10297: 	# prefix that has a part already
                   10298: 	$keyroot=$prefix;
                   10299:     } elsif (defined($prefix)) {
                   10300: 	# prefix that is missing a part
                   10301: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10302:     } else {
                   10303: 	# no prefix at all
                   10304: 	if (defined($part)) { $keyroot='_'.$part; }
                   10305:     }
                   10306:     return $keyroot;
                   10307: }
                   10308: 
1.71      www      10309: # ---------------------------------------------------------------- Get metadata
                   10310: 
1.599     albertel 10311: my %metaentry;
1.1070    www      10312: my %importedpartids;
1.71      www      10313: sub metadata {
1.176     www      10314:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10315:     $uri=&declutter($uri);
1.288     albertel 10316:     # if it is a non metadata possible uri return quickly
1.529     albertel 10317:     if (($uri eq '') || 
                   10318: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10319: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10320:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10321: 	return undef;
                   10322:     }
1.1172.2.49  raeburn  10323:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10324: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10325: 	return undef;
1.288     albertel 10326:     }
1.73      www      10327:     my $filename=$uri;
                   10328:     $uri=~s/\.meta$//;
1.172     www      10329: #
                   10330: # Is the metadata already cached?
1.177     www      10331: # Look at timestamp of caching
1.172     www      10332: # Everything is cached by the main uri, libraries are never directly cached
                   10333: #
1.428     albertel 10334:     if (!defined($liburi)) {
1.599     albertel 10335: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10336: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10337:     }
                   10338:     {
1.1069    www      10339: # Imported parts would go here
1.1070    www      10340:         my %importedids=();
                   10341:         my @origfileimportpartids=();
1.1069    www      10342:         my $importedparts=0;
1.172     www      10343: #
                   10344: # Is this a recursive call for a library?
                   10345: #
1.599     albertel 10346: #	if (! exists($metacache{$uri})) {
                   10347: #	    $metacache{$uri}={};
                   10348: #	}
1.924     albertel 10349: 	my $cachetime = 60*60;
1.171     www      10350:         if ($liburi) {
                   10351: 	    $liburi=&declutter($liburi);
                   10352:             $filename=$liburi;
1.401     bowersj2 10353:         } else {
1.599     albertel 10354: 	    &devalidate_cache_new('meta',$uri);
                   10355: 	    undef(%metaentry);
1.401     bowersj2 10356: 	}
1.140     www      10357:         my %metathesekeys=();
1.73      www      10358:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10359: 	my $metastring;
1.1140    www      10360: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10361: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10362: 	    $metastring = 
1.929     albertel 10363: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10364: 					  ('grade_target' => 'meta'));
                   10365: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10366: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10367:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10368: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10369: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10370: 	    $metastring=&getfile($file);
1.489     albertel 10371: 	}
1.208     albertel 10372:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10373:         my $token;
1.140     www      10374:         undef %metathesekeys;
1.71      www      10375:         while ($token=$parser->get_token) {
1.339     albertel 10376: 	    if ($token->[0] eq 'S') {
                   10377: 		if (defined($token->[2]->{'package'})) {
1.172     www      10378: #
                   10379: # This is a package - get package info
                   10380: #
1.339     albertel 10381: 		    my $package=$token->[2]->{'package'};
                   10382: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10383: 		    if (defined($token->[2]->{'id'})) { 
                   10384: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10385: 		    }
1.599     albertel 10386: 		    if ($metaentry{':packages'}) {
                   10387: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10388: 		    } else {
1.599     albertel 10389: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10390: 		    }
1.736     albertel 10391: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10392: 			my $part=$keyroot;
                   10393: 			$part=~s/^\_//;
1.736     albertel 10394: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10395: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10396: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10397: 			    # ignore package.tab specified default values
                   10398:                             # here &package_tab_default() will fetch those
                   10399: 			    if ($subp eq 'default') { next; }
1.736     albertel 10400: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10401: 			    my $unikey;
                   10402: 			    if ($pack =~ /_0$/) {
                   10403: 				$unikey='parameter_0_'.$name;
                   10404: 				$part=0;
                   10405: 			    } else {
                   10406: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10407: 			    }
1.339     albertel 10408: 			    if ($subp eq 'display') {
                   10409: 				$value.=' [Part: '.$part.']';
                   10410: 			    }
1.599     albertel 10411: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10412: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10413: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10414: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10415: 			    }
1.599     albertel 10416: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10417: 				$metaentry{':'.$unikey}=
                   10418: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10419: 			    }
1.339     albertel 10420: 			}
                   10421: 		    }
                   10422: 		} else {
1.172     www      10423: #
                   10424: # This is not a package - some other kind of start tag
1.339     albertel 10425: #
                   10426: 		    my $entry=$token->[1];
1.1068    www      10427: 		    my $unikey='';
1.175     www      10428: 
1.339     albertel 10429: 		    if ($entry eq 'import') {
1.175     www      10430: #
                   10431: # Importing a library here
1.339     albertel 10432: #
1.1067    www      10433:                         my $location=$parser->get_text('/import');
                   10434:                         my $dir=$filename;
                   10435:                         $dir=~s|[^/]*$||;
                   10436:                         $location=&filelocation($dir,$location);
1.1069    www      10437:                        
1.1068    www      10438:                         my $importmode=$token->[2]->{'importmode'};
                   10439:                         if ($importmode eq 'problem') {
1.1069    www      10440: # Import as problem/response
1.1068    www      10441:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10442:                         } elsif ($importmode eq 'part') {
                   10443: # Import as part(s)
1.1069    www      10444:                            $importedparts=1;
                   10445: # We need to get the original file and the imported file to get the part order correct
                   10446: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10447: # Load and inspect original file
1.1070    www      10448:                            if ($#origfileimportpartids<0) {
                   10449:                               undef(%importedpartids);
                   10450:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10451:                               my $origfile=&getfile($origfilelocation);
                   10452:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10453:                            }
                   10454: 
1.1069    www      10455: # Load and inspect imported file
                   10456:                            my $impfile=&getfile($location);
                   10457:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10458:                            if ($#impfilepartids>=0) {
                   10459: # This problem had parts
1.1070    www      10460:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10461:                            } else {
                   10462: # Importing by turning a single problem into a problem part
                   10463: # It gets the import-tags ID as part-ID
                   10464:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10465:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10466:                            }
1.1068    www      10467:                         } else {
                   10468: # Normal import
                   10469:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10470:                            if (defined($token->[2]->{'id'})) {
                   10471:                               $unikey.='_'.$token->[2]->{'id'};
                   10472:                            }
1.1067    www      10473:                         }
                   10474: 
1.339     albertel 10475: 			if ($depthcount<20) {
1.736     albertel 10476: 			    my $metadata = 
                   10477: 				&metadata($uri,'keys', $location,$unikey,
                   10478: 					  $depthcount+1);
                   10479: 			    foreach my $meta (split(',',$metadata)) {
                   10480: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10481: 				$metathesekeys{$meta}=1;
1.339     albertel 10482: 			    }
1.1068    www      10483: 			
                   10484:                         }
1.1067    www      10485: 		    } else {
                   10486: #
                   10487: # Not importing, some other kind of non-package, non-library start tag
                   10488: # 
                   10489:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10490:                         if (defined($token->[2]->{'id'})) {
                   10491:                             $unikey.='_'.$token->[2]->{'id'};
                   10492:                         }
1.339     albertel 10493: 			if (defined($token->[2]->{'name'})) { 
                   10494: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10495: 			}
                   10496: 			$metathesekeys{$unikey}=1;
1.736     albertel 10497: 			foreach my $param (@{$token->[3]}) {
                   10498: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10499: 				$token->[2]->{$param};
1.339     albertel 10500: 			}
                   10501: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10502: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10503: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10504: 		 # only ws inside the tag, and not in default, so use default
                   10505: 		 # as value
1.599     albertel 10506: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10507: 			} elsif ( $internaltext =~ /\S/ ) {
                   10508: 		  # something interesting inside the tag
                   10509: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10510: 			} else {
1.908     albertel 10511: 		  # no interesting values, don't set a default
1.339     albertel 10512: 			}
1.172     www      10513: # end of not-a-package not-a-library import
1.339     albertel 10514: 		    }
1.172     www      10515: # end of not-a-package start tag
1.339     albertel 10516: 		}
1.172     www      10517: # the next is the end of "start tag"
1.339     albertel 10518: 	    }
                   10519: 	}
1.483     albertel 10520: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10521: 	$extension = lc($extension);
                   10522: 	if ($extension eq 'htm') { $extension='html'; }
                   10523: 
1.737     albertel 10524: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10525: 	    #no specific packages #how's our extension
                   10526: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10527: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10528: 					 \%metathesekeys);
                   10529: 	}
1.883     albertel 10530: 
                   10531: 	if (!exists($metaentry{':packages'})
                   10532: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10533: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10534: 		#no specific packages well let's get default then
                   10535: 		if ($key!~/^default&/) { next; }
1.488     albertel 10536: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10537: 					     \%metathesekeys);
                   10538: 	    }
                   10539: 	}
1.338     www      10540: # are there custom rights to evaluate
1.599     albertel 10541: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10542: 
1.338     www      10543:     #
                   10544:     # Importing a rights file here
1.339     albertel 10545:     #
                   10546: 	    unless ($depthcount) {
1.599     albertel 10547: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10548: 		my $dir=$filename;
                   10549: 		$dir=~s|[^/]*$||;
                   10550: 		$location=&filelocation($dir,$location);
1.736     albertel 10551: 		my $rights_metadata =
                   10552: 		    &metadata($uri,'keys',$location,'_rights',
                   10553: 			      $depthcount+1);
                   10554: 		foreach my $rights (split(',',$rights_metadata)) {
                   10555: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10556: 		    $metathesekeys{$rights}=1;
1.339     albertel 10557: 		}
                   10558: 	    }
                   10559: 	}
1.737     albertel 10560: 	# uniqifiy package listing
                   10561: 	my %seen;
                   10562: 	my @uniq_packages =
                   10563: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10564: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10565: 
1.1070    www      10566:         if ($importedparts) {
                   10567: # We had imported parts and need to rebuild partorder
                   10568:            $metaentry{':partorder'}='';
                   10569:            $metathesekeys{'partorder'}=1;
                   10570:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10571:                if ($origfileimportpartids[$index] eq 'part') {
                   10572: # original part, part of the problem
                   10573:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10574:                } else {
                   10575: # we have imported parts at this position
                   10576:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10577:                }
                   10578:            }
                   10579:            $metaentry{':partorder'}=~s/^\,//;
                   10580:         }
                   10581: 
1.737     albertel 10582: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10583: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58! raeburn  10584: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 10585: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10586: # this is the end of "was not already recently cached
1.71      www      10587:     }
1.599     albertel 10588:     return $metaentry{':'.$what};
1.261     albertel 10589: }
                   10590: 
1.488     albertel 10591: sub metadata_create_package_def {
1.483     albertel 10592:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10593:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10594:     if ($subp eq 'default') { next; }
                   10595:     
1.599     albertel 10596:     if (defined($metaentry{':packages'})) {
                   10597: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10598:     } else {
1.599     albertel 10599: 	$metaentry{':packages'}=$package;
1.483     albertel 10600:     }
                   10601:     my $value=$packagetab{$key};
                   10602:     my $unikey;
                   10603:     $unikey='parameter_0_'.$name;
1.599     albertel 10604:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10605:     $$metathesekeys{$unikey}=1;
1.599     albertel 10606:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10607: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10608:     }
1.599     albertel 10609:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10610: 	$metaentry{':'.$unikey}=
                   10611: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10612:     }
                   10613: }
                   10614: 
1.261     albertel 10615: sub metadata_generate_part0 {
                   10616:     my ($metadata,$metacache,$uri) = @_;
                   10617:     my %allnames;
1.737     albertel 10618:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10619: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10620: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10621: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10622: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10623: 	    $allnames{$name}=$part;
                   10624: 	  }
                   10625: 	}
                   10626:     }
                   10627:     foreach my $name (keys(%allnames)) {
                   10628:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10629:       my $key=":parameter_0_$name";
1.261     albertel 10630:       $$metacache{"$key.part"}='0';
                   10631:       $$metacache{"$key.name"}=$name;
1.428     albertel 10632:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10633: 					   $allnames{$name}.'_'.$name.
                   10634: 					   '.type'};
1.428     albertel 10635:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10636: 			     '.display'};
1.644     www      10637:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10638:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10639:       $$metacache{"$key.display"}=$olddis;
                   10640:     }
1.71      www      10641: }
                   10642: 
1.764     albertel 10643: # ------------------------------------------------------ Devalidate title cache
                   10644: 
                   10645: sub devalidate_title_cache {
                   10646:     my ($url)=@_;
                   10647:     if (!$env{'request.course.id'}) { return; }
                   10648:     my $symb=&symbread($url);
                   10649:     if (!$symb) { return; }
                   10650:     my $key=$env{'request.course.id'}."\0".$symb;
                   10651:     &devalidate_cache_new('title',$key);
                   10652: }
                   10653: 
1.1014    droeschl 10654: # ------------------------------------------------- Get the title of a course
                   10655: 
                   10656: sub current_course_title {
                   10657:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10658: }
1.301     www      10659: # ------------------------------------------------- Get the title of a resource
                   10660: 
                   10661: sub gettitle {
                   10662:     my $urlsymb=shift;
                   10663:     my $symb=&symbread($urlsymb);
1.534     albertel 10664:     if ($symb) {
1.620     albertel 10665: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10666: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10667: 	if (defined($cached)) { 
                   10668: 	    return $result;
                   10669: 	}
1.534     albertel 10670: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10671: 	my $title='';
1.907     albertel 10672: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10673: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10674: 	} else {
                   10675: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10676: 		    &GDBM_READER(),0640)) {
                   10677: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10678: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10679: 		untie(%bighash);
                   10680: 	    }
1.534     albertel 10681: 	}
                   10682: 	$title=~s/\&colon\;/\:/gs;
                   10683: 	if ($title) {
1.1159    www      10684: # Remember both $symb and $title for dynamic metadata
                   10685:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10686:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10687: # Cache this title and then return it
1.599     albertel 10688: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10689: 	}
                   10690: 	$urlsymb=$url;
                   10691:     }
                   10692:     my $title=&metadata($urlsymb,'title');
                   10693:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10694:     return $title;
1.301     www      10695: }
1.613     albertel 10696: 
1.614     albertel 10697: sub get_slot {
                   10698:     my ($which,$cnum,$cdom)=@_;
                   10699:     if (!$cnum || !$cdom) {
1.790     albertel 10700: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10701: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10702: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10703:     }
1.703     albertel 10704:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10705:     my %slotinfo;
                   10706:     if (exists($remembered{$key})) {
                   10707: 	$slotinfo{$which} = $remembered{$key};
                   10708:     } else {
                   10709: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10710: 	&Apache::lonhomework::showhash(%slotinfo);
                   10711: 	my ($tmp)=keys(%slotinfo);
                   10712: 	if ($tmp=~/^error:/) { return (); }
                   10713: 	$remembered{$key} = $slotinfo{$which};
                   10714:     }
1.616     albertel 10715:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10716: 	return %{$slotinfo{$which}};
                   10717:     }
                   10718:     return $slotinfo{$which};
1.614     albertel 10719: }
1.1150    raeburn  10720: 
                   10721: sub get_reservable_slots {
                   10722:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10723:     my $now = time;
                   10724:     my $reservable_info;
                   10725:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10726:     if (exists($remembered{$key})) {
                   10727:         $reservable_info = $remembered{$key};
                   10728:     } else {
                   10729:         my %resv;
                   10730:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10731:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10732:         $reservable_info = \%resv;
                   10733:         $remembered{$key} = $reservable_info;
                   10734:     }
                   10735:     return $reservable_info;
                   10736: }
                   10737: 
                   10738: sub get_course_slots {
                   10739:     my ($cnum,$cdom) = @_;
                   10740:     my $hashid=$cnum.':'.$cdom;
                   10741:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10742:     if (defined($cached)) {
                   10743:         if (ref($result) eq 'HASH') {
                   10744:             return %{$result};
                   10745:         }
                   10746:     } else {
                   10747:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10748:         my ($tmp) = keys(%slots);
                   10749:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  10750:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10751:             return %slots;
                   10752:         }
                   10753:     }
                   10754:     return;
                   10755: }
                   10756: 
                   10757: sub devalidate_slots_cache {
                   10758:     my ($cnum,$cdom)=@_;
                   10759:     my $hashid=$cnum.':'.$cdom;
                   10760:     &devalidate_cache_new('allslots',$hashid);
                   10761: }
                   10762: 
1.1172.2.8  raeburn  10763: sub get_coursechange {
                   10764:     my ($cdom,$cnum) = @_;
                   10765:     if ($cdom eq '' || $cnum eq '') {
                   10766:         return unless ($env{'request.course.id'});
                   10767:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10768:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10769:     }
                   10770:     my $hashid=$cdom.'_'.$cnum;
                   10771:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10772:     if ((defined($cached)) && ($change ne '')) {
                   10773:         return $change;
                   10774:     } else {
                   10775:         my %crshash;
                   10776:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10777:         if ($crshash{'internal.contentchange'} eq '') {
                   10778:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10779:             if ($change eq '') {
                   10780:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10781:                 $change = $crshash{'internal.created'};
                   10782:             }
                   10783:         } else {
                   10784:             $change = $crshash{'internal.contentchange'};
                   10785:         }
                   10786:         my $cachetime = 600;
                   10787:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10788:     }
                   10789:     return $change;
                   10790: }
                   10791: 
                   10792: sub devalidate_coursechange_cache {
                   10793:     my ($cnum,$cdom)=@_;
                   10794:     my $hashid=$cnum.':'.$cdom;
                   10795:     &devalidate_cache_new('crschange',$hashid);
                   10796: }
                   10797: 
1.31      www      10798: # ------------------------------------------------- Update symbolic store links
                   10799: 
                   10800: sub symblist {
                   10801:     my ($mapname,%newhash)=@_;
1.438     www      10802:     $mapname=&deversion(&declutter($mapname));
1.31      www      10803:     my %hash;
1.620     albertel 10804:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10805:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10806:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10807: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10808: 		next if ($url eq 'last_known'
                   10809: 			 && $env{'form.no_update_last_known'});
                   10810: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10811: 						    $newhash{$url}->[1],
                   10812: 						    $newhash{$url}->[0]);
1.191     harris41 10813:             }
1.31      www      10814:             if (untie(%hash)) {
                   10815: 		return 'ok';
                   10816:             }
                   10817:         }
                   10818:     }
                   10819:     return 'error';
1.212     www      10820: }
                   10821: 
                   10822: # --------------------------------------------------------------- Verify a symb
                   10823: 
                   10824: sub symbverify {
1.1172.2.11  raeburn  10825:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10826:     my $thisfn=$thisurl;
1.439     www      10827:     $thisfn=&declutter($thisfn);
1.215     www      10828: # direct jump to resource in page or to a sequence - will construct own symbs
                   10829:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10830: # check URL part
1.409     www      10831:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10832: 
1.431     www      10833:     unless ($url eq $thisfn) { return 0; }
1.213     www      10834: 
1.216     www      10835:     $symb=&symbclean($symb);
1.510     www      10836:     $thisurl=&deversion($thisurl);
1.439     www      10837:     $thisfn=&deversion($thisfn);
1.213     www      10838: 
                   10839:     my %bighash;
                   10840:     my $okay=0;
1.431     www      10841: 
1.620     albertel 10842:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10843:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10844:         my $noclutter;
1.1032    raeburn  10845:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10846:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10847:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10848:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10849:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10850:                 $noclutter = 1;
                   10851:             }
                   10852:         }
                   10853:         my $ids;
                   10854:         if ($noclutter) {
                   10855:             $ids=$bighash{'ids_'.$thisurl};
                   10856:         } else {
                   10857:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10858:         }
1.1102    raeburn  10859:         unless ($ids) {
1.1172.2.13  raeburn  10860:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10861:             $ids=$bighash{$idkey};
1.216     www      10862:         }
                   10863:         if ($ids) {
                   10864: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10865:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10866:                 $symb =~ s/\?.+$//;
                   10867:             }
1.800     albertel 10868: 	    foreach my $id (split(/\,/,$ids)) {
                   10869: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10870:                if (
                   10871:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10872:    eq $symb) {
1.1172.2.11  raeburn  10873:                    if (ref($encstate)) {
                   10874:                        $$encstate = $bighash{'encrypted_'.$id};
                   10875:                    }
1.1172.2.13  raeburn  10876:                    if (($env{'request.role.adv'}) ||
                   10877:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10878:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10879:                        $okay=1;
                   10880:                        last;
                   10881:                    }
                   10882:                }
                   10883:            }
1.216     www      10884:         }
1.213     www      10885: 	untie(%bighash);
                   10886:     }
                   10887:     return $okay;
1.31      www      10888: }
                   10889: 
1.210     www      10890: # --------------------------------------------------------------- Clean-up symb
                   10891: 
                   10892: sub symbclean {
                   10893:     my $symb=shift;
1.568     albertel 10894:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10895: # remove version from map
                   10896:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10897: 
1.210     www      10898: # remove version from URL
                   10899:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10900: 
1.507     www      10901: # remove wrapper
                   10902: 
1.510     www      10903:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10904:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10905:     return $symb;
1.409     www      10906: }
                   10907: 
                   10908: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10909: 
                   10910: sub encode_symb {
                   10911:     my ($map,$resid,$url)=@_;
                   10912:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10913: }
1.409     www      10914: 
                   10915: sub decode_symb {
1.568     albertel 10916:     my $symb=shift;
                   10917:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10918:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10919:     return (&fixversion($map),$resid,&fixversion($url));
                   10920: }
                   10921: 
                   10922: sub fixversion {
                   10923:     my $fn=shift;
1.609     banghart 10924:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10925:     my %bighash;
                   10926:     my $uri=&clutter($fn);
1.620     albertel 10927:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10928: # is this cached?
1.599     albertel 10929:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10930:     if (defined($cached)) { return $result; }
                   10931: # unfortunately not cached, or expired
1.620     albertel 10932:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10933: 	    &GDBM_READER(),0640)) {
                   10934:  	if ($bighash{'version_'.$uri}) {
                   10935:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10936:  	    unless (($version eq 'mostrecent') || 
                   10937: 		    ($version==&getversion($uri))) {
1.440     www      10938:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10939:  	    }
                   10940:  	}
                   10941:  	untie %bighash;
1.413     www      10942:     }
1.599     albertel 10943:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10944: }
                   10945: 
                   10946: sub deversion {
                   10947:     my $url=shift;
                   10948:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10949:     return $url;
1.210     www      10950: }
                   10951: 
1.31      www      10952: # ------------------------------------------------------ Return symb list entry
                   10953: 
                   10954: sub symbread {
1.249     www      10955:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.54  raeburn  10956:     my $cache_str='request.symbread.cached.'.$thisfn;
                   10957:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      10958: # no filename provided? try from environment
1.1172.2.54  raeburn  10959:     unless ($thisfn) {
1.620     albertel 10960:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10961:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10962:         }
                   10963:         $thisfn=$env{'request.filename'};
1.44      www      10964:     }
1.569     albertel 10965:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10966: # is that filename actually a symb? Verify, clean, and return
                   10967:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10968: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10969: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10970: 	}
1.242     www      10971:     }
1.44      www      10972:     $thisfn=declutter($thisfn);
1.31      www      10973:     my %hash;
1.37      www      10974:     my %bighash;
                   10975:     my $syval='';
1.620     albertel 10976:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10977:         my $targetfn = $thisfn;
1.609     banghart 10978:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10979:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10980:         }
1.687     albertel 10981: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10982: 	    $targetfn=$1;
                   10983: 	}
1.620     albertel 10984:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10985:                       &GDBM_READER(),0640)) {
1.481     raeburn  10986: 	    $syval=$hash{$targetfn};
1.37      www      10987:             untie(%hash);
                   10988:         }
                   10989: # ---------------------------------------------------------- There was an entry
                   10990:         if ($syval) {
1.601     albertel 10991: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10992: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10993: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10994: 		    #return $env{$cache_str}='';
1.601     albertel 10995: 		#}    
                   10996: 		#$syval.=$1;
                   10997: 	    #}
1.37      www      10998:         } else {
                   10999: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11000:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11001:                             &GDBM_READER(),0640)) {
1.37      www      11002: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11003:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11004:               unless ($ids) { 
                   11005:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11006:               }
                   11007:               unless ($ids) {
                   11008: # alias?
                   11009: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11010:               }
1.37      www      11011:               if ($ids) {
                   11012: # ------------------------------------------------------------------- Has ID(s)
                   11013:                  my @possibilities=split(/\,/,$ids);
1.39      www      11014:                  if ($#possibilities==0) {
                   11015: # ----------------------------------------------- There is only one possibility
1.37      www      11016: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11017: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11018: 						    $resid,$thisfn);
1.249     www      11019:                  } elsif (!$donotrecurse) {
1.39      www      11020: # ------------------------------------------ There is more than one possibility
                   11021:                      my $realpossible=0;
1.800     albertel 11022:                      foreach my $id (@possibilities) {
                   11023: 			 my $file=$bighash{'src_'.$id};
1.39      www      11024:                          if (&allowed('bre',$file)) {
1.800     albertel 11025:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      11026:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11027: 				$realpossible++;
1.626     albertel 11028:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11029: 						    $resid,$thisfn);
1.39      www      11030:                             }
                   11031: 			 }
1.191     harris41 11032:                      }
1.39      www      11033: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11034:                  } else {
                   11035:                      $syval='';
1.37      www      11036:                  }
                   11037: 	      }
                   11038:               untie(%bighash)
1.481     raeburn  11039:            }
1.31      www      11040:         }
1.62      www      11041:         if ($syval) {
1.620     albertel 11042: 	    return $env{$cache_str}=$syval;
1.62      www      11043:         }
1.31      www      11044:     }
1.949     raeburn  11045:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11046:     return $env{$cache_str}='';
1.31      www      11047: }
                   11048: 
                   11049: # ---------------------------------------------------------- Return random seed
                   11050: 
1.32      www      11051: sub numval {
                   11052:     my $txt=shift;
                   11053:     $txt=~tr/A-J/0-9/;
                   11054:     $txt=~tr/a-j/0-9/;
                   11055:     $txt=~tr/K-T/0-9/;
                   11056:     $txt=~tr/k-t/0-9/;
                   11057:     $txt=~tr/U-Z/0-5/;
                   11058:     $txt=~tr/u-z/0-5/;
                   11059:     $txt=~s/\D//g;
1.564     albertel 11060:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11061:     return int($txt);
1.368     albertel 11062: }
                   11063: 
1.484     albertel 11064: sub numval2 {
                   11065:     my $txt=shift;
                   11066:     $txt=~tr/A-J/0-9/;
                   11067:     $txt=~tr/a-j/0-9/;
                   11068:     $txt=~tr/K-T/0-9/;
                   11069:     $txt=~tr/k-t/0-9/;
                   11070:     $txt=~tr/U-Z/0-5/;
                   11071:     $txt=~tr/u-z/0-5/;
                   11072:     $txt=~s/\D//g;
                   11073:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11074:     my $total;
                   11075:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11076:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11077:     return int($total);
                   11078: }
                   11079: 
1.575     albertel 11080: sub numval3 {
                   11081:     use integer;
                   11082:     my $txt=shift;
                   11083:     $txt=~tr/A-J/0-9/;
                   11084:     $txt=~tr/a-j/0-9/;
                   11085:     $txt=~tr/K-T/0-9/;
                   11086:     $txt=~tr/k-t/0-9/;
                   11087:     $txt=~tr/U-Z/0-5/;
                   11088:     $txt=~tr/u-z/0-5/;
                   11089:     $txt=~s/\D//g;
                   11090:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11091:     my $total;
                   11092:     foreach my $val (@txts) { $total+=$val; }
                   11093:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11094:     return $total;
                   11095: }
                   11096: 
1.675     albertel 11097: sub digest {
                   11098:     my ($data)=@_;
                   11099:     my $digest=&Digest::MD5::md5($data);
                   11100:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11101:     my ($e,$f);
                   11102:     {
                   11103:         use integer;
                   11104:         $e=($a+$b);
                   11105:         $f=($c+$d);
                   11106:         if ($_64bit) {
                   11107:             $e=(($e<<32)>>32);
                   11108:             $f=(($f<<32)>>32);
                   11109:         }
                   11110:     }
                   11111:     if (wantarray) {
                   11112: 	return ($e,$f);
                   11113:     } else {
                   11114: 	my $g;
                   11115: 	{
                   11116: 	    use integer;
                   11117: 	    $g=($e+$f);
                   11118: 	    if ($_64bit) {
                   11119: 		$g=(($g<<32)>>32);
                   11120: 	    }
                   11121: 	}
                   11122: 	return $g;
                   11123:     }
                   11124: }
                   11125: 
1.368     albertel 11126: sub latest_rnd_algorithm_id {
1.675     albertel 11127:     return '64bit5';
1.366     albertel 11128: }
1.32      www      11129: 
1.503     albertel 11130: sub get_rand_alg {
                   11131:     my ($courseid)=@_;
1.790     albertel 11132:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11133:     if ($courseid) {
1.620     albertel 11134: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11135:     }
                   11136:     return &latest_rnd_algorithm_id();
                   11137: }
                   11138: 
1.562     albertel 11139: sub validCODE {
                   11140:     my ($CODE)=@_;
                   11141:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11142:     return 0;
                   11143: }
                   11144: 
1.491     albertel 11145: sub getCODE {
1.620     albertel 11146:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11147:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11148: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11149: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11150: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11151:     }
                   11152:     return undef;
                   11153: }
1.1133    foxr     11154: #
                   11155: #  Determines the random seed for a specific context:
                   11156: #
                   11157: # parameters:
                   11158: #   symb      - in course context the symb for the seed.
                   11159: #   course_id - The course id of the form domain_coursenum.
                   11160: #   domain    - Domain for the user.
                   11161: #   course    - Course for the user.
                   11162: #   cenv      - environment of the course.
                   11163: #
                   11164: # NOTE:
                   11165: #   All parameters are picked out of the environment if missing
                   11166: #   or not defined.
                   11167: #   If a symb cannot be determined the current time is used instead.
                   11168: #
                   11169: #  For a given well defined symb, courside, domain, username,
                   11170: #  and course environment, the seed is reproducible.
                   11171: #
1.31      www      11172: sub rndseed {
1.1133    foxr     11173:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11174:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11175:     if (!defined($symb)) {
1.366     albertel 11176: 	unless ($symb=$wsymb) { return time; }
                   11177:     }
1.1146    foxr     11178:     if (!defined $courseid) { 
                   11179: 	$courseid=$wcourseid; 
                   11180:     }
                   11181:     if (!defined $domain) { $domain=$wdomain; }
                   11182:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11183: 
                   11184:     my $which;
                   11185:     if (defined($cenv->{'rndseed'})) {
                   11186: 	$which = $cenv->{'rndseed'};
                   11187:     } else {
                   11188: 	$which =&get_rand_alg($courseid);
                   11189:     }
1.491     albertel 11190:     if (defined(&getCODE())) {
1.675     albertel 11191: 	if ($which eq '64bit5') {
                   11192: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11193: 	} elsif ($which eq '64bit4') {
1.575     albertel 11194: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11195: 	} else {
                   11196: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11197: 	}
1.675     albertel 11198:     } elsif ($which eq '64bit5') {
                   11199: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11200:     } elsif ($which eq '64bit4') {
                   11201: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11202:     } elsif ($which eq '64bit3') {
                   11203: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11204:     } elsif ($which eq '64bit2') {
                   11205: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11206:     } elsif ($which eq '64bit') {
                   11207: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11208:     }
                   11209:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11210: }
                   11211: 
                   11212: sub rndseed_32bit {
                   11213:     my ($symb,$courseid,$domain,$username)=@_;
                   11214:     {
                   11215: 	use integer;
                   11216: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11217: 	my $symbseed=numval($symb) << 22;
                   11218: 	my $namechck=unpack("%32C*",$username) << 17;
                   11219: 	my $nameseed=numval($username) << 12;
                   11220: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11221: 	my $courseseed=unpack("%32C*",$courseid);
                   11222: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11223: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11224: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11225: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11226: 	return $num;
                   11227:     }
                   11228: }
                   11229: 
                   11230: sub rndseed_64bit {
                   11231:     my ($symb,$courseid,$domain,$username)=@_;
                   11232:     {
                   11233: 	use integer;
                   11234: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11235: 	my $symbseed=numval($symb) << 10;
                   11236: 	my $namechck=unpack("%32S*",$username);
                   11237: 	
                   11238: 	my $nameseed=numval($username) << 21;
                   11239: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11240: 	my $courseseed=unpack("%32S*",$courseid);
                   11241: 	
                   11242: 	my $num1=$symbchck+$symbseed+$namechck;
                   11243: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11244: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11245: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11246: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11247: 	return "$num1,$num2";
1.155     albertel 11248:     }
1.366     albertel 11249: }
                   11250: 
1.443     albertel 11251: sub rndseed_64bit2 {
                   11252:     my ($symb,$courseid,$domain,$username)=@_;
                   11253:     {
                   11254: 	use integer;
                   11255: 	# strings need to be an even # of cahracters long, it it is odd the
                   11256:         # last characters gets thrown away
                   11257: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11258: 	my $symbseed=numval($symb) << 10;
                   11259: 	my $namechck=unpack("%32S*",$username.' ');
                   11260: 	
                   11261: 	my $nameseed=numval($username) << 21;
1.501     albertel 11262: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11263: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11264: 	
                   11265: 	my $num1=$symbchck+$symbseed+$namechck;
                   11266: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11267: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11268: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11269: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11270: 	return "$num1,$num2";
                   11271:     }
                   11272: }
                   11273: 
                   11274: sub rndseed_64bit3 {
                   11275:     my ($symb,$courseid,$domain,$username)=@_;
                   11276:     {
                   11277: 	use integer;
                   11278: 	# strings need to be an even # of cahracters long, it it is odd the
                   11279:         # last characters gets thrown away
                   11280: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11281: 	my $symbseed=numval2($symb) << 10;
                   11282: 	my $namechck=unpack("%32S*",$username.' ');
                   11283: 	
                   11284: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11285: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11286: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11287: 	
                   11288: 	my $num1=$symbchck+$symbseed+$namechck;
                   11289: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11290: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11291: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11292: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11293: 	
1.503     albertel 11294: 	return "$num1:$num2";
1.443     albertel 11295:     }
                   11296: }
                   11297: 
1.575     albertel 11298: sub rndseed_64bit4 {
                   11299:     my ($symb,$courseid,$domain,$username)=@_;
                   11300:     {
                   11301: 	use integer;
                   11302: 	# strings need to be an even # of cahracters long, it it is odd the
                   11303:         # last characters gets thrown away
                   11304: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11305: 	my $symbseed=numval3($symb) << 10;
                   11306: 	my $namechck=unpack("%32S*",$username.' ');
                   11307: 	
                   11308: 	my $nameseed=numval3($username) << 21;
                   11309: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11310: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11311: 	
                   11312: 	my $num1=$symbchck+$symbseed+$namechck;
                   11313: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11314: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11315: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11316: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11317: 	
1.575     albertel 11318: 	return "$num1:$num2";
                   11319:     }
                   11320: }
                   11321: 
1.675     albertel 11322: sub rndseed_64bit5 {
                   11323:     my ($symb,$courseid,$domain,$username)=@_;
                   11324:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11325:     return "$num1:$num2";
                   11326: }
                   11327: 
1.366     albertel 11328: sub rndseed_CODE_64bit {
                   11329:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11330:     {
1.366     albertel 11331: 	use integer;
1.443     albertel 11332: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11333: 	my $symbseed=numval2($symb);
1.491     albertel 11334: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11335: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11336: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11337: 	my $num1=$symbseed+$CODEchck;
                   11338: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11339: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11340: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11341: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11342: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11343: 	return "$num1:$num2";
1.366     albertel 11344:     }
                   11345: }
                   11346: 
1.575     albertel 11347: sub rndseed_CODE_64bit4 {
                   11348:     my ($symb,$courseid,$domain,$username)=@_;
                   11349:     {
                   11350: 	use integer;
                   11351: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11352: 	my $symbseed=numval3($symb);
                   11353: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11354: 	my $CODEseed=numval3(&getCODE());
                   11355: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11356: 	my $num1=$symbseed+$CODEchck;
                   11357: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11358: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11359: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11360: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11361: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11362: 	return "$num1:$num2";
                   11363:     }
                   11364: }
                   11365: 
1.675     albertel 11366: sub rndseed_CODE_64bit5 {
                   11367:     my ($symb,$courseid,$domain,$username)=@_;
                   11368:     my $code = &getCODE();
                   11369:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11370:     return "$num1:$num2";
                   11371: }
                   11372: 
1.366     albertel 11373: sub setup_random_from_rndseed {
                   11374:     my ($rndseed)=@_;
1.503     albertel 11375:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  11376: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11377:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11378:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11379:         } else {
                   11380:             &Math::Random::random_set_seed($num1,$num2);
                   11381:         }
1.366     albertel 11382:     } else {
                   11383: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11384:     }
1.36      albertel 11385: }
                   11386: 
1.474     albertel 11387: sub latest_receipt_algorithm_id {
1.835     albertel 11388:     return 'receipt3';
1.474     albertel 11389: }
                   11390: 
1.480     www      11391: sub recunique {
                   11392:     my $fucourseid=shift;
                   11393:     my $unique;
1.835     albertel 11394:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11395: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11396: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11397:     } else {
                   11398: 	$unique=$perlvar{'lonReceipt'};
                   11399:     }
                   11400:     return unpack("%32C*",$unique);
                   11401: }
                   11402: 
                   11403: sub recprefix {
                   11404:     my $fucourseid=shift;
                   11405:     my $prefix;
1.835     albertel 11406:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11407: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11408: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11409:     } else {
                   11410: 	$prefix=$perlvar{'lonHostID'};
                   11411:     }
                   11412:     return unpack("%32C*",$prefix);
                   11413: }
                   11414: 
1.76      www      11415: sub ireceipt {
1.474     albertel 11416:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11417: 
                   11418:     my $return =&recprefix($fucourseid).'-';
                   11419: 
                   11420:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11421: 	$env{'request.state'} eq 'construct') {
                   11422: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11423: 	return $return;
                   11424:     }
                   11425: 
1.76      www      11426:     my $cuname=unpack("%32C*",$funame);
                   11427:     my $cudom=unpack("%32C*",$fudom);
                   11428:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11429:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11430:     my $cunique=&recunique($fucourseid);
1.474     albertel 11431:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11432:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11433: 
1.790     albertel 11434: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11435: 			       
                   11436: 	$return.= ($cunique%$cuname+
                   11437: 		   $cunique%$cudom+
                   11438: 		   $cusymb%$cuname+
                   11439: 		   $cusymb%$cudom+
                   11440: 		   $cucourseid%$cuname+
                   11441: 		   $cucourseid%$cudom+
                   11442: 		   $cpart%$cuname+
                   11443: 		   $cpart%$cudom);
                   11444:     } else {
                   11445: 	$return.= ($cunique%$cuname+
                   11446: 		   $cunique%$cudom+
                   11447: 		   $cusymb%$cuname+
                   11448: 		   $cusymb%$cudom+
                   11449: 		   $cucourseid%$cuname+
                   11450: 		   $cucourseid%$cudom);
                   11451:     }
                   11452:     return $return;
1.76      www      11453: }
                   11454: 
                   11455: sub receipt {
1.474     albertel 11456:     my ($part)=@_;
1.790     albertel 11457:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11458:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11459: }
1.260     ng       11460: 
1.790     albertel 11461: sub whichuser {
                   11462:     my ($passedsymb)=@_;
                   11463:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11464:     if (defined($env{'form.grade_symb'})) {
                   11465: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11466: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11467: 	if (!$allowed &&
                   11468: 	    exists($env{'request.course.sec'}) &&
                   11469: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11470: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11471: 			      '/'.$env{'request.course.sec'});
                   11472: 	}
                   11473: 	if ($allowed) {
                   11474: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11475: 	    $courseid=$tmp_courseid;
                   11476: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11477: 	    ($name)=&get_env_multiple('form.grade_username');
                   11478: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11479: 	}
                   11480:     }
                   11481:     if (!$passedsymb) {
                   11482: 	$symb=&symbread();
                   11483:     } else {
                   11484: 	$symb=$passedsymb;
                   11485:     }
                   11486:     $courseid=$env{'request.course.id'};
                   11487:     $domain=$env{'user.domain'};
                   11488:     $name=$env{'user.name'};
                   11489:     if ($name eq 'public' && $domain eq 'public') {
                   11490: 	if (!defined($env{'form.username'})) {
                   11491: 	    $env{'form.username'}.=time.rand(10000000);
                   11492: 	}
                   11493: 	$name.=$env{'form.username'};
                   11494:     }
                   11495:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11496: 
                   11497: }
                   11498: 
1.36      albertel 11499: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11500: # returns either the contents of the file or 
                   11501: # -1 if the file doesn't exist
1.481     raeburn  11502: #
                   11503: # if the target is a file that was uploaded via DOCS, 
                   11504: # a check will be made to see if a current copy exists on the local server,
                   11505: # if it does this will be served, otherwise a copy will be retrieved from
                   11506: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11507: # the local server.   
1.472     albertel 11508: 
1.36      albertel 11509: sub getfile {
1.538     albertel 11510:     my ($file) = @_;
1.609     banghart 11511:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11512:     &repcopy($file);
                   11513:     return &readfile($file);
                   11514: }
                   11515: 
                   11516: sub repcopy_userfile {
                   11517:     my ($file)=@_;
1.1142    raeburn  11518:     my $londocroot = $perlvar{'lonDocRoot'};
                   11519:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11520:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11521:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11522: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11523:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11524:     if (-e "$file") {
1.828     www      11525: # we already have a local copy, check it out
1.538     albertel 11526: 	my @fileinfo = stat($file);
1.828     www      11527: 	my $rtncode;
                   11528: 	my $info;
1.538     albertel 11529: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11530: 	if ($lwpresp ne 'ok') {
1.828     www      11531: # there is no such file anymore, even though we had a local copy
1.482     albertel 11532: 	    if ($rtncode eq '404') {
1.538     albertel 11533: 		unlink($file);
1.482     albertel 11534: 	    }
                   11535: 	    return -1;
                   11536: 	}
                   11537: 	if ($info < $fileinfo[9]) {
1.828     www      11538: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11539: 	    return 'ok';
1.828     www      11540: 	} else {
                   11541: # the file is outdated, get rid of it
                   11542: 	    unlink($file);
1.482     albertel 11543: 	}
1.828     www      11544:     }
                   11545: # one way or the other, at this point, we don't have the file
                   11546: # construct the correct path for the file
                   11547:     my @parts = ($cdom,$cnum); 
                   11548:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11549: 	push @parts, split(/\//,$1);
                   11550:     }
                   11551:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11552:     foreach my $part (@parts) {
                   11553: 	$path .= '/'.$part;
                   11554: 	if (!-e $path) {
                   11555: 	    mkdir($path,0770);
1.482     albertel 11556: 	}
                   11557:     }
1.828     www      11558: # now the path exists for sure
                   11559: # get a user agent
                   11560:     my $ua=new LWP::UserAgent;
                   11561:     my $transferfile=$file.'.in.transfer';
                   11562: # FIXME: this should flock
                   11563:     if (-e $transferfile) { return 'ok'; }
                   11564:     my $request;
                   11565:     $uri=~s/^\///;
1.980     raeburn  11566:     my $homeserver = &homeserver($cnum,$cdom);
                   11567:     my $protocol = $protocol{$homeserver};
                   11568:     $protocol = 'http' if ($protocol ne 'https');
                   11569:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11570:     my $response=$ua->request($request,$transferfile);
                   11571: # did it work?
                   11572:     if ($response->is_error()) {
                   11573: 	unlink($transferfile);
                   11574: 	&logthis("Userfile repcopy failed for $uri");
                   11575: 	return -1;
                   11576:     }
                   11577: # worked, rename the transfer file
                   11578:     rename($transferfile,$file);
1.607     raeburn  11579:     return 'ok';
1.481     raeburn  11580: }
                   11581: 
1.517     albertel 11582: sub tokenwrapper {
                   11583:     my $uri=shift;
1.980     raeburn  11584:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11585:     $uri=~s|^/||;
1.620     albertel 11586:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11587:     my $token=$1;
1.552     albertel 11588:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11589:     if ($udom && $uname && $file) {
                   11590: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11591:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11592:         my $homeserver = &homeserver($uname,$udom);
                   11593:         my $protocol = $protocol{$homeserver};
                   11594:         $protocol = 'http' if ($protocol ne 'https');
                   11595:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11596:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11597:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11598:     } else {
                   11599:         return '/adm/notfound.html';
                   11600:     }
                   11601: }
                   11602: 
1.828     www      11603: # call with reqtype HEAD: get last modification time
                   11604: # call with reqtype GET: get the file contents
                   11605: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11606: #
1.481     raeburn  11607: sub getuploaded {
                   11608:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11609:     $uri=~s/^\///;
1.980     raeburn  11610:     my $homeserver = &homeserver($cnum,$cdom);
                   11611:     my $protocol = $protocol{$homeserver};
                   11612:     $protocol = 'http' if ($protocol ne 'https');
                   11613:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11614:     my $ua=new LWP::UserAgent;
                   11615:     my $request=new HTTP::Request($reqtype,$uri);
                   11616:     my $response=$ua->request($request);
                   11617:     $$rtncode = $response->code;
1.482     albertel 11618:     if (! $response->is_success()) {
                   11619: 	return 'failed';
                   11620:     }      
                   11621:     if ($reqtype eq 'HEAD') {
1.486     www      11622: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11623:     } elsif ($reqtype eq 'GET') {
                   11624: 	$$info = $response->content;
1.472     albertel 11625:     }
1.482     albertel 11626:     return 'ok';
1.36      albertel 11627: }
                   11628: 
1.481     raeburn  11629: sub readfile {
                   11630:     my $file = shift;
                   11631:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11632:     my $fh;
                   11633:     open($fh,"<$file");
                   11634:     my $a='';
1.800     albertel 11635:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11636:     return $a;
                   11637: }
                   11638: 
1.36      albertel 11639: sub filelocation {
1.590     banghart 11640:     my ($dir,$file) = @_;
                   11641:     my $location;
                   11642:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11643: 
                   11644:     if ($file =~ m-^/adm/-) {
                   11645: 	$file=~s-^/adm/wrapper/-/-;
                   11646: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11647:     }
1.882     albertel 11648: 
1.1139    www      11649:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11650:         $location = $file;
1.609     banghart 11651:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11652:         my ($udom,$uname,$filename)=
1.811     albertel 11653:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11654:         my $home=&homeserver($uname,$udom);
                   11655:         my $is_me=0;
                   11656:         my @ids=&current_machine_ids();
                   11657:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11658:         if ($is_me) {
1.1117    foxr     11659:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11660:         } else {
                   11661:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11662:   	      $udom.'/'.$uname.'/'.$filename;
                   11663:         }
1.882     albertel 11664:     } elsif ($file =~ m-^/adm/-) {
                   11665: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11666:     } else {
                   11667:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11668:         $file=~s:^/(res|priv)/:/:;
                   11669:         my $space=$1;
1.590     banghart 11670:         if ( !( $file =~ m:^/:) ) {
                   11671:             $location = $dir. '/'.$file;
                   11672:         } else {
1.1142    raeburn  11673:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11674:         }
1.59      albertel 11675:     }
1.590     banghart 11676:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11677:     while ($location=~m{/\.\./}) {
                   11678: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11679: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11680: 	} else {
                   11681: 	    $location=~ s{/\.\./}{/}g;
                   11682: 	}
                   11683:     } #remove dir/..
1.590     banghart 11684:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11685:     return $location;
1.46      www      11686: }
1.36      albertel 11687: 
1.46      www      11688: sub hreflocation {
                   11689:     my ($dir,$file)=@_;
1.980     raeburn  11690:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11691: 	$file=filelocation($dir,$file);
1.700     albertel 11692:     } elsif ($file=~m-^/adm/-) {
                   11693: 	$file=~s-^/adm/wrapper/-/-;
                   11694: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11695:     }
                   11696:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11697: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11698:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11699: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11700: 	        {/uploaded/$1/$2/}x;
1.46      www      11701:     }
1.913     albertel 11702:     if ($file=~ m{^/userfiles/}) {
                   11703: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11704:     }
1.462     albertel 11705:     return $file;
1.465     albertel 11706: }
                   11707: 
1.1139    www      11708: 
                   11709: 
                   11710: 
                   11711: 
1.465     albertel 11712: sub current_machine_domains {
1.853     albertel 11713:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11714: }
                   11715: 
                   11716: sub machine_domains {
                   11717:     my ($hostname) = @_;
1.465     albertel 11718:     my @domains;
1.838     albertel 11719:     my %hostname = &all_hostnames();
1.465     albertel 11720:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11721: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11722: 	if ($hostname eq $name) {
1.844     albertel 11723: 	    push(@domains,&host_domain($id));
1.465     albertel 11724: 	}
                   11725:     }
                   11726:     return @domains;
                   11727: }
                   11728: 
                   11729: sub current_machine_ids {
1.853     albertel 11730:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11731: }
                   11732: 
                   11733: sub machine_ids {
                   11734:     my ($hostname) = @_;
                   11735:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11736:     my @ids;
1.888     albertel 11737:     my %name_to_host = &all_names();
1.889     albertel 11738:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11739: 	return @{ $name_to_host{$hostname} };
                   11740:     }
                   11741:     return;
1.31      www      11742: }
                   11743: 
1.824     raeburn  11744: sub additional_machine_domains {
                   11745:     my @domains;
                   11746:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11747:     while( my $line = <$fh>) {
                   11748:         $line =~ s/\s//g;
                   11749:         push(@domains,$line);
                   11750:     }
                   11751:     return @domains;
                   11752: }
                   11753: 
                   11754: sub default_login_domain {
                   11755:     my $domain = $perlvar{'lonDefDomain'};
                   11756:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11757:     foreach my $posdom (&current_machine_domains(),
                   11758:                         &additional_machine_domains()) {
                   11759:         if (lc($posdom) eq lc($testdomain)) {
                   11760:             $domain=$posdom;
                   11761:             last;
                   11762:         }
                   11763:     }
                   11764:     return $domain;
                   11765: }
                   11766: 
1.31      www      11767: # ------------------------------------------------------------- Declutters URLs
                   11768: 
                   11769: sub declutter {
                   11770:     my $thisfn=shift;
1.569     albertel 11771:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  11772:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   11773:         $thisfn=~s{^/home/httpd/html}{};
                   11774:     }
1.31      www      11775:     $thisfn=~s/^\///;
1.697     albertel 11776:     $thisfn=~s|^adm/wrapper/||;
                   11777:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11778:     $thisfn=~s/^res\///;
1.1172    bisitz   11779:     $thisfn=~s/^priv\///;
1.1032    raeburn  11780:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11781:         $thisfn=~s/\?.+$//;
                   11782:     }
1.268     www      11783:     return $thisfn;
                   11784: }
                   11785: 
                   11786: # ------------------------------------------------------------- Clutter up URLs
                   11787: 
                   11788: sub clutter {
                   11789:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11790:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11791: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11792:        $thisfn='/res'.$thisfn; 
                   11793:     }
1.1031    raeburn  11794:     if ($thisfn !~m|^/adm|) {
                   11795: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11796: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11797: 	} else {
                   11798: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11799: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11800: 	    if ($embstyle eq 'ssi'
                   11801: 		|| ($embstyle eq 'hdn')
                   11802: 		|| ($embstyle eq 'rat')
                   11803: 		|| ($embstyle eq 'prv')
                   11804: 		|| ($embstyle eq 'ign')) {
                   11805: 		#do nothing with these
                   11806: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11807: 		|| ($embstyle eq 'emb')
                   11808: 		|| ($embstyle eq 'wrp')) {
                   11809: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11810: 	    } elsif ($embstyle eq 'unk'
                   11811: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11812: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11813: 	    } else {
1.718     www      11814: #		&logthis("Got a blank emb style");
1.695     albertel 11815: 	    }
1.694     albertel 11816: 	}
                   11817:     }
1.31      www      11818:     return $thisfn;
1.12      www      11819: }
                   11820: 
1.787     albertel 11821: sub clutter_with_no_wrapper {
                   11822:     my $uri = &clutter(shift);
                   11823:     if ($uri =~ m-^/adm/-) {
                   11824: 	$uri =~ s-^/adm/wrapper/-/-;
                   11825: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11826:     }
                   11827:     return $uri;
                   11828: }
                   11829: 
1.557     albertel 11830: sub freeze_escape {
                   11831:     my ($value)=@_;
                   11832:     if (ref($value)) {
                   11833: 	$value=&nfreeze($value);
                   11834: 	return '__FROZEN__'.&escape($value);
                   11835:     }
                   11836:     return &escape($value);
                   11837: }
                   11838: 
1.11      www      11839: 
1.557     albertel 11840: sub thaw_unescape {
                   11841:     my ($value)=@_;
                   11842:     if ($value =~ /^__FROZEN__/) {
                   11843: 	substr($value,0,10,undef);
                   11844: 	$value=&unescape($value);
                   11845: 	return &thaw($value);
                   11846:     }
                   11847:     return &unescape($value);
                   11848: }
                   11849: 
1.436     albertel 11850: sub correct_line_ends {
                   11851:     my ($result)=@_;
                   11852:     $$result =~s/\r\n/\n/mg;
                   11853:     $$result =~s/\r/\n/mg;
1.415     albertel 11854: }
1.1       albertel 11855: # ================================================================ Main Program
                   11856: 
1.184     www      11857: sub goodbye {
1.204     albertel 11858:    &logthis("Starting Shut down");
1.443     albertel 11859: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11860:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11861: #converted
1.599     albertel 11862: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11863:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11864: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11865: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11866: #1.1 only
1.870     albertel 11867: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11868: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11869: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11870: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11871:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11872:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11873:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11874:    &flushcourselogs();
                   11875:    &logthis("Shutting down");
                   11876: }
                   11877: 
1.852     albertel 11878: sub get_dns {
1.1172.2.17  raeburn  11879:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11880:     if (!$ignore_cache) {
                   11881: 	my ($content,$cached)=
                   11882: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11883: 	if ($cached) {
1.1172.2.17  raeburn  11884: 	    &$func($content,$hashref);
1.869     albertel 11885: 	    return;
                   11886: 	}
                   11887:     }
                   11888: 
                   11889:     my %alldns;
1.852     albertel 11890:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11891:     foreach my $dns (<$config>) {
                   11892: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11893:         my $line = $1;
                   11894:         my ($host,$protocol) = split(/:/,$line);
                   11895:         if ($protocol ne 'https') {
                   11896:             $protocol = 'http';
                   11897:         }
                   11898: 	$alldns{$host} = $protocol;
1.869     albertel 11899:     }
                   11900:     while (%alldns) {
1.1172.2.52  raeburn  11901: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 11902: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11903:         $ua->timeout(30);
1.979     raeburn  11904: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11905: 	my $response=$ua->request($request);
1.979     raeburn  11906:         delete($alldns{$dns});
1.852     albertel 11907: 	next if ($response->is_error());
                   11908: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11909:         unless ($nocache) {
1.1172.2.23  raeburn  11910: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  11911:         }
                   11912: 	&$func(\@content,$hashref);
1.869     albertel 11913: 	return;
1.852     albertel 11914:     }
                   11915:     close($config);
1.871     albertel 11916:     my $which = (split('/',$url))[3];
                   11917:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11918:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11919:     my @content = <$config>;
1.1172.2.17  raeburn  11920:     &$func(\@content,$hashref);
                   11921:     return;
                   11922: }
                   11923: 
                   11924: # ------------------------------------------------------Get DNS checksums file
                   11925: sub parse_dns_checksums_tab {
                   11926:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  11927:     my $lonhost = $perlvar{'lonHostID'};
                   11928:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  11929:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  11930:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   11931:     my $webconfdir = '/etc/httpd/conf';
                   11932:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   11933:         $webconfdir = '/etc/apache2';
                   11934:     } elsif ($distro =~ /^sles(\d+)$/) {
                   11935:         if ($1 >= 10) {
                   11936:             $webconfdir = '/etc/apache2';
                   11937:         }
                   11938:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   11939:         if ($1 >= 10.0) {
                   11940:             $webconfdir = '/etc/apache2';
                   11941:         }
                   11942:     }
1.1172.2.17  raeburn  11943:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11944:     my (%chksum,%revnum);
                   11945:     if (ref($lines) eq 'ARRAY') {
                   11946:         chomp(@{$lines});
1.1172.2.34  raeburn  11947:         my $version = shift(@{$lines});
                   11948:         if ($version eq $release) {
1.1172.2.17  raeburn  11949:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  11950:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  11951:                 if ($file =~ m{^/etc/httpd/conf}) {
                   11952:                     if ($webconfdir eq '/etc/apache2') {
                   11953:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   11954:                     }
                   11955:                 }
1.1172.2.34  raeburn  11956:                 $chksum{$file} = $shasum;
                   11957:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  11958:             }
                   11959:             if (ref($hashref) eq 'HASH') {
                   11960:                 %{$hashref} = (
                   11961:                                 sums     => \%chksum,
                   11962:                                 versions => \%revnum,
                   11963:                               );
                   11964:             }
                   11965:         }
                   11966:     }
1.869     albertel 11967:     return;
1.852     albertel 11968: }
1.1172.2.17  raeburn  11969: 
                   11970: sub fetch_dns_checksums {
                   11971:     my %checksums;
1.1172.2.34  raeburn  11972:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  11973:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  11974:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11975:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  11976:              \%checksums);
                   11977:     return \%checksums;
                   11978: }
                   11979: 
1.327     albertel 11980: # ------------------------------------------------------------ Read domain file
                   11981: {
1.852     albertel 11982:     my $loaded;
1.846     albertel 11983:     my %domain;
                   11984: 
1.852     albertel 11985:     sub parse_domain_tab {
                   11986: 	my ($lines) = @_;
                   11987: 	foreach my $line (@$lines) {
                   11988: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11989: 
1.846     albertel 11990: 	    chomp($line);
1.852     albertel 11991: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11992: 	    my %this_domain;
                   11993: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11994: 			       'lang_def', 'city', 'longi', 'lati',
                   11995: 			       'primary') {
                   11996: 		$this_domain{$field} = shift(@elements);
                   11997: 	    }
                   11998: 	    $domain{$name} = \%this_domain;
1.852     albertel 11999: 	}
                   12000:     }
1.864     albertel 12001: 
                   12002:     sub reset_domain_info {
                   12003: 	undef($loaded);
                   12004: 	undef(%domain);
                   12005:     }
                   12006: 
1.852     albertel 12007:     sub load_domain_tab {
1.869     albertel 12008: 	my ($ignore_cache) = @_;
                   12009: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 12010: 	my $fh;
                   12011: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12012: 	    my @lines = <$fh>;
                   12013: 	    &parse_domain_tab(\@lines);
1.448     albertel 12014: 	}
1.852     albertel 12015: 	close($fh);
                   12016: 	$loaded = 1;
1.327     albertel 12017:     }
1.846     albertel 12018: 
                   12019:     sub domain {
1.852     albertel 12020: 	&load_domain_tab() if (!$loaded);
                   12021: 
1.846     albertel 12022: 	my ($name,$what) = @_;
                   12023: 	return if ( !exists($domain{$name}) );
                   12024: 
                   12025: 	if (!$what) {
                   12026: 	    return $domain{$name}{'description'};
                   12027: 	}
                   12028: 	return $domain{$name}{$what};
                   12029:     }
1.974     raeburn  12030: 
                   12031:     sub domain_info {
                   12032:         &load_domain_tab() if (!$loaded);
                   12033:         return %domain;
                   12034:     }
                   12035: 
1.327     albertel 12036: }
                   12037: 
                   12038: 
1.1       albertel 12039: # ------------------------------------------------------------- Read hosts file
                   12040: {
1.838     albertel 12041:     my %hostname;
1.844     albertel 12042:     my %hostdom;
1.845     albertel 12043:     my %libserv;
1.852     albertel 12044:     my $loaded;
1.888     albertel 12045:     my %name_to_host;
1.1074    raeburn  12046:     my %internetdom;
1.1107    raeburn  12047:     my %LC_dns_serv;
1.852     albertel 12048: 
                   12049:     sub parse_hosts_tab {
                   12050: 	my ($file) = @_;
                   12051: 	foreach my $configline (@$file) {
                   12052: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12053:             chomp($configline);
                   12054: 	    if ($configline =~ /^\^/) {
                   12055:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12056:                     $LC_dns_serv{$1} = 1;
                   12057:                 }
                   12058:                 next;
                   12059:             }
1.1074    raeburn  12060: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12061: 	    $name=~s/\s//g;
                   12062: 	    if ($id && $domain && $role && $name) {
                   12063: 		$hostname{$id}=$name;
1.888     albertel 12064: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12065: 		$hostdom{$id}=$domain;
                   12066: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12067:                 if (defined($protocol)) {
                   12068:                     if ($protocol eq 'https') {
                   12069:                         $protocol{$id} = $protocol;
                   12070:                     } else {
                   12071:                         $protocol{$id} = 'http'; 
                   12072:                     }
1.968     raeburn  12073:                 } else {
1.969     raeburn  12074:                     $protocol{$id} = 'http';
1.968     raeburn  12075:                 }
1.1074    raeburn  12076:                 if (defined($intdom)) {
                   12077:                     $internetdom{$id} = $intdom;
                   12078:                 }
1.852     albertel 12079: 	    }
                   12080: 	}
                   12081:     }
1.864     albertel 12082:     
                   12083:     sub reset_hosts_info {
1.897     albertel 12084: 	&purge_remembered();
1.864     albertel 12085: 	&reset_domain_info();
                   12086: 	&reset_hosts_ip_info();
1.892     albertel 12087: 	undef(%name_to_host);
1.864     albertel 12088: 	undef(%hostname);
                   12089: 	undef(%hostdom);
                   12090: 	undef(%libserv);
                   12091: 	undef($loaded);
                   12092:     }
1.1       albertel 12093: 
1.852     albertel 12094:     sub load_hosts_tab {
1.869     albertel 12095: 	my ($ignore_cache) = @_;
                   12096: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 12097: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12098: 	my @config = <$config>;
                   12099: 	&parse_hosts_tab(\@config);
                   12100: 	close($config);
                   12101: 	$loaded=1;
1.1       albertel 12102:     }
1.852     albertel 12103: 
1.838     albertel 12104:     sub hostname {
1.852     albertel 12105: 	&load_hosts_tab() if (!$loaded);
                   12106: 
1.838     albertel 12107: 	my ($lonid) = @_;
                   12108: 	return $hostname{$lonid};
                   12109:     }
1.845     albertel 12110: 
1.838     albertel 12111:     sub all_hostnames {
1.852     albertel 12112: 	&load_hosts_tab() if (!$loaded);
                   12113: 
1.838     albertel 12114: 	return %hostname;
                   12115:     }
1.845     albertel 12116: 
1.888     albertel 12117:     sub all_names {
                   12118: 	&load_hosts_tab() if (!$loaded);
                   12119: 
                   12120: 	return %name_to_host;
                   12121:     }
                   12122: 
1.974     raeburn  12123:     sub all_host_domain {
                   12124:         &load_hosts_tab() if (!$loaded);
                   12125:         return %hostdom;
                   12126:     }
                   12127: 
1.845     albertel 12128:     sub is_library {
1.852     albertel 12129: 	&load_hosts_tab() if (!$loaded);
                   12130: 
1.845     albertel 12131: 	return exists($libserv{$_[0]});
                   12132:     }
                   12133: 
                   12134:     sub all_library {
1.852     albertel 12135: 	&load_hosts_tab() if (!$loaded);
                   12136: 
1.845     albertel 12137: 	return %libserv;
                   12138:     }
                   12139: 
1.1062    droeschl 12140:     sub unique_library {
                   12141: 	#2x reverse removes all hostnames that appear more than once
                   12142:         my %unique = reverse &all_library();
                   12143:         return reverse %unique;
                   12144:     }
                   12145: 
1.841     albertel 12146:     sub get_servers {
1.852     albertel 12147: 	&load_hosts_tab() if (!$loaded);
                   12148: 
1.841     albertel 12149: 	my ($domain,$type) = @_;
                   12150: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12151: 	                                          : %hostname;
                   12152: 	my %result;
1.842     albertel 12153: 	if (ref($domain) eq 'ARRAY') {
                   12154: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12155: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12156: 		    $result{$host} = $hostname;
                   12157: 		}
                   12158: 	    }
                   12159: 	} else {
                   12160: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12161: 		if ($hostdom{$host} eq $domain) {
                   12162: 		    $result{$host} = $hostname;
                   12163: 		}
1.841     albertel 12164: 	    }
                   12165: 	}
                   12166: 	return %result;
                   12167:     }
1.845     albertel 12168: 
1.1062    droeschl 12169:     sub get_unique_servers {
                   12170:         my %unique = reverse &get_servers(@_);
                   12171: 	return reverse %unique;
                   12172:     }
                   12173: 
1.844     albertel 12174:     sub host_domain {
1.852     albertel 12175: 	&load_hosts_tab() if (!$loaded);
                   12176: 
1.844     albertel 12177: 	my ($lonid) = @_;
                   12178: 	return $hostdom{$lonid};
                   12179:     }
                   12180: 
1.841     albertel 12181:     sub all_domains {
1.852     albertel 12182: 	&load_hosts_tab() if (!$loaded);
                   12183: 
1.841     albertel 12184: 	my %seen;
                   12185: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12186: 	return @uniq;
                   12187:     }
1.1074    raeburn  12188: 
                   12189:     sub internet_dom {
                   12190:         &load_hosts_tab() if (!$loaded);
                   12191: 
                   12192:         my ($lonid) = @_;
                   12193:         return $internetdom{$lonid};
                   12194:     }
1.1107    raeburn  12195: 
                   12196:     sub is_LC_dns {
                   12197:         &load_hosts_tab() if (!$loaded);
                   12198: 
                   12199:         my ($hostname) = @_;
                   12200:         return exists($LC_dns_serv{$hostname});
                   12201:     }
                   12202: 
1.1       albertel 12203: }
                   12204: 
1.847     albertel 12205: { 
                   12206:     my %iphost;
1.856     albertel 12207:     my %name_to_ip;
                   12208:     my %lonid_to_ip;
1.869     albertel 12209: 
1.847     albertel 12210:     sub get_hosts_from_ip {
                   12211: 	my ($ip) = @_;
                   12212: 	my %iphosts = &get_iphost();
                   12213: 	if (ref($iphosts{$ip})) {
                   12214: 	    return @{$iphosts{$ip}};
                   12215: 	}
                   12216: 	return;
1.839     albertel 12217:     }
1.864     albertel 12218:     
                   12219:     sub reset_hosts_ip_info {
                   12220: 	undef(%iphost);
                   12221: 	undef(%name_to_ip);
                   12222: 	undef(%lonid_to_ip);
                   12223:     }
1.856     albertel 12224: 
                   12225:     sub get_host_ip {
                   12226: 	my ($lonid) = @_;
                   12227: 	if (exists($lonid_to_ip{$lonid})) {
                   12228: 	    return $lonid_to_ip{$lonid};
                   12229: 	}
                   12230: 	my $name=&hostname($lonid);
                   12231:    	my $ip = gethostbyname($name);
                   12232: 	return if (!$ip || length($ip) ne 4);
                   12233: 	$ip=inet_ntoa($ip);
                   12234: 	$name_to_ip{$name}   = $ip;
                   12235: 	$lonid_to_ip{$lonid} = $ip;
                   12236: 	return $ip;
                   12237:     }
1.847     albertel 12238:     
                   12239:     sub get_iphost {
1.869     albertel 12240: 	my ($ignore_cache) = @_;
1.894     albertel 12241: 
1.869     albertel 12242: 	if (!$ignore_cache) {
                   12243: 	    if (%iphost) {
                   12244: 		return %iphost;
                   12245: 	    }
                   12246: 	    my ($ip_info,$cached)=
                   12247: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12248: 	    if ($cached) {
                   12249: 		%iphost      = %{$ip_info->[0]};
                   12250: 		%name_to_ip  = %{$ip_info->[1]};
                   12251: 		%lonid_to_ip = %{$ip_info->[2]};
                   12252: 		return %iphost;
                   12253: 	    }
                   12254: 	}
1.894     albertel 12255: 
                   12256: 	# get yesterday's info for fallback
                   12257: 	my %old_name_to_ip;
                   12258: 	my ($ip_info,$cached)=
                   12259: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12260: 	if ($cached) {
                   12261: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12262: 	}
                   12263: 
1.888     albertel 12264: 	my %name_to_host = &all_names();
                   12265: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12266: 	    my $ip;
                   12267: 	    if (!exists($name_to_ip{$name})) {
                   12268: 		$ip = gethostbyname($name);
                   12269: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12270: 		    if (defined($old_name_to_ip{$name})) {
                   12271: 			$ip = $old_name_to_ip{$name};
                   12272: 			&logthis("Can't find $name defaulting to old $ip");
                   12273: 		    } else {
                   12274: 			&logthis("Name $name no IP found");
                   12275: 			next;
                   12276: 		    }
                   12277: 		} else {
                   12278: 		    $ip=inet_ntoa($ip);
1.847     albertel 12279: 		}
                   12280: 		$name_to_ip{$name} = $ip;
                   12281: 	    } else {
                   12282: 		$ip = $name_to_ip{$name};
1.653     albertel 12283: 	    }
1.888     albertel 12284: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12285: 		$lonid_to_ip{$id} = $ip;
                   12286: 	    }
                   12287: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12288: 	}
1.1172.2.23  raeburn  12289: 	&do_cache_new('iphost','iphost',
                   12290: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12291: 		      48*60*60);
1.869     albertel 12292: 
1.847     albertel 12293: 	return %iphost;
1.598     albertel 12294:     }
                   12295: 
1.992     raeburn  12296:     #
                   12297:     #  Given a DNS returns the loncapa host name for that DNS 
                   12298:     # 
                   12299:     sub host_from_dns {
                   12300:         my ($dns) = @_;
                   12301:         my @hosts;
                   12302:         my $ip;
                   12303: 
1.993     raeburn  12304:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12305:             $ip = $name_to_ip{$dns};
                   12306:         }
                   12307:         if (!$ip) {
                   12308:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12309:             if (length($ip) == 4) { 
                   12310: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12311:             }
                   12312:         }
                   12313:         if ($ip) {
                   12314: 	    @hosts = get_hosts_from_ip($ip);
                   12315: 	    return $hosts[0];
                   12316:         }
                   12317:         return undef;
1.986     foxr     12318:     }
1.992     raeburn  12319: 
1.1074    raeburn  12320:     sub get_internet_names {
                   12321:         my ($lonid) = @_;
                   12322:         return if ($lonid eq '');
                   12323:         my ($idnref,$cached)=
                   12324:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12325:         if ($cached) {
                   12326:             return $idnref;
                   12327:         }
                   12328:         my $ip = &get_host_ip($lonid);
                   12329:         my @hosts = &get_hosts_from_ip($ip);
                   12330:         my %iphost = &get_iphost();
                   12331:         my (@idns,%seen);
                   12332:         foreach my $id (@hosts) {
                   12333:             my $dom = &host_domain($id);
                   12334:             my $prim_id = &domain($dom,'primary');
                   12335:             my $prim_ip = &get_host_ip($prim_id);
                   12336:             next if ($seen{$prim_ip});
                   12337:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12338:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12339:                     my $intdom = &internet_dom($id);
                   12340:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12341:                         push(@idns,$intdom);
                   12342:                     }
                   12343:                 }
                   12344:             }
                   12345:             $seen{$prim_ip} = 1;
                   12346:         }
1.1172.2.23  raeburn  12347:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12348:     }
                   12349: 
1.986     foxr     12350: }
                   12351: 
1.1079    raeburn  12352: sub all_loncaparevs {
1.1172.2.39  raeburn  12353:     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  12354: }
                   12355: 
1.1172.2.27  raeburn  12356: # ------------------------------------------------------- Read loncaparev table
                   12357: {
                   12358:     sub load_loncaparevs {
                   12359:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12360:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12361:                 while (my $configline=<$config>) {
                   12362:                     chomp($configline);
                   12363:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12364:                     $loncaparevs{$hostid}=$loncaparev;
                   12365:                 }
                   12366:                 close($config);
                   12367:             }
                   12368:         }
                   12369:     }
                   12370: }
                   12371: 
                   12372: # ----------------------------------------------------- Read serverhostID table
                   12373: {
                   12374:     sub load_serverhomeIDs {
                   12375:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12376:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12377:                 while (my $configline=<$config>) {
                   12378:                     chomp($configline);
                   12379:                     my ($name,$id)=split(/:/,$configline);
                   12380:                     $serverhomeIDs{$name}=$id;
                   12381:                 }
                   12382:                 close($config);
                   12383:             }
                   12384:         }
                   12385:     }
                   12386: }
                   12387: 
                   12388: 
1.862     albertel 12389: BEGIN {
                   12390: 
                   12391: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12392:     unless ($readit) {
                   12393: {
                   12394:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12395:     %perlvar = (%perlvar,%{$configvars});
                   12396: }
                   12397: 
                   12398: 
1.1       albertel 12399: # ------------------------------------------------------ Read spare server file
                   12400: {
1.448     albertel 12401:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12402: 
                   12403:     while (my $configline=<$config>) {
                   12404:        chomp($configline);
1.284     matthew  12405:        if ($configline) {
1.784     albertel 12406: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12407: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12408: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12409:        }
                   12410:     }
1.448     albertel 12411:     close($config);
1.1       albertel 12412: }
1.11      www      12413: # ------------------------------------------------------------ Read permissions
                   12414: {
1.448     albertel 12415:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12416: 
                   12417:     while (my $configline=<$config>) {
1.448     albertel 12418: 	chomp($configline);
                   12419: 	if ($configline) {
                   12420: 	    my ($role,$perm)=split(/ /,$configline);
                   12421: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12422: 	}
1.11      www      12423:     }
1.448     albertel 12424:     close($config);
1.11      www      12425: }
                   12426: 
                   12427: # -------------------------------------------- Read plain texts for permissions
                   12428: {
1.448     albertel 12429:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12430: 
                   12431:     while (my $configline=<$config>) {
1.448     albertel 12432: 	chomp($configline);
                   12433: 	if ($configline) {
1.742     raeburn  12434: 	    my ($short,@plain)=split(/:/,$configline);
                   12435:             %{$prp{$short}} = ();
                   12436: 	    if (@plain > 0) {
                   12437:                 $prp{$short}{'std'} = $plain[0];
                   12438:                 for (my $i=1; $i<@plain; $i++) {
                   12439:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12440:                 }
                   12441:             }
1.448     albertel 12442: 	}
1.135     www      12443:     }
1.448     albertel 12444:     close($config);
1.135     www      12445: }
                   12446: 
                   12447: # ---------------------------------------------------------- Read package table
                   12448: {
1.448     albertel 12449:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12450: 
                   12451:     while (my $configline=<$config>) {
1.483     albertel 12452: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12453: 	chomp($configline);
                   12454: 	my ($short,$plain)=split(/:/,$configline);
                   12455: 	my ($pack,$name)=split(/\&/,$short);
                   12456: 	if ($plain ne '') {
                   12457: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12458: 	    $packagetab{$short}=$plain; 
                   12459: 	}
1.11      www      12460:     }
1.448     albertel 12461:     close($config);
1.329     matthew  12462: }
                   12463: 
1.1172.2.27  raeburn  12464: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12465: 
1.1172.2.27  raeburn  12466: &load_loncaparevs();
                   12467: 
                   12468: # ------------------------------------------------------- Read serverhostID table
                   12469: 
                   12470: &load_serverhomeIDs();
1.1074    raeburn  12471: 
1.1172.2.27  raeburn  12472: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12473: {
                   12474:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12475:     if (-e $file) {
                   12476:         my $parser = HTML::LCParser->new($file);
                   12477:         while (my $token = $parser->get_token()) {
                   12478:             if ($token->[0] eq 'S') {
                   12479:                 my $item = $token->[1];
                   12480:                 my $name = $token->[2]{'name'};
                   12481:                 my $value = $token->[2]{'value'};
                   12482:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12483:                     my $release = $parser->get_text();
                   12484:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12485:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12486:                 }
                   12487:             }
                   12488:         }
                   12489:     }
1.1073    raeburn  12490: }
                   12491: 
1.1138    raeburn  12492: # ---------------------------------------------------------- Read managers table
                   12493: {
                   12494:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12495:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12496:             while (my $configline=<$config>) {
                   12497:                 chomp($configline);
                   12498:                 next if ($configline =~ /^\#/);
                   12499:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12500:                     $managerstab{$configline} = 1;
                   12501:                 }
                   12502:             }
                   12503:             close($config);
                   12504:         }
                   12505:     }
                   12506: }
                   12507: 
1.329     matthew  12508: # ------------- set up temporary directory
                   12509: {
1.1117    foxr     12510:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12511: 
1.11      www      12512: }
                   12513: 
1.794     albertel 12514: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12515: 				'compress_threshold'=> 20_000,
                   12516:  			        });
1.185     www      12517: 
1.281     www      12518: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12519: $dumpcount=0;
1.958     www      12520: $locknum=0;
1.22      www      12521: 
1.163     harris41 12522: &logtouch();
1.672     albertel 12523: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12524: $readit=1;
1.564     albertel 12525:     {
                   12526: 	use integer;
                   12527: 	my $test=(2**32)+1;
1.568     albertel 12528: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12529: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12530:     }
1.195     www      12531: }
1.1       albertel 12532: }
1.179     www      12533: 
1.1       albertel 12534: 1;
1.191     harris41 12535: __END__
                   12536: 
1.243     albertel 12537: =pod
                   12538: 
1.191     harris41 12539: =head1 NAME
                   12540: 
1.243     albertel 12541: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12542: 
                   12543: =head1 SYNOPSIS
                   12544: 
1.243     albertel 12545: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12546: 
                   12547:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12548: 
1.243     albertel 12549: Common parameters:
                   12550: 
                   12551: =over 4
                   12552: 
                   12553: =item *
                   12554: 
                   12555: $uname : an internal username (if $cname expecting a course Id specifically)
                   12556: 
                   12557: =item *
                   12558: 
                   12559: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12560: 
                   12561: =item *
                   12562: 
                   12563: $symb : a resource instance identifier
                   12564: 
                   12565: =item *
                   12566: 
                   12567: $namespace : the name of a .db file that contains the data needed or
                   12568: being set.
                   12569: 
                   12570: =back
                   12571: 
1.394     bowersj2 12572: =head1 OVERVIEW
1.191     harris41 12573: 
1.394     bowersj2 12574: lonnet provides subroutines which interact with the
                   12575: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12576: about classes, users, and resources.
1.243     albertel 12577: 
                   12578: For many of these objects you can also use this to store data about
                   12579: them or modify them in various ways.
1.191     harris41 12580: 
1.394     bowersj2 12581: =head2 Symbs
1.191     harris41 12582: 
1.394     bowersj2 12583: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12584: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12585: map, the resource number of the resource in the map, and the URL of
                   12586: the resource itself. The latter is somewhat redundant, but might help
                   12587: if maps change.
                   12588: 
                   12589: An example is
                   12590: 
                   12591:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12592: 
                   12593: The respective map entry is
                   12594: 
                   12595:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12596:   title="Problem 2">
                   12597:  </resource>
                   12598: 
                   12599: Symbs are used by the random number generator, as well as to store and
                   12600: restore data specific to a certain instance of for example a problem.
                   12601: 
                   12602: =head2 Storing And Retrieving Data
                   12603: 
                   12604: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12605: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12606: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12607: is is the non-critical message twin of cstore. These functions are for
                   12608: handlers to store a perl hash to a user's permanent data space in an
                   12609: easy manner, and to retrieve it again on another call. It is expected
                   12610: that a handler would use this once at the beginning to retrieve data,
                   12611: and then again once at the end to send only the new data back.
                   12612: 
                   12613: The data is stored in the user's data directory on the user's
                   12614: homeserver under the ID of the course.
                   12615: 
                   12616: The hash that is returned by restore will have all of the previous
                   12617: value for all of the elements of the hash.
                   12618: 
                   12619: Example:
                   12620: 
                   12621:  #creating a hash
                   12622:  my %hash;
                   12623:  $hash{'foo'}='bar';
                   12624: 
                   12625:  #storing it
                   12626:  &Apache::lonnet::cstore(\%hash);
                   12627: 
                   12628:  #changing a value
                   12629:  $hash{'foo'}='notbar';
                   12630: 
                   12631:  #adding a new value
                   12632:  $hash{'bar'}='foo';
                   12633:  &Apache::lonnet::cstore(\%hash);
                   12634: 
                   12635:  #retrieving the hash
                   12636:  my %history=&Apache::lonnet::restore();
                   12637: 
                   12638:  #print the hash
                   12639:  foreach my $key (sort(keys(%history))) {
                   12640:    print("\%history{$key} = $history{$key}");
                   12641:  }
                   12642: 
                   12643: Will print out:
1.191     harris41 12644: 
1.394     bowersj2 12645:  %history{1:foo} = bar
                   12646:  %history{1:keys} = foo:timestamp
                   12647:  %history{1:timestamp} = 990455579
                   12648:  %history{2:bar} = foo
                   12649:  %history{2:foo} = notbar
                   12650:  %history{2:keys} = foo:bar:timestamp
                   12651:  %history{2:timestamp} = 990455580
                   12652:  %history{bar} = foo
                   12653:  %history{foo} = notbar
                   12654:  %history{timestamp} = 990455580
                   12655:  %history{version} = 2
                   12656: 
                   12657: Note that the special hash entries C<keys>, C<version> and
                   12658: C<timestamp> were added to the hash. C<version> will be equal to the
                   12659: total number of versions of the data that have been stored. The
                   12660: C<timestamp> attribute will be the UNIX time the hash was
                   12661: stored. C<keys> is available in every historical section to list which
                   12662: keys were added or changed at a specific historical revision of a
                   12663: hash.
                   12664: 
                   12665: B<Warning>: do not store the hash that restore returns directly. This
                   12666: will cause a mess since it will restore the historical keys as if the
                   12667: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12668: 
1.394     bowersj2 12669: Calling convention:
1.191     harris41 12670: 
1.1172.2.27  raeburn  12671:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12672:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12673: 
1.394     bowersj2 12674: For more detailed information, see lonnet specific documentation.
1.191     harris41 12675: 
1.394     bowersj2 12676: =head1 RETURN MESSAGES
1.191     harris41 12677: 
1.394     bowersj2 12678: =over 4
1.191     harris41 12679: 
1.394     bowersj2 12680: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12681: 
1.394     bowersj2 12682: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12683: when the connection is brought back up
1.191     harris41 12684: 
1.394     bowersj2 12685: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12686: for later delivery
1.191     harris41 12687: 
1.967     bisitz   12688: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12689: 
1.394     bowersj2 12690: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12691: that was requested
1.191     harris41 12692: 
1.243     albertel 12693: =back
1.191     harris41 12694: 
1.243     albertel 12695: =head1 PUBLIC SUBROUTINES
1.191     harris41 12696: 
1.243     albertel 12697: =head2 Session Environment Functions
1.191     harris41 12698: 
1.243     albertel 12699: =over 4
1.191     harris41 12700: 
1.394     bowersj2 12701: =item * 
                   12702: X<appenv()>
1.949     raeburn  12703: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12704: the user envirnoment file, and will be restored for each access this
1.620     albertel 12705: user makes during this session, also modifies the %env for the current
1.949     raeburn  12706: process. Optional rolesarrayref - if defined contains a reference to an array
                   12707: of roles which are exempt from the restriction on modifying user.role entries 
                   12708: in the user's environment.db and in %env.    
1.191     harris41 12709: 
                   12710: =item *
1.394     bowersj2 12711: X<delenv()>
1.987     raeburn  12712: B<delenv($delthis,$regexp)>: removes all items from the session
                   12713: environment file that begin with $delthis. If the 
                   12714: optional second arg - $regexp - is true, $delthis is treated as a 
                   12715: regular expression, otherwise \Q$delthis\E is used. 
                   12716: The values are also deleted from the current processes %env.
1.191     harris41 12717: 
1.795     albertel 12718: =item * get_env_multiple($name) 
                   12719: 
                   12720: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12721: values may be defined and end up as an array ref.
                   12722: 
                   12723: returns an array of values
                   12724: 
1.243     albertel 12725: =back
                   12726: 
                   12727: =head2 User Information
1.191     harris41 12728: 
1.243     albertel 12729: =over 4
1.191     harris41 12730: 
                   12731: =item *
1.394     bowersj2 12732: X<queryauthenticate()>
                   12733: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12734: authentication scheme
                   12735: 
                   12736: =item *
1.394     bowersj2 12737: X<authenticate()>
1.1073    raeburn  12738: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12739: authenticate user from domain's lib servers (first use the current
                   12740: one). C<$upass> should be the users password.
1.1073    raeburn  12741: $checkdefauth is optional (value is 1 if a check should be made to
                   12742:    authenticate user using default authentication method, and allow
                   12743:    account creation if username does not have account in the domain).
                   12744: $clientcancheckhost is optional (value is 1 if checking whether the
                   12745:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12746: 
                   12747: =item *
1.394     bowersj2 12748: X<homeserver()>
                   12749: B<homeserver($uname,$udom)>: find the server which has
                   12750: the user's directory and files (there must be only one), this caches
                   12751: the answer, and also caches if there is a borken connection.
1.191     harris41 12752: 
                   12753: =item *
1.394     bowersj2 12754: X<idget()>
                   12755: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12756: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12757: username, and only 1 username per ID in a specific domain) (returns
                   12758: hash: id=>name,id=>name)
1.191     harris41 12759: 
                   12760: =item *
1.394     bowersj2 12761: X<idrget()>
                   12762: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12763: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12764: 
                   12765: =item *
1.394     bowersj2 12766: X<idput()>
                   12767: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12768: 
                   12769: =item *
1.394     bowersj2 12770: X<rolesinit()>
1.1169    droeschl 12771: B<rolesinit($udom,$username)>: get user privileges.
                   12772: returns user role, first access and timer interval hashes
1.243     albertel 12773: 
                   12774: =item *
1.1171    droeschl 12775: X<privileged()>
                   12776: B<privileged($username,$domain)>: returns a true if user has a
                   12777: privileged and active role (i.e. su or dc), false otherwise.
                   12778: 
                   12779: =item *
1.551     albertel 12780: X<getsection()>
                   12781: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12782: course $cname, return section name/number or '' for "not in course"
                   12783: and '-1' for "no section"
                   12784: 
                   12785: =item *
1.394     bowersj2 12786: X<userenvironment()>
                   12787: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12788: passed in @what from the requested user's environment, returns a hash
                   12789: 
1.858     raeburn  12790: =item * 
                   12791: X<userlog_query()>
1.859     albertel 12792: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12793: activity.log file. %filters defines filters applied when parsing the
                   12794: log file. These can be start or end timestamps, or the type of action
                   12795: - log to look for Login or Logout events, check for Checkin or
                   12796: Checkout, role for role selection. The response is in the form
                   12797: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12798: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12799: 
1.243     albertel 12800: =back
                   12801: 
                   12802: =head2 User Roles
                   12803: 
                   12804: =over 4
                   12805: 
                   12806: =item *
                   12807: 
1.810     raeburn  12808: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12809:  F: full access
                   12810:  U,I,K: authentication modes (cxx only)
                   12811:  '': forbidden
                   12812:  1: user needs to choose course
                   12813:  2: browse allowed
1.766     albertel 12814:  A: passphrase authentication needed
1.243     albertel 12815: 
                   12816: =item *
                   12817: 
1.1172.2.13  raeburn  12818: constructaccess($url,$setpriv) : check for access to construction space URL
                   12819: 
                   12820: See if the owner domain and name in the URL match those in the
                   12821: expected environment.  If so, return three element list
                   12822: ($ownername,$ownerdomain,$ownerhome).
                   12823: 
                   12824: Otherwise return the null string.
                   12825: 
                   12826: If second argument 'setpriv' is true, it assigns the privileges,
                   12827: and returns the same three element list, unless the owner has
                   12828: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12829: in which case the null string is returned.
                   12830: 
                   12831: =item *
                   12832: 
1.243     albertel 12833: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12834: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12835: and course level
                   12836: 
                   12837: =item *
                   12838: 
1.988     raeburn  12839: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12840: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12841: $type is Course (default) or Community.
1.988     raeburn  12842: If $forcedefault evaluates to true, text returned will be default 
                   12843: text for $type. Otherwise, if this is a course, the text returned 
                   12844: will be a custom name for the role (if defined in the course's 
                   12845: environment).  If no custom name is defined the default is returned.
                   12846:    
1.832     raeburn  12847: =item *
                   12848: 
1.1172.2.23  raeburn  12849: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12850: All arguments are optional. Returns a hash of a roles, either for
                   12851: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12852: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12853: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12854: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12855: For each key, value is set to colon-separated start and end times for
                   12856: the role.  If no username and domain are specified, will default to
1.934     raeburn  12857: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12858: of role statuses (active, future or previous), roles 
                   12859: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12860: to restrict the list of roles reported. If no array ref is 
                   12861: provided for types, will default to return only active roles.
1.834     albertel 12862: 
1.1172.2.13  raeburn  12863: =item *
                   12864: 
                   12865: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12866: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12867: 
                   12868: Additional optional arguments are: $type (if role checking is to be restricted
                   12869: to certain user status types -- previous (expired roles), active (currently
                   12870: available roles) or future (roles available in the future), and
                   12871: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  12872: have active Domain Coordinator role in course's domain or in additional
                   12873: domains (specified in 'Domains to check for privileged users' in course
                   12874: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12875: 
                   12876: =item *
                   12877: 
                   12878: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12879: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12880: $possdomains and $possroles are optional array refs -- to domains to check and
                   12881: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12882: users' roles.db to check for a dc or su role in any domain. This can be
                   12883: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12884: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12885: this then allows &privileged_by_domain() to be used, which caches the identity
                   12886: of privileged users, eliminating the need for repeated calls to &dump().
                   12887: 
                   12888: =item *
                   12889: 
                   12890: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12891: where the outer hash keys are domains specified in the $possdomains array ref,
                   12892: next inner hash keys are privileged roles specified in the $roles array ref,
                   12893: and the innermost hash contains key = value pairs for username:domain = end:start
                   12894: for active or future "privileged" users with that role in that domain. To avoid
                   12895: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12896: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  12897: 
1.243     albertel 12898: =back
                   12899: 
                   12900: =head2 User Modification
                   12901: 
                   12902: =over 4
                   12903: 
                   12904: =item *
                   12905: 
1.957     raeburn  12906: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12907: user for the level given by URL.  Optional start and end dates (leave empty
                   12908: string or zero for "no date")
1.191     harris41 12909: 
                   12910: =item *
                   12911: 
1.243     albertel 12912: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12913: change a users, password, possible return values are: ok,
                   12914: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12915: refused
1.191     harris41 12916: 
                   12917: =item *
                   12918: 
1.243     albertel 12919: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12920: 
                   12921: =item *
                   12922: 
1.1058    raeburn  12923: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12924:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12925: 
                   12926: will update user information (firstname,middlename,lastname,generation,
                   12927: permanentemail), and if forceid is true, student/employee ID also.
                   12928: A user's institutional affiliation(s) can also be updated.
                   12929: User information fields will not be overwritten with empty entries 
                   12930: unless the field is included in the $candelete array reference.
                   12931: This array is included when a single user is modified via "Manage Users",
                   12932: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12933: 
                   12934: =item *
                   12935: 
1.286     matthew  12936: modifystudent
                   12937: 
1.957     raeburn  12938: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  12939: The course id is resolved based on the current user's environment.  
                   12940: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12941: associated with a course.
                   12942: 
1.297     matthew  12943: This call is essentially a wrapper for lonnet::modifyuser and
                   12944: lonnet::modify_student_enrollment
1.286     matthew  12945: 
                   12946: Inputs: 
                   12947: 
                   12948: =over 4
                   12949: 
1.957     raeburn  12950: =item B<$udom> Student's loncapa domain
1.286     matthew  12951: 
1.957     raeburn  12952: =item B<$uname> Student's loncapa login name
1.286     matthew  12953: 
1.964     bisitz   12954: =item B<$uid> Student/Employee ID
1.286     matthew  12955: 
1.957     raeburn  12956: =item B<$umode> Student's authentication mode
1.286     matthew  12957: 
1.957     raeburn  12958: =item B<$upass> Student's password
1.286     matthew  12959: 
1.957     raeburn  12960: =item B<$first> Student's first name
1.286     matthew  12961: 
1.957     raeburn  12962: =item B<$middle> Student's middle name
1.286     matthew  12963: 
1.957     raeburn  12964: =item B<$last> Student's last name
1.286     matthew  12965: 
1.957     raeburn  12966: =item B<$gene> Student's generation
1.286     matthew  12967: 
1.957     raeburn  12968: =item B<$usec> Student's section in course
1.286     matthew  12969: 
                   12970: =item B<$end> Unix time of the roles expiration
                   12971: 
                   12972: =item B<$start> Unix time of the roles start date
                   12973: 
                   12974: =item B<$forceid> If defined, allow $uid to be changed
                   12975: 
                   12976: =item B<$desiredhome> server to use as home server for student
                   12977: 
1.957     raeburn  12978: =item B<$email> Student's permanent e-mail address
                   12979: 
                   12980: =item B<$type> Type of enrollment (auto or manual)
                   12981: 
1.963     raeburn  12982: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12983: 
                   12984: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12985: 
1.963     raeburn  12986: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12987: 
1.963     raeburn  12988: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12989: 
1.1172.2.19  raeburn  12990: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12991: 
                   12992: =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  12993: 
1.286     matthew  12994: =back
1.297     matthew  12995: 
                   12996: =item *
                   12997: 
                   12998: modify_student_enrollment
                   12999: 
1.1172.2.31  raeburn  13000: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13001: 'role.request.course' must be defined for this function to proceed.
                   13002: 
                   13003: Inputs:
                   13004: 
                   13005: =over 4
                   13006: 
1.1172.2.31  raeburn  13007: =item $udom, student's domain
1.297     matthew  13008: 
1.1172.2.31  raeburn  13009: =item $uname, student's name
1.297     matthew  13010: 
1.1172.2.31  raeburn  13011: =item $uid, student's user id
1.297     matthew  13012: 
1.1172.2.31  raeburn  13013: =item $first, student's first name
1.297     matthew  13014: 
                   13015: =item $middle
                   13016: 
                   13017: =item $last
                   13018: 
                   13019: =item $gene
                   13020: 
                   13021: =item $usec
                   13022: 
                   13023: =item $end
                   13024: 
                   13025: =item $start
                   13026: 
1.957     raeburn  13027: =item $type
                   13028: 
                   13029: =item $locktype
                   13030: 
                   13031: =item $cid
                   13032: 
                   13033: =item $selfenroll
                   13034: 
                   13035: =item $context
                   13036: 
1.1172.2.19  raeburn  13037: =item $credits, number of credits student will earn from this class
                   13038: 
1.297     matthew  13039: =back
                   13040: 
1.191     harris41 13041: 
                   13042: =item *
                   13043: 
1.243     albertel 13044: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13045: custom role; give a custom role to a user for the level given by URL.  Specify
                   13046: name and domain of role author, and role name
1.191     harris41 13047: 
                   13048: =item *
                   13049: 
1.243     albertel 13050: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13051: 
                   13052: =item *
                   13053: 
1.243     albertel 13054: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13055: 
                   13056: =back
                   13057: 
                   13058: =head2 Course Infomation
                   13059: 
                   13060: =over 4
1.191     harris41 13061: 
                   13062: =item *
                   13063: 
1.1118    foxr     13064: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13065: specified course id, including all environment settings for the
                   13066: course, the description of the course will be in the hash under the
                   13067: key 'description'
1.191     harris41 13068: 
1.1118    foxr     13069: $options is an optional parameter that if supplied is a hash reference that controls
                   13070: what how this function works.  It has the following key/values:
                   13071: 
                   13072: =over 4
                   13073: 
                   13074: =item freshen_cache
                   13075: 
                   13076: If defined, and the environment cache for the course is valid, it is 
                   13077: returned in the returned hash.
                   13078: 
                   13079: =item one_time
                   13080: 
                   13081: If defined, the last cache time is set to _now_
                   13082: 
                   13083: =item user
                   13084: 
                   13085: If defined, the supplied username is used instead of the current user.
                   13086: 
                   13087: 
                   13088: =back
                   13089: 
1.191     harris41 13090: =item *
                   13091: 
1.624     albertel 13092: resdata($name,$domain,$type,@which) : request for current parameter
                   13093: setting for a specific $type, where $type is either 'course' or 'user',
                   13094: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  13095: answers for 10 minutes.
1.243     albertel 13096: 
1.877     foxr     13097: =item *
                   13098: 
                   13099: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13100: data base, returning a hash that is keyed by the resource name and has
                   13101: values that are the resource value.  I believe that the timestamps and
                   13102: versions are also returned.
                   13103: 
1.1172.2.31  raeburn  13104: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13105: supplemental content area. This routine caches the number of files for
                   13106: 10 minutes.
                   13107: 
1.243     albertel 13108: =back
                   13109: 
                   13110: =head2 Course Modification
                   13111: 
                   13112: =over 4
1.191     harris41 13113: 
                   13114: =item *
                   13115: 
1.243     albertel 13116: writecoursepref($courseid,%prefs) : write preferences (environment
                   13117: database) for a course
1.191     harris41 13118: 
                   13119: =item *
                   13120: 
1.1011    raeburn  13121: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13122: 
                   13123: =item *
                   13124: 
1.1038    raeburn  13125: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13126: 
1.1167    droeschl 13127: =item *
                   13128: 
                   13129: is_course($courseid), is_course($cdom, $cnum)
                   13130: 
                   13131: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13132: two component version $cdom, $cnum. It checks if the specified course exists.
                   13133: 
                   13134: Returns:
                   13135:     undef if the course doesn't exist, otherwise
                   13136:     in scalar context the combined courseid.
                   13137:     in list context the two components of the course identifier, domain and 
                   13138:     courseid.    
                   13139: 
1.243     albertel 13140: =back
                   13141: 
                   13142: =head2 Resource Subroutines
                   13143: 
                   13144: =over 4
1.191     harris41 13145: 
                   13146: =item *
                   13147: 
1.243     albertel 13148: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13149: 
                   13150: =item *
                   13151: 
1.243     albertel 13152: repcopy($filename) : subscribes to the requested file, and attempts to
                   13153: replicate from the owning library server, Might return
1.607     raeburn  13154: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13155: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13156: resource. Expects the local filesystem pathname
                   13157: (/home/httpd/html/res/....)
                   13158: 
                   13159: =back
                   13160: 
                   13161: =head2 Resource Information
                   13162: 
                   13163: =over 4
1.191     harris41 13164: 
                   13165: =item *
                   13166: 
1.1172.2.28  raeburn  13167: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13168: and returns the value of a variety of different possible values,
                   13169: $varname should be a request string, and the other parameters can be
                   13170: used to specify who and what one is asking about. Ordinarily, $cid 
                   13171: does not need to be specified, as it is retrived from 
                   13172: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13173: within lonuserstate::loadmap() when initializing a course, before
                   13174: $env{'request.course.id'} has been set, so it needs to be provided
                   13175: in that one case.
1.243     albertel 13176: 
                   13177: Possible values for $varname are environment.lastname (or other item
                   13178: from the envirnment hash), user.name (or someother aspect about the
                   13179: user), resource.0.maxtries (or some other part and parameter of a
                   13180: resource)
1.204     albertel 13181: 
                   13182: =item *
                   13183: 
1.243     albertel 13184: directcondval($number) : get current value of a condition; reads from a state
                   13185: string
1.204     albertel 13186: 
                   13187: =item *
                   13188: 
1.243     albertel 13189: condval($condidx) : value of condition index based on state
1.204     albertel 13190: 
                   13191: =item *
                   13192: 
1.243     albertel 13193: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13194: resource's metadata, $what should be either a specific key, or either
                   13195: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13196: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13197: 
                   13198: this function automatically caches all requests
1.191     harris41 13199: 
                   13200: =item *
                   13201: 
1.243     albertel 13202: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13203: network of library servers; returns file handle of where SQL and regex results
                   13204: will be stored for query
1.191     harris41 13205: 
                   13206: =item *
                   13207: 
1.243     albertel 13208: symbread($filename) : return symbolic list entry (filename argument optional);
                   13209: returns the data handle
1.191     harris41 13210: 
                   13211: =item *
                   13212: 
1.1172.2.17  raeburn  13213: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13214: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13215: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13216: on failure, user must be in a course, as it assumes the existence of
                   13217: the course initial hash, and uses $env('request.course.id'}.  The third
                   13218: arg is an optional reference to a scalar.  If this arg is passed in the
                   13219: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13220: encrypted; otherwise it will be null.
1.243     albertel 13221: 
1.191     harris41 13222: =item *
                   13223: 
1.243     albertel 13224: symbclean($symb) : removes versions numbers from a symb, returns the
                   13225: cleaned symb
1.191     harris41 13226: 
                   13227: =item *
                   13228: 
1.243     albertel 13229: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13230: course map, user must be in a course for it to work.
1.191     harris41 13231: 
                   13232: =item *
                   13233: 
1.243     albertel 13234: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13235: 
                   13236: =item *
                   13237: 
1.243     albertel 13238: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13239: a random seed, all arguments are optional, if they aren't sent it uses the
                   13240: environment to derive them. Note: if symb isn't sent and it can't get one
                   13241: from &symbread it will use the current time as its return value
1.191     harris41 13242: 
                   13243: =item *
                   13244: 
1.243     albertel 13245: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13246: unfakeable, receipt
1.191     harris41 13247: 
                   13248: =item *
                   13249: 
1.620     albertel 13250: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13251: 
                   13252: =item *
                   13253: 
1.243     albertel 13254: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13255: 
                   13256: =item *
                   13257: 
1.243     albertel 13258: 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 13259: 
                   13260: =item *
                   13261: 
1.243     albertel 13262: 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 13263: 
                   13264: =item *
                   13265: 
1.243     albertel 13266: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13267: 
                   13268: =item *
                   13269: 
1.243     albertel 13270: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13271: forcing spreadsheet to reevaluate the resource scores next time.
                   13272: 
1.1172.2.13  raeburn  13273: =item *
                   13274: 
                   13275: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13276: when viewing in course context.
                   13277: 
                   13278:  input: six args -- filename (decluttered), course number, course domain,
                   13279:                     url, symb (if registered) and group (if this is a
                   13280:                     group item -- e.g., bulletin board, group page etc.).
                   13281: 
                   13282:  output: array of five scalars --
                   13283:          $cfile -- url for file editing if editable on current server
                   13284:          $home -- homeserver of resource (i.e., for author if published,
                   13285:                                           or course if uploaded.).
                   13286:          $switchserver --  1 if server switch will be needed.
                   13287:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13288:          $forceview -- 1 if icon/link should be to go to view mode
                   13289: 
                   13290: =item *
                   13291: 
                   13292: is_course_upload($file,$cnum,$cdom)
                   13293: 
                   13294: Used in course context to determine if current file was uploaded to
                   13295: the course (i.e., would be found in /userfiles/docs on the course's
                   13296: homeserver.
                   13297: 
                   13298:   input: 3 args -- filename (decluttered), course number and course domain.
                   13299:   output: boolean -- 1 if file was uploaded.
                   13300: 
1.243     albertel 13301: =back
                   13302: 
                   13303: =head2 Storing/Retreiving Data
                   13304: 
                   13305: =over 4
1.191     harris41 13306: 
                   13307: =item *
                   13308: 
1.243     albertel 13309: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13310: for this url; hashref needs to be given and should be a \%hashname; the
                   13311: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13312: be derived from the env
1.191     harris41 13313: 
                   13314: =item *
                   13315: 
1.243     albertel 13316: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13317: uses critical subroutine
1.191     harris41 13318: 
                   13319: =item *
                   13320: 
1.243     albertel 13321: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13322: all args are optional
1.191     harris41 13323: 
                   13324: =item *
                   13325: 
1.717     albertel 13326: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13327: dumps the complete (or key matching regexp) namespace into a hash
                   13328: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13329: normally &store()ed into
                   13330: 
                   13331: $range should be either an integer '100' (give me the first 100
                   13332:                                            matching records)
                   13333:               or be  two integers sperated by a - with no spaces
                   13334:                  '30-50' (give me the 30th through the 50th matching
                   13335:                           records)
                   13336: 
                   13337: 
                   13338: =item *
                   13339: 
                   13340: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13341: replaces a &store() version of data with a replacement set of data
                   13342: for a particular resource in a namespace passed in the $storehash hash 
                   13343: reference
                   13344: 
                   13345: =item *
                   13346: 
1.243     albertel 13347: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13348: works very similar to store/cstore, but all data is stored in a
                   13349: temporary location and can be reset using tmpreset, $storehash should
                   13350: be a hash reference, returns nothing on success
1.191     harris41 13351: 
                   13352: =item *
                   13353: 
1.243     albertel 13354: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13355: similar to restore, but all data is stored in a temporary location and
                   13356: can be reset using tmpreset. Returns a hash of values on success,
                   13357: error string otherwise.
1.191     harris41 13358: 
                   13359: =item *
                   13360: 
1.243     albertel 13361: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13362: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13363: 
                   13364: =item *
                   13365: 
1.243     albertel 13366: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13367: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13368: 
                   13369: =item *
                   13370: 
1.243     albertel 13371: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13372: namesp ($udom and $uname are optional)
1.191     harris41 13373: 
                   13374: =item *
                   13375: 
1.702     albertel 13376: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13377: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13378: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13379: 
1.702     albertel 13380: $range should be either an integer '100' (give me the first 100
                   13381:                                            matching records)
                   13382:               or be  two integers sperated by a - with no spaces
                   13383:                  '30-50' (give me the 30th through the 50th matching
                   13384:                           records)
1.449     matthew  13385: =item *
                   13386: 
                   13387: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13388: $store can be a scalar, an array reference, or if the amount to be 
                   13389: incremented is > 1, a hash reference.
                   13390: 
                   13391: ($udom and $uname are optional)
1.191     harris41 13392: 
                   13393: =item *
                   13394: 
1.243     albertel 13395: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13396: ($udom and $uname are optional)
1.191     harris41 13397: 
                   13398: =item *
                   13399: 
1.243     albertel 13400: cput($namespace,$storehash,$udom,$uname) : critical put
                   13401: ($udom and $uname are optional)
1.191     harris41 13402: 
                   13403: =item *
                   13404: 
1.748     albertel 13405: newput($namespace,$storehash,$udom,$uname) :
                   13406: 
                   13407: Attempts to store the items in the $storehash, but only if they don't
                   13408: currently exist, if this succeeds you can be certain that you have 
                   13409: successfully created a new key value pair in the $namespace db.
                   13410: 
                   13411: 
                   13412: Args:
                   13413:  $namespace: name of database to store values to
                   13414:  $storehash: hashref to store to the db
                   13415:  $udom: (optional) domain of user containing the db
                   13416:  $uname: (optional) name of user caontaining the db
                   13417: 
                   13418: Returns:
                   13419:  'ok' -> succeeded in storing all keys of $storehash
                   13420:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13421:                         least <key> already existed in the db (other
                   13422:                         requested keys may also already exist)
1.967     bisitz   13423:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13424:  'con_lost' -> unable to contact request server
                   13425:  'refused' -> action was not allowed by remote machine
                   13426: 
                   13427: 
                   13428: =item *
                   13429: 
1.243     albertel 13430: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13431: reference filled in from namesp (encrypts the return communication)
                   13432: ($udom and $uname are optional)
1.191     harris41 13433: 
                   13434: =item *
                   13435: 
1.243     albertel 13436: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13437: critical subroutine
                   13438: 
1.806     raeburn  13439: =item *
                   13440: 
1.860     raeburn  13441: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13442: array reference filled in from namespace found in domain level on either
                   13443: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13444: 
                   13445: =item *
                   13446: 
1.860     raeburn  13447: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13448: domain level either on specified domain server ($uhome) or primary domain 
                   13449: server ($udom and $uhome are optional)
1.806     raeburn  13450: 
1.943     raeburn  13451: =item * 
                   13452: 
1.1172.2.35  raeburn  13453: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   13454: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13455: the target domain.
                   13456: 
                   13457: May also include additional key => value pairs for the following groups:
                   13458: 
                   13459: =over
                   13460: 
                   13461: =item
                   13462: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13463: 
                   13464: =over
                   13465: 
                   13466: =item defaultquota, authorquota
                   13467: 
                   13468: =back
                   13469: 
                   13470: =item
                   13471: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13472: portfolio for users).
                   13473: 
                   13474: =over
                   13475: 
                   13476: =item
                   13477: aboutme, blog, webdav, portfolio
                   13478: 
                   13479: =back
                   13480: 
                   13481: =item
                   13482: requestcourses: ability to request courses, and how requests are processed.
                   13483: 
                   13484: =over
                   13485: 
                   13486: =item
1.1172.2.37  raeburn  13487: official, unofficial, community, textbook
1.1172.2.35  raeburn  13488: 
                   13489: =back
                   13490: 
                   13491: =item
                   13492: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13493: 
                   13494: =over
                   13495: 
                   13496: =item
1.1172.2.44  raeburn  13497: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  13498: 
                   13499: =back
                   13500: 
                   13501: =item
                   13502: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13503: for course's uploaded content.
                   13504: 
                   13505: =over
                   13506: 
                   13507: =item
1.1172.2.37  raeburn  13508: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35  raeburn  13509: 
                   13510: =back
                   13511: 
                   13512: =item
                   13513: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13514: on your servers.
                   13515: 
                   13516: =over
                   13517: 
                   13518: =item
                   13519: remotesessions, hostedsessions
                   13520: 
                   13521: =back
                   13522: 
                   13523: =back
                   13524: 
                   13525: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13526: utility to create a configuration.db file on a domain's primary library server
                   13527: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13528: -- corresponding values are authentication type (internal, krb4, krb5,
                   13529: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   13530: will be available. Values are retrieved from cache (if current), unless the
                   13531: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13532: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13533: 
                   13534: Typical usage:
1.943     raeburn  13535: 
1.1172.2.35  raeburn  13536: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13537: 
1.243     albertel 13538: =back
                   13539: 
                   13540: =head2 Network Status Functions
                   13541: 
                   13542: =over 4
1.191     harris41 13543: 
                   13544: =item *
                   13545: 
1.1137    raeburn  13546: dirlist() : return directory list based on URI (first arg).
                   13547: 
                   13548: Inputs: 1 required, 5 optional.
                   13549: 
                   13550: =over
                   13551: 
                   13552: =item 
                   13553: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13554: 
                   13555: =item
                   13556: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13557: 
                   13558: =item
                   13559: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13560: 
                   13561: =item
                   13562: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13563: 
                   13564: =item
                   13565: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13566: 
                   13567: =item 
                   13568: $alternateRoot - path to prepend in place of path from $uri.
                   13569: 
                   13570: =back
                   13571: 
                   13572: Returns: Array of up to two items.
                   13573: 
                   13574: =over
                   13575: 
                   13576: a reference to an array of files/subdirectories
                   13577: 
                   13578: =over
                   13579: 
                   13580: Each element in the array of files/subdirectories is a & separated list of
                   13581: item name and the result of running stat on the item.  If dirlist was requested
                   13582: for a file instead of a directory, the item name will be ''. For a directory 
                   13583: listing, if the item is a metadata file, the element will end &N&M 
                   13584: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13585: default copyright set (1).  
                   13586: 
                   13587: =back
                   13588: 
                   13589: a scalar containing error condition (if encountered).
                   13590: 
                   13591: =over
                   13592: 
                   13593: =item 
                   13594: no_host (no homeserver identified for $username:$domain).
                   13595: 
                   13596: =item 
                   13597: no_such_host (server contacted for listing not identified as valid host).
                   13598: 
                   13599: =item 
                   13600: con_lost (connection to remote server failed).
                   13601: 
                   13602: =item 
                   13603: refused (invalid $username:$domain received on lond side).
                   13604: 
                   13605: =item 
                   13606: no_such_dir (directory at specified path on lond side does not exist). 
                   13607: 
                   13608: =item 
                   13609: empty (directory at specified path on lond side is empty).
                   13610: 
                   13611: =over
                   13612: 
                   13613: This is currently not encountered because the &ls3, &ls2, 
                   13614: &ls (_handler) routines on the lond side do not filter out
                   13615: . and .. from a directory listing. 
                   13616: 
                   13617: =back
                   13618: 
                   13619: =back
                   13620: 
                   13621: =back
1.191     harris41 13622: 
                   13623: =item *
                   13624: 
1.243     albertel 13625: spareserver() : find server with least workload from spare.tab
                   13626: 
1.986     foxr     13627: 
                   13628: =item *
                   13629: 
                   13630: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13631: if there is no corresponding loncapa host.
                   13632: 
1.243     albertel 13633: =back
                   13634: 
1.986     foxr     13635: 
1.243     albertel 13636: =head2 Apache Request
                   13637: 
                   13638: =over 4
1.191     harris41 13639: 
                   13640: =item *
                   13641: 
1.243     albertel 13642: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13643: localhost, posts hash
                   13644: 
                   13645: =back
                   13646: 
                   13647: =head2 Data to String to Data
                   13648: 
                   13649: =over 4
1.191     harris41 13650: 
                   13651: =item *
                   13652: 
1.243     albertel 13653: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13654: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13655: 
                   13656: =item *
                   13657: 
1.243     albertel 13658: hashref2str($hashref) : convert a hashref into a string complete with
                   13659: escaping and '=' and '&' separators, supports elements that are
                   13660: arrayrefs and hashrefs
1.191     harris41 13661: 
                   13662: =item *
                   13663: 
1.243     albertel 13664: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13665: with escaping and '&' separators, supports elements that are arrayrefs
                   13666: and hashrefs
1.191     harris41 13667: 
                   13668: =item *
                   13669: 
1.243     albertel 13670: str2hash($string) : convert string to hash using unescaping and
                   13671: splitting on '=' and '&', supports elements that are arrayrefs and
                   13672: hashrefs
1.191     harris41 13673: 
                   13674: =item *
                   13675: 
1.243     albertel 13676: str2array($string) : convert string to hash using unescaping and
                   13677: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13678: 
                   13679: =back
                   13680: 
                   13681: =head2 Logging Routines
                   13682: 
                   13683: 
                   13684: These routines allow one to make log messages in the lonnet.log and
                   13685: lonnet.perm logfiles.
1.191     harris41 13686: 
1.1119    foxr     13687: =over 4
                   13688: 
1.191     harris41 13689: =item *
                   13690: 
1.243     albertel 13691: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13692: 
                   13693: =item *
                   13694: 
1.243     albertel 13695: logthis() : append message to the normal lonnet.log file, it gets
                   13696: preiodically rolled over and deleted.
1.191     harris41 13697: 
                   13698: =item *
                   13699: 
1.243     albertel 13700: logperm() : append a permanent message to lonnet.perm.log, this log
                   13701: file never gets deleted by any automated portion of the system, only
                   13702: messages of critical importance should go in here.
                   13703: 
1.1119    foxr     13704: 
1.243     albertel 13705: =back
                   13706: 
                   13707: =head2 General File Helper Routines
                   13708: 
                   13709: =over 4
1.191     harris41 13710: 
                   13711: =item *
                   13712: 
1.481     raeburn  13713: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13714: (a) files in /uploaded
                   13715:   (i) If a local copy of the file exists - 
                   13716:       compares modification date of local copy with last-modified date for 
                   13717:       definitive version stored on home server for course. If local copy is 
                   13718:       stale, requests a new version from the home server and stores it. 
                   13719:       If the original has been removed from the home server, then local copy 
                   13720:       is unlinked.
                   13721:   (ii) If local copy does not exist -
                   13722:       requests the file from the home server and stores it. 
                   13723:   
                   13724:   If $caller is 'uploadrep':  
                   13725:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13726:     for request for files originally uploaded via DOCS. 
                   13727:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13728:   
                   13729:   Otherwise:
                   13730:      This indicates a call from the content generation phase of the request.
                   13731:      -  returns the entire contents of the file or -1.
                   13732:      
                   13733: (b) files in /res
                   13734:    - returns the entire contents of a file or -1; 
                   13735:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13736: 
1.712     albertel 13737: 
                   13738: =item *
                   13739: 
                   13740: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13741:                   reference
                   13742: 
                   13743: returns either a stat() list of data about the file or an empty list
                   13744: if the file doesn't exist or couldn't find out about it (connection
                   13745: problems or user unknown)
                   13746: 
1.191     harris41 13747: =item *
                   13748: 
1.243     albertel 13749: filelocation($dir,$file) : returns file system location of a file
                   13750: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13751: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13752: and a file of ../bob will become /a/bob)
1.191     harris41 13753: 
                   13754: =item *
                   13755: 
                   13756: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13757: filelocation except for hrefs
                   13758: 
                   13759: =item *
                   13760: 
1.1172.2.49  raeburn  13761: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   13762: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 13763: 
1.243     albertel 13764: =back
                   13765: 
1.608     albertel 13766: =head2 Usererfile file routines (/uploaded*)
                   13767: 
                   13768: =over 4
                   13769: 
                   13770: =item *
                   13771: 
                   13772: userfileupload(): main rotine for putting a file in a user or course's
                   13773:                   filespace, arguments are,
                   13774: 
1.620     albertel 13775:  formname - required - this is the name of the element in $env where the
1.608     albertel 13776:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13777:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13778:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13779:  context - if coursedoc, store the file in the course of the active role
                   13780:              of the current user; 
                   13781:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13782:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13783:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13784:          if undefined, it will be placed in "unknown"
                   13785: 
                   13786:  (This routine calls clean_filename() to remove any dangerous
                   13787:  characters from the filename, and then calls finuserfileupload() to
                   13788:  complete the transaction)
                   13789: 
                   13790:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13791:  and /adm/notfound.html if unsuccessful
                   13792: 
                   13793: =item *
                   13794: 
                   13795: clean_filename(): routine for cleaing a filename up for storage in
                   13796:                  userfile space, argument is:
                   13797: 
                   13798:  filename - proposed filename
                   13799: 
                   13800: returns: the new clean filename
                   13801: 
                   13802: =item *
                   13803: 
1.1090    raeburn  13804: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13805: userspace, probably shouldn't be called directly
                   13806: 
                   13807:   docuname: username or courseid of destination for the file
                   13808:   docudom: domain of user/course of destination for the file
                   13809:   formname: same as for userfileupload()
1.1090    raeburn  13810:   fname: filename (including subdirectories) for the file
                   13811:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13812:   allfiles: reference to hash used to store objects found by parser
                   13813:   codebase: reference to hash used for codebases of java objects found by parser
                   13814:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13815:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13816:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13817:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13818:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13819:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13820:   mimetype: reference to scalar to accommodate mime type determined
                   13821:             from File::MMagic if $parser = parse.
1.608     albertel 13822: 
                   13823:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13824:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13825:  was 'overwrite').
                   13826:  
1.608     albertel 13827: 
                   13828: =item *
                   13829: 
                   13830: renameuserfile(): renames an existing userfile to a new name
                   13831: 
                   13832:   Args:
                   13833:    docuname: username or courseid of destination for the file
                   13834:    docudom: domain of user/course of destination for the file
                   13835:    old: current file name (including any subdirs under userfiles)
                   13836:    new: desired file name (including any subdirs under userfiles)
                   13837: 
                   13838: =item *
                   13839: 
                   13840: mkdiruserfile(): creates a directory is a userfiles dir
                   13841: 
                   13842:   Args:
                   13843:    docuname: username or courseid of destination for the file
                   13844:    docudom: domain of user/course of destination for the file
                   13845:    dir: dir to create (including any subdirs under userfiles)
                   13846: 
                   13847: =item *
                   13848: 
                   13849: removeuserfile(): removes a file that exists in userfiles
                   13850: 
                   13851:   Args:
                   13852:    docuname: username or courseid of destination for the file
                   13853:    docudom: domain of user/course of destination for the file
                   13854:    fname: filname to delete (including any subdirs under userfiles)
                   13855: 
                   13856: =item *
                   13857: 
                   13858: removeuploadedurl(): convience function for removeuserfile()
                   13859: 
                   13860:   Args:
                   13861:    url:  a full /uploaded/... url to delete
                   13862: 
1.747     albertel 13863: =item * 
                   13864: 
                   13865: get_portfile_permissions():
                   13866:   Args:
                   13867:     domain: domain of user or course contain the portfolio files
                   13868:     user: name of user or num of course contain the portfolio files
                   13869:   Returns:
                   13870:     hashref of a dump of the proper file_permissions.db
                   13871:    
                   13872: 
                   13873: =item * 
                   13874: 
                   13875: get_access_controls():
                   13876: 
                   13877: Args:
                   13878:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13879:   group: (optional) the group you want the files associated with
                   13880:   file: (optional) the file you want access info on
                   13881: 
                   13882: Returns:
1.749     raeburn  13883:     a hash (keys are file names) of hashes containing
                   13884:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13885:         values are XML containing access control settings (see below) 
1.747     albertel 13886: 
                   13887: Internal notes:
                   13888: 
1.749     raeburn  13889:  access controls are stored in file_permissions.db as key=value pairs.
                   13890:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13891:         where scope -> public,guest,course,group,domains or users.
                   13892:               end -> UNIX time for end of access (0 -> no end date)
                   13893:               start -> UNIX time for start of access
                   13894: 
                   13895:     value -> XML description of access control
                   13896:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13897:             <start></start>
                   13898:             <end></end>
                   13899: 
                   13900:             <password></password>  for scope type = guest
                   13901: 
                   13902:             <domain></domain>     for scope type = course or group
                   13903:             <number></number>
                   13904:             <roles id="">
                   13905:              <role></role>
                   13906:              <access></access>
                   13907:              <section></section>
                   13908:              <group></group>
                   13909:             </roles>
                   13910: 
                   13911:             <dom></dom>         for scope type = domains
                   13912: 
                   13913:             <users>             for scope type = users
                   13914:              <user>
                   13915:               <uname></uname>
                   13916:               <udom></udom>
                   13917:              </user>
                   13918:             </users>
                   13919:            </scope> 
                   13920:               
                   13921:  Access data is also aggregated for each file in an additional key=value pair:
                   13922:  key -> path to file/file_name\0accesscontrol 
                   13923:  value -> reference to hash
                   13924:           hash contains key = value pairs
                   13925:           where key = uniqueID:scope_end_start
                   13926:                 value = UNIX time record was last updated
                   13927: 
                   13928:           Used to improve speed of look-ups of access controls for each file.  
                   13929:  
                   13930:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13931: 
1.1172.2.13  raeburn  13932: =item *
                   13933: 
1.749     raeburn  13934: modify_access_controls():
                   13935: 
                   13936: Modifies access controls for a portfolio file
                   13937: Args
                   13938: 1. file name
                   13939: 2. reference to hash of required changes,
                   13940: 3. domain
                   13941: 4. username
                   13942:   where domain,username are the domain of the portfolio owner 
                   13943:   (either a user or a course) 
                   13944: 
                   13945: Returns:
                   13946: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13947: 2. result of deletions ('ok' or 'error', with error message).
                   13948: 3. reference to hash of any new or updated access controls.
                   13949: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13950:    key = integer (inbound ID)
1.1172.2.13  raeburn  13951:    value = uniqueID
                   13952: 
                   13953: =item *
                   13954: 
                   13955: get_timebased_id():
                   13956: 
                   13957: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13958: course via the Course Editor (e.g., folders, composite pages,
                   13959: group bulletin boards).
                   13960: 
                   13961: Args: (first three required; six others optional)
                   13962: 
                   13963: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13964:    docssequence, or name of group
                   13965: 
                   13966: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13967:    e.g., num, boardids
                   13968: 
                   13969: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13970:    file will be named nohist_namespace.db
                   13971: 
                   13972: 4. cdom: domain of course; default is current course domain from %env
                   13973: 
                   13974: 5. cnum: course number; default is current course number from %env
                   13975: 
                   13976: 6. idtype: set to concat if an additional digit is to be appended to the
                   13977:    unix timestamp to form the suffix, if the plain timestamp is already
                   13978:    in use.  Default is to not do this, but simply increment the unix
                   13979:    timestamp by 1 until a unique key is obtained.
                   13980: 
                   13981: 7. who: holder of locking key; defaults to user:domain for user.
                   13982: 
                   13983: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13984:    retrying); default is 3.
                   13985: 
                   13986: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13987: 
                   13988: Returns:
                   13989: 
                   13990: 1. suffix obtained (numeric)
                   13991: 
                   13992: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13993: 
                   13994: 3. error: contains (localized) error message if an error occurred.
                   13995: 
1.747     albertel 13996: 
1.608     albertel 13997: =back
                   13998: 
1.243     albertel 13999: =head2 HTTP Helper Routines
                   14000: 
                   14001: =over 4
                   14002: 
1.191     harris41 14003: =item *
                   14004: 
                   14005: escape() : unpack non-word characters into CGI-compatible hex codes
                   14006: 
                   14007: =item *
                   14008: 
                   14009: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14010: 
1.243     albertel 14011: =back
                   14012: 
                   14013: =head1 PRIVATE SUBROUTINES
                   14014: 
                   14015: =head2 Underlying communication routines (Shouldn't call)
                   14016: 
                   14017: =over 4
                   14018: 
                   14019: =item *
                   14020: 
                   14021: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14022: 
                   14023: =item *
                   14024: 
                   14025: reply() : uses subreply to send a message to remote machine, logs all failures
                   14026: 
                   14027: =item *
                   14028: 
                   14029: critical() : passes a critical message to another server; if cannot
                   14030: get through then place message in connection buffer directory and
                   14031: returns con_delayed, if incapable of saving message, returns
                   14032: con_failed
                   14033: 
                   14034: =item *
                   14035: 
                   14036: reconlonc() : tries to reconnect lonc client processes.
                   14037: 
                   14038: =back
                   14039: 
                   14040: =head2 Resource Access Logging
                   14041: 
                   14042: =over 4
                   14043: 
                   14044: =item *
                   14045: 
                   14046: flushcourselogs() : flush (save) buffer logs and access logs
                   14047: 
                   14048: =item *
                   14049: 
                   14050: courselog($what) : save message for course in hash
                   14051: 
                   14052: =item *
                   14053: 
                   14054: courseacclog($what) : save message for course using &courselog().  Perform
                   14055: special processing for specific resource types (problems, exams, quizzes, etc).
                   14056: 
1.191     harris41 14057: =item *
                   14058: 
                   14059: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14060: as a PerlChildExitHandler
1.243     albertel 14061: 
                   14062: =back
                   14063: 
                   14064: =head2 Other
                   14065: 
                   14066: =over 4
                   14067: 
                   14068: =item *
                   14069: 
                   14070: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14071: 
                   14072: =back
                   14073: 
                   14074: =cut
1.877     foxr     14075: 

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