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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.93.4  13(raebu    4:20): # $Id: lonnet.pm,v 1.1172.2.93.4.12 2019/02/03 20:41:27 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1172.2.36  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    92: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   100: use LONCAPA::Lond;
1.1117    foxr      101: 
1.1090    raeburn   102: use File::Copy;
1.676     albertel  103: 
1.195     www       104: my $readit;
1.1172.2.79  raeburn   105: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  106: 
1.619     albertel  107: require Exporter;
                    108: 
                    109: our @ISA = qw (Exporter);
                    110: our @EXPORT = qw(%env);
                    111: 
1.1172.2.9  raeburn   112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       113: {
                    114:     my $logid;
1.1172.2.9  raeburn   115:     sub write_log {
                    116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    117:         if ($context eq 'course') {
                    118:             if (($cnum eq '') || ($cdom eq '')) {
                    119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    121:             }
1.957     raeburn   122:         }
1.1172.2.13  raeburn   123: 	$logid ++;
1.957     raeburn   124:         my $now = time();
                    125: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   126:         my $logentry = {
                    127:                          $id => {
                    128:                                   'exe_uname' => $env{'user.name'},
                    129:                                   'exe_udom'  => $env{'user.domain'},
                    130:                                   'exe_time'  => $now,
                    131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    132:                                   'delflag'   => $delflag,
                    133:                                   'logentry'  => $storehash,
                    134:                                   'uname'     => $uname,
                    135:                                   'udom'      => $udom,
                    136:                                 }
                    137:                        };
                    138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       139:     }
                    140: }
1.1       albertel  141: 
1.163     harris41  142: sub logtouch {
                    143:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  144:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.93.4  7(raebur  145:7): 	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.1172.2.93.4  7(raebur  157:7):     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.1172.2.93.4  7(raebur  170:7):     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  171: 	print $fh "$now:$message:$local\n";
                    172: 	close($fh);
                    173:     }
1.1       albertel  174:     return 1;
                    175: }
                    176: 
1.850     albertel  177: sub create_connection {
1.853     albertel  178:     my ($hostname,$lonid) = @_;
1.851     albertel  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  180: 				     Type    => SOCK_STREAM,
                    181: 				     Timeout => 10);
                    182:     return 0 if (!$client);
1.890     albertel  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  184:     my $result = <$client>;
                    185:     chomp($result);
                    186:     return 1 if ($result eq 'done');
                    187:     return 0;
                    188: }
                    189: 
1.983     raeburn   190: sub get_server_timezone {
                    191:     my ($cnum,$cdom) = @_;
                    192:     my $home=&homeserver($cnum,$cdom);
                    193:     if ($home ne 'no_host') {
                    194:         my $cachetime = 24*3600;
                    195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    196:         if (defined($cached)) {
                    197:             return $timezone;
                    198:         } else {
                    199:             my $timezone = &reply('servertimezone',$home);
                    200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    201:         }
                    202:     }
                    203: }
1.850     albertel  204: 
1.1106    raeburn   205: sub get_server_distarch {
                    206:     my ($lonhost,$ignore_cache) = @_;
                    207:     if (defined($lonhost)) {
                    208:         if (!defined(&hostname($lonhost))) {
                    209:             return;
                    210:         }
                    211:         my $cachetime = 12*3600;
                    212:         if (!$ignore_cache) {
                    213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    214:             if (defined($cached)) {
                    215:                 return $distarch;
                    216:             }
                    217:         }
                    218:         my $rep = &reply('serverdistarch',$lonhost);
                    219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    221:                 $rep eq '') {
                    222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    223:         }
                    224:     }
                    225:     return;
                    226: }
                    227: 
1.993     raeburn   228: sub get_server_loncaparev {
1.1073    raeburn   229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   230:     if (defined($lonhost)) {
                    231:         if (!defined(&hostname($lonhost))) {
                    232:             undef($lonhost);
                    233:         }
                    234:     }
                    235:     if (!defined($lonhost)) {
                    236:         if (defined(&domain($dom,'primary'))) {
                    237:             $lonhost=&domain($dom,'primary');
                    238:             if ($lonhost eq 'no_host') {
                    239:                 undef($lonhost);
                    240:             }
                    241:         }
                    242:     }
                    243:     if (defined($lonhost)) {
1.1073    raeburn   244:         my $cachetime = 12*3600;
                    245:         if (!$ignore_cache) {
                    246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    247:             if (defined($cached)) {
                    248:                 return $loncaparev;
                    249:             }
                    250:         }
                    251:         my ($answer,$loncaparev);
                    252:         my @ids=&current_machine_ids();
                    253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    254:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   256:                 $loncaparev = $1;
                    257:             }
                    258:         } else {
                    259:             $answer = &reply('serverloncaparev',$lonhost);
                    260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    261:                 if ($caller eq 'loncron') {
                    262:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   263:                     $ua->timeout(4);
1.1073    raeburn   264:                     my $protocol = $protocol{$lonhost};
                    265:                     $protocol = 'http' if ($protocol ne 'https');
                    266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    267:                     my $request=new HTTP::Request('GET',$url);
                    268:                     my $response=$ua->request($request);
                    269:                     unless ($response->is_error()) {
                    270:                         my $content = $response->content;
1.1081    raeburn   271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   272:                             $loncaparev = $1;
                    273:                         }
                    274:                     }
                    275:                 } else {
                    276:                     $loncaparev = $loncaparevs{$lonhost};
                    277:                 }
1.1081    raeburn   278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   279:                 $loncaparev = $1;
                    280:             }
1.993     raeburn   281:         }
1.1073    raeburn   282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   283:     }
                    284: }
                    285: 
1.1074    raeburn   286: sub get_server_homeID {
                    287:     my ($hostname,$ignore_cache,$caller) = @_;
                    288:     unless ($ignore_cache) {
                    289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    290:         if (defined($cached)) {
                    291:             return $serverhomeID;
                    292:         }
                    293:     }
                    294:     my $cachetime = 12*3600;
                    295:     my $serverhomeID;
                    296:     if ($caller eq 'loncron') { 
                    297:         my @machine_ids = &machine_ids($hostname);
                    298:         foreach my $id (@machine_ids) {
                    299:             my $response = &reply('serverhomeID',$id);
                    300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    301:                 $serverhomeID = $response;
                    302:                 last;
                    303:             }
                    304:         }
                    305:         if ($serverhomeID eq '') {
                    306:             $serverhomeID = $machine_ids[-1];
                    307:         }
                    308:     } else {
                    309:         $serverhomeID = $serverhomeIDs{$hostname};
                    310:     }
                    311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    312: }
                    313: 
1.1121    raeburn   314: sub get_remote_globals {
                    315:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   316:     my ($result,%returnhash,%whatneeded);
                    317:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   318:         foreach my $what (sort(keys(%{$whathash}))) {
                    319:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   320:             my ($response,$cached);
1.1121    raeburn   321:             unless ($ignore_cache) {
1.1125    raeburn   322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   323:             }
                    324:             if (defined($cached)) {
1.1125    raeburn   325:                 $returnhash{$what} = $response;
1.1121    raeburn   326:             } else {
1.1125    raeburn   327:                 $whatneeded{$what} = 1;
1.1121    raeburn   328:             }
                    329:         }
1.1125    raeburn   330:         if (keys(%whatneeded) == 0) {
                    331:             $result = 'ok';
                    332:         } else {
1.1121    raeburn   333:             my $requested = &freeze_escape(\%whatneeded);
                    334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    336:                 ($rep eq 'unknown_cmd')) {
                    337:                 $result = $rep;
                    338:             } else {
                    339:                 $result = 'ok';
1.1121    raeburn   340:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   341:                 foreach my $item (@pairs) {
                    342:                     my ($key,$value)=split(/=/,$item,2);
                    343:                     my $what = &unescape($key);
                    344:                     my $hashid = $lonhost.'-'.$what;
                    345:                     $returnhash{$what}=&thaw_unescape($value);
                    346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   347:                 }
                    348:             }
                    349:         }
                    350:     }
1.1125    raeburn   351:     return ($result,\%returnhash);
1.1121    raeburn   352: }
                    353: 
1.1124    raeburn   354: sub remote_devalidate_cache {
1.1172.2.35  raeburn   355:     my ($lonhost,$cachekeys) = @_;
                    356:     my $items;
                    357:     return unless (ref($cachekeys) eq 'ARRAY');
                    358:     my $cachestr = join('&',@{$cachekeys});
                    359:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   360: }
                    361: 
1.1       albertel  362: # -------------------------------------------------- Non-critical communication
                    363: sub subreply {
                    364:     my ($cmd,$server)=@_;
1.838     albertel  365:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      366:     #
                    367:     #  With loncnew process trimming, there's a timing hole between lonc server
                    368:     #  process exit and the master server picking up the listen on the AF_UNIX
                    369:     #  socket.  In that time interval, a lock file will exist:
                    370: 
                    371:     my $lockfile=$peerfile.".lock";
                    372:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   373: 	sleep(0.1);
1.549     foxr      374:     }
                    375:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      376:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      377:     #
1.550     foxr      378:     #   We'll give the connection a few tries before abandoning it.  If
                    379:     #   connection is not possible, we'll con_lost back to the client.
                    380:     #   
                    381:     my $client;
                    382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    384: 				      Type    => SOCK_STREAM,
                    385: 				      Timeout => 10);
1.869     albertel  386: 	if ($client) {
1.550     foxr      387: 	    last;		# Connected!
1.850     albertel  388: 	} else {
1.853     albertel  389: 	    &create_connection(&hostname($server),$server);
1.550     foxr      390: 	}
1.1172.2.79  raeburn   391:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      392:     }
                    393:     my $answer;
                    394:     if ($client) {
1.704     albertel  395: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      396: 	$answer=<$client>;
                    397: 	if (!$answer) { $answer="con_lost"; }
                    398: 	chomp($answer);
                    399:     } else {
                    400: 	$answer = 'con_lost';	# Failed connection.
                    401:     }
1.1       albertel  402:     return $answer;
                    403: }
                    404: 
                    405: sub reply {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  408:     my $answer=subreply($cmd,$server);
1.65      www       409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  410:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       411:                 " $cmd to $server returned $answer</font>");
                    412:     }
1.1       albertel  413:     return $answer;
                    414: }
                    415: 
                    416: # ----------------------------------------------------------- Send USR1 to lonc
                    417: 
                    418: sub reconlonc {
1.891     albertel  419:     my ($lonid) = @_;
                    420:     if ($lonid) {
1.1172.2.72  raeburn   421:         my $hostname = &hostname($lonid);
1.891     albertel  422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    423: 	if ($hostname && -e $peerfile) {
                    424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    426: 					     Type    => SOCK_STREAM,
                    427: 					     Timeout => 10);
                    428: 	    if ($client) {
                    429: 		print $client ("reset_retries\n");
                    430: 		my $answer=<$client>;
                    431: 		#reset just this one.
                    432: 	    }
                    433: 	}
                    434: 	return;
                    435:     }
                    436: 
1.836     www       437:     &logthis("Trying to reconnect lonc");
1.1       albertel  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.93.4  7(raebur  439:7):     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  440: 	my $loncpid=<$fh>;
                    441:         chomp($loncpid);
                    442:         if (kill 0 => $loncpid) {
                    443: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    444:             kill USR1 => $loncpid;
                    445:             sleep 1;
1.836     www       446:          } else {
1.12      www       447: 	    &logthis(
1.672     albertel  448:                "<font color=\"blue\">WARNING:".
1.12      www       449:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  450:         }
                    451:     } else {
1.836     www       452: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  453:     }
                    454: }
                    455: 
                    456: # ------------------------------------------------------ Critical communication
1.12      www       457: 
1.1       albertel  458: sub critical {
                    459:     my ($cmd,$server)=@_;
1.838     albertel  460:     unless (&hostname($server)) {
1.672     albertel  461:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       462:                " Critical message to unknown server ($server)</font>");
                    463:         return 'no_such_host';
                    464:     }
1.1       albertel  465:     my $answer=reply($cmd,$server);
                    466:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   467: 	&reconlonc($server);
1.589     albertel  468: 	my $answer=reply($cmd,$server);
1.1       albertel  469:         if ($answer eq 'con_lost') {
                    470:             my $now=time;
                    471:             my $middlename=$cmd;
1.5       www       472:             $middlename=substr($middlename,0,16);
1.1       albertel  473:             $middlename=~s/\W//g;
                    474:             my $dfilename=
1.305     www       475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    476:             $dumpcount++;
1.1       albertel  477:             {
1.448     albertel  478: 		my $dfh;
1.1172.2.93.4  7(raebur  479:7): 		if (open($dfh,">",$dfilename)) {
1.448     albertel  480: 		    print $dfh "$cmd\n"; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
1.1172.2.79  raeburn   484:             sleep 1;
1.1       albertel  485:             my $wcmd='';
                    486:             {
1.448     albertel  487: 		my $dfh;
1.1172.2.93.4  7(raebur  488:7): 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  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.93.4  3(raebur  604:7):     my ($r,$name,$userhashref,$domref) = @_;
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.1172.2.93.4  3(raebur  619:7):     if (!-e "$lonidsdir/$handle.id") {
                    620:7):         if ((ref($domref)) && ($name eq 'lonID') &&
                    621:7):             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    622:7):             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    623:7):             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    624:7):                 $$domref = $possudom;
                    625:7):             }
                    626:7):         }
                    627:7):         return undef;
                    628:7):     }
1.916     albertel  629: 
1.917     albertel  630:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    631:     return undef if (!$opened);
1.916     albertel  632: 
                    633:     flock($idf,LOCK_SH);
                    634:     my %disk_env;
                    635:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    636: 	    &GDBM_READER(),0640)) {
                    637: 	return undef;	
                    638:     }
                    639: 
                    640:     if (!defined($disk_env{'user.name'})
                    641: 	|| !defined($disk_env{'user.domain'})) {
                    642: 	return undef;
                    643:     }
1.1172.2.18  raeburn   644: 
1.1172.2.36  raeburn   645:     if (ref($userhashref) eq 'HASH') {
                    646:         $userhashref->{'name'} = $disk_env{'user.name'};
                    647:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   648:     }
                    649: 
1.916     albertel  650:     return $handle;
                    651: }
                    652: 
1.830     albertel  653: sub timed_flock {
                    654:     my ($file,$lock_type) = @_;
                    655:     my $failed=0;
                    656:     eval {
                    657: 	local $SIG{__DIE__}='DEFAULT';
                    658: 	local $SIG{ALRM}=sub {
                    659: 	    $failed=1;
                    660: 	    die("failed lock");
                    661: 	};
                    662: 	alarm(13);
                    663: 	flock($file,$lock_type);
                    664: 	alarm(0);
                    665:     };
                    666:     if ($failed) {
                    667: 	return undef;
                    668:     } else {
                    669: 	return 1;
                    670:     }
                    671: }
                    672: 
1.5       www       673: # ---------------------------------------------------------- Append Environment
                    674: 
                    675: sub appenv {
1.949     raeburn   676:     my ($newenv,$roles) = @_;
                    677:     if (ref($newenv) eq 'HASH') {
                    678:         foreach my $key (keys(%{$newenv})) {
                    679:             my $refused = 0;
                    680: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    681:                 $refused = 1;
                    682:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   683:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   684:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    685:                         $refused = 0;
                    686:                     }
                    687:                 }
                    688:             }
                    689:             if ($refused) {
                    690:                 &logthis("<font color=\"blue\">WARNING: ".
                    691:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    692:                          .'</font>');
                    693: 	        delete($newenv->{$key});
                    694:             } else {
                    695:                 $env{$key}=$newenv->{$key};
                    696:             }
                    697:         }
1.1172.2.93.4  11(raebu  698:18):         my $lonids = $perlvar{'lonIDsDir'};
                    699:18):         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    700:18):             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    701:18):             if ($opened
                    702:18): 	        && &timed_flock($env_file,LOCK_EX)
                    703:18): 	        &&
                    704:18): 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    705:18): 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    706:18): 	        while (my ($key,$value) = each(%{$newenv})) {
                    707:18): 	            $disk_env{$key} = $value;
                    708:18): 	        }
                    709:18): 	        untie(%disk_env);
                    710:18):             }
1.35      www       711:         }
1.191     harris41  712:     }
1.56      www       713:     return 'ok';
                    714: }
                    715: # ----------------------------------------------------- Delete from Environment
                    716: 
                    717: sub delenv {
1.1104    raeburn   718:     my ($delthis,$regexp,$roles) = @_;
                    719:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    720:         my $refused = 1;
                    721:         if (ref($roles) eq 'ARRAY') {
                    722:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    723:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    724:                 $refused = 0;
                    725:             }
                    726:         }
                    727:         if ($refused) {
                    728:             &logthis("<font color=\"blue\">WARNING: ".
                    729:                      "Attempt to delete from environment ".$delthis);
                    730:             return 'error';
                    731:         }
1.56      www       732:     }
1.917     albertel  733:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    734:     if ($opened
1.915     albertel  735: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  736: 	&&
                    737: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    738: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  739: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   740: 	    if ($regexp) {
                    741:                 if ($key=~/^$delthis/) {
                    742:                     delete($env{$key});
                    743:                     delete($disk_env{$key});
                    744:                 } 
                    745:             } else {
                    746:                 if ($key=~/^\Q$delthis\E/) {
                    747: 		    delete($env{$key});
                    748: 		    delete($disk_env{$key});
                    749: 	        }
                    750:             }
1.448     albertel  751: 	}
1.783     albertel  752: 	untie(%disk_env);
1.5       www       753:     }
                    754:     return 'ok';
1.369     albertel  755: }
                    756: 
1.790     albertel  757: sub get_env_multiple {
                    758:     my ($name) = @_;
                    759:     my @values;
                    760:     if (defined($env{$name})) {
                    761:         # exists is it an array
                    762:         if (ref($env{$name})) {
                    763:             @values=@{ $env{$name} };
                    764:         } else {
                    765:             $values[0]=$env{$name};
                    766:         }
                    767:     }
                    768:     return(@values);
                    769: }
                    770: 
1.958     www       771: # ------------------------------------------------------------------- Locking
                    772: 
                    773: sub set_lock {
                    774:     my ($text)=@_;
                    775:     $locknum++;
                    776:     my $id=$$.'-'.$locknum;
                    777:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    778:              'session.lock.'.$id => $text});
                    779:     return $id;
                    780: }
                    781: 
                    782: sub get_locks {
                    783:     my $num=0;
                    784:     my %texts=();
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if ($lock=~/\w/) {
                    787:           $num++;
                    788:           $texts{$lock}=$env{'session.lock.'.$lock};
                    789:        }
                    790:    }
                    791:    return ($num,%texts);
                    792: }
                    793: 
                    794: sub remove_lock {
                    795:     my ($id)=@_;
                    796:     my $newlocks='';
                    797:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    798:        if (($lock=~/\w/) && ($lock ne $id)) {
                    799:           $newlocks.=','.$lock;
                    800:        }
                    801:     }
                    802:     &appenv({'session.locks' => $newlocks});
                    803:     &delenv('session.lock.'.$id);
                    804: }
                    805: 
                    806: sub remove_all_locks {
                    807:     my $activelocks=$env{'session.locks'};
                    808:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    809:        if ($lock=~/\w/) {
                    810:           &remove_lock($lock);
                    811:        }
                    812:     }
                    813: }
                    814: 
                    815: 
1.369     albertel  816: # ------------------------------------------ Find out current server userload
                    817: sub userload {
                    818:     my $numusers=0;
                    819:     {
                    820: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    821: 	my $filename;
                    822: 	my $curtime=time;
                    823: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  824: 	    next if ($filename eq '.' || $filename eq '..');
                    825: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  826: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  827: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  828: 	}
                    829: 	closedir(LONIDS);
                    830:     }
                    831:     my $userloadpercent=0;
                    832:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    833:     if ($maxuserload) {
1.371     albertel  834: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  835:     }
1.372     albertel  836:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  837:     return $userloadpercent;
1.283     www       838: }
                    839: 
1.1       albertel  840: # ------------------------------ Find server with least workload from spare.tab
1.11      www       841: 
1.1       albertel  842: sub spareserver {
1.1083    raeburn   843:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  844:     my $spare_server;
1.370     albertel  845:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  846:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    847:                                                      :  $userloadpercent;
1.1083    raeburn   848:     my ($uint_dom,$remotesessions);
                    849:     if (($udom ne '') && (&domain($udom) ne '')) {
                    850:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    851:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    852:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    853:         $remotesessions = $udomdefaults{'remotesessions'};
                    854:     }
1.1123    raeburn   855:     my $spareshash = &this_host_spares($udom);
                    856:     if (ref($spareshash) eq 'HASH') {
                    857:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    858:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   859:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    860:                                              $try_server));
1.1123    raeburn   861: 	        ($spare_server, $lowest_load) =
                    862: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    863:             }
1.1083    raeburn   864:         }
1.784     albertel  865: 
1.1123    raeburn   866:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    867: 
                    868:         if (!$found_server) {
                    869:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    870: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   871:                     next unless (&spare_can_host($udom,$uint_dom,
                    872:                                                  $remotesessions,$try_server));
1.1123    raeburn   873: 	            ($spare_server, $lowest_load) =
                    874: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    875:                 }
                    876: 	    }
                    877:         }
1.784     albertel  878:     }
                    879: 
                    880:     if (!$want_server_name) {
1.968     raeburn   881:         my $protocol = 'http';
                    882:         if ($protocol{$spare_server} eq 'https') {
                    883:             $protocol = $protocol{$spare_server};
                    884:         }
1.1001    raeburn   885:         if (defined($spare_server)) {
                    886:             my $hostname = &hostname($spare_server);
1.1083    raeburn   887:             if (defined($hostname)) {
1.1001    raeburn   888: 	        $spare_server = $protocol.'://'.$hostname;
                    889:             }
                    890:         }
1.784     albertel  891:     }
                    892:     return $spare_server;
                    893: }
                    894: 
                    895: sub compare_server_load {
1.1172.2.41  raeburn   896:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    897: 
                    898:     if ($required) {
                    899:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    900:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    901:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    902:         if (($major eq '' && $minor eq '') ||
                    903:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    904:             return ($spare_server,$lowest_load);
                    905:         }
                    906:     }
1.784     albertel  907: 
                    908:     my $loadans     = &reply('load',    $try_server);
                    909:     my $userloadans = &reply('userload',$try_server);
                    910: 
                    911:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   912: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  913:     }
                    914: 
                    915:     my $load;
                    916:     if ($loadans =~ /\d/) {
                    917: 	if ($userloadans =~ /\d/) {
                    918: 	    #both are numbers, pick the bigger one
                    919: 	    $load = ($loadans > $userloadans) ? $loadans 
                    920: 		                              : $userloadans;
1.411     albertel  921: 	} else {
1.784     albertel  922: 	    $load = $loadans;
1.411     albertel  923: 	}
1.784     albertel  924:     } else {
                    925: 	$load = $userloadans;
                    926:     }
                    927: 
                    928:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    929: 	$spare_server = $try_server;
                    930: 	$lowest_load  = $load;
1.370     albertel  931:     }
1.784     albertel  932:     return ($spare_server,$lowest_load);
1.202     matthew   933: }
1.914     albertel  934: 
                    935: # --------------------------- ask offload servers if user already has a session
                    936: sub find_existing_session {
                    937:     my ($udom,$uname) = @_;
1.1123    raeburn   938:     my $spareshash = &this_host_spares($udom);
                    939:     if (ref($spareshash) eq 'HASH') {
                    940:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    941:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    942:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    943:             }
                    944:         }
                    945:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    946:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    947:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    948:             }
                    949:         }
1.914     albertel  950:     }
                    951:     return;
                    952: }
                    953: 
                    954: # -------------------------------- ask if server already has a session for user
                    955: sub has_user_session {
                    956:     my ($lonid,$udom,$uname) = @_;
                    957:     my $result = &reply(join(':','userhassession',
                    958: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    959:     return 1 if ($result eq 'ok');
                    960: 
                    961:     return 0;
                    962: }
                    963: 
1.1076    raeburn   964: # --------- determine least loaded server in a user's domain which allows login
                    965: 
                    966: sub choose_server {
1.1172.2.47  raeburn   967:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   968:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   969:     my %servers = &get_servers($udom);
1.1076    raeburn   970:     my $lowest_load = 30000;
1.1172.2.47  raeburn   971:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    972:     if ($skiploadbal) {
                    973:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    974:         unless (defined($cached)) {
                    975:             my $cachetime = 60*60*24;
                    976:             my %domconfig =
                    977:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    978:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    979:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    980:                                            $cachetime);
                    981:             }
                    982:         }
                    983:     }
1.1076    raeburn   984:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   985:         my $loginvia;
1.1172.2.47  raeburn   986:         if ($skiploadbal) {
                    987:             if (ref($balancers) eq 'HASH') {
                    988:                 next if (exists($balancers->{$lonhost}));
                    989:             }
                    990:         }
1.1115    raeburn   991:         if ($checkloginvia) {
                    992:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   993:             if ($loginvia) {
                    994:                 my ($server,$path) = split(/:/,$loginvia);
                    995:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   996:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   997:                 if ($login_host eq $server) {
                    998:                     $portal_path = $path;
1.1151    raeburn   999:                     $isredirect = 1;
1.1116    raeburn  1000:                 }
                   1001:             } else {
                   1002:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1003:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1004:                 if ($login_host eq $lonhost) {
                   1005:                     $portal_path = '';
1.1151    raeburn  1006:                     $isredirect = ''; 
1.1116    raeburn  1007:                 }
                   1008:             }
                   1009:         } else {
1.1076    raeburn  1010:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1011:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1012:         }
                   1013:     }
                   1014:     if ($login_host ne '') {
1.1116    raeburn  1015:         $hostname = &hostname($login_host);
1.1076    raeburn  1016:     }
1.1172.2.88  raeburn  1017:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1018: }
                   1019: 
1.202     matthew  1020: # --------------------------------------------- Try to change a user's password
                   1021: 
                   1022: sub changepass {
1.799     raeburn  1023:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1024:     $currentpass = &escape($currentpass);
                   1025:     $newpass     = &escape($newpass);
1.1030    raeburn  1026:     my $lonhost = $perlvar{'lonHostID'};
                   1027:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1028: 		       $server);
                   1029:     if (! $answer) {
                   1030: 	&logthis("No reply on password change request to $server ".
                   1031: 		 "by $uname in domain $udom.");
                   1032:     } elsif ($answer =~ "^ok") {
                   1033:         &logthis("$uname in $udom successfully changed their password ".
                   1034: 		 "on $server.");
                   1035:     } elsif ($answer =~ "^pwchange_failure") {
                   1036: 	&logthis("$uname in $udom was unable to change their password ".
                   1037: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1038: 		 "or pwchange");
                   1039:     } elsif ($answer =~ "^non_authorized") {
                   1040:         &logthis("$uname in $udom did not get their password correct when ".
                   1041: 		 "attempting to change it on $server.");
                   1042:     } elsif ($answer =~ "^auth_mode_error") {
                   1043:         &logthis("$uname in $udom attempted to change their password despite ".
                   1044: 		 "not being locally or internally authenticated on $server.");
                   1045:     } elsif ($answer =~ "^unknown_user") {
                   1046:         &logthis("$uname in $udom attempted to change their password ".
                   1047: 		 "on $server but were unable to because $server is not ".
                   1048: 		 "their home server.");
                   1049:     } elsif ($answer =~ "^refused") {
                   1050: 	&logthis("$server refused to change $uname in $udom password because ".
                   1051: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1052:     } elsif ($answer =~ "invalid_client") {
                   1053:         &logthis("$server refused to change $uname in $udom password because ".
                   1054:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1055:     }
                   1056:     return $answer;
1.1       albertel 1057: }
                   1058: 
1.169     harris41 1059: # ----------------------- Try to determine user's current authentication scheme
                   1060: 
                   1061: sub queryauthenticate {
                   1062:     my ($uname,$udom)=@_;
1.456     albertel 1063:     my $uhome=&homeserver($uname,$udom);
                   1064:     if (!$uhome) {
                   1065: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1066: 	return 'no_host';
                   1067:     }
                   1068:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1069:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1070: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1071:     }
1.456     albertel 1072:     return $answer;
1.169     harris41 1073: }
                   1074: 
1.1       albertel 1075: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1076: 
1.1       albertel 1077: sub authenticate {
1.1073    raeburn  1078:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1079:     $upass=&escape($upass);
                   1080:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1081:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1082:     my $newhome;
1.836     www      1083:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1084: # Maybe the machine was offline and only re-appeared again recently?
                   1085:         &reconlonc();
                   1086: # One more
1.952     raeburn  1087: 	$uhome=&homeserver($uname,$udom,1);
                   1088:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1089:             if (defined(&domain($udom,'primary'))) {
                   1090:                 $newhome=&domain($udom,'primary');
                   1091:             }
                   1092:             if ($newhome ne '') {
                   1093:                 $uhome = $newhome;
                   1094:             }
                   1095:         }
1.836     www      1096: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1097: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1098: 	    return 'no_host';
                   1099:         }
1.1       albertel 1100:     }
1.1073    raeburn  1101:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1102:     if ($answer eq 'authorized') {
1.952     raeburn  1103:         if ($newhome) {
                   1104:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1105:             return 'no_account_on_host'; 
                   1106:         } else {
                   1107:             &logthis("User $uname at $udom authorized by $uhome");
                   1108:             return $uhome;
                   1109:         }
1.471     albertel 1110:     }
                   1111:     if ($answer eq 'non_authorized') {
                   1112: 	&logthis("User $uname at $udom rejected by $uhome");
                   1113: 	return 'no_host'; 
1.9       www      1114:     }
1.471     albertel 1115:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1116:     return 'no_host';
                   1117: }
                   1118: 
1.1073    raeburn  1119: sub can_host_session {
1.1074    raeburn  1120:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1121:     my $canhost = 1;
1.1074    raeburn  1122:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1123:     if (ref($remotesessions) eq 'HASH') {
                   1124:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1126:                 $canhost = 0;
                   1127:             } else {
                   1128:                 $canhost = 1;
                   1129:             }
                   1130:         }
                   1131:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1132:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1133:                 $canhost = 1;
                   1134:             } else {
                   1135:                 $canhost = 0;
                   1136:             }
                   1137:         }
                   1138:         if ($canhost) {
                   1139:             if ($remotesessions->{'version'} ne '') {
                   1140:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1141:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1142:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1143:                         my $major = $1;
                   1144:                         my $minor = $2;
                   1145:                         if (($major < $reqmajor ) ||
                   1146:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1147:                             $canhost = 0;
                   1148:                         }
                   1149:                     } else {
                   1150:                         $canhost = 0;
                   1151:                     }
                   1152:                 }
                   1153:             }
                   1154:         }
                   1155:     }
                   1156:     if ($canhost) {
                   1157:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1158:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1159:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1160:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1161:                 if (($uint_dom ne '') && 
                   1162:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1163:                     $canhost = 0;
                   1164:                 } else {
                   1165:                     $canhost = 1;
                   1166:                 }
                   1167:             }
                   1168:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1169:                 if (($uint_dom ne '') && 
                   1170:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1171:                     $canhost = 1;
                   1172:                 } else {
                   1173:                     $canhost = 0;
                   1174:                 }
                   1175:             }
                   1176:         }
                   1177:     }
                   1178:     return $canhost;
                   1179: }
                   1180: 
1.1083    raeburn  1181: sub spare_can_host {
                   1182:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1183:     my $canhost=1;
1.1172.2.62  raeburn  1184:     my $try_server_hostname = &hostname($try_server);
                   1185:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1186:     my $serverhomedom = &host_domain($serverhomeID);
                   1187:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1188:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1189:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1190:             $canhost = 0;
                   1191:         }
                   1192:     }
                   1193:     if (($canhost) && ($uint_dom)) {
                   1194:         my @intdoms;
                   1195:         my $internet_names = &get_internet_names($try_server);
                   1196:         if (ref($internet_names) eq 'ARRAY') {
                   1197:             @intdoms = @{$internet_names};
                   1198:         }
                   1199:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1200:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1201:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1202:                                          $remotesessions,
                   1203:                                          $defdomdefaults{'hostedsessions'});
                   1204:         }
1.1083    raeburn  1205:     }
                   1206:     return $canhost;
                   1207: }
                   1208: 
1.1123    raeburn  1209: sub this_host_spares {
                   1210:     my ($dom) = @_;
1.1126    raeburn  1211:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1212:     my @hosts = &current_machine_ids();
                   1213:     foreach my $lonhost (@hosts) {
                   1214:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1215:             $dom_in_use = $dom;
                   1216:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1217:             last;
                   1218:         }
                   1219:     }
1.1126    raeburn  1220:     if ($dom_in_use ne '') {
                   1221:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1222:     }
                   1223:     if (ref($result) ne 'HASH') {
                   1224:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1225:         $dom_in_use = &host_domain($lonhost_in_use);
                   1226:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1227:         if (ref($result) ne 'HASH') {
                   1228:             $result = \%spareid;
                   1229:         }
                   1230:     }
                   1231:     return $result;
                   1232: }
                   1233: 
                   1234: sub spares_for_offload  {
                   1235:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1236:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1237:     if (defined($cached)) {
                   1238:         return $result;
                   1239:     } else {
1.1126    raeburn  1240:         my $cachetime = 60*60*24;
                   1241:         my %domconfig =
                   1242:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1243:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1244:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1245:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1246:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1247:                 }
                   1248:             }
                   1249:         }
                   1250:     }
1.1126    raeburn  1251:     return;
1.1123    raeburn  1252: }
                   1253: 
1.1129    raeburn  1254: sub get_lonbalancer_config {
                   1255:     my ($servers) = @_;
                   1256:     my ($currbalancer,$currtargets);
                   1257:     if (ref($servers) eq 'HASH') {
                   1258:         foreach my $server (keys(%{$servers})) {
                   1259:             my %what = (
                   1260:                          spareid => 1,
                   1261:                          perlvar => 1,
                   1262:                        );
                   1263:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1264:             if ($result eq 'ok') {
                   1265:                 if (ref($returnhash) eq 'HASH') {
                   1266:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1267:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1268:                             $currbalancer = $server;
                   1269:                             $currtargets = {};
                   1270:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1271:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1272:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1273:                                 }
                   1274:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1275:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1276:                                 }
                   1277:                             }
                   1278:                             last;
                   1279:                         }
                   1280:                     }
                   1281:                 }
                   1282:             }
                   1283:         }
                   1284:     }
                   1285:     return ($currbalancer,$currtargets);
                   1286: }
                   1287: 
                   1288: sub check_loadbalancing {
1.1172.2.88  raeburn  1289:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1290:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1291:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1292:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1293:     my @hosts = &current_machine_ids();
1.1129    raeburn  1294:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1295:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1296:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1297:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1298:     my $domneedscache; 
1.1129    raeburn  1299:     my $cachetime = 60*60*24;
                   1300: 
                   1301:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1302:         $dom_in_use = $udom;
                   1303:         $homeintdom = 1;
                   1304:     } else {
                   1305:         $dom_in_use = $serverhomedom;
                   1306:     }
                   1307:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1308:     unless (defined($cached)) {
                   1309:         my %domconfig =
                   1310:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1311:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1312:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1313:         } else {
                   1314:             $domneedscache = $dom_in_use;
1.1129    raeburn  1315:         }
                   1316:     }
                   1317:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1318:         ($is_balancer,$currtargets,$currrules) =
                   1319:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1320:         if ($is_balancer) {
                   1321:             if (ref($currrules) eq 'HASH') {
                   1322:                 if ($homeintdom) {
                   1323:                     if ($uname ne '') {
                   1324:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1325:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1326:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1327:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1328:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1329:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1330:                             }
                   1331:                         }
                   1332:                         if ($rule_in_effect eq '') {
                   1333:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1334:                             if ($userenv{'inststatus'} ne '') {
                   1335:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1336:                                 my ($othertitle,$usertypes,$types) =
                   1337:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1338:                                 if (ref($types) eq 'ARRAY') {
                   1339:                                     foreach my $type (@{$types}) {
                   1340:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1341:                                             if (exists($currrules->{$type})) {
                   1342:                                                 $rule_in_effect = $currrules->{$type};
                   1343:                                             }
                   1344:                                         }
                   1345:                                     }
                   1346:                                 }
                   1347:                             } else {
                   1348:                                 if (exists($currrules->{'default'})) {
                   1349:                                     $rule_in_effect = $currrules->{'default'};
                   1350:                                 }
                   1351:                             }
                   1352:                         }
                   1353:                     } else {
                   1354:                         if (exists($currrules->{'default'})) {
                   1355:                             $rule_in_effect = $currrules->{'default'};
                   1356:                         }
                   1357:                     }
                   1358:                 } else {
                   1359:                     if ($currrules->{'_LC_external'} ne '') {
                   1360:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1361:                     }
                   1362:                 }
                   1363:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1364:                                                        $uname,$udom);
                   1365:             }
                   1366:         }
                   1367:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1368:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1369:         unless (defined($cached)) {
                   1370:             my %domconfig =
                   1371:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1372:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1373:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1374:             } else {
                   1375:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1376:             }
                   1377:         }
                   1378:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1379:             ($is_balancer,$currtargets,$currrules) =
                   1380:                 &check_balancer_result($result,@hosts);
                   1381:             if ($is_balancer) {
1.1129    raeburn  1382:                 if (ref($currrules) eq 'HASH') {
                   1383:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1384:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1385:                     }
                   1386:                 }
                   1387:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1388:                                                        $uname,$udom);
                   1389:             }
                   1390:         } else {
                   1391:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1392:                 $is_balancer = 1;
                   1393:                 $offloadto = &this_host_spares($dom_in_use);
                   1394:             }
1.1172.2.75  raeburn  1395:             unless (defined($cached)) {
                   1396:                 $domneedscache = $serverhomedom;
                   1397:             }
1.1129    raeburn  1398:         }
                   1399:     } else {
                   1400:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1401:             $is_balancer = 1;
                   1402:             $offloadto = &this_host_spares($dom_in_use);
                   1403:         }
1.1172.2.75  raeburn  1404:         unless (defined($cached)) {
                   1405:             $domneedscache = $serverhomedom;
                   1406:         }
                   1407:     }
                   1408:     if ($domneedscache) {
                   1409:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1410:     }
1.1172.2.5  raeburn  1411:     if ($is_balancer) {
                   1412:         my $lowest_load = 30000;
                   1413:         if (ref($offloadto) eq 'HASH') {
                   1414:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1415:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1416:                     ($otherserver,$lowest_load) =
                   1417:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1418:                 }
1.1129    raeburn  1419:             }
1.1172.2.5  raeburn  1420:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1421: 
1.1172.2.5  raeburn  1422:             if (!$found_server) {
                   1423:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1424:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1425:                         ($otherserver,$lowest_load) =
                   1426:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1427:                     }
                   1428:                 }
                   1429:             }
                   1430:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1431:             if (@{$offloadto} == 1) {
                   1432:                 $otherserver = $offloadto->[0];
                   1433:             } elsif (@{$offloadto} > 1) {
                   1434:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1435:                     ($otherserver,$lowest_load) =
                   1436:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1437:                 }
                   1438:             }
                   1439:         }
1.1172.2.88  raeburn  1440:         unless ($caller eq 'login') {
                   1441:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1442:                 $is_balancer = 0;
                   1443:                 if ($uname ne '' && $udom ne '') {
                   1444:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1172.2.5  raeburn  1445: 
1.1172.2.88  raeburn  1446:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1447:                                  'user.loadbalcheck.time' => time});
                   1448:                     }
1.1172.2.5  raeburn  1449:                 }
1.1129    raeburn  1450:             }
                   1451:         }
                   1452:     }
                   1453:     return ($is_balancer,$otherserver);
                   1454: }
                   1455: 
1.1172.2.12  raeburn  1456: sub check_balancer_result {
                   1457:     my ($result,@hosts) = @_;
                   1458:     my ($is_balancer,$currtargets,$currrules);
                   1459:     if (ref($result) eq 'HASH') {
                   1460:         if ($result->{'lonhost'} ne '') {
                   1461:             my $currbalancer = $result->{'lonhost'};
                   1462:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1463:                 $is_balancer = 1;
                   1464:                 $currtargets = $result->{'targets'};
                   1465:                 $currrules = $result->{'rules'};
                   1466:             }
                   1467:         } else {
                   1468:             foreach my $key (keys(%{$result})) {
                   1469:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1470:                     (ref($result->{$key}) eq 'HASH')) {
                   1471:                     $is_balancer = 1;
                   1472:                     $currrules = $result->{$key}{'rules'};
                   1473:                     $currtargets = $result->{$key}{'targets'};
                   1474:                     last;
                   1475:                 }
                   1476:             }
                   1477:         }
                   1478:     }
                   1479:     return ($is_balancer,$currtargets,$currrules);
                   1480: }
                   1481: 
1.1129    raeburn  1482: sub get_loadbalancer_targets {
                   1483:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1484:     my $offloadto;
1.1172.2.4  raeburn  1485:     if ($rule_in_effect eq 'none') {
                   1486:         return [$perlvar{'lonHostID'}];
                   1487:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1488:         $offloadto = $currtargets;
                   1489:     } else {
                   1490:         if ($rule_in_effect eq 'homeserver') {
                   1491:             my $homeserver = &homeserver($uname,$udom);
                   1492:             if ($homeserver ne 'no_host') {
                   1493:                 $offloadto = [$homeserver];
                   1494:             }
                   1495:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1496:             my %domconfig =
                   1497:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1498:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1499:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1500:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1501:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1502:                     }
                   1503:                 }
                   1504:             } else {
1.1172.2.7  raeburn  1505:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1506:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1507:                 if (&hostname($remotebalancer) ne '') {
                   1508:                     $offloadto = [$remotebalancer];
                   1509:                 }
                   1510:             }
                   1511:         } elsif (&hostname($rule_in_effect) ne '') {
                   1512:             $offloadto = [$rule_in_effect];
                   1513:         }
                   1514:     }
                   1515:     return $offloadto;
                   1516: }
                   1517: 
1.1127    raeburn  1518: sub internet_dom_servers {
                   1519:     my ($dom) = @_;
                   1520:     my (%uniqservers,%servers);
                   1521:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1522:     my @machinedoms = &machine_domains($primaryserver);
                   1523:     foreach my $mdom (@machinedoms) {
                   1524:         my %currservers = %servers;
                   1525:         my %server = &get_servers($mdom);
                   1526:         %servers = (%currservers,%server);
                   1527:     }
                   1528:     my %by_hostname;
                   1529:     foreach my $id (keys(%servers)) {
                   1530:         push(@{$by_hostname{$servers{$id}}},$id);
                   1531:     }
                   1532:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1533:         if (@{$by_hostname{$hostname}} > 1) {
                   1534:             my $match = 0;
                   1535:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1536:                 if (&host_domain($id) eq $dom) {
                   1537:                     $uniqservers{$id} = $hostname;
                   1538:                     $match = 1;
                   1539:                 }
                   1540:             }
                   1541:             unless ($match) {
                   1542:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1543:             }
                   1544:         } else {
                   1545:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1546:         }
                   1547:     }
                   1548:     return %uniqservers;
                   1549: }
                   1550: 
1.1       albertel 1551: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1552: 
1.599     albertel 1553: my %homecache;
1.1       albertel 1554: sub homeserver {
1.230     stredwic 1555:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1556:     my $index="$uname:$udom";
1.426     albertel 1557: 
1.599     albertel 1558:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1559: 
                   1560:     my %servers = &get_servers($udom,'library');
                   1561:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1562:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1563: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1564: 
                   1565: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1566: 	if ($answer eq 'found') {
                   1567: 	    delete($badServerCache{$tryserver}); 
                   1568: 	    return $homecache{$index}=$tryserver;
                   1569: 	} elsif ($answer eq 'no_host') {
                   1570: 	    $badServerCache{$tryserver}=1;
                   1571: 	}
1.1       albertel 1572:     }    
                   1573:     return 'no_host';
1.70      www      1574: }
                   1575: 
                   1576: # ------------------------------------- Find the usernames behind a list of IDs
                   1577: 
                   1578: sub idget {
                   1579:     my ($udom,@ids)=@_;
                   1580:     my %returnhash=();
                   1581:     
1.841     albertel 1582:     my %servers = &get_servers($udom,'library');
                   1583:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1584: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1585: 	$idlist=~tr/A-Z/a-z/; 
                   1586: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1587: 	my @answer=();
                   1588: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1589: 	    @answer=split(/\&/,$reply);
                   1590: 	}                    ;
                   1591: 	my $i;
                   1592: 	for ($i=0;$i<=$#ids;$i++) {
                   1593: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1594: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1595: 	    } 
                   1596: 	}
                   1597:     } 
1.70      www      1598:     return %returnhash;
                   1599: }
                   1600: 
                   1601: # ------------------------------------- Find the IDs behind a list of usernames
                   1602: 
                   1603: sub idrget {
                   1604:     my ($udom,@unames)=@_;
                   1605:     my %returnhash=();
1.800     albertel 1606:     foreach my $uname (@unames) {
                   1607:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1608:     }
1.70      www      1609:     return %returnhash;
                   1610: }
                   1611: 
                   1612: # ------------------------------- Store away a list of names and associated IDs
                   1613: 
                   1614: sub idput {
                   1615:     my ($udom,%ids)=@_;
                   1616:     my %servers=();
1.800     albertel 1617:     foreach my $uname (keys(%ids)) {
                   1618: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1619:         my $uhom=&homeserver($uname,$udom);
1.70      www      1620:         if ($uhom ne 'no_host') {
1.800     albertel 1621:             my $id=&escape($ids{$uname});
1.70      www      1622:             $id=~tr/A-Z/a-z/;
1.800     albertel 1623:             my $esc_unam=&escape($uname);
1.70      www      1624: 	    if ($servers{$uhom}) {
1.800     albertel 1625: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1626:             } else {
1.800     albertel 1627:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1628:             }
                   1629:         }
1.191     harris41 1630:     }
1.800     albertel 1631:     foreach my $server (keys(%servers)) {
                   1632:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1633:     }
1.344     www      1634: }
                   1635: 
1.1172.2.30  raeburn  1636: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1637: 
                   1638: sub iddel {
                   1639:     my ($udom,$idshashref,$uhome)=@_;
                   1640:     my %result=();
                   1641:     unless (ref($idshashref) eq 'HASH') {
                   1642:         return %result;
                   1643:     }
                   1644:     my %servers=();
                   1645:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1646:         my $uhom;
                   1647:         if ($uhome) {
                   1648:             $uhom = $uhome;
                   1649:         } else {
                   1650:             $uhom=&homeserver($uname,$udom);
                   1651:         }
                   1652:         if ($uhom ne 'no_host') {
                   1653:             if ($servers{$uhom}) {
                   1654:                 $servers{$uhom}.='&'.&escape($id);
                   1655:             } else {
                   1656:                 $servers{$uhom}=&escape($id);
                   1657:             }
                   1658:         }
                   1659:     }
                   1660:     foreach my $server (keys(%servers)) {
                   1661:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1662:     }
                   1663:     return %result;
                   1664: }
                   1665: 
1.1023    raeburn  1666: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1667: sub dump_dom {
1.1165    droeschl 1668:     my ($namespace, $udom, $regexp) = @_;
                   1669: 
                   1670:     $udom ||= $env{'user.domain'};
                   1671: 
                   1672:     return () unless $udom;
                   1673: 
                   1674:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1675: }
                   1676: 
1.1023    raeburn  1677: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1678: 
                   1679: sub get_dom {
1.860     raeburn  1680:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1681:     return if ($udom eq 'public');
1.806     raeburn  1682:     my $items='';
                   1683:     foreach my $item (@$storearr) {
                   1684:         $items.=&escape($item).'&';
                   1685:     }
                   1686:     $items=~s/\&$//;
1.860     raeburn  1687:     if (!$udom) {
                   1688:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1689:         return if ($udom eq 'public');
1.860     raeburn  1690:         if (defined(&domain($udom,'primary'))) {
                   1691:             $uhome=&domain($udom,'primary');
                   1692:         } else {
1.874     albertel 1693:             undef($uhome);
1.860     raeburn  1694:         }
                   1695:     } else {
                   1696:         if (!$uhome) {
                   1697:             if (defined(&domain($udom,'primary'))) {
                   1698:                 $uhome=&domain($udom,'primary');
                   1699:             }
                   1700:         }
                   1701:     }
                   1702:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.93.4  2(raebur 1703:7):         my $rep;
                   1704:7):         if ($namespace =~ /^enc/) {
                   1705:7):             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1706:7):         } else {
                   1707:7):             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1708:7):         }
1.866     raeburn  1709:         my %returnhash;
1.875     albertel 1710:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1711:             return %returnhash;
                   1712:         }
1.806     raeburn  1713:         my @pairs=split(/\&/,$rep);
                   1714:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1715:             return @pairs;
                   1716:         }
                   1717:         my $i=0;
                   1718:         foreach my $item (@$storearr) {
                   1719:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1720:             $i++;
                   1721:         }
                   1722:         return %returnhash;
                   1723:     } else {
1.880     banghart 1724:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1725:     }
                   1726: }
                   1727: 
                   1728: # -------------------------------------------- put items in domain db files 
                   1729: 
                   1730: sub put_dom {
1.860     raeburn  1731:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1732:     if (!$udom) {
                   1733:         $udom=$env{'user.domain'};
                   1734:         if (defined(&domain($udom,'primary'))) {
                   1735:             $uhome=&domain($udom,'primary');
                   1736:         } else {
1.874     albertel 1737:             undef($uhome);
1.860     raeburn  1738:         }
                   1739:     } else {
                   1740:         if (!$uhome) {
                   1741:             if (defined(&domain($udom,'primary'))) {
                   1742:                 $uhome=&domain($udom,'primary');
                   1743:             }
                   1744:         }
                   1745:     } 
                   1746:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1747:         my $items='';
                   1748:         foreach my $item (keys(%$storehash)) {
                   1749:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1750:         }
                   1751:         $items=~s/\&$//;
1.1172.2.93.4  2(raebur 1752:7):         if ($namespace =~ /^enc/) {
                   1753:7):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1754:7):         } else {
                   1755:7):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1756:7):         }
1.806     raeburn  1757:     } else {
1.860     raeburn  1758:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1759:     }
                   1760: }
                   1761: 
1.1023    raeburn  1762: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1763: sub newput_dom {
1.1023    raeburn  1764:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1765:     my $result;
                   1766:     if (!$udom) {
                   1767:         $udom=$env{'user.domain'};
                   1768:     }
1.1023    raeburn  1769:     if ($udom) {
                   1770:         my $uname = &get_domainconfiguser($udom);
                   1771:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1772:     }
                   1773:     return $result;
                   1774: }
                   1775: 
1.1023    raeburn  1776: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1777: sub del_dom {
1.1023    raeburn  1778:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1779:     if (ref($storearr) eq 'ARRAY') {
                   1780:         if (!$udom) {
                   1781:             $udom=$env{'user.domain'};
                   1782:         }
1.1023    raeburn  1783:         if ($udom) {
                   1784:             my $uname = &get_domainconfiguser($udom); 
                   1785:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1786:         }
                   1787:     }
                   1788: }
                   1789: 
1.1023    raeburn  1790: # ----------------------------------construct domainconfig user for a domain 
                   1791: sub get_domainconfiguser {
                   1792:     my ($udom) = @_;
                   1793:     return $udom.'-domainconfig';
                   1794: }
                   1795: 
1.837     raeburn  1796: sub retrieve_inst_usertypes {
                   1797:     my ($udom) = @_;
                   1798:     my (%returnhash,@order);
1.989     raeburn  1799:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1800:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1801:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1802:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1803:     } else {
                   1804:         if (defined(&domain($udom,'primary'))) {
                   1805:             my $uhome=&domain($udom,'primary');
                   1806:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1807:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1808:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1809:                 return (\%returnhash,\@order);
                   1810:             }
                   1811:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1812:             my @pairs=split(/\&/,$hashitems);
                   1813:             foreach my $item (@pairs) {
                   1814:                 my ($key,$value)=split(/=/,$item,2);
                   1815:                 $key = &unescape($key);
                   1816:                 next if ($key =~ /^error: 2 /);
                   1817:                 $returnhash{$key}=&thaw_unescape($value);
                   1818:             }
                   1819:             my @esc_order = split(/\&/,$orderitems);
                   1820:             foreach my $item (@esc_order) {
                   1821:                 push(@order,&unescape($item));
                   1822:             }
                   1823:         } else {
1.1172.2.44  raeburn  1824:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1825:         }
1.1172.2.44  raeburn  1826:         return (\%returnhash,\@order);
1.837     raeburn  1827:     }
                   1828: }
                   1829: 
1.868     raeburn  1830: sub is_domainimage {
                   1831:     my ($url) = @_;
1.1172.2.74  raeburn  1832:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1833:         if (&domain($1) ne '') {
                   1834:             return '1';
                   1835:         }
                   1836:     }
                   1837:     return;
                   1838: }
                   1839: 
1.899     raeburn  1840: sub inst_directory_query {
                   1841:     my ($srch) = @_;
                   1842:     my $udom = $srch->{'srchdomain'};
                   1843:     my %results;
                   1844:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1845:     my $outcome;
1.899     raeburn  1846:     if ($homeserver ne '') {
1.1172.2.93.4  4(raebur 1847:7):         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   1848:7):             if ($srch->{'srchby'} eq 'email') {
                   1849:7):                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   1850:7):                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.([\w.\-]+)\'?$/);
                   1851:7):                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   1852:7):                     (($major == 2) && ($minor < 11)) || 
                   1853:7):                     (($major == 2) && ($minor == 11) && ($subver !~ /^2\.B/))) {
                   1854:7):                     return;
                   1855:7):                 }
                   1856:7):             }
                   1857:7):         }
1.904     albertel 1858: 	my $queryid=&reply("querysend:instdirsearch:".
                   1859: 			   &escape($srch->{'srchby'}).':'.
                   1860: 			   &escape($srch->{'srchterm'}).':'.
                   1861: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1862: 	my $host=&hostname($homeserver);
                   1863: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.93.4  1(raebur 1864:7): 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1865: 	    return;
                   1866: 	}
                   1867: 	my $response = &get_query_reply($queryid);
                   1868: 	my $maxtries = 5;
                   1869: 	my $tries = 1;
                   1870: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1871: 	    $response = &get_query_reply($queryid);
                   1872: 	    $tries ++;
                   1873: 	}
                   1874: 
                   1875:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1876:             if ($response eq 'unavailable') {
                   1877:                 $outcome = $response;
                   1878:             } else {
                   1879:                 $outcome = 'ok';
                   1880:                 my @matches = split(/\n/,$response);
                   1881:                 foreach my $match (@matches) {
                   1882:                     my ($key,$value) = split(/=/,$match);
                   1883:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1884:                 }
1.899     raeburn  1885:             }
                   1886:         }
                   1887:     }
1.909     raeburn  1888:     return ($outcome,%results);
1.899     raeburn  1889: }
                   1890: 
                   1891: sub usersearch {
                   1892:     my ($srch) = @_;
                   1893:     my $dom = $srch->{'srchdomain'};
                   1894:     my %results;
                   1895:     my %libserv = &all_library();
                   1896:     my $query = 'usersearch';
                   1897:     foreach my $tryserver (keys(%libserv)) {
                   1898:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.93.4  4(raebur 1899:7):             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   1900:7):                 if ($srch->{'srchby'} eq 'email') {
                   1901:7):                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   1902:7):                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.([\w.\-]+)\'?$/);
                   1903:7):                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   1904:7):                              (($major == 2) && ($minor < 11)) || 
          6(raebur 1905:7):                              (($major == 2) && ($minor == 11) && ($subver !~ /^2\.B/)));
          4(raebur 1906:7):                 }
                   1907:7):             }
1.899     raeburn  1908:             my $host=&hostname($tryserver);
                   1909:             my $queryid=
1.911     raeburn  1910:                 &reply("querysend:".&escape($query).':'.
                   1911:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1912:                        &escape($srch->{'srchtype'}).':'.
                   1913:                        &escape($srch->{'srchterm'}),$tryserver);
                   1914:             if ($queryid !~/^\Q$host\E\_/) {
                   1915:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1916:                 next;
1.899     raeburn  1917:             }
                   1918:             my $reply = &get_query_reply($queryid);
                   1919:             my $maxtries = 1;
                   1920:             my $tries = 1;
                   1921:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1922:                 $reply = &get_query_reply($queryid);
                   1923:                 $tries ++;
                   1924:             }
                   1925:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1926:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1927:             } else {
1.911     raeburn  1928:                 my @matches;
                   1929:                 if ($reply =~ /\n/) {
                   1930:                     @matches = split(/\n/,$reply);
                   1931:                 } else {
                   1932:                     @matches = split(/\&/,$reply);
                   1933:                 }
1.899     raeburn  1934:                 foreach my $match (@matches) {
                   1935:                     my ($uname,$udom,%userhash);
1.911     raeburn  1936:                     foreach my $entry (split(/:/,$match)) {
                   1937:                         my ($key,$value) =
                   1938:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1939:                         $userhash{$key} = $value;
                   1940:                         if ($key eq 'username') {
                   1941:                             $uname = $value;
                   1942:                         } elsif ($key eq 'domain') {
                   1943:                             $udom = $value;
1.911     raeburn  1944:                         }
1.899     raeburn  1945:                     }
                   1946:                     $results{$uname.':'.$udom} = \%userhash;
                   1947:                 }
                   1948:             }
                   1949:         }
                   1950:     }
                   1951:     return %results;
                   1952: }
                   1953: 
1.912     raeburn  1954: sub get_instuser {
                   1955:     my ($udom,$uname,$id) = @_;
                   1956:     my $homeserver = &domain($udom,'primary');
                   1957:     my ($outcome,%results);
                   1958:     if ($homeserver ne '') {
                   1959:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1960:                            &escape($id).':'.&escape($udom),$homeserver);
                   1961:         my $host=&hostname($homeserver);
                   1962:         if ($queryid !~/^\Q$host\E\_/) {
                   1963:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1964:             return;
                   1965:         }
                   1966:         my $response = &get_query_reply($queryid);
                   1967:         my $maxtries = 5;
                   1968:         my $tries = 1;
                   1969:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1970:             $response = &get_query_reply($queryid);
                   1971:             $tries ++;
                   1972:         }
                   1973:         if (!&error($response) && $response ne 'refused') {
                   1974:             if ($response eq 'unavailable') {
                   1975:                 $outcome = $response;
                   1976:             } else {
                   1977:                 $outcome = 'ok';
                   1978:                 my @matches = split(/\n/,$response);
                   1979:                 foreach my $match (@matches) {
                   1980:                     my ($key,$value) = split(/=/,$match);
                   1981:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1982:                 }
                   1983:             }
                   1984:         }
                   1985:     }
                   1986:     my %userinfo;
                   1987:     if (ref($results{$uname}) eq 'HASH') {
                   1988:         %userinfo = %{$results{$uname}};
                   1989:     } 
                   1990:     return ($outcome,%userinfo);
                   1991: }
                   1992: 
1.1172.2.69  raeburn  1993: sub get_multiple_instusers {
                   1994:     my ($udom,$users,$caller) = @_;
                   1995:     my ($outcome,$results);
                   1996:     if (ref($users) eq 'HASH') {
                   1997:         my $count = keys(%{$users});
                   1998:         my $requested = &freeze_escape($users);
                   1999:         my $homeserver = &domain($udom,'primary');
                   2000:         if ($homeserver ne '') {
                   2001:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2002:             my $host=&hostname($homeserver);
                   2003:             if ($queryid !~/^\Q$host\E\_/) {
                   2004:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2005:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2006:                 return ($outcome,$results);
                   2007:             }
                   2008:             my $response = &get_query_reply($queryid);
                   2009:             my $maxtries = 5;
                   2010:             if ($count > 100) {
                   2011:                 $maxtries = 1+int($count/20);
                   2012:             }
                   2013:             my $tries = 1;
                   2014:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2015:                 $response = &get_query_reply($queryid);
                   2016:                 $tries ++;
                   2017:             }
                   2018:             if ($response eq '') {
                   2019:                 $results = {};
                   2020:                 foreach my $key (keys(%{$users})) {
                   2021:                     my ($uname,$id);
                   2022:                     if ($caller eq 'id') {
                   2023:                         $id = $key;
                   2024:                     } else {
                   2025:                         $uname = $key;
                   2026:                     }
                   2027:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2028:                     $outcome = $resp;
                   2029:                     if ($resp eq 'ok') {
                   2030:                         %{$results} = (%{$results}, %info);
                   2031:                     } else {
                   2032:                         last;
                   2033:                     }
                   2034:                 }
                   2035:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2036:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2037:                     $outcome = $response;
                   2038:                 } else {
                   2039:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2040:                     if ($outcome eq 'ok') {
                   2041:                         $results = &thaw_unescape($userdata);
                   2042:                     }
                   2043:                 }
                   2044:             }
                   2045:         }
                   2046:     }
                   2047:     return ($outcome,$results);
                   2048: }
                   2049: 
1.912     raeburn  2050: sub inst_rulecheck {
1.923     raeburn  2051:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2052:     my %returnhash;
                   2053:     if ($udom ne '') {
                   2054:         if (ref($rules) eq 'ARRAY') {
                   2055:             @{$rules} = map {&escape($_);} (@{$rules});
                   2056:             my $rulestr = join(':',@{$rules});
                   2057:             my $homeserver=&domain($udom,'primary');
                   2058:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2059:                 my $response;
                   2060:                 if ($item eq 'username') {                
                   2061:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2062:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2063:                                               $homeserver));
1.923     raeburn  2064:                 } elsif ($item eq 'id') {
                   2065:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2066:                                               ':'.&escape($id).':'.$rulestr,
                   2067:                                               $homeserver));
1.945     raeburn  2068:                 } elsif ($item eq 'selfcreate') {
                   2069:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2070:                                                &escape($udom).':'.&escape($uname).
                   2071:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2072:                 }
1.912     raeburn  2073:                 if ($response ne 'refused') {
                   2074:                     my @pairs=split(/\&/,$response);
                   2075:                     foreach my $item (@pairs) {
                   2076:                         my ($key,$value)=split(/=/,$item,2);
                   2077:                         $key = &unescape($key);
                   2078:                         next if ($key =~ /^error: 2 /);
                   2079:                         $returnhash{$key}=&thaw_unescape($value);
                   2080:                     }
                   2081:                 }
                   2082:             }
                   2083:         }
                   2084:     }
                   2085:     return %returnhash;
                   2086: }
                   2087: 
                   2088: sub inst_userrules {
1.923     raeburn  2089:     my ($udom,$check) = @_;
1.912     raeburn  2090:     my (%ruleshash,@ruleorder);
                   2091:     if ($udom ne '') {
                   2092:         my $homeserver=&domain($udom,'primary');
                   2093:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2094:             my $response;
                   2095:             if ($check eq 'id') {
                   2096:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2097:                                  $homeserver);
1.943     raeburn  2098:             } elsif ($check eq 'email') {
                   2099:                 $response=&reply('instemailrules:'.&escape($udom),
                   2100:                                  $homeserver);
1.923     raeburn  2101:             } else {
                   2102:                 $response=&reply('instuserrules:'.&escape($udom),
                   2103:                                  $homeserver);
                   2104:             }
1.912     raeburn  2105:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2106:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2107:                 ($response ne 'no_such_host')) {
                   2108:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2109:                 my @pairs=split(/\&/,$hashitems);
                   2110:                 foreach my $item (@pairs) {
                   2111:                     my ($key,$value)=split(/=/,$item,2);
                   2112:                     $key = &unescape($key);
                   2113:                     next if ($key =~ /^error: 2 /);
                   2114:                     $ruleshash{$key}=&thaw_unescape($value);
                   2115:                 }
                   2116:                 my @esc_order = split(/\&/,$orderitems);
                   2117:                 foreach my $item (@esc_order) {
                   2118:                     push(@ruleorder,&unescape($item));
                   2119:                 }
                   2120:             }
                   2121:         }
                   2122:     }
                   2123:     return (\%ruleshash,\@ruleorder);
                   2124: }
                   2125: 
1.976     raeburn  2126: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2127: 
                   2128: sub get_domain_defaults {
1.1172.2.35  raeburn  2129:     my ($domain,$ignore_cache) = @_;
                   2130:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2131:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2132:     unless ($ignore_cache) {
                   2133:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2134:         if (defined($cached)) {
                   2135:             if (ref($result) eq 'HASH') {
                   2136:                 return %{$result};
                   2137:             }
1.943     raeburn  2138:         }
                   2139:     }
                   2140:     my %domdefaults;
                   2141:     my %domconfig =
1.989     raeburn  2142:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2143:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2144:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2145:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2146:                                   'coursecategories','autoenroll',
                   2147:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2148:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2149:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2150:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2151:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2152:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2153:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2154:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2155:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2156:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2157:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2158:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2159:     } else {
                   2160:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2161:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2162:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2163:     }
1.976     raeburn  2164:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2165:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2166:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2167:         } else {
                   2168:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2169:         }
1.1172.2.6  raeburn  2170:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2171:         foreach my $item (@usertools) {
                   2172:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2173:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2174:             }
                   2175:         }
1.1172.2.29  raeburn  2176:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2177:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2178:         }
1.976     raeburn  2179:     }
1.985     raeburn  2180:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2181:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2182:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2183:         }
                   2184:     }
1.1172.2.9  raeburn  2185:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2186:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2187:     }
1.989     raeburn  2188:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2189:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2190:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2191:         }
                   2192:     }
1.1047    raeburn  2193:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2194:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2195:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2196:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2197:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2198:         }
1.1172.2.41  raeburn  2199:         foreach my $type (@coursetypes) {
                   2200:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2201:                 unless ($type eq 'community') {
                   2202:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2203:                 }
                   2204:             }
                   2205:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2206:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2207:             }
1.1172.2.60  raeburn  2208:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2209:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2210:                     $domdefaults{$type.'postsubtimeout'} =
                   2211:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2212:                 }
                   2213:             }
1.1172.2.30  raeburn  2214:         }
1.1172.2.67  raeburn  2215:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2216:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2217:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2218:                 if (@clonecodes) {
                   2219:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2220:                 }
                   2221:             }
                   2222:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2223:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2224:         }
1.1047    raeburn  2225:     }
1.1073    raeburn  2226:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2227:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2228:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2229:         }
                   2230:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2231:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2232:         }
1.1172.2.62  raeburn  2233:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2234:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2235:         }
1.1073    raeburn  2236:     }
1.1172.2.41  raeburn  2237:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2238:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2239:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2240:                             'approval','limit');
                   2241:             foreach my $type (@coursetypes) {
                   2242:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2243:                     my @mgrdc = ();
                   2244:                     foreach my $item (@settings) {
                   2245:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2246:                             push(@mgrdc,$item);
                   2247:                         }
                   2248:                     }
                   2249:                     if (@mgrdc) {
                   2250:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2251:                     }
                   2252:                 }
                   2253:             }
                   2254:         }
                   2255:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2256:             foreach my $type (@coursetypes) {
                   2257:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2258:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2259:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2260:                     }
                   2261:                 }
                   2262:             }
                   2263:         }
                   2264:     }
1.1172.2.46  raeburn  2265:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2266:         $domdefaults{'catauth'} = 'std';
                   2267:         $domdefaults{'catunauth'} = 'std';
                   2268:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2269:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2270:         }
                   2271:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2272:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2273:         }
                   2274:     }
1.1172.2.76  raeburn  2275:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2276:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2277:     }
1.1172.2.89  raeburn  2278:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2279:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2280:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2281:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2282:         }
                   2283:     }
1.1172.2.23  raeburn  2284:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2285:     return %domdefaults;
                   2286: }
                   2287: 
1.1172.2.93.4  2(raebur 2288:7): sub course_portal_url {
                   2289:7):     my ($cnum,$cdom) = @_;
                   2290:7):     my $chome = &homeserver($cnum,$cdom);
                   2291:7):     my $hostname = &hostname($chome);
                   2292:7):     my $protocol = $protocol{$chome};
                   2293:7):     $protocol = 'http' if ($protocol ne 'https');
                   2294:7):     my %domdefaults = &get_domain_defaults($cdom);
                   2295:7):     my $firsturl;
                   2296:7):     if ($domdefaults{'portal_def'}) {
                   2297:7):         $firsturl = $domdefaults{'portal_def'};
                   2298:7):     } else {
                   2299:7):         $firsturl = $protocol.'://'.$hostname;
                   2300:7):     }
                   2301:7):     return $firsturl;
                   2302:7): }
                   2303:7): 
1.344     www      2304: # --------------------------------------------------- Assign a key to a student
                   2305: 
                   2306: sub assign_access_key {
1.364     www      2307: #
                   2308: # a valid key looks like uname:udom#comments
                   2309: # comments are being appended
                   2310: #
1.498     www      2311:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2312:     $kdom=
1.620     albertel 2313:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2314:     $knum=
1.620     albertel 2315:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2316:     $cdom=
1.620     albertel 2317:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2318:     $cnum=
1.620     albertel 2319:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2320:     $udom=$env{'user.name'} unless (defined($udom));
                   2321:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2322:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2323:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2324:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2325:                                                   # assigned to this person
                   2326:                                                   # - this should not happen,
1.345     www      2327:                                                   # unless something went wrong
                   2328:                                                   # the first time around
                   2329: # ready to assign
1.364     www      2330:         $logentry=$1.'; '.$logentry;
1.496     www      2331:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2332:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2333: # key now belongs to user
1.346     www      2334: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2335:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2336:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2337:                 return 'ok';
                   2338:             } else {
                   2339:                 return 
                   2340:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2341: 	    }
                   2342:         } else {
                   2343:             return 'error: Could not assign key, try again later.';
                   2344:         }
1.364     www      2345:     } elsif (!$existing{$ckey}) {
1.345     www      2346: # the key does not exist
                   2347: 	return 'error: The key does not exist';
                   2348:     } else {
                   2349: # the key is somebody else's
                   2350: 	return 'error: The key is already in use';
                   2351:     }
1.344     www      2352: }
                   2353: 
1.364     www      2354: # ------------------------------------------ put an additional comment on a key
                   2355: 
                   2356: sub comment_access_key {
                   2357: #
                   2358: # a valid key looks like uname:udom#comments
                   2359: # comments are being appended
                   2360: #
                   2361:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2362:     $cdom=
1.620     albertel 2363:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2364:     $cnum=
1.620     albertel 2365:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2366:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2367:     if ($existing{$ckey}) {
                   2368:         $existing{$ckey}.='; '.$logentry;
                   2369: # ready to assign
1.367     www      2370:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2371:                                                  $cdom,$cnum) eq 'ok') {
                   2372: 	    return 'ok';
                   2373:         } else {
                   2374: 	    return 'error: Count not store comment.';
                   2375:         }
                   2376:     } else {
                   2377: # the key does not exist
                   2378: 	return 'error: The key does not exist';
                   2379:     }
                   2380: }
                   2381: 
1.344     www      2382: # ------------------------------------------------------ Generate a set of keys
                   2383: 
                   2384: sub generate_access_keys {
1.364     www      2385:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2386:     $cdom=
1.620     albertel 2387:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2388:     $cnum=
1.620     albertel 2389:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2390:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2391:     unless (($cdom) && ($cnum)) { return 0; }
                   2392:     if ($number>10000) { return 0; }
                   2393:     sleep(2); # make sure don't get same seed twice
                   2394:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2395:     my $total=0;
                   2396:     for (my $i=1;$i<=$number;$i++) {
                   2397:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2398:                   sprintf("%lx",int(100000*rand)).'-'.
                   2399:                   sprintf("%lx",int(100000*rand));
                   2400:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2401:        $newkey=~s/0/h/g; # and also 0 and O
                   2402:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2403:        if ($existing{$newkey}) {
                   2404:            $i--;
                   2405:        } else {
1.364     www      2406: 	  if (&put('accesskeys',
                   2407:               { $newkey => '# generated '.localtime().
1.620     albertel 2408:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2409:                            '; '.$logentry },
                   2410: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2411:               $total++;
                   2412: 	  }
                   2413:        }
                   2414:     }
1.620     albertel 2415:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2416:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2417:     return $total;
                   2418: }
                   2419: 
                   2420: # ------------------------------------------------------- Validate an accesskey
                   2421: 
                   2422: sub validate_access_key {
                   2423:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2424:     $cdom=
1.620     albertel 2425:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2426:     $cnum=
1.620     albertel 2427:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2428:     $udom=$env{'user.domain'} unless (defined($udom));
                   2429:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2430:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2431:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2432: }
                   2433: 
                   2434: # ------------------------------------- Find the section of student in a course
1.652     albertel 2435: sub devalidate_getsection_cache {
                   2436:     my ($udom,$unam,$courseid)=@_;
                   2437:     my $hashid="$udom:$unam:$courseid";
                   2438:     &devalidate_cache_new('getsection',$hashid);
                   2439: }
1.298     matthew  2440: 
1.815     albertel 2441: sub courseid_to_courseurl {
                   2442:     my ($courseid) = @_;
                   2443:     #already url style courseid
                   2444:     return $courseid if ($courseid =~ m{^/});
                   2445: 
                   2446:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2447: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2448: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2449: 	return "/$cdom/$cnum";
                   2450:     }
                   2451: 
                   2452:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2453:     if (exists($courseinfo{'num'})) {
                   2454: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2455:     }
                   2456: 
                   2457:     return undef;
                   2458: }
                   2459: 
1.298     matthew  2460: sub getsection {
                   2461:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2462:     my $cachetime=1800;
1.551     albertel 2463: 
                   2464:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2465:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2466:     if (defined($cached)) { return $result; }
                   2467: 
1.298     matthew  2468:     my %Pending; 
                   2469:     my %Expired;
                   2470:     #
                   2471:     # Each role can either have not started yet (pending), be active, 
                   2472:     #    or have expired.
                   2473:     #
                   2474:     # If there is an active role, we are done.
                   2475:     #
                   2476:     # If there is more than one role which has not started yet, 
                   2477:     #     choose the one which will start sooner
                   2478:     # If there is one role which has not started yet, return it.
                   2479:     #
                   2480:     # If there is more than one expired role, choose the one which ended last.
                   2481:     # If there is a role which has expired, return it.
                   2482:     #
1.815     albertel 2483:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2484:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2485:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2486:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2487:         my $section=$1;
                   2488:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2489:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2490:         my $now=time;
1.548     albertel 2491:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2492:             $Expired{$end}=$section;
                   2493:             next;
                   2494:         }
1.548     albertel 2495:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2496:             $Pending{$start}=$section;
                   2497:             next;
                   2498:         }
1.599     albertel 2499:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2500:     }
                   2501:     #
                   2502:     # Presumedly there will be few matching roles from the above
                   2503:     # loop and the sorting time will be negligible.
                   2504:     if (scalar(keys(%Pending))) {
                   2505:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2506:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2507:     } 
                   2508:     if (scalar(keys(%Expired))) {
                   2509:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2510:         my $time = pop(@sorted);
1.599     albertel 2511:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2512:     }
1.599     albertel 2513:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2514: }
1.70      www      2515: 
1.599     albertel 2516: sub save_cache {
                   2517:     &purge_remembered();
1.722     albertel 2518:     #&Apache::loncommon::validate_page();
1.620     albertel 2519:     undef(%env);
1.780     albertel 2520:     undef($env_loaded);
1.599     albertel 2521: }
1.452     albertel 2522: 
1.599     albertel 2523: my $to_remember=-1;
                   2524: my %remembered;
                   2525: my %accessed;
                   2526: my $kicks=0;
                   2527: my $hits=0;
1.849     albertel 2528: sub make_key {
                   2529:     my ($name,$id) = @_;
1.872     albertel 2530:     if (length($id) > 65 
                   2531: 	&& length(&escape($id)) > 200) {
                   2532: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2533:     }
1.849     albertel 2534:     return &escape($name.':'.$id);
                   2535: }
                   2536: 
1.599     albertel 2537: sub devalidate_cache_new {
                   2538:     my ($name,$id,$debug) = @_;
                   2539:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2540:     my $remembered_id=$name.':'.$id;
1.849     albertel 2541:     $id=&make_key($name,$id);
1.599     albertel 2542:     $memcache->delete($id);
1.1172.2.81  raeburn  2543:     delete($remembered{$remembered_id});
                   2544:     delete($accessed{$remembered_id});
1.599     albertel 2545: }
                   2546: 
                   2547: sub is_cached_new {
                   2548:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2549:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2550:                                      # keys in %remembered hash, which persists for
                   2551:                                      # duration of request (no restriction on key length).
                   2552:     if (exists($remembered{$remembered_id})) {
                   2553: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2554: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2555: 	$hits++;
1.1172.2.81  raeburn  2556: 	return ($remembered{$remembered_id},1);
1.599     albertel 2557:     }
1.1172.2.81  raeburn  2558:     $id=&make_key($name,$id);
1.599     albertel 2559:     my $value = $memcache->get($id);
                   2560:     if (!(defined($value))) {
                   2561: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2562: 	return (undef,undef);
1.416     albertel 2563:     }
1.599     albertel 2564:     if ($value eq '__undef__') {
                   2565: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2566: 	$value=undef;
                   2567:     }
1.1172.2.81  raeburn  2568:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2569:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2570:     return ($value,1);
                   2571: }
                   2572: 
                   2573: sub do_cache_new {
                   2574:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2575:     my $remembered_id=$name.':'.$id;
1.849     albertel 2576:     $id=&make_key($name,$id);
1.599     albertel 2577:     my $setvalue=$value;
                   2578:     if (!defined($setvalue)) {
                   2579: 	$setvalue='__undef__';
                   2580:     }
1.623     albertel 2581:     if (!defined($time) ) {
                   2582: 	$time=600;
                   2583:     }
1.599     albertel 2584:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2585:     my $result = $memcache->set($id,$setvalue,$time);
                   2586:     if (! $result) {
1.872     albertel 2587: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2588: 	$memcache->disconnect_all();
1.872     albertel 2589:     }
1.600     albertel 2590:     # need to make a copy of $value
1.1172.2.81  raeburn  2591:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2592:     return $value;
                   2593: }
                   2594: 
                   2595: sub make_room {
1.1172.2.81  raeburn  2596:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2597: 
1.1172.2.81  raeburn  2598:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2599:                                     : $value;
1.599     albertel 2600:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2601:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2602:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2603:     my $to_kick;
                   2604:     my $max_time=0;
                   2605:     foreach my $other (keys(%accessed)) {
                   2606: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2607: 	    $to_kick=$other;
                   2608: 	    $max_time=&tv_interval($accessed{$other});
                   2609: 	}
                   2610:     }
                   2611:     delete($remembered{$to_kick});
                   2612:     delete($accessed{$to_kick});
                   2613:     $kicks++;
                   2614:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2615:     return;
                   2616: }
                   2617: 
1.599     albertel 2618: sub purge_remembered {
1.604     albertel 2619:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2620:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2621:     undef(%remembered);
                   2622:     undef(%accessed);
1.428     albertel 2623: }
1.70      www      2624: # ------------------------------------- Read an entry from a user's environment
                   2625: 
                   2626: sub userenvironment {
                   2627:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2628:     my $items;
                   2629:     foreach my $item (@what) {
                   2630:         $items.=&escape($item).'&';
                   2631:     }
                   2632:     $items=~s/\&$//;
1.70      www      2633:     my %returnhash=();
1.1009    raeburn  2634:     my $uhome = &homeserver($unam,$udom);
                   2635:     unless ($uhome eq 'no_host') {
                   2636:         my @answer=split(/\&/, 
                   2637:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2638:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2639:             return %returnhash;
                   2640:         }
1.1009    raeburn  2641:         my $i;
                   2642:         for ($i=0;$i<=$#what;$i++) {
                   2643: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2644:         }
1.70      www      2645:     }
                   2646:     return %returnhash;
1.1       albertel 2647: }
                   2648: 
1.617     albertel 2649: # ---------------------------------------------------------- Get a studentphoto
                   2650: sub studentphoto {
                   2651:     my ($udom,$unam,$ext) = @_;
                   2652:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2653:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2654:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2655:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2656:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2657:             } else {
                   2658:                 my ($result,$perm_reqd)=
1.707     albertel 2659: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2660:                 if ($result eq 'ok') {
                   2661:                     if (!($perm_reqd eq 'yes')) {
                   2662:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2663:                     }
                   2664:                 }
                   2665:             }
                   2666:         }
                   2667:     } else {
                   2668:         my ($result,$perm_reqd) = 
1.707     albertel 2669: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2670:         if ($result eq 'ok') {
                   2671:             if (!($perm_reqd eq 'yes')) {
                   2672:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2673:             }
                   2674:         }
                   2675:     }
                   2676:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2677: }
                   2678: 
                   2679: sub retrievestudentphoto {
                   2680:     my ($udom,$unam,$ext,$type) = @_;
                   2681:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2682:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2683:     if ($ret eq 'ok') {
                   2684:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2685:         if ($type eq 'thumbnail') {
                   2686:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2687:         }
                   2688:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2689:         return $tokenurl;
                   2690:     } else {
                   2691:         if ($type eq 'thumbnail') {
                   2692:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2693:         } else { 
                   2694:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2695:         }
1.617     albertel 2696:     }
                   2697: }
                   2698: 
1.263     www      2699: # -------------------------------------------------------------------- New chat
                   2700: 
                   2701: sub chatsend {
1.724     raeburn  2702:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2703:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2704:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2705:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2706:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2707: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2708: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2709: }
                   2710: 
                   2711: # ------------------------------------------ Find current version of a resource
                   2712: 
                   2713: sub getversion {
                   2714:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2715:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2716:     return &currentversion(&filelocation('',$fname));
                   2717: }
                   2718: 
                   2719: sub currentversion {
                   2720:     my $fname=shift;
                   2721:     my $author=$fname;
                   2722:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2723:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2724:     my $home=&homeserver($uname,$udom);
1.292     www      2725:     if ($home eq 'no_host') { 
                   2726:         return -1; 
                   2727:     }
1.1112    www      2728:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2729:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2730: 	return -1;
                   2731:     }
1.1112    www      2732:     return $answer;
1.263     www      2733: }
                   2734: 
1.1111    www      2735: #
                   2736: # Return special version number of resource if set by override, empty otherwise
                   2737: #
                   2738: sub usedversion {
                   2739:     my $fname=shift;
                   2740:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2741:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2742:     if ($urlversion) { return $urlversion; }
                   2743:     return '';
                   2744: }
                   2745: 
1.1       albertel 2746: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2747: 
1.1       albertel 2748: sub subscribe {
                   2749:     my $fname=shift;
1.761     raeburn  2750:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2751:     $fname=~s/[\n\r]//g;
1.1       albertel 2752:     my $author=$fname;
                   2753:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2754:     my ($udom,$uname)=split(/\//,$author);
                   2755:     my $home=homeserver($uname,$udom);
1.335     albertel 2756:     if ($home eq 'no_host') {
                   2757:         return 'not_found';
1.1       albertel 2758:     }
                   2759:     my $answer=reply("sub:$fname",$home);
1.64      www      2760:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2761: 	$answer.=' by '.$home;
                   2762:     }
1.1       albertel 2763:     return $answer;
                   2764: }
                   2765:     
1.8       www      2766: # -------------------------------------------------------------- Replicate file
                   2767: 
                   2768: sub repcopy {
                   2769:     my $filename=shift;
1.23      www      2770:     $filename=~s/\/+/\//g;
1.1142    raeburn  2771:     my $londocroot = $perlvar{'lonDocRoot'};
                   2772:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2773:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2774:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2775: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2776: 	return &repcopy_userfile($filename);
                   2777:     }
1.532     albertel 2778:     $filename=~s/[\n\r]//g;
1.8       www      2779:     my $transname="$filename.in.transfer";
1.828     www      2780: # FIXME: this should flock
1.607     raeburn  2781:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2782:     my $remoteurl=subscribe($filename);
1.64      www      2783:     if ($remoteurl =~ /^con_lost by/) {
                   2784: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2785:            return 'unavailable';
1.8       www      2786:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2787: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2788: 	   return 'not_found';
1.64      www      2789:     } elsif ($remoteurl =~ /^rejected by/) {
                   2790: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2791:            return 'forbidden';
1.20      www      2792:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2793:            return 'ok';
1.8       www      2794:     } else {
1.290     www      2795:         my $author=$filename;
                   2796:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2797:         my ($udom,$uname)=split(/\//,$author);
                   2798:         my $home=homeserver($uname,$udom);
                   2799:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2800:            my @parts=split(/\//,$filename);
                   2801:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2802:            if ($path ne "$londocroot/res") {
1.8       www      2803:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2804: 	       return 'bad_request';
1.8       www      2805:            }
                   2806:            my $count;
                   2807:            for ($count=5;$count<$#parts;$count++) {
                   2808:                $path.="/$parts[$count]";
                   2809:                if ((-e $path)!=1) {
                   2810: 		   mkdir($path,0777);
                   2811:                }
                   2812:            }
                   2813:            my $ua=new LWP::UserAgent;
                   2814:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2815:            my $response=$ua->request($request,$transname);
                   2816:            if ($response->is_error()) {
                   2817: 	       unlink($transname);
                   2818:                my $message=$response->status_line;
1.672     albertel 2819:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2820:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2821:                return 'unavailable';
1.8       www      2822:            } else {
1.16      www      2823: 	       if ($remoteurl!~/\.meta$/) {
                   2824:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2825:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2826:                   if ($mresponse->is_error()) {
                   2827: 		      unlink($filename.'.meta');
                   2828:                       &logthis(
1.672     albertel 2829:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2830:                   }
                   2831: 	       }
1.8       www      2832:                rename($transname,$filename);
1.607     raeburn  2833:                return 'ok';
1.8       www      2834:            }
1.290     www      2835:        }
1.8       www      2836:     }
1.330     www      2837: }
                   2838: 
                   2839: # ------------------------------------------------ Get server side include body
                   2840: sub ssi_body {
1.381     albertel 2841:     my ($filelink,%form)=@_;
1.606     matthew  2842:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2843:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2844:     }
1.953     www      2845:     my $output='';
                   2846:     my $response;
1.980     raeburn  2847:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2848:        ($output,$response)=&externalssi($filelink);
1.953     www      2849:     } else {
1.1004    droeschl 2850:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2851:        $filelink .= 'inhibitmenu=yes';
1.953     www      2852:        ($output,$response)=&ssi($filelink,%form);
                   2853:     }
1.778     albertel 2854:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2855:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2856:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2857:     if (wantarray) {
                   2858:         return ($output, $response);
                   2859:     } else {
                   2860:         return $output;
                   2861:     }
1.8       www      2862: }
                   2863: 
1.15      www      2864: # --------------------------------------------------------- Server Side Include
                   2865: 
1.782     albertel 2866: sub absolute_url {
                   2867:     my ($host_name) = @_;
                   2868:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2869:     if ($host_name eq '') {
                   2870: 	$host_name = $ENV{'SERVER_NAME'};
                   2871:     }
                   2872:     return $protocol.$host_name;
                   2873: }
                   2874: 
1.942     foxr     2875: #
                   2876: #   Server side include.
                   2877: # Parameters:
                   2878: #  fn     Possibly encrypted resource name/id.
                   2879: #  form   Hash that describes how the rendering should be done
                   2880: #         and other things.
1.944     foxr     2881: # Returns:
1.950     raeburn  2882: #   Scalar context: The content of the response.
                   2883: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2884: #     
1.15      www      2885: sub ssi {
                   2886: 
1.944     foxr     2887:     my ($fn,%form)=@_;
1.15      www      2888:     my $ua=new LWP::UserAgent;
1.23      www      2889:     my $request;
1.711     albertel 2890: 
                   2891:     $form{'no_update_last_known'}=1;
1.895     albertel 2892:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2893:     if (%form) {
1.782     albertel 2894:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2895:       $request->content(join('&',map {
                   2896:             my $name = escape($_);
                   2897:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2898:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2899:             : &escape($form{$_}) );
                   2900:         } keys(%form)));
1.23      www      2901:     } else {
1.782     albertel 2902:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2903:     }
                   2904: 
1.15      www      2905:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2906:     my $response= $ua->request($request);
1.944     foxr     2907:     if (wantarray) {
1.1172.2.3  raeburn  2908: 	return ($response->content, $response);
1.944     foxr     2909:     } else {
1.1172.2.3  raeburn  2910: 	return $response->content;
1.942     foxr     2911:     }
1.324     www      2912: }
                   2913: 
                   2914: sub externalssi {
                   2915:     my ($url)=@_;
                   2916:     my $ua=new LWP::UserAgent;
                   2917:     my $request=new HTTP::Request('GET',$url);
                   2918:     my $response=$ua->request($request);
1.954     raeburn  2919:     if (wantarray) {
                   2920:         return ($response->content, $response);
                   2921:     } else {
                   2922:         return $response->content;
                   2923:     }
1.15      www      2924: }
1.254     www      2925: 
1.492     albertel 2926: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2927: 
                   2928: sub allowuploaded {
                   2929:     my ($srcurl,$url)=@_;
                   2930:     $url=&clutter(&declutter($url));
                   2931:     my $dir=$url;
                   2932:     $dir=~s/\/[^\/]+$//;
                   2933:     my %httpref=();
                   2934:     my $httpurl=&hreflocation('',$url);
                   2935:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2936:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2937: }
1.477     raeburn  2938: 
1.1172.2.13  raeburn  2939: #
                   2940: # Determine if the current user should be able to edit a particular resource,
                   2941: # when viewing in course context.
                   2942: # (a) When viewing resource used to determine if "Edit" item is included in
                   2943: #     Functions.
                   2944: # (b) When displaying folder contents in course editor, used to determine if
                   2945: #     "Edit" link will be displayed alongside resource.
                   2946: #
                   2947: #  input: six args -- filename (decluttered), course number, course domain,
                   2948: #                   url, symb (if registered) and group (if this is a group
                   2949: #                   item -- e.g., bulletin board, group page etc.).
                   2950: #  output: array of five scalars --
                   2951: #          $cfile -- url for file editing if editable on current server
                   2952: #          $home -- homeserver of resource (i.e., for author if published,
                   2953: #                                           or course if uploaded.).
                   2954: #          $switchserver --  1 if server switch will be needed.
                   2955: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2956: #          $forceview -- 1 if icon/link should be to go to view mode
                   2957: #
                   2958: 
                   2959: sub can_edit_resource {
                   2960:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2961:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2962: #
                   2963: # For aboutme pages user can only edit his/her own.
                   2964: #
                   2965:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2966:         my ($sdom,$sname) = ($1,$2);
                   2967:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2968:             $home = $env{'user.home'};
                   2969:             $cfile = $resurl;
                   2970:             if ($env{'form.forceedit'}) {
                   2971:                 $forceview = 1;
                   2972:             } else {
                   2973:                 $forceedit = 1;
                   2974:             }
                   2975:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2976:         } else {
                   2977:             return;
                   2978:         }
                   2979:     }
                   2980: 
                   2981:     if ($env{'request.course.id'}) {
                   2982:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2983:         if ($group ne '') {
                   2984: # if this is a group homepage or group bulletin board, check group privs
                   2985:             my $allowed = 0;
                   2986:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2987:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2988:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2989:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2990:                     $allowed = 1;
                   2991:                 }
                   2992:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2993:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2994:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2995:                     $allowed = 1;
                   2996:                 }
                   2997:             }
                   2998:             if ($allowed) {
                   2999:                 $home=&homeserver($cnum,$cdom);
                   3000:                 if ($env{'form.forceedit'}) {
                   3001:                     $forceview = 1;
                   3002:                 } else {
                   3003:                     $forceedit = 1;
                   3004:                 }
                   3005:                 $cfile = $resurl;
                   3006:             } else {
                   3007:                 return;
                   3008:             }
                   3009:         } else {
1.1172.2.15  raeburn  3010:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3011:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3012:                     return;
                   3013:                 }
                   3014:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3015: #
                   3016: # No edit allowed where CC has switched to student role.
                   3017: #
                   3018:                 return;
                   3019:             }
                   3020:         }
                   3021:     }
                   3022: 
                   3023:     if ($file ne '') {
                   3024:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3025:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3026:                 $uploaded = 1;
                   3027:                 $incourse = 1;
                   3028:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3029:                     $cfile = &hreflocation('',$file);
                   3030:                     if ($env{'form.forceedit'}) {
                   3031:                         $forceview = 1;
                   3032:                     } else {
                   3033:                         $forceedit = 1;
                   3034:                     }
                   3035:                 }
                   3036:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3037:                 $incourse = 1;
                   3038:                 if ($env{'form.forceedit'}) {
                   3039:                     $forceview = 1;
                   3040:                 } else {
                   3041:                     $forceedit = 1;
                   3042:                 }
                   3043:                 $cfile = $resurl;
                   3044:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3045:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3046:                     $incourse = 1;
                   3047:                     if ($env{'form.forceedit'}) {
                   3048:                         $forceview = 1;
                   3049:                     } else {
                   3050:                         $forceedit = 1;
                   3051:                     }
                   3052:                     $cfile = $resurl;
                   3053:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3054:                     $incourse = 1;
                   3055:                     $cfile = $resurl.'/smpedit';
                   3056:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3057:                     $incourse = 1;
                   3058:                     if ($env{'form.forceedit'}) {
                   3059:                         $forceview = 1;
                   3060:                     } else {
                   3061:                         $forceedit = 1;
                   3062:                     }
                   3063:                     $cfile = $resurl;
1.1172.2.93.4  2(raebur 3064:7):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3065:7):                     $incourse = 1;
                   3066:7):                     if ($env{'form.forceedit'}) {
                   3067:7):                         $forceview = 1;
                   3068:7):                     } else {
                   3069:7):                         $forceedit = 1;
                   3070:7):                     }
                   3071:7):                     $cfile = $resurl;
1.1172.2.15  raeburn  3072:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3073:                     $incourse = 1;
                   3074:                     if ($env{'form.forceedit'}) {
                   3075:                         $forceview = 1;
                   3076:                     } else {
                   3077:                         $forceedit = 1;
                   3078:                     }
                   3079:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3080:                 }
                   3081:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3082:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3083:                 if (&is_on_map($template)) {
                   3084:                     $incourse = 1;
                   3085:                     $forceview = 1;
                   3086:                     $cfile = $template;
                   3087:                 }
                   3088:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3089:                     $incourse = 1;
                   3090:                     if ($env{'form.forceedit'}) {
                   3091:                         $forceview = 1;
                   3092:                     } else {
                   3093:                         $forceedit = 1;
                   3094:                     }
                   3095:                     $cfile = $resurl;
1.1172.2.93.4  2(raebur 3096:7):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3097:7):                 $incourse = 1;
                   3098:7):                 if ($env{'form.forceedit'}) {
                   3099:7):                     $forceview = 1;
                   3100:7):                 } else {
                   3101:7):                     $forceedit = 1;
                   3102:7):                 }
                   3103:7):                 $cfile = $resurl;
1.1172.2.13  raeburn  3104:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3105:                 $incourse = 1;
                   3106:                 $forceview = 1;
                   3107:                 if ($symb) {
                   3108:                     my ($map,$id,$res)=&decode_symb($symb);
                   3109:                     $env{'request.symb'} = $symb;
                   3110:                     $cfile = &clutter($res);
                   3111:                 } else {
                   3112:                     $cfile = $env{'form.suppurl'};
1.1172.2.93.4  1(raebur 3113:7):                     my $escfile = &unescape($cfile);
          2(raebur 3114:7):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3115:7):                         $cfile = '/adm/wrapper'.$escfile;
                   3116:7):                     } else {
                   3117:7):                         $escfile =~ s{^http://}{};
                   3118:7):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3119:7):                     }
1.1172.2.13  raeburn  3120:                 }
1.1172.2.31  raeburn  3121:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3122:                 if ($env{'form.forceedit'}) {
                   3123:                     $forceview = 1;
                   3124:                 } else {
                   3125:                     $forceedit = 1;
                   3126:                 }
                   3127:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3128:             }
                   3129:         }
                   3130:         if ($uploaded || $incourse) {
                   3131:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3132:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3133:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3134:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3135:             # Check that the user has permission to edit this resource
                   3136:             my $setpriv = 1;
                   3137:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3138:             if (defined($cfudom)) {
                   3139:                 $home=&homeserver($cfuname,$cfudom);
                   3140:                 $cfile=$file;
                   3141:             }
                   3142:         }
                   3143:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3144:             (($home ne '') && ($home ne 'no_host'))) {
                   3145:             my @ids=&current_machine_ids();
                   3146:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3147:                 $switchserver=1;
                   3148:             }
                   3149:         }
                   3150:     }
                   3151:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3152: }
                   3153: 
                   3154: sub is_course_upload {
                   3155:     my ($file,$cnum,$cdom) = @_;
                   3156:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3157:     $uploadpath =~ s{^\/}{};
                   3158:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3159:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3160:         return 1;
                   3161:     }
                   3162:     return;
                   3163: }
                   3164: 
                   3165: sub in_course {
                   3166:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3167:     if ($hideprivileged) {
                   3168:         my $skipuser;
1.1172.2.23  raeburn  3169:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3170:         my @possdoms = ($cdom);
                   3171:         if ($coursehash{'checkforpriv'}) {
                   3172:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3173:         }
                   3174:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3175:             $skipuser = 1;
                   3176:             if ($coursehash{'nothideprivileged'}) {
                   3177:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3178:                     my $user;
                   3179:                     if ($item =~ /:/) {
                   3180:                         $user = $item;
                   3181:                     } else {
                   3182:                         $user = join(':',split(/[\@]/,$item));
                   3183:                     }
                   3184:                     if ($user eq $uname.':'.$udom) {
                   3185:                         undef($skipuser);
                   3186:                         last;
                   3187:                     }
                   3188:                 }
                   3189:             }
                   3190:             if ($skipuser) {
                   3191:                 return 0;
                   3192:             }
                   3193:         }
                   3194:     }
                   3195:     $type ||= 'any';
                   3196:     if (!defined($cdom) || !defined($cnum)) {
                   3197:         my $cid  = $env{'request.course.id'};
                   3198:         $cdom = $env{'course.'.$cid.'.domain'};
                   3199:         $cnum = $env{'course.'.$cid.'.num'};
                   3200:     }
                   3201:     my $typesref;
                   3202:     if (($type eq 'any') || ($type eq 'all')) {
                   3203:         $typesref = ['active','previous','future'];
                   3204:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3205:         $typesref = [$type];
                   3206:     }
                   3207:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3208:                               $typesref,undef,[$cdom]);
                   3209:     my ($tmp) = keys(%roles);
                   3210:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3211:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3212:     if (@course_roles > 0) {
                   3213:         return 1;
                   3214:     }
                   3215:     return 0;
                   3216: }
                   3217: 
1.478     albertel 3218: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3219: # input: action, courseID, current domain, intended
1.637     raeburn  3220: #        path to file, source of file, instruction to parse file for objects,
                   3221: #        ref to hash for embedded objects,
                   3222: #        ref to hash for codebase of java objects.
1.1095    raeburn  3223: #        reference to scalar to accommodate mime type determined
                   3224: #          from File::MMagic if $parser = parse.
1.637     raeburn  3225: #
1.485     raeburn  3226: # output: url to file (if action was uploaddoc), 
                   3227: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3228: #
1.478     albertel 3229: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3230: # course.
1.477     raeburn  3231: #
1.478     albertel 3232: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3233: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3234: #          course's home server.
1.477     raeburn  3235: #
1.478     albertel 3236: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3237: #          be copied from $source (current location) to 
                   3238: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3239: #         and will then be copied to
                   3240: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3241: #         course's home server.
1.485     raeburn  3242: #
1.481     raeburn  3243: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3244: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3245: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3246: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3247: #         in course's home server.
1.637     raeburn  3248: #
1.477     raeburn  3249: 
                   3250: sub process_coursefile {
1.1095    raeburn  3251:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3252:         $mimetype)=@_;
1.477     raeburn  3253:     my $fetchresult;
1.638     albertel 3254:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3255:     if ($action eq 'propagate') {
1.638     albertel 3256:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3257: 			     $home);
1.481     raeburn  3258:     } else {
1.477     raeburn  3259:         my $fpath = '';
                   3260:         my $fname = $file;
1.478     albertel 3261:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3262:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3263:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3264:         if ($action eq 'copy') {
                   3265:             if ($source eq '') {
                   3266:                 $fetchresult = 'no source file';
                   3267:                 return $fetchresult;
                   3268:             } else {
                   3269:                 my $destination = $filepath.'/'.$fname;
                   3270:                 rename($source,$destination);
                   3271:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3272:                                  $home);
1.481     raeburn  3273:             }
                   3274:         } elsif ($action eq 'uploaddoc') {
1.1172.2.93.4  7(raebur 3275:7):             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3276:             print $fh $env{'form.'.$source};
1.481     raeburn  3277:             close($fh);
1.637     raeburn  3278:             if ($parser eq 'parse') {
1.1024    raeburn  3279:                 my $mm = new File::MMagic;
1.1095    raeburn  3280:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3281:                 if ($type eq 'text/html') {
1.1024    raeburn  3282:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3283:                     unless ($parse_result eq 'ok') {
                   3284:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3285:                     }
1.637     raeburn  3286:                 }
1.1095    raeburn  3287:                 if (ref($mimetype)) {
                   3288:                     $$mimetype = $type;
                   3289:                 } 
1.637     raeburn  3290:             }
1.477     raeburn  3291:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3292:                                  $home);
1.481     raeburn  3293:             if ($fetchresult eq 'ok') {
                   3294:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3295:             } else {
                   3296:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3297:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3298:                 return '/adm/notfound.html';
                   3299:             }
1.477     raeburn  3300:         }
                   3301:     }
1.485     raeburn  3302:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3303:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3304:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3305:     }
                   3306:     return $fetchresult;
                   3307: }
                   3308: 
1.637     raeburn  3309: sub build_filepath {
                   3310:     my ($fpath) = @_;
                   3311:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3312:     unless ($fpath eq '') {
                   3313:         my @parts=split('/',$fpath);
                   3314:         foreach my $part (@parts) {
                   3315:             $filepath.= '/'.$part;
                   3316:             if ((-e $filepath)!=1) {
                   3317:                 mkdir($filepath,0777);
                   3318:             }
                   3319:         }
                   3320:     }
                   3321:     return $filepath;
                   3322: }
                   3323: 
                   3324: sub store_edited_file {
1.638     albertel 3325:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3326:     my $file = $primary_url;
                   3327:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3328:     my $fpath = '';
                   3329:     my $fname = $file;
                   3330:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3331:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3332:     my $filepath = &build_filepath($fpath);
1.1172.2.93.4  7(raebur 3333:7):     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3334:     print $fh $content;
                   3335:     close($fh);
1.638     albertel 3336:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3337:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3338: 			  $home);
1.637     raeburn  3339:     if ($$fetchresult eq 'ok') {
                   3340:         return '/uploaded/'.$fpath.'/'.$fname;
                   3341:     } else {
1.638     albertel 3342:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3343: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3344:         return '/adm/notfound.html';
                   3345:     }
                   3346: }
                   3347: 
1.531     albertel 3348: sub clean_filename {
1.831     albertel 3349:     my ($fname,$args)=@_;
1.315     www      3350: # Replace Windows backslashes by forward slashes
1.257     www      3351:     $fname=~s/\\/\//g;
1.831     albertel 3352:     if (!$args->{'keep_path'}) {
                   3353:         # Get rid of everything but the actual filename
                   3354: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3355:     }
1.315     www      3356: # Replace spaces by underscores
                   3357:     $fname=~s/\s+/\_/g;
                   3358: # Replace all other weird characters by nothing
1.831     albertel 3359:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3360: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3361: # numbers
                   3362:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3363:     return $fname;
                   3364: }
1.1051    raeburn  3365: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3366: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3367: # image with the same aspect ratio as the original, but with dimensions which do 
                   3368: # not exceed $resizewidth and $resizeheight.
                   3369:  
1.984     neumanie 3370: sub resizeImage {
1.1051    raeburn  3371:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3372:     my $ima = Image::Magick->new;
                   3373:     my $resized;
                   3374:     if (-e $img_path) {
                   3375:         $ima->Read($img_path);
                   3376:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3377:             my $width = $ima->Get('width');
                   3378:             my $height = $ima->Get('height');
                   3379:             if ($width > $resizewidth) {
                   3380: 	        my $factor = $width/$resizewidth;
                   3381:                 my $newheight = $height/$factor;
                   3382:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3383:                 $resized = 1;
                   3384:             }
                   3385:         }
                   3386:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3387:             my $width = $ima->Get('width');
                   3388:             my $height = $ima->Get('height');
                   3389:             if ($height > $resizeheight) {
                   3390:                 my $factor = $height/$resizeheight;
                   3391:                 my $newwidth = $width/$factor;
                   3392:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3393:                 $resized = 1;
                   3394:             }
                   3395:         }
                   3396:         if ($resized) {
                   3397:             $ima->Write($img_path);
                   3398:         }
                   3399:     }
                   3400:     return;
1.977     amueller 3401: }
                   3402: 
1.608     albertel 3403: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3404: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3405: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3406: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.93.4  12(raebu 3407:19): #                                    canceloverwrite, scantron or ''.
1.1090    raeburn  3408: #                   if 'coursedoc': upload to the current course
                   3409: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3410: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3411: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3412: #        $subdir - directory in userfile to store the file into
1.1172.2.93.4  12(raebu 3413:19): #        $parser - instruction to parse file for objects ($parser = parse) or
                   3414:19): #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3415:19): #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   3416:19): #                          Section => 4, CODE => 5, FirstQuestion => 9 }).    
1.858     raeburn  3417: #        $allfiles - reference to hash for embedded objects
                   3418: #        $codebase - reference to hash for codebase of java objects
                   3419: #        $desuname - username for permanent storage of uploaded file
                   3420: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3421: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3422: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3423: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3424: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3425: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3426: #                    from File::MMagic.
1.858     raeburn  3427: # 
1.686     albertel 3428: # output: url of file in userspace, or error: <message> 
                   3429: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3430: 
1.531     albertel 3431: sub userfileupload {
1.1090    raeburn  3432:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3433:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3434:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3435:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3436:     $fname=&clean_filename($fname);
1.1090    raeburn  3437:     # See if there is anything left
1.257     www      3438:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3439:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3440:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3441:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3442:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3443:         my $now = time;
1.1090    raeburn  3444:         my $filepath;
1.1095    raeburn  3445:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3446:              $filepath = 'tmp/helprequests/'.$now;
                   3447:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3448:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3449:                          '_'.$env{'user.domain'}.'/pending';
                   3450:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3451:             my ($docuname,$docudom);
1.1172.2.93.4  5(raebur 3452:7):             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3453:                 $docudom = $destudom;
                   3454:             } else {
                   3455:                 $docudom = $env{'user.domain'};
                   3456:             }
1.1172.2.93.4  5(raebur 3457:7):             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3458:                 $docuname = $destuname;
                   3459:             } else {
                   3460:                 $docuname = $env{'user.name'};
                   3461:             }
                   3462:             if (exists($env{'form.group'})) {
                   3463:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3464:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3465:             }
                   3466:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3467:             if ($context eq 'canceloverwrite') {
                   3468:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3469:                 if (-e  $tempfile) {
                   3470:                     my @info = stat($tempfile);
                   3471:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3472:                         unlink($tempfile);
                   3473:                     }
                   3474:                 }
                   3475:                 return;
1.523     raeburn  3476:             }
                   3477:         }
1.1090    raeburn  3478:         # Create the directory if not present
1.741     raeburn  3479:         my @parts=split(/\//,$filepath);
                   3480:         my $fullpath = $perlvar{'lonDaemons'};
                   3481:         for (my $i=0;$i<@parts;$i++) {
                   3482:             $fullpath .= '/'.$parts[$i];
                   3483:             if ((-e $fullpath)!=1) {
                   3484:                 mkdir($fullpath,0777);
                   3485:             }
                   3486:         }
1.1172.2.93.4  7(raebur 3487:7):         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3488:         print $fh $env{'form.'.$formname};
                   3489:         close($fh);
1.1090    raeburn  3490:         if ($context eq 'existingfile') {
                   3491:             my @info = stat($fullpath.'/'.$fname);
                   3492:             return ($fullpath.'/'.$fname,$info[9]);
                   3493:         } else {
                   3494:             return $fullpath.'/'.$fname;
                   3495:         }
1.523     raeburn  3496:     }
1.995     raeburn  3497:     if ($subdir eq 'scantron') {
                   3498:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3499:     } else {
1.995     raeburn  3500:         $fname="$subdir/$fname";
                   3501:     }
1.1090    raeburn  3502:     if ($context eq 'coursedoc') {
1.638     albertel 3503: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3504: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3505:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3506:             return &finishuserfileupload($docuname,$docudom,
                   3507: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3508: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3509:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3510:         } else {
1.1172.2.21  raeburn  3511:             if ($env{'form.folder'}) {
                   3512:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3513:             }
1.638     albertel 3514:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3515: 				       $fname,$formname,$parser,
1.1095    raeburn  3516: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3517:         }
1.719     banghart 3518:     } elsif (defined($destuname)) {
                   3519:         my $docuname=$destuname;
                   3520:         my $docudom=$destudom;
1.860     raeburn  3521: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3522: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3523:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3524:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3525:     } else {
1.638     albertel 3526:         my $docuname=$env{'user.name'};
                   3527:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3528:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3529:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3530:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3531:         }
1.860     raeburn  3532: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3533: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3534:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3535:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3536:     }
1.271     www      3537: }
                   3538: 
                   3539: sub finishuserfileupload {
1.860     raeburn  3540:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3541:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3542:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3543:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3544:   
1.860     raeburn  3545:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3546:     $file=$fname;
                   3547:     if ($fname=~m|/|) {
                   3548:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3549: 	$path.=$fnamepath.'/';
                   3550:     }
1.259     www      3551:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3552:     my $count;
                   3553:     for ($count=4;$count<=$#parts;$count++) {
                   3554:         $filepath.="/$parts[$count]";
                   3555:         if ((-e $filepath)!=1) {
                   3556: 	    mkdir($filepath,0777);
                   3557:         }
                   3558:     }
1.984     neumanie 3559: 
1.258     www      3560: # Save the file
                   3561:     {
1.1172.2.93.4  7(raebur 3562:7): 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3563: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3564: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3565: 	    return '/adm/notfound.html';
                   3566: 	}
1.1090    raeburn  3567:         if ($context eq 'overwrite') {
1.1117    foxr     3568:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3569:             my $target = $filepath.'/'.$file;
                   3570:             if (-e $source) {
                   3571:                 my @info = stat($source);
                   3572:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3573:                     unless (&File::Copy::move($source,$target)) {
                   3574:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3575:                         return "Moving from $source failed";
                   3576:                     }
                   3577:                 } else {
                   3578:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3579:                 }
                   3580:             } else {
                   3581:                 return "Temporary file: $source missing";
                   3582:             }
                   3583:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3584: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3585: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3586: 	    return '/adm/notfound.html';
                   3587: 	}
1.570     albertel 3588: 	close(FH);
1.1051    raeburn  3589:         if ($resizewidth && $resizeheight) {
                   3590:             my $mm = new File::MMagic;
                   3591:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3592:             if ($mime_type =~ m{^image/}) {
                   3593: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3594:             }  
1.977     amueller 3595: 	}
1.258     www      3596:     }
1.1152    raeburn  3597:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3598:         if (ref($mimetype)) {
                   3599:             if ($$mimetype eq '') {
                   3600:                 my $mm = new File::MMagic;
                   3601:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3602:                 $$mimetype = $type;
                   3603:             }
                   3604:         }
                   3605:     }
1.1172.2.93.4  12(raebu 3606:19):     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3607:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3608:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3609:                                                        $allfiles,$codebase);
                   3610:             unless ($parse_result eq 'ok') {
                   3611:                 &logthis('Failed to parse '.$filepath.$file.
                   3612: 	   	         ' for embedded media: '.$parse_result); 
                   3613:             }
1.637     raeburn  3614:         }
1.1172.2.93.4  12(raebu 3615:19):     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   3616:19):         my $format = $env{'form.scantron_format'};
                   3617:19):         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  3618:     }
1.860     raeburn  3619:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3620:         my $input = $filepath.'/'.$file;
                   3621:         my $output = $filepath.'/'.'tn-'.$file;
                   3622:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.93.4  7(raebur 3623:7):         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3624:7):         system({$args[0]} @args);
1.860     raeburn  3625:         if (-e $filepath.'/'.'tn-'.$file) {
                   3626:             $fetchthumb  = 1; 
                   3627:         }
                   3628:     }
1.858     raeburn  3629:  
1.259     www      3630: # Notify homeserver to grep it
                   3631: #
1.984     neumanie 3632:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3633:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3634:     if ($fetchresult eq 'ok') {
1.860     raeburn  3635:         if ($fetchthumb) {
                   3636:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3637:             if ($thumbresult ne 'ok') {
                   3638:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3639:                          $docuhome.': '.$thumbresult);
                   3640:             }
                   3641:         }
1.259     www      3642: #
1.258     www      3643: # Return the URL to it
1.494     albertel 3644:         return '/uploaded/'.$path.$file;
1.263     www      3645:     } else {
1.494     albertel 3646:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3647: 		 ': '.$fetchresult);
1.263     www      3648:         return '/adm/notfound.html';
1.858     raeburn  3649:     }
1.493     albertel 3650: }
                   3651: 
1.637     raeburn  3652: sub extract_embedded_items {
1.961     raeburn  3653:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3654:     my @state = ();
1.1164    raeburn  3655:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3656:     my %javafiles = (
                   3657:                       codebase => '',
                   3658:                       code => '',
                   3659:                       archive => ''
                   3660:                     );
                   3661:     my %mediafiles = (
                   3662:                       src => '',
                   3663:                       movie => '',
                   3664:                      );
1.648     raeburn  3665:     my $p;
                   3666:     if ($content) {
                   3667:         $p = HTML::LCParser->new($content);
                   3668:     } else {
1.961     raeburn  3669:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3670:     }
1.641     albertel 3671:     while (my $t=$p->get_token()) {
1.640     albertel 3672: 	if ($t->[0] eq 'S') {
                   3673: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3674: 	    push(@state, $tagname);
1.648     raeburn  3675:             if (lc($tagname) eq 'allow') {
                   3676:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3677:             }
1.640     albertel 3678: 	    if (lc($tagname) eq 'img') {
                   3679: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3680: 	    }
1.886     albertel 3681: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3682:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3683: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3684:                 }
1.886     albertel 3685: 	    }
1.645     raeburn  3686:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3687:                 my $src;
1.645     raeburn  3688:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3689:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3690:                 } else {
1.1164    raeburn  3691:                     if ($attr->{'src'} ne '') {
                   3692:                         $src = $attr->{'src'};
                   3693:                         &add_filetype($allfiles,$src,'src');
                   3694:                     }
                   3695:                 }
                   3696:                 my $text = $p->get_trimmed_text();
                   3697:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3698:                     my @swfargs = split(/,/,$1);
                   3699:                     foreach my $item (@swfargs) {
                   3700:                         $item =~ s/["']//g;
                   3701:                         $item =~ s/^\s+//;
                   3702:                         $item =~ s/\s+$//;
                   3703:                     }
                   3704:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3705:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3706:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3707:                         } else {
                   3708:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3709:                         }
                   3710:                     }
1.645     raeburn  3711:                 }
                   3712:             }
                   3713:             if (lc($tagname) eq 'link') {
                   3714:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3715:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3716:                 }
                   3717:             }
1.640     albertel 3718: 	    if (lc($tagname) eq 'object' ||
                   3719: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3720: 		foreach my $item (keys(%javafiles)) {
                   3721: 		    $javafiles{$item} = '';
                   3722: 		}
1.1164    raeburn  3723:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3724:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3725:                 }
1.640     albertel 3726: 	    }
                   3727: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3728: 		my $name = lc($attr->{'name'});
                   3729: 		foreach my $item (keys(%javafiles)) {
                   3730: 		    if ($name eq $item) {
                   3731: 			$javafiles{$item} = $attr->{'value'};
                   3732: 			last;
                   3733: 		    }
                   3734: 		}
1.1164    raeburn  3735:                 my $pathfrom;
1.640     albertel 3736: 		foreach my $item (keys(%mediafiles)) {
                   3737: 		    if ($name eq $item) {
1.1164    raeburn  3738:                         $pathfrom = $attr->{'value'};
                   3739:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3740: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3741: 			last;
                   3742: 		    }
                   3743: 		}
1.1164    raeburn  3744:                 if ($name eq 'flashvars') {
                   3745:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3746:                 }
                   3747:                 if ($pathfrom ne '') {
                   3748:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3749:                                          $pathfrom);
                   3750:                 }
1.640     albertel 3751: 	    }
                   3752: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3753: 		foreach my $item (keys(%javafiles)) {
                   3754: 		    if ($attr->{$item}) {
                   3755: 			$javafiles{$item} = $attr->{$item};
                   3756: 			last;
                   3757: 		    }
                   3758: 		}
                   3759: 		foreach my $item (keys(%mediafiles)) {
                   3760: 		    if ($attr->{$item}) {
                   3761: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3762: 			last;
                   3763: 		    }
                   3764: 		}
1.1164    raeburn  3765:                 if (lc($tagname) eq 'embed') {
                   3766:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3767:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3768:                                              $attr->{'src'});
                   3769:                     }
                   3770:                 }
1.640     albertel 3771: 	    }
1.1172.2.35  raeburn  3772:             if (lc($tagname) eq 'iframe') {
                   3773:                 my $src = $attr->{'src'} ;
                   3774:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3775:                     &add_filetype($allfiles,$src,'src');
                   3776:                 } elsif ($src =~ m{^/}) {
                   3777:                     if ($env{'request.course.id'}) {
                   3778:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3779:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3780:                         my $url = &hreflocation('',$fullpath);
                   3781:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3782:                             my $relpath = $1;
                   3783:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3784:                                 &add_filetype($allfiles,$1,'src');
                   3785:                             }
                   3786:                         }
                   3787:                     }
                   3788:                 }
                   3789:             }
1.1164    raeburn  3790:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3791:                 pop(@state);
1.1164    raeburn  3792:             }
1.640     albertel 3793: 	} elsif ($t->[0] eq 'E') {
                   3794: 	    my ($tagname) = ($t->[1]);
                   3795: 	    if ($javafiles{'codebase'} ne '') {
                   3796: 		$javafiles{'codebase'} .= '/';
                   3797: 	    }  
                   3798: 	    if (lc($tagname) eq 'applet' ||
                   3799: 		lc($tagname) eq 'object' ||
                   3800: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3801: 		) {
                   3802: 		foreach my $item (keys(%javafiles)) {
                   3803: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3804: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3805: 			&add_filetype($allfiles,$file,$item);
                   3806: 		    }
                   3807: 		}
                   3808: 	    } 
                   3809: 	    pop @state;
                   3810: 	}
                   3811:     }
1.1164    raeburn  3812:     foreach my $id (sort(keys(%flashvars))) {
                   3813:         if ($shockwave{$id} ne '') {
                   3814:             my @pairs = split(/\&/,$flashvars{$id});
                   3815:             foreach my $pair (@pairs) {
                   3816:                 my ($key,$value) = split(/\=/,$pair);
                   3817:                 if ($key eq 'thumb') {
                   3818:                     &add_filetype($allfiles,$value,$key);
                   3819:                 } elsif ($key eq 'content') {
                   3820:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3821:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3822:                     if ($ext ne '') {
                   3823:                         &add_filetype($allfiles,$path.$value,$ext);
                   3824:                     }
                   3825:                 }
                   3826:             }
                   3827:         }
                   3828:     }
1.637     raeburn  3829:     return 'ok';
                   3830: }
                   3831: 
1.639     albertel 3832: sub add_filetype {
                   3833:     my ($allfiles,$file,$type)=@_;
                   3834:     if (exists($allfiles->{$file})) {
                   3835: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3836: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3837: 	}
                   3838:     } else {
                   3839: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3840:     }
                   3841: }
                   3842: 
1.1164    raeburn  3843: sub embedded_dependency {
                   3844:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3845:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3846:         if (($identifier ne '') &&
                   3847:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3848:             ($pathfrom ne '')) {
                   3849:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3850:             foreach my $dep (@{$related->{$identifier}}) {
                   3851:                 &add_filetype($allfiles,$path.$dep,'object');
                   3852:             }
                   3853:         }
                   3854:     }
                   3855:     return;
                   3856: }
                   3857: 
1.1172.2.93.4  12(raebu 3858:19): sub bubblesheet_converter {
                   3859:19):     my ($cdom,$fullpath,$config,$format) = @_;
                   3860:19):     if ((&domain($cdom) ne '') &&
                   3861:19):         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   3862:19):         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   3863:19):         my (%csvcols,%csvoptions);
                   3864:19):         if (ref($config->{'fields'}) eq 'HASH') {
                   3865:19):             %csvcols = %{$config->{'fields'}};
                   3866:19):         }
                   3867:19):         if (ref($config->{'options'}) eq 'HASH') {
                   3868:19):             %csvoptions = %{$config->{'options'}};
                   3869:19):         }
                   3870:19):         my %csvbynum = reverse(%csvcols);
                   3871:19):         my %scantronconf = &get_scantron_config($format,$cdom);
                   3872:19):         if (keys(%scantronconf)) {
                   3873:19):             my %bynum = (
                   3874:19):                           $scantronconf{CODEstart} => 'CODEstart',
                   3875:19):                           $scantronconf{IDstart}   => 'IDstart',
                   3876:19):                           $scantronconf{PaperID}   => 'PaperID',
                   3877:19):                           $scantronconf{FirstName} => 'FirstName',
                   3878:19):                           $scantronconf{LastName}  => 'LastName',
                   3879:19):                           $scantronconf{Qstart}    => 'Qstart',
                   3880:19):                         );
                   3881:19):             my @ordered;
                   3882:19):             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   3883:19):                 push(@ordered,$bynum{$item});
                   3884:19):             }
                   3885:19):             my %mapstart = (
                   3886:19):                               CODEstart => 'CODE',
                   3887:19):                               IDstart   => 'ID',
                   3888:19):                               PaperID   => 'PaperID',
                   3889:19):                               FirstName => 'FirstName',
                   3890:19):                               LastName  => 'LastName',
                   3891:19):                               Qstart    => 'FirstQuestion',
                   3892:19):                            );
                   3893:19):             my %maplength = (
                   3894:19):                               CODEstart => 'CODElength',
                   3895:19):                               IDstart   => 'IDlength',
                   3896:19):                               PaperID   => 'PaperIDlength',
                   3897:19):                               FirstName => 'FirstNamelength',
                   3898:19):                               LastName  => 'LastNamelength',
                   3899:19):             );
                   3900:19):             if (open(my $fh,'<',$fullpath)) {
                   3901:19):                 my $output;
                   3902:19):                 my %lettdig = &letter_to_digits();
                   3903:19):                 my %diglett = reverse(%lettdig);
                   3904:19):                 my $numletts = scalar(keys(%lettdig));
                   3905:19):                 my $num = 0;
                   3906:19):                 while (my $line=<$fh>) {
                   3907:19):                     $num ++;
                   3908:19):                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   3909:19):                     $line =~ s{[\r\n]+$}{};
                   3910:19):                     my %found;
                   3911:19):                     my @values = split(/,/,$line);
                   3912:19):                     my ($qstart,$record);
                   3913:19):                     for (my $i=0; $i<@values; $i++) {
                   3914:19):                         if ((($qstart ne '') && ($i > $qstart)) ||
                   3915:19):                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   3916:19):                             if ($values[$i] eq '') {
                   3917:19):                                 $values[$i] = $scantronconf{'Qoff'};
                   3918:19):                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   3919:19):                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   3920:19):                                     $values[$i] = $lettdig{uc($values[$i])};
                   3921:19):                                 }
                   3922:19):                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   3923:19):                                 if ($values[$i] =~ /^[0-9]$/) {
                   3924:19):                                     $values[$i] = $diglett{$values[$i]};
                   3925:19):                                 }
                   3926:19):                             } else {
                   3927:19):                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   3928:19):                                     my $digit;
                   3929:19):                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   3930:19):                                         $digit = $lettdig{uc($values[$i])}-1;
                   3931:19):                                         if ($values[$i] eq 'J') {
                   3932:19):                                             $digit += $numletts;
                   3933:19):                                         }
                   3934:19):                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   3935:19):                                         $digit = $values[$i]-1;
                   3936:19):                                         if ($values[$i] eq '0') {
                   3937:19):                                             $digit += $numletts;
                   3938:19):                                         }
                   3939:19):                                     }
                   3940:19):                                     my $qval='';
                   3941:19):                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   3942:19):                                         if ($j == $digit) {
                   3943:19):                                             $qval .= $scantronconf{'Qon'};
                   3944:19):                                         } else {
                   3945:19):                                             $qval .= $scantronconf{'Qoff'};
                   3946:19):                                         }
                   3947:19):                                     }
                   3948:19):                                     $values[$i] = $qval;
                   3949:19):                                 }
                   3950:19):                             }
                   3951:19):                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   3952:19):                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   3953:19):                             }
                   3954:19):                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   3955:19):                             if ($numblank > 0) {
                   3956:19):                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   3957:19):                             }
                   3958:19):                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   3959:19):                                 $qstart = $i;
                   3960:19):                                 $found{$csvbynum{$i}} = $values[$i];
                   3961:19):                             } else {
                   3962:19):                                 $found{'FirstQuestion'} .= $values[$i];
                   3963:19):                             }
                   3964:19):                         } elsif (exists($csvbynum{$i})) {
                   3965:19):                             if ($csvoptions{'rem'}) {
                   3966:19):                                 $values[$i] =~ s/^\s+//;
                   3967:19):                             }
                   3968:19):                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   3969:19):                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   3970:19):                                     $values[$i] = '0'.$values[$i];
                   3971:19):                                 }
                   3972:19):                             }
                   3973:19):                             $found{$csvbynum{$i}} = $values[$i];
                   3974:19):                         }
                   3975:19):                     }
                   3976:19):                     foreach my $item (@ordered) {
                   3977:19):                         my $currlength = 1+length($record);
                   3978:19):                         my $numspaces = $scantronconf{$item} - $currlength;
                   3979:19):                         if ($numspaces > 0) {
                   3980:19):                             $record .= (' ' x $numspaces);
                   3981:19):                         }
                   3982:19):                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   3983:19):                             unless ($item eq 'Qstart') {
                   3984:19):                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   3985:19):                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   3986:19):                                 }
                   3987:19):                             }
                   3988:19):                             $record .= $found{$mapstart{$item}};
                   3989:19):                         }
                   3990:19):                     }
                   3991:19):                     $output .= "$record\n";
                   3992:19):                 }
                   3993:19):                 close($fh);
                   3994:19):                 if ($output) {
                   3995:19):                     if (open(my $fh,'>',$fullpath)) {
                   3996:19):                         print $fh $output;
                   3997:19):                         close($fh);
                   3998:19):                     }
                   3999:19):                 }
                   4000:19):             }
                   4001:19):         }
                   4002:19):         return;
                   4003:19):     }
                   4004:19): }
                   4005:19): 
                   4006:19): sub letter_to_digits {
                   4007:19):     my %lettdig = (
                   4008:19):                     A => 1,
                   4009:19):                     B => 2,
                   4010:19):                     C => 3,
                   4011:19):                     D => 4,
                   4012:19):                     E => 5,
                   4013:19):                     F => 6,
                   4014:19):                     G => 7,
                   4015:19):                     H => 8,
                   4016:19):                     I => 9,
                   4017:19):                     J => 0,
                   4018:19):                   );
                   4019:19):     return %lettdig;
                   4020:19): }
                   4021:19): 
                   4022:19): sub get_scantron_config {
                   4023:19):     my ($which,$cdom) = @_;
                   4024:19):     my @lines = &get_scantronformat_file($cdom);
                   4025:19):     my %config;
                   4026:19):     #FIXME probably should move to XML it has already gotten a bit much now
                   4027:19):     foreach my $line (@lines) {
                   4028:19):         my ($name,$descrip)=split(/:/,$line);
                   4029:19):         if ($name ne $which ) { next; }
                   4030:19):         chomp($line);
                   4031:19):         my @config=split(/:/,$line);
                   4032:19):         $config{'name'}=$config[0];
                   4033:19):         $config{'description'}=$config[1];
                   4034:19):         $config{'CODElocation'}=$config[2];
                   4035:19):         $config{'CODEstart'}=$config[3];
                   4036:19):         $config{'CODElength'}=$config[4];
                   4037:19):         $config{'IDstart'}=$config[5];
                   4038:19):         $config{'IDlength'}=$config[6];
                   4039:19):         $config{'Qstart'}=$config[7];
                   4040:19):         $config{'Qlength'}=$config[8];
                   4041:19):         $config{'Qoff'}=$config[9];
                   4042:19):         $config{'Qon'}=$config[10];
                   4043:19):         $config{'PaperID'}=$config[11];
                   4044:19):         $config{'PaperIDlength'}=$config[12];
                   4045:19):         $config{'FirstName'}=$config[13];
                   4046:19):         $config{'FirstNamelength'}=$config[14];
                   4047:19):         $config{'LastName'}=$config[15];
                   4048:19):         $config{'LastNamelength'}=$config[16];
                   4049:19):         $config{'BubblesPerRow'}=$config[17];
                   4050:19):         last;
                   4051:19):     }
                   4052:19):     return %config;
                   4053:19): }
                   4054:19): 
                   4055:19): sub get_scantronformat_file {
                   4056:19):     my ($cdom) = @_;
                   4057:19):     if ($cdom eq '') {
                   4058:19):         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4059:19):     }
                   4060:19):     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4061:19):     my $gottab = 0;
                   4062:19):     my @lines;
                   4063:19):     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4064:19):         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4065:19):             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4066:19):             if ($formatfile ne '-1') {
                   4067:19):                 @lines = split("\n",$formatfile,-1);
                   4068:19):                 $gottab = 1;
                   4069:19):             }
                   4070:19):         }
                   4071:19):     }
                   4072:19):     if (!$gottab) {
                   4073:19):         my $confname = $cdom.'-domainconfig';
                   4074:19):         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4075:19):         my $formatfile = &getfile($default);
                   4076:19):         if ($formatfile ne '-1') {
                   4077:19):             @lines = split("\n",$formatfile,-1);
                   4078:19):             $gottab = 1;
                   4079:19):         }
                   4080:19):     }
                   4081:19):     if (!$gottab) {
                   4082:19):         my @domains = &current_machine_domains();
                   4083:19):         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4084:19):             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4085:19):                 @lines = <$fh>;
                   4086:19):                 close($fh);
                   4087:19):             }
                   4088:19):         } else {
                   4089:19):             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4090:19):                 @lines = <$fh>;
                   4091:19):                 close($fh);
                   4092:19):             }
                   4093:19):         }
                   4094:19):     }
                   4095:19):     return @lines;
                   4096:19): }
                   4097:19): 
1.493     albertel 4098: sub removeuploadedurl {
1.984     neumanie 4099:     my ($url)=@_;	
                   4100:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4101:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4102: }
                   4103: 
                   4104: sub removeuserfile {
                   4105:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4106:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4107:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4108:     if ($result eq 'ok') {	
1.798     raeburn  4109:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4110:             my $metafile = $fname.'.meta';
                   4111:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4112: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4113:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4114:             my $sqlresult = 
1.823     albertel 4115:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4116:                                         'portfolio_metadata',$group,
                   4117:                                         'delete');
1.798     raeburn  4118:         }
                   4119:     }
                   4120:     return $result;
1.257     www      4121: }
1.15      www      4122: 
1.530     albertel 4123: sub mkdiruserfile {
                   4124:     my ($docuname,$docudom,$dir)=@_;
                   4125:     my $home=&homeserver($docuname,$docudom);
                   4126:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4127: }
                   4128: 
1.531     albertel 4129: sub renameuserfile {
                   4130:     my ($docuname,$docudom,$old,$new)=@_;
                   4131:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4132:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4133:                         &escape("$old").':'.&escape("$new"),$home);
                   4134:     if ($result eq 'ok') {
                   4135:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4136:             my $oldmeta = $old.'.meta';
                   4137:             my $newmeta = $new.'.meta';
                   4138:             my $metaresult = 
                   4139:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4140: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4141:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4142:             my $sqlresult = 
1.823     albertel 4143:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4144:                                         'portfolio_metadata',$group,
                   4145:                                         'delete');
1.798     raeburn  4146:         }
                   4147:     }
                   4148:     return $result;
1.531     albertel 4149: }
                   4150: 
1.14      www      4151: # ------------------------------------------------------------------------- Log
                   4152: 
                   4153: sub log {
                   4154:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4155:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4156: }
                   4157: 
                   4158: # ------------------------------------------------------------------ Course Log
1.352     www      4159: #
                   4160: # This routine flushes several buffers of non-mission-critical nature
                   4161: #
1.157     www      4162: 
                   4163: sub flushcourselogs {
1.352     www      4164:     &logthis('Flushing log buffers');
                   4165: #
                   4166: # course logs
                   4167: # This is a log of all transactions in a course, which can be used
                   4168: # for data mining purposes
                   4169: #
                   4170: # It also collects the courseid database, which lists last transaction
                   4171: # times and course titles for all courseids
                   4172: #
                   4173:     my %courseidbuffer=();
1.921     raeburn  4174:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4175:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4176: 		          &escape($courselogs{$crsid}),
                   4177: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4178: 	    delete $courselogs{$crsid};
                   4179:         } else {
                   4180:             &logthis('Failed to flush log buffer for '.$crsid);
                   4181:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4182:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4183:                         " exceeded maximum size, deleting.</font>");
                   4184:                delete $courselogs{$crsid};
                   4185:             }
1.352     www      4186:         }
1.920     raeburn  4187:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4188:             'description' => $coursedescrbuf{$crsid},
                   4189:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4190:             'type'        => $coursetypebuf{$crsid},
                   4191:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4192:         };
1.191     harris41 4193:     }
1.352     www      4194: #
                   4195: # Write course id database (reverse lookup) to homeserver of courses 
                   4196: # Is used in pickcourse
                   4197: #
1.840     albertel 4198:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4199:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4200:                                     $courseidbuffer{$crs_home},
                   4201:                                     $crs_home,'timeonly');
1.352     www      4202:     }
                   4203: #
                   4204: # File accesses
                   4205: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4206: #
1.449     matthew  4207:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4208:         if ($entry =~ /___count$/) {
                   4209:             my ($dom,$name);
1.807     albertel 4210:             ($dom,$name,undef)=
1.811     albertel 4211: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4212:             if (! defined($dom) || $dom eq '' || 
                   4213:                 ! defined($name) || $name eq '') {
1.620     albertel 4214:                 my $cid = $env{'request.course.id'};
                   4215:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4216:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4217:             }
1.450     matthew  4218:             my $value = $accesshash{$entry};
                   4219:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4220:             my %temphash=($url => $value);
1.449     matthew  4221:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4222:             if ($result eq 'ok') {
                   4223:                 delete $accesshash{$entry};
                   4224:             }
                   4225:         } else {
1.811     albertel 4226:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4227:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4228:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4229:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4230:                 delete $accesshash{$entry};
                   4231:             }
1.185     www      4232:         }
1.191     harris41 4233:     }
1.352     www      4234: #
                   4235: # Roles
                   4236: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4237: #
1.800     albertel 4238:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4239:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4240: 	    split(/\:/,$entry);
                   4241:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4242:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4243:                 $rudom,$runame) eq 'ok') {
                   4244: 	    delete $userrolehash{$entry};
                   4245:         }
                   4246:     }
1.662     raeburn  4247: #
1.1172.2.90  raeburn  4248: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4249: #
                   4250:     my %domrolebuffer = ();
1.1000    raeburn  4251:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4252:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4253:         if ($domrolebuffer{$rudom}) {
                   4254:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4255:                       '='.&escape($domainrolehash{$entry});
                   4256:         } else {
                   4257:             $domrolebuffer{$rudom}.=&escape($entry).
                   4258:                       '='.&escape($domainrolehash{$entry});
                   4259:         }
                   4260:         delete $domainrolehash{$entry};
                   4261:     }
                   4262:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4263:         my %servers;
                   4264:         if (defined(&domain($dom,'primary'))) {
                   4265:             my $primary=&domain($dom,'primary');
                   4266:             my $hostname=&hostname($primary);
                   4267:             $servers{$primary} = $hostname;
                   4268:         } else {
                   4269:             %servers = &get_servers($dom,'library');
                   4270:         }
1.841     albertel 4271: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4272: 	    if (&reply('domroleput:'.$dom.':'.
                   4273: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4274: 	        last;
                   4275: 	    } else {
1.841     albertel 4276: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4277: 	    }
1.662     raeburn  4278:         }
                   4279:     }
1.186     www      4280:     $dumpcount++;
1.157     www      4281: }
                   4282: 
                   4283: sub courselog {
                   4284:     my $what=shift;
1.158     www      4285:     $what=time.':'.$what;
1.620     albertel 4286:     unless ($env{'request.course.id'}) { return ''; }
                   4287:     $coursedombuf{$env{'request.course.id'}}=
                   4288:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4289:     $coursenumbuf{$env{'request.course.id'}}=
                   4290:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4291:     $coursehombuf{$env{'request.course.id'}}=
                   4292:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4293:     $coursedescrbuf{$env{'request.course.id'}}=
                   4294:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4295:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4296:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4297:     $courseownerbuf{$env{'request.course.id'}}=
                   4298:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4299:     $coursetypebuf{$env{'request.course.id'}}=
                   4300:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4301:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4302: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4303:     } else {
1.620     albertel 4304: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4305:     }
1.620     albertel 4306:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4307: 	&flushcourselogs();
                   4308:     }
1.158     www      4309: }
                   4310: 
                   4311: sub courseacclog {
                   4312:     my $fnsymb=shift;
1.620     albertel 4313:     unless ($env{'request.course.id'}) { return ''; }
                   4314:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4315:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4316:         $what.=':POST';
1.583     matthew  4317:         # FIXME: Probably ought to escape things....
1.800     albertel 4318: 	foreach my $key (keys(%env)) {
                   4319:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4320:                 my $formitem = $1;
                   4321:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4322:                     $what.=':'.$formitem.'='.$env{$key};
                   4323:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4324:                     $what.=':'.$formitem.'='.$env{$key};
                   4325:                 }
1.158     www      4326:             }
1.191     harris41 4327:         }
1.583     matthew  4328:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4329:         # FIXME: We should not be depending on a form parameter that someone
                   4330:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4331:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4332:             $what.= ':POST';
                   4333:             # FIXME: Probably ought to escape things....
                   4334:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4335:                                  'crsdiscuss') {
1.620     albertel 4336:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4337:             }
                   4338:         }
1.158     www      4339:     }
                   4340:     &courselog($what);
1.149     www      4341: }
                   4342: 
1.185     www      4343: sub countacc {
                   4344:     my $url=&declutter(shift);
1.458     matthew  4345:     return if (! defined($url) || $url eq '');
1.620     albertel 4346:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4347: #
                   4348: # Mark that this url was used in this course
                   4349: #
1.620     albertel 4350:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4351: #
                   4352: # Increase the access count for this resource in this child process
                   4353: #
1.281     www      4354:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4355:     $accesshash{$key}++;
1.185     www      4356: }
1.349     www      4357: 
1.361     www      4358: sub linklog {
                   4359:     my ($from,$to)=@_;
                   4360:     $from=&declutter($from);
                   4361:     $to=&declutter($to);
                   4362:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4363:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4364: }
1.1160    www      4365: 
                   4366: sub statslog {
                   4367:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4368:     if ($users<2) { return; }
                   4369:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4370:             'course'       => $env{'request.course.id'},
                   4371:             'sections'     => '"all"',
                   4372:             'num_students' => $users,
                   4373:             'part'         => $part,
                   4374:             'symb'         => $symb,
                   4375:             'mean_tries'   => $av_attempts,
                   4376:             'deg_of_diff'  => $degdiff});
                   4377:     foreach my $key (keys(%dynstore)) {
                   4378:         $accesshash{$key}=$dynstore{$key};
                   4379:     }
                   4380: }
1.361     www      4381:   
1.349     www      4382: sub userrolelog {
                   4383:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4384:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4385:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4386:        $userrolehash
                   4387:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4388:                     =$tend.':'.$tstart;
1.662     raeburn  4389:     }
1.1169    droeschl 4390:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4391:        $userrolehash
                   4392:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4393:                     =$tend.':'.$tstart;
                   4394:     }
1.1172.2.90  raeburn  4395:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4396:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4397:        $domainrolehash
                   4398:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4399:                     = $tend.':'.$tstart;
                   4400:     }
1.351     www      4401: }
                   4402: 
1.957     raeburn  4403: sub courserolelog {
                   4404:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4405:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4406:         my $cdom = $1;
                   4407:         my $cnum = $2;
                   4408:         my $sec = $3;
                   4409:         my $namespace = 'rolelog';
                   4410:         my %storehash = (
                   4411:                            role    => $trole,
                   4412:                            start   => $tstart,
                   4413:                            end     => $tend,
                   4414:                            selfenroll => $selfenroll,
                   4415:                            context    => $context,
                   4416:                         );
                   4417:         if ($trole eq 'gr') {
                   4418:             $namespace = 'groupslog';
                   4419:             $storehash{'group'} = $sec;
                   4420:         } else {
                   4421:             $storehash{'section'} = $sec;
                   4422:         }
                   4423:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4424:                    $domain,$cnum,$cdom);
                   4425:         if (($trole ne 'st') || ($sec ne '')) {
                   4426:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4427:         }
                   4428:     }
                   4429:     return;
                   4430: }
                   4431: 
1.1172.2.9  raeburn  4432: sub domainrolelog {
                   4433:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4434:     if ($area =~ m{^/($match_domain)/$}) {
                   4435:         my $cdom = $1;
                   4436:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4437:         my $namespace = 'rolelog';
                   4438:         my %storehash = (
                   4439:                            role    => $trole,
                   4440:                            start   => $tstart,
                   4441:                            end     => $tend,
                   4442:                            context => $context,
                   4443:                         );
                   4444:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4445:                    $domain,$domconfiguser,$cdom);
                   4446:     }
                   4447:     return;
                   4448: 
                   4449: }
                   4450: 
                   4451: sub coauthorrolelog {
                   4452:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4453:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4454:         my $audom = $1;
                   4455:         my $auname = $2;
                   4456:         my $namespace = 'rolelog';
                   4457:         my %storehash = (
                   4458:                            role    => $trole,
                   4459:                            start   => $tstart,
                   4460:                            end     => $tend,
                   4461:                            context => $context,
                   4462:                         );
                   4463:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4464:                    $domain,$auname,$audom);
                   4465:     }
                   4466:     return;
                   4467: }
                   4468: 
1.351     www      4469: sub get_course_adv_roles {
1.948     raeburn  4470:     my ($cid,$codes) = @_;
1.620     albertel 4471:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4472:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4473:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4474:     my %nothide=();
1.800     albertel 4475:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4476:         if ($user !~ /:/) {
                   4477: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4478:         } else {
                   4479:             $nothide{$user}=1;
                   4480:         }
1.470     www      4481:     }
1.1172.2.23  raeburn  4482:     my @possdoms = ($coursehash{'domain'});
                   4483:     if ($coursehash{'checkforpriv'}) {
                   4484:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4485:     }
1.351     www      4486:     my %returnhash=();
                   4487:     my %dumphash=
                   4488:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4489:     my $now=time;
1.997     raeburn  4490:     my %privileged;
1.1000    raeburn  4491:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4492: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4493:         if (($tstart) && ($tstart<0)) { next; }
                   4494:         if (($tend) && ($tend<$now)) { next; }
                   4495:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4496:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4497: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4498:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4499:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4500: 	if ($role eq 'cr') { next; }
1.948     raeburn  4501:         if ($codes) {
                   4502:             if ($section) { $role .= ':'.$section; }
                   4503:             if ($returnhash{$role}) {
                   4504:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4505:             } else {
                   4506:                 $returnhash{$role}=$username.':'.$domain;
                   4507:             }
1.351     www      4508:         } else {
1.988     raeburn  4509:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4510:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4511:             if ($returnhash{$key}) {
                   4512: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4513:             } else {
                   4514:                 $returnhash{$key}=$username.':'.$domain;
                   4515:             }
1.351     www      4516:         }
1.948     raeburn  4517:     }
1.400     www      4518:     return %returnhash;
                   4519: }
                   4520: 
                   4521: sub get_my_roles {
1.937     raeburn  4522:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4523:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4524:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4525:     my (%dumphash,%nothide);
1.1086    raeburn  4526:     if ($context eq 'userroles') {
1.1166    raeburn  4527:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4528:     } else {
1.1172.2.23  raeburn  4529:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4530:         if ($hidepriv) {
                   4531:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4532:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4533:                 if ($user !~ /:/) {
                   4534:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4535:                 } else {
                   4536:                     $nothide{$user} = 1;
                   4537:                 }
                   4538:             }
                   4539:         }
1.858     raeburn  4540:     }
1.400     www      4541:     my %returnhash=();
                   4542:     my $now=time;
1.999     raeburn  4543:     my %privileged;
1.800     albertel 4544:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4545:         my ($role,$tend,$tstart);
                   4546:         if ($context eq 'userroles') {
1.1149    raeburn  4547:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4548: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4549:         } else {
                   4550:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4551:         }
1.400     www      4552:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4553:         my $status = 'active';
1.939     raeburn  4554:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4555:             $status = 'previous';
                   4556:         } 
                   4557:         if (($tstart) && ($now<$tstart)) {
                   4558:             $status = 'future';
                   4559:         }
                   4560:         if (ref($types) eq 'ARRAY') {
                   4561:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4562:                 next;
                   4563:             } 
                   4564:         } else {
                   4565:             if ($status ne 'active') {
                   4566:                 next;
                   4567:             }
                   4568:         }
1.867     raeburn  4569:         my ($rolecode,$username,$domain,$section,$area);
                   4570:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4571:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4572:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4573:         } else {
                   4574:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4575:         }
1.832     raeburn  4576:         if (ref($roledoms) eq 'ARRAY') {
                   4577:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4578:                 next;
                   4579:             }
                   4580:         }
                   4581:         if (ref($roles) eq 'ARRAY') {
                   4582:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4583:                 if ($role =~ /^cr\//) {
                   4584:                     if (!grep(/^cr$/,@{$roles})) {
                   4585:                         next;
                   4586:                     }
1.1104    raeburn  4587:                 } elsif ($role =~ /^gr\//) {
                   4588:                     if (!grep(/^gr$/,@{$roles})) {
                   4589:                         next;
                   4590:                     }
1.922     raeburn  4591:                 } else {
                   4592:                     next;
                   4593:                 }
1.832     raeburn  4594:             }
1.867     raeburn  4595:         }
1.937     raeburn  4596:         if ($hidepriv) {
1.1172.2.23  raeburn  4597:             my @privroles = ('dc','su');
1.999     raeburn  4598:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4599:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4600:             } else {
1.1172.2.23  raeburn  4601:                 my $possdoms = [$domain];
                   4602:                 if (ref($roledoms) eq 'ARRAY') {
                   4603:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4604:                 }
1.1172.2.23  raeburn  4605:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4606:                     if (!$nothide{$username.':'.$domain}) {
                   4607:                         next;
                   4608:                     }
                   4609:                 }
1.937     raeburn  4610:             }
                   4611:         }
1.933     raeburn  4612:         if ($withsec) {
                   4613:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4614:                 $tstart.':'.$tend;
                   4615:         } else {
                   4616:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4617:         }
1.832     raeburn  4618:     }
1.373     www      4619:     return %returnhash;
1.399     www      4620: }
                   4621: 
1.1172.2.89  raeburn  4622: sub get_all_adhocroles {
                   4623:     my ($dom) = @_;
                   4624:     my @roles_by_num = ();
                   4625:     my %domdefaults = &get_domain_defaults($dom);
                   4626:     my (%description,%access_in_dom,%access_info);
                   4627:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4628:         my $count = 0;
                   4629:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4630:         my %ordered;
                   4631:         foreach my $role (sort(keys(%domcurrent))) {
                   4632:             my ($order,$desc,$access_in_dom);
                   4633:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4634:                 $order = $domcurrent{$role}{'order'};
                   4635:                 $desc = $domcurrent{$role}{'desc'};
                   4636:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4637:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4638:             }
                   4639:             if ($order eq '') {
                   4640:                 $order = $count;
                   4641:             }
                   4642:             $ordered{$order} = $role;
                   4643:             if ($desc ne '') {
                   4644:                 $description{$role} = $desc;
                   4645:             } else {
                   4646:                 $description{$role}= $role;
                   4647:             }
                   4648:             $count++;
                   4649:         }
                   4650:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4651:             push(@roles_by_num,$ordered{$item});
                   4652:         }
                   4653:     }
                   4654:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4655: }
                   4656: 
                   4657: sub get_my_adhocroles {
                   4658:     my ($cid,$checkreg) = @_;
                   4659:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4660:     if ($env{'request.course.id'} eq $cid) {
                   4661:         $cdom = $env{'course.'.$cid.'.domain'};
                   4662:         $cnum = $env{'course.'.$cid.'.num'};
                   4663:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4664:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4665:         $cdom = $1;
                   4666:         $cnum = $2;
                   4667:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4668:                                      $cdom,$cnum);
                   4669:     }
                   4670:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4671:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4672:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4673:         if ($rosterhash{$user} ne '') {
                   4674:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4675:             return ([],{}) if ($type eq 'auto');
                   4676:         }
                   4677:     }
                   4678:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4679:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4680:             my $then=$env{'user.login.time'};
                   4681:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4682:             if (!$update) {
                   4683:                 $update = $then;
                   4684:             }
                   4685:             my @liveroles;
                   4686:             foreach my $role ('dh','da') {
                   4687:                 if ($env{"user.role.$role./$cdom/"}) {
                   4688:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4689:                     my $limit = $update;
                   4690:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4691:                         $limit = $then;
                   4692:                     }
                   4693:                     my $activerole = 1;
                   4694:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4695:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4696:                     if ($activerole) {
                   4697:                         push(@liveroles,$role);
                   4698:                     }
                   4699:                 }
                   4700:             }
                   4701:             if (@liveroles) {
1.1172.2.89  raeburn  4702:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4703:                     my ($accessref,$accessinfo,%access_in_dom);
                   4704:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4705:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4706:                         if (@{$roles_by_num}) {
                   4707:                             my %settings;
                   4708:                             if ($env{'request.course.id'} eq $cid) {
                   4709:                                 foreach my $envkey (keys(%env)) {
                   4710:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4711:                                         $settings{$1} = $env{$envkey};
                   4712:                                     }
                   4713:                                 }
                   4714:                             } else {
                   4715:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4716:                             }
                   4717:                             my %setincrs;
                   4718:                             if ($settings{'internal.adhocaccess'}) {
                   4719:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4720:                             }
                   4721:                             my @statuses;
                   4722:                             if ($env{'environment.inststatus'}) {
                   4723:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4724:                             }
                   4725:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4726:                             if (ref($accessref) eq 'HASH') {
                   4727:                                 %access_in_dom = %{$accessref};
                   4728:                             }
                   4729:                             foreach my $role (@{$roles_by_num}) {
                   4730:                                 my ($curraccess,@okstatus,@personnel);
                   4731:                                 if ($setincrs{$role}) {
                   4732:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4733:                                     if ($curraccess eq 'status') {
                   4734:                                         @okstatus = split(/\&/,$rest);
                   4735:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4736:                                         @personnel = split(/\&/,$rest);
                   4737:                                     }
                   4738:                                 } else {
                   4739:                                     $curraccess = $access_in_dom{$role};
                   4740:                                     if (ref($accessinfo) eq 'HASH') {
                   4741:                                         if ($curraccess eq 'status') {
                   4742:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4743:                                                 @okstatus = @{$accessinfo->{$role}};
                   4744:                                             }
                   4745:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4746:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4747:                                                 @personnel = @{$accessinfo->{$role}};
                   4748:                                             }
                   4749:                                         }
                   4750:                                     }
                   4751:                                 }
                   4752:                                 if ($curraccess eq 'none') {
                   4753:                                     next;
                   4754:                                 } elsif ($curraccess eq 'all') {
                   4755:                                     push(@possroles,$role);
1.1172.2.90  raeburn  4756:                                 } elsif ($curraccess eq 'dh') {
                   4757:                                     if (grep(/^dh$/,@liveroles)) {
                   4758:                                         push(@possroles,$role);
                   4759:                                     } else {
                   4760:                                         next;
                   4761:                                     }
                   4762:                                 } elsif ($curraccess eq 'da') {
                   4763:                                     if (grep(/^da$/,@liveroles)) {
                   4764:                                         push(@possroles,$role);
                   4765:                                     } else {
                   4766:                                         next;
                   4767:                                     }
1.1172.2.89  raeburn  4768:                                 } elsif ($curraccess eq 'status') {
                   4769:                                     if (@okstatus) {
                   4770:                                         if (!@statuses) {
                   4771:                                             if (grep(/^default$/,@okstatus)) {
                   4772:                                                 push(@possroles,$role);
                   4773:                                             }
                   4774:                                         } else {
                   4775:                                             foreach my $status (@okstatus) {
                   4776:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4777:                                                     push(@possroles,$role);
                   4778:                                                     last;
                   4779:                                                 }
                   4780:                                             }
                   4781:                                         }
                   4782:                                     }
                   4783:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4784:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4785:                                         if ($curraccess eq 'exc') {
                   4786:                                             push(@possroles,$role);
                   4787:                                         }
                   4788:                                     } elsif ($curraccess eq 'inc') {
                   4789:                                         push(@possroles,$role);
                   4790:                                     }
                   4791:                                 }
                   4792:                             }
                   4793:                         }
                   4794:                     }
                   4795:                 }
                   4796:             }
                   4797:         }
                   4798:     }
                   4799:     unless (ref($description) eq 'HASH') {
                   4800:         if (ref($roles_by_num) eq 'ARRAY') {
                   4801:             my %desc;
                   4802:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4803:             $description = \%desc;
                   4804:         } else {
                   4805:             $description = {};
                   4806:         }
                   4807:     }
                   4808:     return (\@possroles,$description);
                   4809: }
                   4810: 
1.399     www      4811: # ----------------------------------------------------- Frontpage Announcements
                   4812: #
                   4813: #
                   4814: 
                   4815: sub postannounce {
                   4816:     my ($server,$text)=@_;
1.844     albertel 4817:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4818:     unless ($text=~/\w/) { $text=''; }
                   4819:     return &reply('setannounce:'.&escape($text),$server);
                   4820: }
                   4821: 
                   4822: sub getannounce {
1.448     albertel 4823: 
1.1172.2.93.4  7(raebur 4824:7):     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4825: 	my $announcement='';
1.800     albertel 4826: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4827: 	close($fh);
1.399     www      4828: 	if ($announcement=~/\w/) { 
                   4829: 	    return 
                   4830:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4831:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4832: 	} else {
                   4833: 	    return '';
                   4834: 	}
                   4835:     } else {
                   4836: 	return '';
                   4837:     }
1.351     www      4838: }
1.353     www      4839: 
                   4840: # ---------------------------------------------------------- Course ID routines
                   4841: # Deal with domain's nohist_courseid.db files
                   4842: #
                   4843: 
                   4844: sub courseidput {
1.921     raeburn  4845:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4846:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4847:     my $outcome;
                   4848:     if ($caller eq 'timeonly') {
                   4849:         my $cids = '';
                   4850:         foreach my $item (keys(%$storehash)) {
                   4851:             $cids.=&escape($item).'&';
                   4852:         }
                   4853:         $cids=~s/\&$//;
                   4854:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4855:                           $coursehome);       
                   4856:     } else {
                   4857:         my $items = '';
                   4858:         foreach my $item (keys(%$storehash)) {
                   4859:             $items.= &escape($item).'='.
                   4860:                      &freeze_escape($$storehash{$item}).'&';
                   4861:         }
                   4862:         $items=~s/\&$//;
                   4863:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4864:                           $coursehome);
1.918     raeburn  4865:     }
                   4866:     if ($outcome eq 'unknown_cmd') {
                   4867:         my $what;
                   4868:         foreach my $cid (keys(%$storehash)) {
                   4869:             $what .= &escape($cid).'=';
1.921     raeburn  4870:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4871:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4872:             }
                   4873:             $what =~ s/\:$/&/;
                   4874:         }
                   4875:         $what =~ s/\&$//;  
                   4876:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4877:     } else {
                   4878:         return $outcome;
                   4879:     }
1.353     www      4880: }
                   4881: 
                   4882: sub courseiddump {
1.921     raeburn  4883:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4884:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4885:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4886:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4887:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4888:     my $as_hash = 1;
                   4889:     my %returnhash;
                   4890:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4891:     my %libserv = &all_library();
                   4892:     foreach my $tryserver (keys(%libserv)) {
                   4893:         if ( (  $hostidflag == 1 
                   4894: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4895: 	     || (!defined($hostidflag)) ) {
                   4896: 
1.918     raeburn  4897: 	    if (($domfilter eq '') ||
                   4898: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4899:                 my $rep;
                   4900:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4901:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4902:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4903:                                 &escape($descfilter), &escape($instcodefilter),
                   4904:                                 &escape($ownerfilter), &escape($coursefilter),
                   4905:                                 &escape($typefilter), &escape($regexp_ok),
                   4906:                                 $as_hash, &escape($selfenrollonly),
                   4907:                                 &escape($catfilter), $showhidden, $caller,
                   4908:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4909:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4910:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4911:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4912:                 } else {
                   4913:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4914:                              $sincefilter.':'.&escape($descfilter).':'.
                   4915:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4916:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4917:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4918:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4919:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4920:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4921:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4922:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4923:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4924:                 }
                   4925: 
1.918     raeburn  4926:                 my @pairs=split(/\&/,$rep);
                   4927:                 foreach my $item (@pairs) {
                   4928:                     my ($key,$value)=split(/\=/,$item,2);
                   4929:                     $key = &unescape($key);
                   4930:                     next if ($key =~ /^error: 2 /);
                   4931:                     my $result = &thaw_unescape($value);
                   4932:                     if (ref($result) eq 'HASH') {
                   4933:                         $returnhash{$key}=$result;
                   4934:                     } else {
1.921     raeburn  4935:                         my @responses = split(/:/,$value);
                   4936:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4937:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4938:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4939:                         }
1.1008    raeburn  4940:                     }
1.353     www      4941:                 }
                   4942:             }
                   4943:         }
                   4944:     }
                   4945:     return %returnhash;
                   4946: }
                   4947: 
1.1055    raeburn  4948: sub courselastaccess {
                   4949:     my ($cdom,$cnum,$hostidref) = @_;
                   4950:     my %returnhash;
                   4951:     if ($cdom && $cnum) {
                   4952:         my $chome = &homeserver($cnum,$cdom);
                   4953:         if ($chome ne 'no_host') {
                   4954:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4955:             &extract_lastaccess(\%returnhash,$rep);
                   4956:         }
                   4957:     } else {
                   4958:         if (!$cdom) { $cdom=''; }
                   4959:         my %libserv = &all_library();
                   4960:         foreach my $tryserver (keys(%libserv)) {
                   4961:             if (ref($hostidref) eq 'ARRAY') {
                   4962:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4963:             } 
                   4964:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4965:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4966:                 &extract_lastaccess(\%returnhash,$rep);
                   4967:             }
                   4968:         }
                   4969:     }
                   4970:     return %returnhash;
                   4971: }
                   4972: 
                   4973: sub extract_lastaccess {
                   4974:     my ($returnhash,$rep) = @_;
                   4975:     if (ref($returnhash) eq 'HASH') {
                   4976:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4977:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4978:                  $rep eq '') {
                   4979:             my @pairs=split(/\&/,$rep);
                   4980:             foreach my $item (@pairs) {
                   4981:                 my ($key,$value)=split(/\=/,$item,2);
                   4982:                 $key = &unescape($key);
                   4983:                 next if ($key =~ /^error: 2 /);
                   4984:                 $returnhash->{$key} = &thaw_unescape($value);
                   4985:             }
                   4986:         }
                   4987:     }
                   4988:     return;
                   4989: }
                   4990: 
1.658     raeburn  4991: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4992: 
                   4993: sub dcmailput {
1.685     raeburn  4994:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4995:     my $status = &Apache::lonnet::critical(
1.740     www      4996:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4997:        &escape($message),$server);
1.662     raeburn  4998:     return $status;
                   4999: }
                   5000: 
1.658     raeburn  5001: sub dcmaildump {
                   5002:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5003:     my %returnhash=();
1.846     albertel 5004: 
                   5005:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5006:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5007:                                                          &escape($enddate).':';
                   5008: 	my @esc_senders=map { &escape($_)} @$senders;
                   5009: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5010: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5011:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5012:             if (($key) && ($value)) {
                   5013:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5014:             }
                   5015:         }
                   5016:     }
                   5017:     return %returnhash;
                   5018: }
1.662     raeburn  5019: # ---------------------------------------------------------- Domain roles
                   5020: 
                   5021: sub get_domain_roles {
                   5022:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5023:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5024:         $startdate = '.';
                   5025:     }
1.1018    raeburn  5026:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5027:         $enddate = '.';
                   5028:     }
1.922     raeburn  5029:     my $rolelist;
                   5030:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5031:         $rolelist = join('&',@{$roles});
1.922     raeburn  5032:     }
1.662     raeburn  5033:     my %personnel = ();
1.841     albertel 5034: 
                   5035:     my %servers = &get_servers($dom,'library');
                   5036:     foreach my $tryserver (keys(%servers)) {
                   5037: 	%{$personnel{$tryserver}}=();
                   5038: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5039: 					    &escape($startdate).':'.
                   5040: 					    &escape($enddate).':'.
                   5041: 					    &escape($rolelist), $tryserver))) {
                   5042: 	    my ($key,$value) = split(/\=/,$line,2);
                   5043: 	    if (($key) && ($value)) {
                   5044: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5045: 	    }
                   5046: 	}
1.662     raeburn  5047:     }
                   5048:     return %personnel;
                   5049: }
1.658     raeburn  5050: 
1.1172.2.89  raeburn  5051: sub get_active_domroles {
                   5052:     my ($dom,$roles) = @_;
                   5053:     return () unless (ref($roles) eq 'ARRAY');
                   5054:     my $now = time;
                   5055:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5056:     my %domroles;
                   5057:     foreach my $server (keys(%dompersonnel)) {
                   5058:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5059:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5060:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5061:         }
                   5062:     }
                   5063:     return %domroles;
                   5064: }
                   5065: 
1.1057    www      5066: # ----------------------------------------------------------- Interval timing 
1.149     www      5067: 
1.1153    www      5068: {
                   5069: # Caches needed for speedup of navmaps
                   5070: # We don't want to cache this for very long at all (5 seconds at most)
                   5071: # 
                   5072: # The user for whom we cache
                   5073: my $cachedkey='';
                   5074: # The cached times for this user
                   5075: my %cachedtimes=();
                   5076: # When this was last done
1.1172.2.66  raeburn  5077: my $cachedtime='';
1.1153    www      5078: 
                   5079: sub load_all_first_access {
1.1172.2.93.4  1(raebur 5080:7):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5081:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.93.4  1(raebur 5082:7):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5083:7):         (!$ignorecache)) {
1.1154    raeburn  5084:         return;
                   5085:     }
                   5086:     $cachedtime=time;
                   5087:     $cachedkey=$uname.':'.$udom;
                   5088:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5089: }
                   5090: 
1.504     albertel 5091: sub get_first_access {
1.1172.2.93.4  1(raebur 5092:7):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5093:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5094:     if ($argsymb) { $symb=$argsymb; }
                   5095:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5096:     if ($argmap) { $map = $argmap; }
1.926     albertel 5097:     if ($type eq 'course') {
                   5098: 	$res='course';
                   5099:     } elsif ($type eq 'map') {
1.588     albertel 5100: 	$res=&symbread($map);
                   5101:     } else {
                   5102: 	$res=$symb;
                   5103:     }
1.1172.2.93.4  1(raebur 5104:7):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5105:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5106: }
                   5107: 
                   5108: sub set_first_access {
1.1162    raeburn  5109:     my ($type,$interval)=@_;
1.790     albertel 5110:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5111:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5112:     if ($type eq 'course') {
                   5113: 	$res='course';
                   5114:     } elsif ($type eq 'map') {
1.588     albertel 5115: 	$res=&symbread($map);
                   5116:     } else {
                   5117: 	$res=$symb;
                   5118:     }
1.1153    www      5119:     $cachedkey='';
1.1162    raeburn  5120:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 5121:     if (!$firstaccess) {
1.1162    raeburn  5122:         my $start = time;
                   5123: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5124:                           $udom,$uname);
                   5125:         if ($putres eq 'ok') {
                   5126:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5127:                  $udom,$uname); 
                   5128:             &appenv(
                   5129:                      {
                   5130:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5131:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5132:                      }
                   5133:                   );
                   5134:         }
                   5135:         return $putres;
1.505     albertel 5136:     }
                   5137:     return 'already_set';
1.504     albertel 5138: }
1.1153    www      5139: }
1.1172.2.32  raeburn  5140: 
                   5141: sub checkout {
                   5142:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5143:     my $now=time;
                   5144:     my $lonhost=$perlvar{'lonHostID'};
                   5145:     my $infostr=&escape(
                   5146:                  'CHECKOUTTOKEN&'.
                   5147:                  $tuname.'&'.
                   5148:                  $tudom.'&'.
                   5149:                  $tcrsid.'&'.
                   5150:                  $symb.'&'.
                   5151:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5152:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5153:     if ($token=~/^error\:/) {
                   5154:         &logthis("<font color=\"blue\">WARNING: ".
                   5155:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5156:                  "</font>");
                   5157:         return '';
                   5158:     }
                   5159: 
                   5160:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5161:     $token=~tr/a-z/A-Z/;
                   5162: 
                   5163:     my %infohash=('resource.0.outtoken' => $token,
                   5164:                   'resource.0.checkouttime' => $now,
                   5165:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5166: 
                   5167:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5168:        return '';
                   5169:     } else {
                   5170:         &logthis("<font color=\"blue\">WARNING: ".
                   5171:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5172:                  "</font>");
                   5173:     }
                   5174: 
                   5175:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5176:                          &escape('Checkout '.$infostr.' - '.
                   5177:                                                  $token)) ne 'ok') {
                   5178:         return '';
                   5179:     } else {
                   5180:         &logthis("<font color=\"blue\">WARNING: ".
                   5181:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5182:                  "</font>");
                   5183:     }
                   5184:     return $token;
                   5185: }
                   5186: 
                   5187: # ------------------------------------------------------------ Check in an item
                   5188: 
                   5189: sub checkin {
                   5190:     my $token=shift;
                   5191:     my $now=time;
                   5192:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5193:     $lonhost=~tr/A-Z/a-z/;
                   5194:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5195:     $dtoken=~s/\W/\_/g;
                   5196:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5197:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5198: 
                   5199:     unless (($tuname) && ($tudom)) {
                   5200:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5201:         return '';
                   5202:     }
                   5203: 
                   5204:     unless (&allowed('mgr',$tcrsid)) {
                   5205:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5206:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5207:         return '';
                   5208:     }
                   5209: 
                   5210:     my %infohash=('resource.0.intoken' => $token,
                   5211:                   'resource.0.checkintime' => $now,
                   5212:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5213: 
                   5214:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5215:        return '';
                   5216:     }
                   5217: 
                   5218:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5219:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5220:         return '';
                   5221:     }
                   5222: 
                   5223:     return ($symb,$tuname,$tudom,$tcrsid);
                   5224: }
                   5225: 
1.110     www      5226: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5227: 
                   5228: sub expirespread {
                   5229:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5230:     my $cid=$env{'request.course.id'}; 
1.110     www      5231:     if ($cid) {
                   5232:        my $now=time;
                   5233:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5234:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5235:                             $env{'course.'.$cid.'.num'}.
1.110     www      5236: 	        	    ':nohist_expirationdates:'.
                   5237:                             &escape($key).'='.$now,
1.620     albertel 5238:                             $env{'course.'.$cid.'.home'})
1.110     www      5239:     }
                   5240:     return 'ok';
1.14      www      5241: }
                   5242: 
1.109     www      5243: # ----------------------------------------------------- Devalidate Spreadsheets
                   5244: 
                   5245: sub devalidate {
1.325     www      5246:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5247:     my $cid=$env{'request.course.id'}; 
1.109     www      5248:     if ($cid) {
1.391     matthew  5249:         # delete the stored spreadsheets for
                   5250:         # - the student level sheet of this user in course's homespace
                   5251:         # - the assessment level sheet for this resource 
                   5252:         #   for this user in user's homespace
1.553     albertel 5253: 	# - current conditional state info
1.325     www      5254: 	my $key=$uname.':'.$udom.':';
1.109     www      5255:         my $status=
1.299     matthew  5256: 	    &del('nohist_calculatedsheets',
1.391     matthew  5257: 		 [$key.'studentcalc:'],
1.620     albertel 5258: 		 $env{'course.'.$cid.'.domain'},
                   5259: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5260: 		.' '.
                   5261: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5262: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5263:         unless ($status eq 'ok ok') {
                   5264:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5265:                     $uname.' at '.$udom.' for '.
1.109     www      5266: 		    $symb.': '.$status);
1.133     albertel 5267:         }
1.553     albertel 5268: 	&delenv('user.state.'.$cid);
1.109     www      5269:     }
                   5270: }
                   5271: 
1.265     albertel 5272: sub get_scalar {
                   5273:     my ($string,$end) = @_;
                   5274:     my $value;
                   5275:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5276: 	$value = $1;
                   5277:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5278: 	$value = $1;
                   5279:     }
                   5280:     return &unescape($value);
                   5281: }
                   5282: 
                   5283: sub array2str {
                   5284:   my (@array) = @_;
                   5285:   my $result=&arrayref2str(\@array);
                   5286:   $result=~s/^__ARRAY_REF__//;
                   5287:   $result=~s/__END_ARRAY_REF__$//;
                   5288:   return $result;
                   5289: }
                   5290: 
1.204     albertel 5291: sub arrayref2str {
                   5292:   my ($arrayref) = @_;
1.265     albertel 5293:   my $result='__ARRAY_REF__';
1.204     albertel 5294:   foreach my $elem (@$arrayref) {
1.265     albertel 5295:     if(ref($elem) eq 'ARRAY') {
                   5296:       $result.=&arrayref2str($elem).'&';
                   5297:     } elsif(ref($elem) eq 'HASH') {
                   5298:       $result.=&hashref2str($elem).'&';
                   5299:     } elsif(ref($elem)) {
                   5300:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5301:     } else {
                   5302:       $result.=&escape($elem).'&';
                   5303:     }
                   5304:   }
                   5305:   $result=~s/\&$//;
1.265     albertel 5306:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5307:   return $result;
                   5308: }
                   5309: 
1.168     albertel 5310: sub hash2str {
1.204     albertel 5311:   my (%hash) = @_;
                   5312:   my $result=&hashref2str(\%hash);
1.265     albertel 5313:   $result=~s/^__HASH_REF__//;
                   5314:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5315:   return $result;
                   5316: }
                   5317: 
                   5318: sub hashref2str {
                   5319:   my ($hashref)=@_;
1.265     albertel 5320:   my $result='__HASH_REF__';
1.800     albertel 5321:   foreach my $key (sort(keys(%$hashref))) {
                   5322:     if (ref($key) eq 'ARRAY') {
                   5323:       $result.=&arrayref2str($key).'=';
                   5324:     } elsif (ref($key) eq 'HASH') {
                   5325:       $result.=&hashref2str($key).'=';
                   5326:     } elsif (ref($key)) {
1.265     albertel 5327:       $result.='=';
1.800     albertel 5328:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5329:     } else {
1.1132    raeburn  5330: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5331:     }
                   5332: 
1.800     albertel 5333:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5334:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5335:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5336:       $result.=&hashref2str($hashref->{$key}).'&';
                   5337:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5338:        $result.='&';
1.800     albertel 5339:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5340:     } else {
1.800     albertel 5341:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5342:     }
                   5343:   }
1.168     albertel 5344:   $result=~s/\&$//;
1.265     albertel 5345:   $result .= '__END_HASH_REF__';
1.168     albertel 5346:   return $result;
                   5347: }
                   5348: 
                   5349: sub str2hash {
1.265     albertel 5350:     my ($string)=@_;
                   5351:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5352:     return %$hash;
                   5353: }
                   5354: 
                   5355: sub str2hashref {
1.168     albertel 5356:   my ($string) = @_;
1.265     albertel 5357: 
                   5358:   my %hash;
                   5359: 
                   5360:   if($string !~ /^__HASH_REF__/) {
                   5361:       if (! ($string eq '' || !defined($string))) {
                   5362: 	  $hash{'error'}='Not hash reference';
                   5363:       }
                   5364:       return (\%hash, $string);
                   5365:   }
                   5366: 
                   5367:   $string =~ s/^__HASH_REF__//;
                   5368: 
                   5369:   while($string !~ /^__END_HASH_REF__/) {
                   5370:       #key
                   5371:       my $key='';
                   5372:       if($string =~ /^__HASH_REF__/) {
                   5373:           ($key, $string)=&str2hashref($string);
                   5374:           if(defined($key->{'error'})) {
                   5375:               $hash{'error'}='Bad data';
                   5376:               return (\%hash, $string);
                   5377:           }
                   5378:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5379:           ($key, $string)=&str2arrayref($string);
                   5380:           if($key->[0] eq 'Array reference error') {
                   5381:               $hash{'error'}='Bad data';
                   5382:               return (\%hash, $string);
                   5383:           }
                   5384:       } else {
                   5385:           $string =~ s/^(.*?)=//;
1.267     albertel 5386: 	  $key=&unescape($1);
1.265     albertel 5387:       }
                   5388:       $string =~ s/^=//;
                   5389: 
                   5390:       #value
                   5391:       my $value='';
                   5392:       if($string =~ /^__HASH_REF__/) {
                   5393:           ($value, $string)=&str2hashref($string);
                   5394:           if(defined($value->{'error'})) {
                   5395:               $hash{'error'}='Bad data';
                   5396:               return (\%hash, $string);
                   5397:           }
                   5398:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5399:           ($value, $string)=&str2arrayref($string);
                   5400:           if($value->[0] eq 'Array reference error') {
                   5401:               $hash{'error'}='Bad data';
                   5402:               return (\%hash, $string);
                   5403:           }
                   5404:       } else {
                   5405: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5406:       }
                   5407:       $string =~ s/^&//;
                   5408: 
                   5409:       $hash{$key}=$value;
1.204     albertel 5410:   }
1.265     albertel 5411: 
                   5412:   $string =~ s/^__END_HASH_REF__//;
                   5413: 
                   5414:   return (\%hash, $string);
1.204     albertel 5415: }
                   5416: 
                   5417: sub str2array {
1.265     albertel 5418:     my ($string)=@_;
                   5419:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5420:     return @$array;
                   5421: }
                   5422: 
                   5423: sub str2arrayref {
1.204     albertel 5424:   my ($string) = @_;
1.265     albertel 5425:   my @array;
                   5426: 
                   5427:   if($string !~ /^__ARRAY_REF__/) {
                   5428:       if (! ($string eq '' || !defined($string))) {
                   5429: 	  $array[0]='Array reference error';
                   5430:       }
                   5431:       return (\@array, $string);
                   5432:   }
                   5433: 
                   5434:   $string =~ s/^__ARRAY_REF__//;
                   5435: 
                   5436:   while($string !~ /^__END_ARRAY_REF__/) {
                   5437:       my $value='';
                   5438:       if($string =~ /^__HASH_REF__/) {
                   5439:           ($value, $string)=&str2hashref($string);
                   5440:           if(defined($value->{'error'})) {
                   5441:               $array[0] ='Array reference error';
                   5442:               return (\@array, $string);
                   5443:           }
                   5444:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5445:           ($value, $string)=&str2arrayref($string);
                   5446:           if($value->[0] eq 'Array reference error') {
                   5447:               $array[0] ='Array reference error';
                   5448:               return (\@array, $string);
                   5449:           }
                   5450:       } else {
                   5451: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5452:       }
                   5453:       $string =~ s/^&//;
                   5454: 
                   5455:       push(@array, $value);
1.191     harris41 5456:   }
1.265     albertel 5457: 
                   5458:   $string =~ s/^__END_ARRAY_REF__//;
                   5459: 
                   5460:   return (\@array, $string);
1.168     albertel 5461: }
                   5462: 
1.167     albertel 5463: # -------------------------------------------------------------------Temp Store
                   5464: 
1.168     albertel 5465: sub tmpreset {
                   5466:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5467:   if (!$symb) {
                   5468:     $symb=&symbread();
1.620     albertel 5469:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5470:   }
                   5471:   $symb=escape($symb);
                   5472: 
1.620     albertel 5473:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5474:   $namespace=~s/\//\_/g;
                   5475:   $namespace=~s/\W//g;
                   5476: 
1.620     albertel 5477:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5478:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5479:   if ($domain eq 'public' && $stuname eq 'public') {
                   5480:       $stuname=$ENV{'REMOTE_ADDR'};
                   5481:   }
1.1117    foxr     5482:   my $path=LONCAPA::tempdir();
1.168     albertel 5483:   my %hash;
                   5484:   if (tie(%hash,'GDBM_File',
                   5485: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5486: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5487:     foreach my $key (keys(%hash)) {
1.180     albertel 5488:       if ($key=~ /:$symb/) {
1.168     albertel 5489: 	delete($hash{$key});
                   5490:       }
                   5491:     }
                   5492:   }
                   5493: }
                   5494: 
1.167     albertel 5495: sub tmpstore {
1.168     albertel 5496:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5497: 
                   5498:   if (!$symb) {
                   5499:     $symb=&symbread();
1.620     albertel 5500:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5501:   }
                   5502:   $symb=escape($symb);
                   5503: 
                   5504:   if (!$namespace) {
                   5505:     # I don't think we would ever want to store this for a course.
                   5506:     # it seems this will only be used if we don't have a course.
1.620     albertel 5507:     #$namespace=$env{'request.course.id'};
1.168     albertel 5508:     #if (!$namespace) {
1.620     albertel 5509:       $namespace=$env{'request.state'};
1.168     albertel 5510:     #}
                   5511:   }
                   5512:   $namespace=~s/\//\_/g;
                   5513:   $namespace=~s/\W//g;
1.620     albertel 5514:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5515:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5516:   if ($domain eq 'public' && $stuname eq 'public') {
                   5517:       $stuname=$ENV{'REMOTE_ADDR'};
                   5518:   }
1.168     albertel 5519:   my $now=time;
                   5520:   my %hash;
1.1117    foxr     5521:   my $path=LONCAPA::tempdir();
1.168     albertel 5522:   if (tie(%hash,'GDBM_File',
                   5523: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5524: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5525:     $hash{"version:$symb"}++;
                   5526:     my $version=$hash{"version:$symb"};
                   5527:     my $allkeys=''; 
                   5528:     foreach my $key (keys(%$storehash)) {
                   5529:       $allkeys.=$key.':';
1.591     albertel 5530:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5531:     }
                   5532:     $hash{"$version:$symb:timestamp"}=$now;
                   5533:     $allkeys.='timestamp';
                   5534:     $hash{"$version:keys:$symb"}=$allkeys;
                   5535:     if (untie(%hash)) {
                   5536:       return 'ok';
                   5537:     } else {
                   5538:       return "error:$!";
                   5539:     }
                   5540:   } else {
                   5541:     return "error:$!";
                   5542:   }
                   5543: }
1.167     albertel 5544: 
1.168     albertel 5545: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5546: 
1.168     albertel 5547: sub tmprestore {
                   5548:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5549: 
1.168     albertel 5550:   if (!$symb) {
                   5551:     $symb=&symbread();
1.620     albertel 5552:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5553:   }
                   5554:   $symb=escape($symb);
                   5555: 
1.620     albertel 5556:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5557: 
1.620     albertel 5558:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5559:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5560:   if ($domain eq 'public' && $stuname eq 'public') {
                   5561:       $stuname=$ENV{'REMOTE_ADDR'};
                   5562:   }
1.168     albertel 5563:   my %returnhash;
                   5564:   $namespace=~s/\//\_/g;
                   5565:   $namespace=~s/\W//g;
                   5566:   my %hash;
1.1117    foxr     5567:   my $path=LONCAPA::tempdir();
1.168     albertel 5568:   if (tie(%hash,'GDBM_File',
                   5569: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5570: 	  &GDBM_READER(),0640)) {
1.168     albertel 5571:     my $version=$hash{"version:$symb"};
                   5572:     $returnhash{'version'}=$version;
                   5573:     my $scope;
                   5574:     for ($scope=1;$scope<=$version;$scope++) {
                   5575:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5576:       my @keys=split(/:/,$vkeys);
                   5577:       my $key;
                   5578:       $returnhash{"$scope:keys"}=$vkeys;
                   5579:       foreach $key (@keys) {
1.591     albertel 5580: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5581: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5582:       }
                   5583:     }
1.168     albertel 5584:     if (!(untie(%hash))) {
                   5585:       return "error:$!";
                   5586:     }
                   5587:   } else {
                   5588:     return "error:$!";
                   5589:   }
                   5590:   return %returnhash;
1.167     albertel 5591: }
                   5592: 
1.9       www      5593: # ----------------------------------------------------------------------- Store
                   5594: 
                   5595: sub store {
1.1172.2.64  raeburn  5596:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5597:     my $home='';
                   5598: 
1.168     albertel 5599:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5600: 
1.213     www      5601:     $symb=&symbclean($symb);
1.122     albertel 5602:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5603: 
1.620     albertel 5604:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5605:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5606: 
                   5607:     &devalidate($symb,$stuname,$domain);
1.109     www      5608: 
                   5609:     $symb=escape($symb);
1.187     www      5610:     if (!$namespace) { 
1.620     albertel 5611:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5612:           return ''; 
                   5613:        } 
                   5614:     }
1.620     albertel 5615:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5616: 
                   5617:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5618:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5619: 
1.12      www      5620:     my $namevalue='';
1.800     albertel 5621:     foreach my $key (keys(%$storehash)) {
                   5622:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5623:     }
1.12      www      5624:     $namevalue=~s/\&$//;
1.187     www      5625:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5626:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5627: }
                   5628: 
1.47      www      5629: # -------------------------------------------------------------- Critical Store
                   5630: 
                   5631: sub cstore {
1.1172.2.64  raeburn  5632:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5633:     my $home='';
                   5634: 
1.168     albertel 5635:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5636: 
1.213     www      5637:     $symb=&symbclean($symb);
1.122     albertel 5638:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5639: 
1.620     albertel 5640:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5641:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5642: 
                   5643:     &devalidate($symb,$stuname,$domain);
1.109     www      5644: 
                   5645:     $symb=escape($symb);
1.187     www      5646:     if (!$namespace) { 
1.620     albertel 5647:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5648:           return ''; 
                   5649:        } 
                   5650:     }
1.620     albertel 5651:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5652: 
                   5653:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5654:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5655: 
1.47      www      5656:     my $namevalue='';
1.800     albertel 5657:     foreach my $key (keys(%$storehash)) {
                   5658:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5659:     }
1.47      www      5660:     $namevalue=~s/\&$//;
1.187     www      5661:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5662:     return critical
1.1172.2.64  raeburn  5663:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5664: }
                   5665: 
1.9       www      5666: # --------------------------------------------------------------------- Restore
                   5667: 
                   5668: sub restore {
1.124     www      5669:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5670:     my $home='';
                   5671: 
1.168     albertel 5672:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5673: 
1.122     albertel 5674:     if (!$symb) {
1.1172.2.26  raeburn  5675:         return if ($namespace eq 'courserequests');
                   5676:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5677:     } else {
1.1172.2.26  raeburn  5678:         unless ($namespace eq 'courserequests') {
                   5679:             $symb=&escape(&symbclean($symb));
                   5680:         }
1.122     albertel 5681:     }
1.188     www      5682:     if (!$namespace) { 
1.620     albertel 5683:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5684:           return ''; 
                   5685:        } 
                   5686:     }
1.620     albertel 5687:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5688:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5689:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5690:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5691: 
1.12      www      5692:     my %returnhash=();
1.800     albertel 5693:     foreach my $line (split(/\&/,$answer)) {
                   5694: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5695:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5696:     }
1.75      www      5697:     my $version;
                   5698:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5699:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5700:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5701:        }
1.75      www      5702:     }
1.13      www      5703:     return %returnhash;
1.34      www      5704: }
                   5705: 
                   5706: # ---------------------------------------------------------- Course Description
1.1118    foxr     5707: #
                   5708: #  
1.34      www      5709: 
                   5710: sub coursedescription {
1.731     albertel 5711:     my ($courseid,$args)=@_;
1.34      www      5712:     $courseid=~s/^\///;
1.49      www      5713:     $courseid=~s/\_/\//g;
1.34      www      5714:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5715:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5716:     my $normalid=$cdomain.'_'.$cnum;
                   5717:     # need to always cache even if we get errors otherwise we keep 
                   5718:     # trying and trying and trying to get the course description.
                   5719:     my %envhash=();
                   5720:     my %returnhash=();
1.731     albertel 5721:     
                   5722:     my $expiretime=600;
                   5723:     if ($env{'request.course.id'} eq $normalid) {
                   5724: 	$expiretime=120;
                   5725:     }
                   5726: 
                   5727:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5728:     if (!$args->{'freshen_cache'}
                   5729: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5730: 	foreach my $key (keys(%env)) {
                   5731: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5732: 	    my ($setting) = $1;
                   5733: 	    $returnhash{$setting} = $env{$key};
                   5734: 	}
                   5735: 	return %returnhash;
                   5736:     }
                   5737: 
1.1118    foxr     5738:     # get the data again
                   5739: 
1.731     albertel 5740:     if (!$args->{'one_time'}) {
                   5741: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5742:     }
1.811     albertel 5743: 
1.34      www      5744:     if ($chome ne 'no_host') {
1.302     albertel 5745:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5746:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5747: 	   my $username = $env{'user.name'}; # Defult username
                   5748: 	   if(defined $args->{'user'}) {
                   5749: 	       $username = $args->{'user'};
                   5750: 	   }
1.129     albertel 5751:            $returnhash{'home'}= $chome;
                   5752: 	   $returnhash{'domain'} = $cdomain;
                   5753: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5754:            if (!defined($returnhash{'type'})) {
                   5755:                $returnhash{'type'} = 'Course';
                   5756:            }
1.130     albertel 5757:            while (my ($name,$value) = each %returnhash) {
1.53      www      5758:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5759:            }
1.270     www      5760:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5761:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5762: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5763:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5764:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5765:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5766:        }
                   5767:     }
1.731     albertel 5768:     if (!$args->{'one_time'}) {
1.949     raeburn  5769: 	&appenv(\%envhash);
1.731     albertel 5770:     }
1.302     albertel 5771:     return %returnhash;
1.461     www      5772: }
                   5773: 
1.1080    raeburn  5774: sub update_released_required {
                   5775:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5776:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5777:         $cid = $env{'request.course.id'};
                   5778:         $cdom = $env{'course.'.$cid.'.domain'};
                   5779:         $cnum = $env{'course.'.$cid.'.num'};
                   5780:         $chome = $env{'course.'.$cid.'.home'};
                   5781:     }
                   5782:     if ($needsrelease) {
                   5783:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5784:         my $needsupdate;
                   5785:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5786:             $needsupdate = 1;
                   5787:         } else {
                   5788:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5789:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5790:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5791:                 $needsupdate = 1;
                   5792:             }
                   5793:         }
                   5794:         if ($needsupdate) {
                   5795:             my %needshash = (
                   5796:                              'internal.releaserequired' => $needsrelease,
                   5797:                             );
                   5798:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5799:             if ($putresult eq 'ok') {
                   5800:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5801:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5802:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5803:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5804:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5805:                 }
                   5806:             }
                   5807:         }
                   5808:     }
                   5809:     return;
                   5810: }
                   5811: 
1.461     www      5812: # -------------------------------------------------See if a user is privileged
                   5813: 
                   5814: sub privileged {
1.1172.2.23  raeburn  5815:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5816:     my $now = time;
1.1172.2.23  raeburn  5817:     my $roles;
                   5818:     if (ref($possroles) eq 'ARRAY') {
                   5819:         $roles = $possroles;
                   5820:     } else {
                   5821:         $roles = ['dc','su'];
                   5822:     }
                   5823:     if (ref($possdomains) eq 'ARRAY') {
                   5824:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5825:         foreach my $dom (@{$possdomains}) {
                   5826:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5827:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5828:                 foreach my $role (@{$roles}) {
                   5829:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5830:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5831:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5832:                             return 1 unless (($end && $end < $now) ||
                   5833:                                              ($start && $start > $now));
                   5834:                         }
                   5835:                     }
                   5836:                 }
                   5837:             }
                   5838:         }
                   5839:     } else {
                   5840:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5841:         my $now = time;
1.1170    droeschl 5842: 
1.1172.2.58  raeburn  5843:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5844:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5845:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5846:                 return 1 unless ($tend && $tend < $now)
                   5847:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5848:             }
1.1172.2.23  raeburn  5849:         }
                   5850:     }
1.461     www      5851:     return 0;
1.9       www      5852: }
1.1       albertel 5853: 
1.1172.2.23  raeburn  5854: sub privileged_by_domain {
                   5855:     my ($domains,$roles) = @_;
                   5856:     my %privileged = ();
                   5857:     my $cachetime = 60*60*24;
                   5858:     my $now = time;
                   5859:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5860:         return %privileged;
                   5861:     }
                   5862:     foreach my $dom (@{$domains}) {
                   5863:         next if (ref($privileged{$dom}) eq 'HASH');
                   5864:         my $needroles;
                   5865:         foreach my $role (@{$roles}) {
                   5866:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5867:             if (defined($cached)) {
                   5868:                 if (ref($result) eq 'HASH') {
                   5869:                     $privileged{$dom}{$role} = $result;
                   5870:                 }
                   5871:             } else {
                   5872:                 $needroles = 1;
                   5873:             }
                   5874:         }
                   5875:         if ($needroles) {
                   5876:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5877:             $privileged{$dom} = {};
                   5878:             foreach my $server (keys(%dompersonnel)) {
                   5879:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5880:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5881:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5882:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5883:                         next if ($end && $end < $now);
                   5884:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5885:                             $dompersonnel{$server}{$item};
                   5886:                     }
                   5887:                 }
                   5888:             }
                   5889:             if (ref($privileged{$dom}) eq 'HASH') {
                   5890:                 foreach my $role (@{$roles}) {
                   5891:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5892:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5893:                     } else {
                   5894:                         my %hash = ();
                   5895:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5896:                     }
                   5897:                 }
                   5898:             }
                   5899:         }
                   5900:     }
                   5901:     return %privileged;
                   5902: }
                   5903: 
1.103     harris41 5904: # -------------------------------------------------------- Get user privileges
1.11      www      5905: 
                   5906: sub rolesinit {
1.1169    droeschl 5907:     my ($domain, $username) = @_;
                   5908:     my %userroles = ('user.login.time' => time);
                   5909:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5910: 
                   5911:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5912:     # also, blocking can be triggered by an activating timer
                   5913:     # it's saved in the user's %env.
                   5914:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5915:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5916:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5917:         %timerintchk, %timerintenv);
                   5918: 
1.1162    raeburn  5919:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5920:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5921:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5922:     }
1.1169    droeschl 5923: 
1.1162    raeburn  5924:     foreach my $key (keys(%timerinterval)) {
                   5925:         my ($cid,$rest) = split(/\0/,$key);
                   5926:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5927:     }
1.1169    droeschl 5928: 
1.11      www      5929:     my %allroles=();
1.1162    raeburn  5930:     my %allgroups=();
1.11      www      5931: 
1.1172.2.58  raeburn  5932:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5933:         my $role = $rolesdump{$area};
                   5934:         $area =~ s/\_\w\w$//;
                   5935: 
                   5936:         my ($trole, $tend, $tstart, $group_privs);
                   5937: 
                   5938:         if ($role =~ /^cr/) {
                   5939:         # Custom role, defined by a user 
                   5940:         # e.g., user.role.cr/msu/smith/mynewrole
                   5941:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5942:                 $trole = $1;
                   5943:                 ($tend, $tstart) = split('_', $2);
                   5944:             } else {
                   5945:                 $trole = $role;
                   5946:             }
                   5947:         } elsif ($role =~ m|^gr/|) {
                   5948:         # Role of member in a group, defined within a course/community
                   5949:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5950:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5951:             next if $tstart eq '-1';
                   5952:             ($trole, $group_privs) = split(/\//, $trole);
                   5953:             $group_privs = &unescape($group_privs);
                   5954:         } else {
                   5955:         # Just a normal role, defined in roles.tab
                   5956:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5957:         }
                   5958: 
                   5959:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5960:                  $username);
                   5961:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5962: 
                   5963:         # role expired or not available yet?
                   5964:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5965:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5966: 
                   5967:         next if $area eq '' or $trole eq '';
                   5968: 
                   5969:         my $spec = "$trole.$area";
                   5970:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5971: 
                   5972:         if ($trole =~ /^cr\//) {
                   5973:         # Custom role, defined by a user
                   5974:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5975:         } elsif ($trole eq 'gr') {
                   5976:         # Role of a member in a group, defined within a course/community
                   5977:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5978:             next;
                   5979:         } else {
                   5980:         # Normal role, defined in roles.tab
                   5981:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5982:         }
                   5983: 
                   5984:         my $cid = $tdomain.'_'.$trest;
                   5985:         unless ($firstaccchk{$cid}) {
                   5986:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5987:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5988:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5989:                         $coursetimerstarts{$cid}{$item}; 
                   5990:                 }
                   5991:             }
                   5992:             $firstaccchk{$cid} = 1;
                   5993:         }
                   5994:         unless ($timerintchk{$cid}) {
                   5995:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5996:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5997:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5998:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5999:                 }
1.12      www      6000:             }
1.1169    droeschl 6001:             $timerintchk{$cid} = 1;
1.191     harris41 6002:         }
1.11      www      6003:     }
1.1169    droeschl 6004: 
1.1172.2.91  raeburn  6005:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6006:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6007:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6008:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6009: 
1.1162    raeburn  6010:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6011: }
                   6012: 
1.567     raeburn  6013: sub set_arearole {
1.1172.2.19  raeburn  6014:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6015:     unless ($nolog) {
1.567     raeburn  6016: # log the associated role with the area
1.1172.2.19  raeburn  6017:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6018:     }
1.743     albertel 6019:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6020: }
                   6021: 
                   6022: sub custom_roleprivs {
                   6023:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6024:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6025:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6026:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6027:         my ($rdummy,$roledef)=
                   6028:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6029:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6030:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6031:             if (defined($syspriv)) {
1.1043    raeburn  6032:                 if ($trest =~ /^$match_community$/) {
                   6033:                     $syspriv =~ s/bre\&S//; 
                   6034:                 }
1.567     raeburn  6035:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6036:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6037:             }
                   6038:             if ($tdomain ne '') {
                   6039:                 if (defined($dompriv)) {
                   6040:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6041:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6042:                 }
                   6043:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6044:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6045:                         my $rolename = $1;
                   6046:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6047:                     }
1.567     raeburn  6048:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6049:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6050:                 }
                   6051:             }
                   6052:         }
                   6053:     }
                   6054: }
                   6055: 
1.1172.2.89  raeburn  6056: sub course_adhocrole_privs {
                   6057:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6058:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6059:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6060:         my (%currprivs,%storeprivs);
                   6061:         foreach my $item (split(/:/,$coursepriv)) {
                   6062:             my ($priv,$restrict) = split(/\&/,$item);
                   6063:             $currprivs{$priv} = $restrict;
                   6064:         }
                   6065:         my (%possadd,%possremove,%full);
                   6066:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6067:             my ($priv,$restrict)=split(/\&/,$item);
                   6068:             $full{$priv} = $restrict;
                   6069:         }
                   6070:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6071:              next if ($item eq '');
                   6072:              my ($rule,$rest) = split(/=/,$item);
                   6073:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6074:              foreach my $priv (split(/:/,$rest)) {
                   6075:                  if ($priv ne '') {
                   6076:                      if ($rule eq 'off') {
                   6077:                          $possremove{$priv} = 1;
                   6078:                      } else {
                   6079:                          $possadd{$priv} = 1;
                   6080:                      }
                   6081:                  }
                   6082:              }
                   6083:          }
                   6084:          foreach my $priv (sort(keys(%full))) {
                   6085:              if (exists($currprivs{$priv})) {
                   6086:                  unless (exists($possremove{$priv})) {
                   6087:                      $storeprivs{$priv} = $currprivs{$priv};
                   6088:                  }
                   6089:              } elsif (exists($possadd{$priv})) {
                   6090:                  $storeprivs{$priv} = $full{$priv};
                   6091:              }
                   6092:          }
                   6093:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6094:      }
                   6095:      return $coursepriv;
                   6096: }
                   6097: 
1.678     raeburn  6098: sub group_roleprivs {
                   6099:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6100:     my $access = 1;
                   6101:     my $now = time;
                   6102:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6103:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6104:     if ($access) {
1.811     albertel 6105:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6106:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6107:     }
                   6108: }
1.567     raeburn  6109: 
                   6110: sub standard_roleprivs {
                   6111:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6112:     if (defined($pr{$trole.':s'})) {
                   6113:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6114:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6115:     }
                   6116:     if ($tdomain ne '') {
                   6117:         if (defined($pr{$trole.':d'})) {
                   6118:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6119:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6120:         }
                   6121:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6122:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6123:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6124:         }
                   6125:     }
                   6126: }
                   6127: 
                   6128: sub set_userprivs {
1.1064    raeburn  6129:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6130:     my $author=0;
                   6131:     my $adv=0;
1.1172.2.91  raeburn  6132:     my $rar=0;
1.678     raeburn  6133:     my %grouproles = ();
                   6134:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6135:         my @groupkeys; 
1.1000    raeburn  6136:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6137:             push(@groupkeys,$role);
                   6138:         }
                   6139:         if (ref($groups_roles) eq 'HASH') {
                   6140:             foreach my $key (keys(%{$groups_roles})) {
                   6141:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6142:                     push(@groupkeys,$key);
                   6143:                 }
                   6144:             }
                   6145:         }
                   6146:         if (@groupkeys > 0) {
                   6147:             foreach my $role (@groupkeys) {
                   6148:                 my ($trole,$area,$sec,$extendedarea);
                   6149:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6150:                     $trole = $1;
                   6151:                     $area = $2;
                   6152:                     $sec = $3;
                   6153:                     $extendedarea = $area.$sec;
                   6154:                     if (exists($$allgroups{$area})) {
                   6155:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6156:                             my $spec = $trole.'.'.$extendedarea;
                   6157:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6158:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6159:                         }
1.678     raeburn  6160:                     }
                   6161:                 }
                   6162:             }
                   6163:         }
                   6164:     }
1.800     albertel 6165:     foreach my $group (keys(%grouproles)) {
                   6166:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6167:     }
1.800     albertel 6168:     foreach my $role (keys(%{$allroles})) {
                   6169:         my %thesepriv;
1.941     raeburn  6170:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6171:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6172:             if ($item ne '') {
                   6173:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6174:                 if ($restrictions eq '') {
                   6175:                     $thesepriv{$privilege}='F';
                   6176:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6177:                     $thesepriv{$privilege}.=$restrictions;
                   6178:                 }
                   6179:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6180:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6181:             }
                   6182:         }
                   6183:         my $thesestr='';
1.1104    raeburn  6184:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6185: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6186: 	}
                   6187:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6188:     }
1.1172.2.91  raeburn  6189:     return ($author,$adv,$rar);
1.567     raeburn  6190: }
                   6191: 
1.994     raeburn  6192: sub role_status {
1.1104    raeburn  6193:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6194:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6195:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6196:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6197:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6198:             $$where = '/'.$two;
1.994     raeburn  6199:             $$trolecode=$$role.'.'.$$where;
                   6200:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6201:             $$tstatus='is';
1.1104    raeburn  6202:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6203:                 $$tstatus='future';
1.1034    raeburn  6204:                 if ($$tstart<$now) {
                   6205:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6206:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6207:                             my (%allroles,%allgroups,$group_privs,
                   6208:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6209:                             my %userroles = (
                   6210:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6211:                             );
1.1064    raeburn  6212:                             @rolecodes = ('cm'); 
1.1002    raeburn  6213:                             my $spec=$$role.'.'.$$where;
                   6214:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6215:                             if ($$role =~ /^cr\//) {
                   6216:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6217:                                 push(@rolecodes,'cr');
1.1002    raeburn  6218:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6219:                                 push(@rolecodes,$$role);
1.1002    raeburn  6220:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6221:                                                     $env{'user.name'});
1.1064    raeburn  6222:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6223:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6224:                                 $group_privs = &unescape($group_privs);
                   6225:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6226:                                 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  6227:                                 &get_groups_roles($tdomain,$trest,
                   6228:                                                   \%course_roles,\@rolecodes,
                   6229:                                                   \%groups_roles);
1.1002    raeburn  6230:                             } else {
1.1064    raeburn  6231:                                 push(@rolecodes,$$role);
1.1002    raeburn  6232:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6233:                             }
1.1172.2.91  raeburn  6234:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6235:                                                                    \%groups_roles);
1.1064    raeburn  6236:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6237:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6238:                         }
                   6239:                     }
1.1034    raeburn  6240:                     $$tstatus = 'is';
1.1002    raeburn  6241:                 }
1.994     raeburn  6242:             }
                   6243:             if ($$tend) {
1.1104    raeburn  6244:                 if ($$tend<$update) {
1.994     raeburn  6245:                     $$tstatus='expired';
                   6246:                 } elsif ($$tend<$now) {
                   6247:                     $$tstatus='will_not';
                   6248:                 }
                   6249:             }
                   6250:         }
                   6251:     }
                   6252: }
                   6253: 
1.1104    raeburn  6254: sub get_groups_roles {
                   6255:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6256:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6257:                   (ref($rolecodes) eq 'ARRAY') && 
                   6258:                   (ref($groups_roles) eq 'HASH')); 
                   6259:     if (keys(%{$cdom_courseroles}) > 0) {
                   6260:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6261:         if ($cdom ne '' && $cnum ne '') {
                   6262:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6263:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6264:                     my $crsrole = $1;
                   6265:                     my $crssec = $2;
                   6266:                     if ($crsrole =~ /^cr/) {
                   6267:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6268:                             push(@{$rolecodes},'cr');
                   6269:                         }
                   6270:                     } else {
                   6271:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6272:                             push(@{$rolecodes},$crsrole);
                   6273:                         }
                   6274:                     }
                   6275:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6276:                     if ($crssec ne '') {
                   6277:                         $rolekey .= "/$crssec";
                   6278:                     }
                   6279:                     $rolekey .= './';
                   6280:                     $groups_roles->{$rolekey} = $rolecodes;
                   6281:                 }
                   6282:             }
                   6283:         }
                   6284:     }
                   6285:     return;
                   6286: }
                   6287: 
                   6288: sub delete_env_groupprivs {
                   6289:     my ($where,$courseroles,$possroles) = @_;
                   6290:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6291:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6292:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6293:         %{$courseroles->{$udom}} =
                   6294:             &get_my_roles('','','userroles',['active'],
                   6295:                           $possroles,[$udom],1);
                   6296:     }
                   6297:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6298:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6299:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6300:             my $area = '/'.$cdom.'/'.$cnum;
                   6301:             my $privkey = "user.priv.$crsrole.$area";
                   6302:             if ($crssec ne '') {
                   6303:                 $privkey .= '/'.$crssec;
                   6304:             }
                   6305:             $privkey .= ".$area/$group";
                   6306:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6307:         }
                   6308:     }
                   6309:     return;
                   6310: }
                   6311: 
1.994     raeburn  6312: sub check_adhoc_privs {
1.1172.2.86  raeburn  6313:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6314:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6315:     if ($sec) {
                   6316:         $cckey .= '/'.$sec;
                   6317:     }
1.1172.2.9  raeburn  6318:     my $setprivs;
1.994     raeburn  6319:     if ($env{$cckey}) {
                   6320:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6321:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6322:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6323:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6324:             $setprivs = 1;
1.994     raeburn  6325:         }
                   6326:     } else {
1.1172.2.87  raeburn  6327:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6328:         $setprivs = 1;
1.994     raeburn  6329:     }
1.1172.2.9  raeburn  6330:     return $setprivs;
1.994     raeburn  6331: }
                   6332: 
                   6333: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6334: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6335:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6336:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6337:     if ($sec ne '') {
                   6338:         $area .= '/'.$sec;
                   6339:     }
1.994     raeburn  6340:     my $spec = $role.'.'.$area;
                   6341:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6342:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6343:     my %rolehash = ();
1.1172.2.89  raeburn  6344:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6345:         my $rolename = $1;
1.1172.2.84  raeburn  6346:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6347:         my %domdef = &get_domain_defaults($dcdom);
                   6348:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6349:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6350:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6351:             }
                   6352:         }
1.1172.2.84  raeburn  6353:     } else {
                   6354:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6355:     }
1.1172.2.91  raeburn  6356:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6357:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6358:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6359:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6360:         &appenv( {'request.role'        => $spec,
                   6361:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6362:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6363:                  }
                   6364:                );
                   6365:         my $tadv=0;
                   6366:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6367:         &appenv({'request.role.adv'    => $tadv});
                   6368:     }
1.994     raeburn  6369: }
                   6370: 
1.12      www      6371: # --------------------------------------------------------------- get interface
                   6372: 
                   6373: sub get {
1.131     albertel 6374:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6375:    my $items='';
1.800     albertel 6376:    foreach my $item (@$storearr) {
                   6377:        $items.=&escape($item).'&';
1.191     harris41 6378:    }
1.12      www      6379:    $items=~s/\&$//;
1.620     albertel 6380:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6381:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6382:    my $uhome=&homeserver($uname,$udomain);
                   6383: 
1.133     albertel 6384:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6385:    my @pairs=split(/\&/,$rep);
1.273     albertel 6386:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6387:      return @pairs;
                   6388:    }
1.15      www      6389:    my %returnhash=();
1.42      www      6390:    my $i=0;
1.800     albertel 6391:    foreach my $item (@$storearr) {
                   6392:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6393:       $i++;
1.191     harris41 6394:    }
1.15      www      6395:    return %returnhash;
1.27      www      6396: }
                   6397: 
                   6398: # --------------------------------------------------------------- del interface
                   6399: 
                   6400: sub del {
1.133     albertel 6401:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6402:    my $items='';
1.800     albertel 6403:    foreach my $item (@$storearr) {
                   6404:        $items.=&escape($item).'&';
1.191     harris41 6405:    }
1.984     neumanie 6406: 
1.27      www      6407:    $items=~s/\&$//;
1.620     albertel 6408:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6409:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6410:    my $uhome=&homeserver($uname,$udomain);
                   6411:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6412: }
                   6413: 
                   6414: # -------------------------------------------------------------- dump interface
                   6415: 
1.1172.2.22  raeburn  6416: sub unserialize {
                   6417:     my ($rep, $escapedkeys) = @_;
                   6418: 
                   6419:     return {} if $rep =~ /^error/;
                   6420: 
                   6421:     my %returnhash=();
                   6422:     foreach my $item (split(/\&/,$rep)) {
                   6423:         my ($key, $value) = split(/=/, $item, 2);
                   6424:         $key = unescape($key) unless $escapedkeys;
                   6425:         next if $key =~ /^error: 2 /;
                   6426:         $returnhash{$key} = &thaw_unescape($value);
                   6427:     }
                   6428:     return \%returnhash;
                   6429: }
                   6430: 
                   6431: # see Lond::dump_with_regexp
                   6432: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6433: sub dump {
1.1172.2.22  raeburn  6434:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6435:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6436:     if (!$uname) { $uname=$env{'user.name'}; }
                   6437:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6438: 
1.1172.2.55  raeburn  6439:     if ($regexp) {
                   6440:         $regexp=&escape($regexp);
                   6441:     } else {
                   6442:         $regexp='.';
                   6443:     }
1.1172.2.22  raeburn  6444:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6445:         # user is hosted on this machine
1.1172.2.55  raeburn  6446:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6447:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6448:         return %{&unserialize($reply, $escapedkeys)};
                   6449:     }
1.1166    raeburn  6450:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6451:     my @pairs=split(/\&/,$rep);
                   6452:     my %returnhash=();
1.1098    foxr     6453:     if (!($rep =~ /^error/ )) {
                   6454: 	foreach my $item (@pairs) {
                   6455: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6456:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6457: 	    next if ($key =~ /^error: 2 /);
                   6458: 	    $returnhash{$key}=&thaw_unescape($value);
                   6459: 	}
1.755     albertel 6460:     }
                   6461:     return %returnhash;
1.407     www      6462: }
                   6463: 
1.1098    foxr     6464: 
1.717     albertel 6465: # --------------------------------------------------------- dumpstore interface
                   6466: 
                   6467: sub dumpstore {
                   6468:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6469:    # same as dump but keys must be escaped. They may contain colon separated
                   6470:    # lists of values that may themself contain colons (e.g. symbs).
                   6471:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6472: }
                   6473: 
1.407     www      6474: # -------------------------------------------------------------- keys interface
                   6475: 
                   6476: sub getkeys {
                   6477:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6478:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6479:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6480:    my $uhome=&homeserver($uname,$udomain);
                   6481:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6482:    my @keyarray=();
1.800     albertel 6483:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6484:       next if ($key =~ /^error: 2 /);
1.800     albertel 6485:       push(@keyarray,&unescape($key));
1.407     www      6486:    }
                   6487:    return @keyarray;
1.318     matthew  6488: }
                   6489: 
1.319     matthew  6490: # --------------------------------------------------------------- currentdump
                   6491: sub currentdump {
1.328     matthew  6492:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6493:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6494:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6495:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6496:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6497:    my $rep;
                   6498: 
                   6499:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6500:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6501:                    $courseid)));
                   6502:    } else {
                   6503:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6504:    }
                   6505: 
1.318     matthew  6506:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6507:    #
1.318     matthew  6508:    my %returnhash=();
1.319     matthew  6509:    #
1.1172.2.93.4  2(raebur 6510:7):    if ($rep eq 'unknown_cmd') { 
1.319     matthew  6511:        # an old lond will not know currentdump
                   6512:        # Do a dump and make it look like a currentdump
1.822     albertel 6513:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6514:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6515:        my %hash = @tmp;
                   6516:        @tmp=();
1.424     matthew  6517:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6518:    } else {
                   6519:        my @pairs=split(/\&/,$rep);
1.800     albertel 6520:        foreach my $pair (@pairs) {
                   6521:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6522:            my ($symb,$param) = split(/:/,$key);
                   6523:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6524:                                                         &thaw_unescape($value);
1.319     matthew  6525:        }
1.191     harris41 6526:    }
1.12      www      6527:    return %returnhash;
1.424     matthew  6528: }
                   6529: 
                   6530: sub convert_dump_to_currentdump{
                   6531:     my %hash = %{shift()};
                   6532:     my %returnhash;
                   6533:     # Code ripped from lond, essentially.  The only difference
                   6534:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6535:     # we might run in to problems with parameter names =~ /^v\./
                   6536:     while (my ($key,$value) = each(%hash)) {
                   6537:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6538: 	$symb  = &unescape($symb);
                   6539: 	$param = &unescape($param);
1.424     matthew  6540:         next if ($v eq 'version' || $symb eq 'keys');
                   6541:         next if (exists($returnhash{$symb}) &&
                   6542:                  exists($returnhash{$symb}->{$param}) &&
                   6543:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6544:         $returnhash{$symb}->{$param}=$value;
                   6545:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6546:     }
                   6547:     #
                   6548:     # Remove all of the keys in the hashes which keep track of
                   6549:     # the version of the parameter.
                   6550:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6551:         # use a foreach because we are going to delete from the hash.
                   6552:         foreach my $key (keys(%$param_hash)) {
                   6553:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6554:         }
                   6555:     }
                   6556:     return \%returnhash;
1.12      www      6557: }
                   6558: 
1.627     albertel 6559: # ------------------------------------------------------ critical inc interface
                   6560: 
                   6561: sub cinc {
                   6562:     return &inc(@_,'critical');
                   6563: }
                   6564: 
1.449     matthew  6565: # --------------------------------------------------------------- inc interface
                   6566: 
                   6567: sub inc {
1.627     albertel 6568:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6569:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6570:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6571:     my $uhome=&homeserver($uname,$udomain);
                   6572:     my $items='';
                   6573:     if (! ref($store)) {
                   6574:         # got a single value, so use that instead
                   6575:         $items = &escape($store).'=&';
                   6576:     } elsif (ref($store) eq 'SCALAR') {
                   6577:         $items = &escape($$store).'=&';        
                   6578:     } elsif (ref($store) eq 'ARRAY') {
                   6579:         $items = join('=&',map {&escape($_);} @{$store});
                   6580:     } elsif (ref($store) eq 'HASH') {
                   6581:         while (my($key,$value) = each(%{$store})) {
                   6582:             $items.= &escape($key).'='.&escape($value).'&';
                   6583:         }
                   6584:     }
                   6585:     $items=~s/\&$//;
1.627     albertel 6586:     if ($critical) {
                   6587: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6588:     } else {
                   6589: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6590:     }
1.449     matthew  6591: }
                   6592: 
1.12      www      6593: # --------------------------------------------------------------- put interface
                   6594: 
                   6595: sub put {
1.134     albertel 6596:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6597:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6598:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6599:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6600:    my $items='';
1.800     albertel 6601:    foreach my $item (keys(%$storehash)) {
                   6602:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6603:    }
1.12      www      6604:    $items=~s/\&$//;
1.134     albertel 6605:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6606: }
                   6607: 
1.631     albertel 6608: # ------------------------------------------------------------ newput interface
                   6609: 
                   6610: sub newput {
                   6611:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6612:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6613:    if (!$uname) { $uname=$env{'user.name'}; }
                   6614:    my $uhome=&homeserver($uname,$udomain);
                   6615:    my $items='';
                   6616:    foreach my $key (keys(%$storehash)) {
                   6617:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6618:    }
                   6619:    $items=~s/\&$//;
                   6620:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6621: }
                   6622: 
                   6623: # ---------------------------------------------------------  putstore interface
                   6624: 
1.524     raeburn  6625: sub putstore {
1.1172.2.59  raeburn  6626:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6627:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6628:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6629:    my $uhome=&homeserver($uname,$udomain);
                   6630:    my $items='';
1.715     albertel 6631:    foreach my $key (keys(%$storehash)) {
                   6632:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6633:    }
1.715     albertel 6634:    $items=~s/\&$//;
1.716     albertel 6635:    my $esc_symb=&escape($symb);
                   6636:    my $esc_v=&escape($version);
1.715     albertel 6637:    my $reply =
1.716     albertel 6638:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6639: 	      $uhome);
1.1172.2.59  raeburn  6640:    if (($tolog) && ($reply eq 'ok')) {
                   6641:        my $namevalue='';
                   6642:        foreach my $key (keys(%{$storehash})) {
                   6643:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6644:        }
                   6645:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6646:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6647:                      '&version='.$esc_v.
                   6648:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6649:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6650:    }
1.715     albertel 6651:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6652:        # gfall back to way things use to be done
1.715     albertel 6653:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6654: 			    $uname);
1.524     raeburn  6655:    }
1.715     albertel 6656:    return $reply;
                   6657: }
                   6658: 
                   6659: sub old_putstore {
1.716     albertel 6660:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6661:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6662:     if (!$uname) { $uname=$env{'user.name'}; }
                   6663:     my $uhome=&homeserver($uname,$udomain);
                   6664:     my %newstorehash;
1.800     albertel 6665:     foreach my $item (keys(%$storehash)) {
                   6666: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6667: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6668:     }
                   6669:     my $items='';
                   6670:     my %allitems = ();
1.800     albertel 6671:     foreach my $item (keys(%newstorehash)) {
                   6672: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6673: 	    my $key = $1.':keys:'.$2;
                   6674: 	    $allitems{$key} .= $3.':';
                   6675: 	}
1.800     albertel 6676: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6677:     }
1.800     albertel 6678:     foreach my $item (keys(%allitems)) {
                   6679: 	$allitems{$item} =~ s/\:$//;
                   6680: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6681:     }
                   6682:     $items=~s/\&$//;
                   6683:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6684: }
                   6685: 
1.47      www      6686: # ------------------------------------------------------ critical put interface
                   6687: 
                   6688: sub cput {
1.134     albertel 6689:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6690:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6691:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6692:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6693:    my $items='';
1.800     albertel 6694:    foreach my $item (keys(%$storehash)) {
                   6695:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6696:    }
1.47      www      6697:    $items=~s/\&$//;
1.134     albertel 6698:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6699: }
                   6700: 
                   6701: # -------------------------------------------------------------- eget interface
                   6702: 
                   6703: sub eget {
1.133     albertel 6704:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6705:    my $items='';
1.800     albertel 6706:    foreach my $item (@$storearr) {
                   6707:        $items.=&escape($item).'&';
1.191     harris41 6708:    }
1.12      www      6709:    $items=~s/\&$//;
1.620     albertel 6710:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6711:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6712:    my $uhome=&homeserver($uname,$udomain);
                   6713:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6714:    my @pairs=split(/\&/,$rep);
                   6715:    my %returnhash=();
1.42      www      6716:    my $i=0;
1.800     albertel 6717:    foreach my $item (@$storearr) {
                   6718:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6719:       $i++;
1.191     harris41 6720:    }
1.12      www      6721:    return %returnhash;
                   6722: }
                   6723: 
1.667     albertel 6724: # ------------------------------------------------------------ tmpput interface
                   6725: sub tmpput {
1.802     raeburn  6726:     my ($storehash,$server,$context)=@_;
1.667     albertel 6727:     my $items='';
1.800     albertel 6728:     foreach my $item (keys(%$storehash)) {
                   6729: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6730:     }
                   6731:     $items=~s/\&$//;
1.802     raeburn  6732:     if (defined($context)) {
                   6733:         $items .= ':'.&escape($context);
                   6734:     }
1.667     albertel 6735:     return &reply("tmpput:$items",$server);
                   6736: }
                   6737: 
                   6738: # ------------------------------------------------------------ tmpget interface
                   6739: sub tmpget {
1.688     albertel 6740:     my ($token,$server)=@_;
                   6741:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6742:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6743:     my %returnhash;
1.1172.2.85  raeburn  6744:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6745:         return %returnhash;
                   6746:     }
1.667     albertel 6747:     foreach my $item (split(/\&/,$rep)) {
                   6748: 	my ($key,$value)=split(/=/,$item);
                   6749: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6750:     }
                   6751:     return %returnhash;
                   6752: }
                   6753: 
1.1113    raeburn  6754: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6755: sub tmpdel {
                   6756:     my ($token,$server)=@_;
                   6757:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6758:     return &reply("tmpdel:$token",$server);
                   6759: }
                   6760: 
1.1172.2.13  raeburn  6761: # ------------------------------------------------------------ get_timebased_id
                   6762: 
                   6763: sub get_timebased_id {
                   6764:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6765:         $maxtries) = @_;
                   6766:     my ($newid,$error,$dellock);
                   6767:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6768:         return ('','ok','invalid call to get suffix');
                   6769:     }
                   6770: 
                   6771: # set defaults for any optional args for which values were not supplied
                   6772:     if ($who eq '') {
                   6773:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6774:     }
                   6775:     if (!$locktries) {
                   6776:         $locktries = 3;
                   6777:     }
                   6778:     if (!$maxtries) {
                   6779:         $maxtries = 10;
                   6780:     }
                   6781: 
                   6782:     if (($cdom eq '') || ($cnum eq '')) {
                   6783:         if ($env{'request.course.id'}) {
                   6784:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6785:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6786:         }
                   6787:         if (($cdom eq '') || ($cnum eq '')) {
                   6788:             return ('','ok','call to get suffix not in course context');
                   6789:         }
                   6790:     }
                   6791: 
                   6792: # construct locking item
                   6793:     my $lockhash = {
                   6794:                       $prefix."\0".'locked_'.$keyid => $who,
                   6795:                    };
                   6796:     my $tries = 0;
                   6797: 
                   6798: # attempt to get lock on nohist_$namespace file
                   6799:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6800:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6801:         $tries ++;
                   6802:         sleep 1;
                   6803:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6804:     }
                   6805: 
                   6806: # attempt to get unique identifier, based on current timestamp
                   6807:     if ($gotlock eq 'ok') {
                   6808:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6809:         my $id = time;
                   6810:         $newid = $id;
1.1172.2.56  raeburn  6811:         if ($idtype eq 'addcode') {
                   6812:             $newid .= &sixnum_code();
                   6813:         }
1.1172.2.13  raeburn  6814:         my $idtries = 0;
                   6815:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6816:             if ($idtype eq 'concat') {
                   6817:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6818:             } elsif ($idtype eq 'addcode') {
                   6819:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6820:             } else {
                   6821:                 $newid ++;
                   6822:             }
                   6823:             $idtries ++;
                   6824:         }
                   6825:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6826:             my %new_item =  (
                   6827:                               $prefix."\0".$newid => $who,
                   6828:                             );
                   6829:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6830:                                                  $cdom,$cnum);
                   6831:             if ($putresult ne 'ok') {
                   6832:                 undef($newid);
                   6833:                 $error = 'error saving new item: '.$putresult;
                   6834:             }
                   6835:         } else {
1.1172.2.56  raeburn  6836:              undef($newid);
1.1172.2.13  raeburn  6837:              $error = ('error: no unique suffix available for the new item ');
                   6838:         }
                   6839: #  remove lock
                   6840:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6841:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6842:     } else {
                   6843:         $error = "error: could not obtain lockfile\n";
                   6844:         $dellock = 'ok';
1.1172.2.58  raeburn  6845:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6846:             $dellock = 'nolock';
                   6847:         }
1.1172.2.13  raeburn  6848:     }
                   6849:     return ($newid,$dellock,$error);
                   6850: }
                   6851: 
1.1172.2.56  raeburn  6852: sub sixnum_code {
                   6853:     my $code;
                   6854:     for (0..6) {
                   6855:         $code .= int( rand(9) );
                   6856:     }
                   6857:     return $code;
                   6858: }
                   6859: 
1.765     albertel 6860: # -------------------------------------------------- portfolio access checking
                   6861: 
                   6862: sub portfolio_access {
1.1172.2.77  raeburn  6863:     my ($requrl,$clientip) = @_;
1.765     albertel 6864:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6865:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6866:     if ($result) {
                   6867:         my %setters;
                   6868:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6869:             my ($startblock,$endblock) =
                   6870:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6871:             if ($startblock && $endblock) {
                   6872:                 return 'B';
                   6873:             }
                   6874:         } else {
                   6875:             my ($startblock,$endblock) =
                   6876:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6877:             if ($startblock && $endblock) {
                   6878:                 return 'B';
                   6879:             }
                   6880:         }
                   6881:     }
1.765     albertel 6882:     if ($result eq 'ok') {
1.766     albertel 6883:        return 'F';
1.765     albertel 6884:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6885:        return 'A';
1.765     albertel 6886:     }
1.766     albertel 6887:     return '';
1.765     albertel 6888: }
                   6889: 
                   6890: sub get_portfolio_access {
1.1172.2.77  raeburn  6891:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6892: 
                   6893:     if (!ref($access_hash)) {
                   6894: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6895: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6896: 						   $file_name);
                   6897: 	$access_hash = $access_controls{$file_name};
                   6898:     }
                   6899: 
1.1172.2.77  raeburn  6900:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6901:     my $now = time;
                   6902:     if (ref($access_hash) eq 'HASH') {
                   6903:         foreach my $key (keys(%{$access_hash})) {
                   6904:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6905:             if ($start > $now) {
                   6906:                 next;
                   6907:             }
                   6908:             if ($end && $end<$now) {
                   6909:                 next;
                   6910:             }
                   6911:             if ($scope eq 'public') {
                   6912:                 $public = $key;
                   6913:                 last;
                   6914:             } elsif ($scope eq 'guest') {
                   6915:                 $guest = $key;
                   6916:             } elsif ($scope eq 'domains') {
                   6917:                 push(@domains,$key);
                   6918:             } elsif ($scope eq 'users') {
                   6919:                 push(@users,$key);
                   6920:             } elsif ($scope eq 'course') {
                   6921:                 push(@courses,$key);
                   6922:             } elsif ($scope eq 'group') {
                   6923:                 push(@groups,$key);
1.1172.2.77  raeburn  6924:             } elsif ($scope eq 'ip') {
                   6925:                 push(@ips,$key);
1.765     albertel 6926:             }
                   6927:         }
                   6928:         if ($public) {
                   6929:             return 'ok';
1.1172.2.77  raeburn  6930:         } elsif (@ips > 0) {
                   6931:             my $allowed;
                   6932:             foreach my $ipkey (@ips) {
                   6933:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6934:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6935:                         $allowed = 1;
                   6936:                         last;
                   6937:                     }
                   6938:                 }
                   6939:             }
                   6940:             if ($allowed) {
                   6941:                 return 'ok';
                   6942:             }
1.765     albertel 6943:         }
                   6944:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6945:             if ($guest) {
                   6946:                 return $guest;
                   6947:             }
                   6948:         } else {
                   6949:             if (@domains > 0) {
                   6950:                 foreach my $domkey (@domains) {
                   6951:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6952:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6953:                             return 'ok';
                   6954:                         }
                   6955:                     }
                   6956:                 }
                   6957:             }
                   6958:             if (@users > 0) {
                   6959:                 foreach my $userkey (@users) {
1.865     raeburn  6960:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6961:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6962:                             if (ref($item) eq 'HASH') {
                   6963:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6964:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6965:                                     return 'ok';
                   6966:                                 }
                   6967:                             }
                   6968:                         }
                   6969:                     } 
1.765     albertel 6970:                 }
                   6971:             }
                   6972:             my %roleshash;
                   6973:             my @courses_and_groups = @courses;
                   6974:             push(@courses_and_groups,@groups); 
                   6975:             if (@courses_and_groups > 0) {
                   6976:                 my (%allgroups,%allroles); 
                   6977:                 my ($start,$end,$role,$sec,$group);
                   6978:                 foreach my $envkey (%env) {
1.1060    raeburn  6979:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6980:                         my $cid = $2.'_'.$3; 
                   6981:                         if ($1 eq 'gr') {
                   6982:                             $group = $4;
                   6983:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6984:                         } else {
                   6985:                             if ($4 eq '') {
                   6986:                                 $sec = 'none';
                   6987:                             } else {
                   6988:                                 $sec = $4;
                   6989:                             }
                   6990:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6991:                         }
1.811     albertel 6992:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6993:                         my $cid = $2.'_'.$3;
                   6994:                         if ($4 eq '') {
                   6995:                             $sec = 'none';
                   6996:                         } else {
                   6997:                             $sec = $4;
                   6998:                         }
                   6999:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7000:                     }
                   7001:                 }
                   7002:                 if (keys(%allroles) == 0) {
                   7003:                     return;
                   7004:                 }
                   7005:                 foreach my $key (@courses_and_groups) {
                   7006:                     my %content = %{$$access_hash{$key}};
                   7007:                     my $cnum = $content{'number'};
                   7008:                     my $cdom = $content{'domain'};
                   7009:                     my $cid = $cdom.'_'.$cnum;
                   7010:                     if (!exists($allroles{$cid})) {
                   7011:                         next;
                   7012:                     }    
                   7013:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7014:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7015:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7016:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7017:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7018:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7019:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7020:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7021:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7022:                                         if (grep/^all$/,@sections) {
                   7023:                                             return 'ok';
                   7024:                                         } else {
                   7025:                                             if (grep/^$sec$/,@sections) {
                   7026:                                                 return 'ok';
                   7027:                                             }
                   7028:                                         }
                   7029:                                     }
                   7030:                                 }
                   7031:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7032:                                     if (grep/^none$/,@groups) {
                   7033:                                         return 'ok';
                   7034:                                     }
                   7035:                                 } else {
                   7036:                                     if (grep/^all$/,@groups) {
                   7037:                                         return 'ok';
                   7038:                                     } 
                   7039:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7040:                                         if (grep/^$group$/,@groups) {
                   7041:                                             return 'ok';
                   7042:                                         }
                   7043:                                     }
                   7044:                                 } 
                   7045:                             }
                   7046:                         }
                   7047:                     }
                   7048:                 }
                   7049:             }
                   7050:             if ($guest) {
                   7051:                 return $guest;
                   7052:             }
                   7053:         }
                   7054:     }
                   7055:     return;
                   7056: }
                   7057: 
                   7058: sub course_group_datechecker {
                   7059:     my ($dates,$now,$status) = @_;
                   7060:     my ($start,$end) = split(/\./,$dates);
                   7061:     if (!$start && !$end) {
                   7062:         return 'ok';
                   7063:     }
                   7064:     if (grep/^active$/,@{$status}) {
                   7065:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7066:             return 'ok';
                   7067:         }
                   7068:     }
                   7069:     if (grep/^previous$/,@{$status}) {
                   7070:         if ($end > $now ) {
                   7071:             return 'ok';
                   7072:         }
                   7073:     }
                   7074:     if (grep/^future$/,@{$status}) {
                   7075:         if ($start > $now) {
                   7076:             return 'ok';
                   7077:         }
                   7078:     }
                   7079:     return; 
                   7080: }
                   7081: 
                   7082: sub parse_portfolio_url {
                   7083:     my ($url) = @_;
                   7084: 
                   7085:     my ($type,$udom,$unum,$group,$file_name);
                   7086:     
1.823     albertel 7087:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7088: 	$type = 1;
                   7089:         $udom = $1;
                   7090:         $unum = $2;
                   7091:         $file_name = $3;
1.823     albertel 7092:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7093: 	$type = 2;
                   7094:         $udom = $1;
                   7095:         $unum = $2;
                   7096:         $group = $3;
                   7097:         $file_name = $3.'/'.$4;
                   7098:     }
                   7099:     if (wantarray) {
                   7100: 	return ($type,$udom,$unum,$file_name,$group);
                   7101:     }
                   7102:     return $type;
                   7103: }
                   7104: 
                   7105: sub is_portfolio_url {
                   7106:     my ($url) = @_;
                   7107:     return scalar(&parse_portfolio_url($url));
                   7108: }
                   7109: 
1.798     raeburn  7110: sub is_portfolio_file {
                   7111:     my ($file) = @_;
1.820     raeburn  7112:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7113:         return 1;
                   7114:     }
                   7115:     return;
                   7116: }
                   7117: 
1.976     raeburn  7118: sub usertools_access {
1.1084    raeburn  7119:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7120:     my ($access,%tools);
                   7121:     if ($context eq '') {
                   7122:         $context = 'tools';
                   7123:     }
                   7124:     if ($context eq 'requestcourses') {
                   7125:         %tools = (
                   7126:                       official   => 1,
                   7127:                       unofficial => 1,
1.1006    raeburn  7128:                       community  => 1,
1.1172.2.37  raeburn  7129:                       textbook   => 1,
1.985     raeburn  7130:                  );
1.1172.2.9  raeburn  7131:     } elsif ($context eq 'requestauthor') {
                   7132:         %tools = (
                   7133:                       requestauthor => 1,
                   7134:                  );
1.985     raeburn  7135:     } else {
                   7136:         %tools = (
                   7137:                       aboutme   => 1,
                   7138:                       blog      => 1,
1.1172.2.6  raeburn  7139:                       webdav    => 1,
1.985     raeburn  7140:                       portfolio => 1,
                   7141:                  );
                   7142:     }
1.976     raeburn  7143:     return if (!defined($tools{$tool}));
                   7144: 
1.1172.2.35  raeburn  7145:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7146:         $udom = $env{'user.domain'};
                   7147:         $uname = $env{'user.name'};
                   7148:     }
                   7149: 
1.978     raeburn  7150:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7151:         if ($action ne 'reload') {
1.985     raeburn  7152:             if ($context eq 'requestcourses') {
                   7153:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7154:             } elsif ($context eq 'requestauthor') {
                   7155:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7156:             } else {
                   7157:                 return $env{'environment.availabletools.'.$tool};
                   7158:             }
                   7159:         }
1.976     raeburn  7160:     }
                   7161: 
1.1172.2.9  raeburn  7162:     my ($toolstatus,$inststatus,$envkey);
                   7163:     if ($context eq 'requestauthor') {
                   7164:         $envkey = $context;
                   7165:     } else {
                   7166:         $envkey = $context.'.'.$tool;
                   7167:     }
1.976     raeburn  7168: 
1.985     raeburn  7169:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7170:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7171:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7172:         $inststatus = $env{'environment.inststatus'};
                   7173:     } else {
1.1084    raeburn  7174:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7175:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7176:             $inststatus = $userenvref->{'inststatus'};
                   7177:         } else {
1.1172.2.9  raeburn  7178:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7179:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7180:             $inststatus = $userenv{'inststatus'};
                   7181:         }
1.976     raeburn  7182:     }
                   7183: 
                   7184:     if ($toolstatus ne '') {
                   7185:         if ($toolstatus) {
                   7186:             $access = 1;
                   7187:         } else {
                   7188:             $access = 0;
                   7189:         }
                   7190:         return $access;
                   7191:     }
                   7192: 
1.1084    raeburn  7193:     my ($is_adv,%domdef);
                   7194:     if (ref($is_advref) eq 'HASH') {
                   7195:         $is_adv = $is_advref->{'is_adv'};
                   7196:     } else {
                   7197:         $is_adv = &is_advanced_user($udom,$uname);
                   7198:     }
                   7199:     if (ref($domdefref) eq 'HASH') {
                   7200:         %domdef = %{$domdefref};
                   7201:     } else {
                   7202:         %domdef = &get_domain_defaults($udom);
                   7203:     }
1.976     raeburn  7204:     if (ref($domdef{$tool}) eq 'HASH') {
                   7205:         if ($is_adv) {
                   7206:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7207:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7208:                     $access = 1;
                   7209:                 } else {
                   7210:                     $access = 0;
                   7211:                 }
                   7212:                 return $access;
                   7213:             }
                   7214:         }
                   7215:         if ($inststatus ne '') {
                   7216:             my ($hasaccess,$hasnoaccess);
                   7217:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7218:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7219:                     if ($domdef{$tool}{$affiliation}) {
                   7220:                         $hasaccess = 1;
                   7221:                     } else {
                   7222:                         $hasnoaccess = 1;
                   7223:                     }
                   7224:                 }
                   7225:             }
                   7226:             if ($hasaccess || $hasnoaccess) {
                   7227:                 if ($hasaccess) {
                   7228:                     $access = 1;
                   7229:                 } elsif ($hasnoaccess) {
                   7230:                     $access = 0; 
                   7231:                 }
                   7232:                 return $access;
                   7233:             }
                   7234:         } else {
                   7235:             if ($domdef{$tool}{'default'} ne '') {
                   7236:                 if ($domdef{$tool}{'default'}) {
                   7237:                     $access = 1;
                   7238:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7239:                     $access = 0;
                   7240:                 }
                   7241:                 return $access;
                   7242:             }
                   7243:         }
                   7244:     } else {
1.1172.2.6  raeburn  7245:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7246:             $access = 1;
                   7247:         } else {
                   7248:             $access = 0;
                   7249:         }
1.976     raeburn  7250:         return $access;
                   7251:     }
                   7252: }
                   7253: 
1.1050    raeburn  7254: sub is_course_owner {
                   7255:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7256:     if (($udom eq '') || ($uname eq '')) {
                   7257:         $udom = $env{'user.domain'};
                   7258:         $uname = $env{'user.name'};
                   7259:     }
                   7260:     unless (($udom eq '') || ($uname eq '')) {
                   7261:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7262:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7263:                 return 1;
                   7264:             } else {
                   7265:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7266:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7267:                     return 1;
                   7268:                 }
                   7269:             }
                   7270:         }
                   7271:     }
                   7272:     return;
                   7273: }
                   7274: 
1.976     raeburn  7275: sub is_advanced_user {
                   7276:     my ($udom,$uname) = @_;
1.1085    raeburn  7277:     if ($udom ne '' && $uname ne '') {
                   7278:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7279:             if (wantarray) {
                   7280:                 return ($env{'user.adv'},$env{'user.author'});
                   7281:             } else {
                   7282:                 return $env{'user.adv'};
                   7283:             }
1.1085    raeburn  7284:         }
                   7285:     }
1.976     raeburn  7286:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7287:     my %allroles;
1.1128    raeburn  7288:     my ($is_adv,$is_author);
1.976     raeburn  7289:     foreach my $role (keys(%roleshash)) {
                   7290:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7291:         my $area = '/'.$tdomain.'/'.$trest;
                   7292:         if ($sec ne '') {
                   7293:             $area .= '/'.$sec;
                   7294:         }
                   7295:         if (($area ne '') && ($trole ne '')) {
                   7296:             my $spec=$trole.'.'.$area;
                   7297:             if ($trole =~ /^cr\//) {
                   7298:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7299:             } elsif ($trole ne 'gr') {
                   7300:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7301:             }
1.1128    raeburn  7302:             if ($trole eq 'au') {
                   7303:                 $is_author = 1;
                   7304:             }
1.976     raeburn  7305:         }
                   7306:     }
                   7307:     foreach my $role (keys(%allroles)) {
                   7308:         last if ($is_adv);
                   7309:         foreach my $item (split(/:/,$allroles{$role})) {
                   7310:             if ($item ne '') {
                   7311:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7312:                 if ($privilege eq 'adv') {
                   7313:                     $is_adv = 1;
                   7314:                     last;
                   7315:                 }
                   7316:             }
                   7317:         }
                   7318:     }
1.1128    raeburn  7319:     if (wantarray) {
                   7320:         return ($is_adv,$is_author);
                   7321:     }
1.976     raeburn  7322:     return $is_adv;
                   7323: }
1.798     raeburn  7324: 
1.1035    raeburn  7325: sub check_can_request {
1.1036    raeburn  7326:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7327:     my $canreq = 0;
                   7328:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7329:     my @options = ('approval','validate','autolimit');
                   7330:     my $optregex = join('|',@options);
                   7331:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7332:         foreach my $type (@{$types}) {
                   7333:             if (&usertools_access($env{'user.name'},
                   7334:                                   $env{'user.domain'},
                   7335:                                   $type,undef,'requestcourses')) {
                   7336:                 $canreq ++;
1.1036    raeburn  7337:                 if (ref($request_domains) eq 'HASH') {
                   7338:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7339:                 }
1.1035    raeburn  7340:                 if ($dom eq $env{'user.domain'}) {
                   7341:                     $can_request->{$type} = 1;
                   7342:                 }
                   7343:             }
                   7344:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7345:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7346:                 if (@curr > 0) {
1.1036    raeburn  7347:                     foreach my $item (@curr) {
                   7348:                         if (ref($request_domains) eq 'HASH') {
                   7349:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7350:                             if ($otherdom ne '') {
                   7351:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7352:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7353:                                         push(@{$request_domains->{$type}},$otherdom);
                   7354:                                     }
                   7355:                                 } else {
                   7356:                                     push(@{$request_domains->{$type}},$otherdom);
                   7357:                                 }
                   7358:                             }
                   7359:                         }
                   7360:                     }
                   7361:                     unless($dom eq $env{'user.domain'}) {
                   7362:                         $canreq ++;
1.1035    raeburn  7363:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7364:                             $can_request->{$type} = 1;
                   7365:                         }
                   7366:                     }
                   7367:                 }
                   7368:             }
                   7369:         }
                   7370:     }
                   7371:     return $canreq;
                   7372: }
                   7373: 
1.341     www      7374: # ---------------------------------------------- Custom access rule evaluation
                   7375: 
                   7376: sub customaccess {
                   7377:     my ($priv,$uri)=@_;
1.807     albertel 7378:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7379:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7380:     $udom = &LONCAPA::clean_domain($udom);
                   7381:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7382:     my $access=0;
1.800     albertel 7383:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7384: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7385: 	if ($type eq 'user') {
                   7386: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7387: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7388: 		if ($tdom) {
                   7389: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7390: 		}
1.896     albertel 7391: 		if ($tuname) {
                   7392: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7393: 		}
                   7394: 		$access=($effect eq 'allow');
                   7395: 		last;
                   7396: 	    }
                   7397: 	} else {
                   7398: 	    if ($role) {
                   7399: 		if ($role ne $urole) { next; }
                   7400: 	    }
                   7401: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7402: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7403: 		if ($tdom) {
                   7404: 		    if ($tdom ne $udom) { next; }
                   7405: 		}
                   7406: 		if ($tcrs) {
                   7407: 		    if ($tcrs ne $ucrs) { next; }
                   7408: 		}
                   7409: 		if ($tsec) {
                   7410: 		    if ($tsec ne $usec) { next; }
                   7411: 		}
                   7412: 		$access=($effect eq 'allow');
                   7413: 		last;
                   7414: 	    }
                   7415: 	    if ($realm eq '' && $role eq '') {
                   7416: 		$access=($effect eq 'allow');
                   7417: 	    }
1.402     bowersj2 7418: 	}
1.341     www      7419:     }
                   7420:     return $access;
                   7421: }
                   7422: 
1.103     harris41 7423: # ------------------------------------------------- Check for a user privilege
1.12      www      7424: 
                   7425: sub allowed {
1.1172.2.65  raeburn  7426:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7427:     my $ver_orguri=$uri;
1.439     www      7428:     $uri=&deversion($uri);
1.152     www      7429:     my $orguri=$uri;
1.52      www      7430:     $uri=&declutter($uri);
1.809     raeburn  7431: 
1.810     raeburn  7432:     if ($priv eq 'evb') {
                   7433: # Evade communication block restrictions for specified role in a course
                   7434:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7435:             return $1;
                   7436:         } else {
                   7437:             return;
                   7438:         }
                   7439:     }
                   7440: 
1.620     albertel 7441:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7442: # Free bre access to adm and meta resources
1.1172.2.93.4  2(raebur 7443:7):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7444: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7445: 	&& ($priv eq 'bre')) {
1.14      www      7446: 	return 'F';
1.159     www      7447:     }
                   7448: 
1.545     banghart 7449: # Free bre access to user's own portfolio contents
1.714     raeburn  7450:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7451:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7452: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7453:         my %setters;
                   7454:         my ($startblock,$endblock) = 
                   7455:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7456:         if ($startblock && $endblock) {
                   7457:             return 'B';
                   7458:         } else {
                   7459:             return 'F';
                   7460:         }
1.545     banghart 7461:     }
                   7462: 
1.762     raeburn  7463: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7464:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7465:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7466:         if (exists($env{'request.course.id'})) {
                   7467:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7468:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7469:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7470:                 my $courseprivid=$env{'request.course.id'};
                   7471:                 $courseprivid=~s/\_/\//;
                   7472:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7473:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7474:                     return $1; 
1.762     raeburn  7475:                 } else {
                   7476:                     if ($env{'request.course.sec'}) {
                   7477:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7478:                     }
                   7479:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7480:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7481:                         return $2;
                   7482:                     }
1.714     raeburn  7483:                 }
                   7484:             }
                   7485:         }
                   7486:     }
                   7487: 
1.159     www      7488: # Free bre to public access
                   7489: 
                   7490:     if ($priv eq 'bre') {
1.238     www      7491:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7492: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7493:            return 'F'; 
                   7494:         }
1.238     www      7495:         if ($copyright eq 'priv') {
                   7496:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7497: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7498: 		return '';
                   7499:             }
                   7500:         }
                   7501:         if ($copyright eq 'domain') {
                   7502:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7503: 	    unless (($env{'user.domain'} eq $1) ||
                   7504:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7505: 		return '';
                   7506:             }
1.262     matthew  7507:         }
1.620     albertel 7508:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7509:             # Library role, so allow browsing of resources in this domain.
                   7510:             return 'F';
1.238     www      7511:         }
1.341     www      7512:         if ($copyright eq 'custom') {
                   7513: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7514:         }
1.14      www      7515:     }
1.264     matthew  7516:     # Domain coordinator is trying to create a course
1.620     albertel 7517:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7518:         # uri is the requested domain in this case.
                   7519:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7520:         # a role of dc for the domain in question.
1.620     albertel 7521:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7522:     }
1.29      www      7523: 
1.52      www      7524:     my $thisallowed='';
                   7525:     my $statecond=0;
                   7526:     my $courseprivid='';
                   7527: 
1.1039    raeburn  7528:     my $ownaccess;
1.1043    raeburn  7529:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7530:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7531:         if ($uri eq '') {
                   7532:             $ownaccess = 1;
                   7533:         } else {
                   7534:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7535:                 my $udom = $env{'user.domain'};
                   7536:                 my $uname = $env{'user.name'};
                   7537:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7538:                     $ownaccess = 1;
1.1040    raeburn  7539:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7540:                     unless ($uri =~ m{\.\./}) {
                   7541:                         $ownaccess = 1;
                   7542:                     }
                   7543:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7544:                     my $now = time;
                   7545:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7546:                         my $adom = $1;
                   7547:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7548:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7549:                                 my ($start,$end) = split('.',$env{$key});
                   7550:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7551:                                     $ownaccess = 1;
                   7552:                                     last;
                   7553:                                 }
                   7554:                             }
                   7555:                         }
                   7556:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7557:                         my $adom = $1;
                   7558:                         my $aname = $2;
1.1042    raeburn  7559:                         foreach my $role ('ca','aa') { 
                   7560:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7561:                                 my ($start,$end) =
                   7562:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7563:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7564:                                     $ownaccess = 1;
                   7565:                                     last;
                   7566:                                 }
1.1039    raeburn  7567:                             }
                   7568:                         }
                   7569:                     }
                   7570:                 }
                   7571:             }
                   7572:         }
                   7573:     }
                   7574: 
1.52      www      7575: # Course
                   7576: 
1.620     albertel 7577:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7578:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7579:             $thisallowed.=$1;
                   7580:         }
1.52      www      7581:     }
1.29      www      7582: 
1.52      www      7583: # Domain
                   7584: 
1.620     albertel 7585:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7586:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7587:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7588:             $thisallowed.=$1;
                   7589:         }
1.12      www      7590:     }
1.52      www      7591: 
1.1141    raeburn  7592: # User who is not author or co-author might still be able to edit
                   7593: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7594:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7595:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7596:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7597:             $thisallowed.=$1;
                   7598:         }
                   7599:     }
                   7600: 
1.52      www      7601: # Course: uri itself is a course
1.66      www      7602:     my $courseuri=$uri;
                   7603:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7604:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7605: 
1.620     albertel 7606:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7607:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7608:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7609:             $thisallowed.=$1;
                   7610:         }
1.12      www      7611:     }
1.29      www      7612: 
1.665     albertel 7613: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7614: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7615:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7616: 	$thisallowed='';
1.671     raeburn  7617:         my ($match)=&is_on_map($uri);
                   7618:         if ($match) {
                   7619:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7620:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7621:                 my $value = $1;
                   7622:                 if ($noblockcheck) {
                   7623:                     $thisallowed.=$value;
1.1162    raeburn  7624:                 } else {
1.1172.2.65  raeburn  7625:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7626:                     if (@blockers > 0) {
                   7627:                         $thisallowed = 'B';
                   7628:                     } else {
                   7629:                         $thisallowed.=$value;
                   7630:                     }
1.1162    raeburn  7631:                 }
1.671     raeburn  7632:             }
                   7633:         } else {
1.705     albertel 7634:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7635:             if ($refuri) {
                   7636:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7637:                     $thisallowed='F';
1.671     raeburn  7638:                 } else {
                   7639:                     $refuri=&declutter($refuri);
                   7640:                     my ($match) = &is_on_map($refuri);
                   7641:                     if ($match) {
1.1172.2.65  raeburn  7642:                         if ($noblockcheck) {
1.1162    raeburn  7643:                             $thisallowed='F';
1.1172.2.65  raeburn  7644:                         } else {
                   7645:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7646:                             if (@blockers > 0) {
                   7647:                                 $thisallowed = 'B';
                   7648:                             } else {
                   7649:                                 $thisallowed='F';
                   7650:                             }
1.1162    raeburn  7651:                         }
1.671     raeburn  7652:                     }
1.669     raeburn  7653:                 }
1.671     raeburn  7654:             }
                   7655:         }
1.314     www      7656:     }
1.492     albertel 7657: 
1.766     albertel 7658:     if ($priv eq 'bre'
                   7659: 	&& $thisallowed ne 'F' 
                   7660: 	&& $thisallowed ne '2'
                   7661: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7662: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7663:     }
                   7664:     
1.52      www      7665: # Full access at system, domain or course-wide level? Exit.
1.29      www      7666:     if ($thisallowed=~/F/) {
                   7667: 	return 'F';
                   7668:     }
                   7669: 
1.52      www      7670: # If this is generating or modifying users, exit with special codes
1.29      www      7671: 
1.643     www      7672:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7673: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7674: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7675: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7676: 	    unless ($auname) { return $thisallowed; }
                   7677: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7678: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7679: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7680: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7681: 	}
1.52      www      7682: 	return $thisallowed;
                   7683:     }
                   7684: #
1.103     harris41 7685: # Gathered so far: system, domain and course wide privileges
1.52      www      7686: #
                   7687: # Course: See if uri or referer is an individual resource that is part of 
                   7688: # the course
                   7689: 
1.620     albertel 7690:     if ($env{'request.course.id'}) {
1.232     www      7691: 
1.620     albertel 7692:        $courseprivid=$env{'request.course.id'};
                   7693:        if ($env{'request.course.sec'}) {
                   7694:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7695:        }
                   7696:        $courseprivid=~s/\_/\//;
                   7697:        my $checkreferer=1;
1.232     www      7698:        my ($match,$cond)=&is_on_map($uri);
                   7699:        if ($match) {
                   7700:            $statecond=$cond;
1.620     albertel 7701:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7702:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7703:                my $value = $1;
                   7704:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7705:                    if ($noblockcheck) {
1.1162    raeburn  7706:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7707:                    } else {
                   7708:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7709:                        if (@blockers > 0) {
                   7710:                            $thisallowed = 'B';
                   7711:                        } else {
                   7712:                            $thisallowed.=$value;
                   7713:                        }
1.1162    raeburn  7714:                    }
                   7715:                } else {
                   7716:                    $thisallowed.=$value;
                   7717:                }
1.52      www      7718:                $checkreferer=0;
                   7719:            }
1.29      www      7720:        }
1.83      www      7721:        
1.148     www      7722:        if ($checkreferer) {
1.620     albertel 7723: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7724:             unless ($refuri) {
1.800     albertel 7725:                 foreach my $key (keys(%env)) {
                   7726: 		    if ($key=~/^httpref\..*\*/) {
                   7727: 			my $pattern=$key;
1.156     www      7728:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7729:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7730:                         $pattern=~s/\//\\\//g;
1.152     www      7731:                         if ($orguri=~/$pattern/) {
1.800     albertel 7732: 			    $refuri=$env{$key};
1.148     www      7733:                         }
                   7734:                     }
1.191     harris41 7735:                 }
1.148     www      7736:             }
1.232     www      7737: 
1.148     www      7738:          if ($refuri) { 
1.152     www      7739: 	  $refuri=&declutter($refuri);
1.232     www      7740:           my ($match,$cond)=&is_on_map($refuri);
                   7741:             if ($match) {
                   7742:               my $refstatecond=$cond;
1.620     albertel 7743:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7744:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7745:                   my $value = $1;
                   7746:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7747:                       if ($noblockcheck) {
1.1162    raeburn  7748:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7749:                       } else {
                   7750:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7751:                           if (@blockers > 0) {
                   7752:                               $thisallowed = 'B';
                   7753:                           } else {
                   7754:                               $thisallowed.=$value;
                   7755:                           }
1.1162    raeburn  7756:                       }
                   7757:                   } else {
                   7758:                       $thisallowed.=$value;
                   7759:                   }
1.53      www      7760:                   $uri=$refuri;
                   7761:                   $statecond=$refstatecond;
1.52      www      7762:               }
                   7763:           }
1.148     www      7764:         }
1.29      www      7765:        }
1.52      www      7766:    }
1.29      www      7767: 
1.52      www      7768: #
1.103     harris41 7769: # Gathered now: all privileges that could apply, and condition number
1.52      www      7770: # 
                   7771: #
                   7772: # Full or no access?
                   7773: #
1.29      www      7774: 
1.52      www      7775:     if ($thisallowed=~/F/) {
                   7776: 	return 'F';
                   7777:     }
1.29      www      7778: 
1.52      www      7779:     unless ($thisallowed) {
                   7780:         return '';
                   7781:     }
1.29      www      7782: 
1.52      www      7783: # Restrictions exist, deal with them
                   7784: #
                   7785: #   C:according to course preferences
                   7786: #   R:according to resource settings
                   7787: #   L:unless locked
                   7788: #   X:according to user session state
                   7789: #
                   7790: 
                   7791: # Possibly locked functionality, check all courses
1.54      www      7792: # Locks might take effect only after 10 minutes cache expiration for other
                   7793: # courses, and 2 minutes for current course
1.52      www      7794: 
                   7795:     my $envkey;
                   7796:     if ($thisallowed=~/L/) {
1.1000    raeburn  7797:         foreach $envkey (keys(%env)) {
1.54      www      7798:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7799:                my $courseid=$2;
                   7800:                my $roleid=$1.'.'.$2;
1.92      www      7801:                $courseid=~s/^\///;
1.54      www      7802:                my $expiretime=600;
1.620     albertel 7803:                if ($env{'request.role'} eq $roleid) {
1.54      www      7804: 		  $expiretime=120;
                   7805:                }
                   7806: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7807:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7808:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7809: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7810:                }
1.620     albertel 7811:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7812:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7813: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7814:                        &log($env{'user.domain'},$env{'user.name'},
                   7815:                             $env{'user.home'},
1.57      www      7816:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7817:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7818:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7819: 		       return '';
                   7820:                    }
                   7821:                }
1.620     albertel 7822:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7823:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7824: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7825:                        &log($env{'user.domain'},$env{'user.name'},
                   7826:                             $env{'user.home'},
1.57      www      7827:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7828:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7829:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7830: 		       return '';
                   7831:                    }
                   7832:                }
                   7833: 	   }
1.29      www      7834:        }
1.52      www      7835:     }
                   7836:    
                   7837: #
                   7838: # Rest of the restrictions depend on selected course
                   7839: #
                   7840: 
1.620     albertel 7841:     unless ($env{'request.course.id'}) {
1.766     albertel 7842: 	if ($thisallowed eq 'A') {
                   7843: 	    return 'A';
1.814     raeburn  7844:         } elsif ($thisallowed eq 'B') {
                   7845:             return 'B';
1.766     albertel 7846: 	} else {
                   7847: 	    return '1';
                   7848: 	}
1.52      www      7849:     }
1.29      www      7850: 
1.52      www      7851: #
                   7852: # Now user is definitely in a course
                   7853: #
1.53      www      7854: 
                   7855: 
                   7856: # Course preferences
                   7857: 
                   7858:    if ($thisallowed=~/C/) {
1.620     albertel 7859:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7860:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7861:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7862: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7863: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7864: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7865: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7866: 			$env{'request.course.id'});
                   7867: 	   }
1.237     www      7868:            return '';
                   7869:        }
                   7870: 
1.620     albertel 7871:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7872: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7873: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7874: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7875: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7876: 			$env{'request.course.id'});
                   7877: 	   }
1.54      www      7878:            return '';
                   7879:        }
1.53      www      7880:    }
                   7881: 
                   7882: # Resource preferences
                   7883: 
                   7884:    if ($thisallowed=~/R/) {
1.620     albertel 7885:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7886:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7887: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7888: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7889: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7890: 	   }
                   7891: 	   return '';
1.54      www      7892:        }
1.53      www      7893:    }
1.30      www      7894: 
1.246     www      7895: # Restricted by state or randomout?
1.30      www      7896: 
1.52      www      7897:    if ($thisallowed=~/X/) {
1.620     albertel 7898:       if ($env{'acc.randomout'}) {
1.579     albertel 7899: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7900:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7901:             return ''; 
                   7902:          }
1.247     www      7903:       }
                   7904:       if (&condval($statecond)) {
1.52      www      7905: 	 return '2';
                   7906:       } else {
                   7907:          return '';
                   7908:       }
                   7909:    }
1.30      www      7910: 
1.766     albertel 7911:     if ($thisallowed eq 'A') {
                   7912: 	return 'A';
1.814     raeburn  7913:     } elsif ($thisallowed eq 'B') {
                   7914:         return 'B';
1.766     albertel 7915:     }
1.52      www      7916:    return 'F';
1.232     www      7917: }
1.1162    raeburn  7918: 
1.1172.2.13  raeburn  7919: # ------------------------------------------- Check construction space access
                   7920: 
                   7921: sub constructaccess {
                   7922:     my ($url,$setpriv)=@_;
                   7923: 
                   7924: # We do not allow editing of previous versions of files
                   7925:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7926: 
                   7927: # Get username and domain from URL
                   7928:     my ($ownername,$ownerdomain,$ownerhome);
                   7929: 
                   7930:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  7931:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  7932: 
                   7933: # The URL does not really point to any authorspace, forget it
                   7934:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7935: 
                   7936: # Now we need to see if the user has access to the authorspace of
                   7937: # $ownername at $ownerdomain
                   7938: 
                   7939:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7940: # Real author for this?
                   7941:        $ownerhome = $env{'user.home'};
                   7942:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7943:           return ($ownername,$ownerdomain,$ownerhome);
                   7944:        }
                   7945:     } else {
                   7946: # Co-author for this?
                   7947:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7948:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7949:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7950:             return ($ownername,$ownerdomain,$ownerhome);
                   7951:         }
                   7952:     }
                   7953: 
                   7954: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7955: # we might as well leave
                   7956:    unless ($setpriv) { return ''; }
                   7957: 
                   7958: # Backdoor access?
                   7959:     my $allowed=&allowed('eco',$ownerdomain);
                   7960: # Nope
                   7961:     unless ($allowed) { return ''; }
                   7962: # Looks like we may have access, but could be locked by the owner of the construction space
                   7963:     if ($allowed eq 'U') {
                   7964:         my %blocked=&get('environment',['domcoord.author'],
                   7965:                          $ownerdomain,$ownername);
                   7966: # Is blocked by owner
                   7967:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7968:     }
                   7969:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7970: # Grant temporary access
                   7971:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7972:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7973:         if (!$update) { $update = $then; }
                   7974:         my $refresh=$env{'user.refresh.time'};
                   7975:         if (!$refresh) { $refresh = $update; }
                   7976:         my $now = time;
                   7977:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7978:                            $now,'ca','constructaccess');
                   7979:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7980:         return($ownername,$ownerdomain,$ownerhome);
                   7981:     }
                   7982: # No business here
                   7983:     return '';
                   7984: }
                   7985: 
1.1172.2.66  raeburn  7986: # ----------------------------------------------------------- Content Blocking
                   7987: 
                   7988: {
                   7989: # Caches for faster Course Contents display where content blocking
                   7990: # is in operation (i.e., interval param set) for timed quiz.
                   7991: #
                   7992: # User for whom data are being temporarily cached.
                   7993: my $cacheduser='';
                   7994: # Cached blockers for this user (a hash of blocking items).
                   7995: my %cachedblockers=();
                   7996: # When the data were last cached.
                   7997: my $cachedlast='';
                   7998: 
                   7999: sub load_all_blockers {
                   8000:     my ($uname,$udom,$blocks)=@_;
                   8001:     if (($uname ne '') && ($udom ne '')) {
                   8002:         if (($cacheduser eq $uname.':'.$udom) &&
                   8003:             (abs($cachedlast-time)<5)) {
                   8004:             return;
                   8005:         }
                   8006:     }
                   8007:     $cachedlast=time;
                   8008:     $cacheduser=$uname.':'.$udom;
                   8009:     %cachedblockers = &get_commblock_resources($blocks);
                   8010: }
                   8011: 
1.1162    raeburn  8012: sub get_comm_blocks {
                   8013:     my ($cdom,$cnum) = @_;
                   8014:     if ($cdom eq '' || $cnum eq '') {
                   8015:         return unless ($env{'request.course.id'});
                   8016:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8017:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8018:     }
                   8019:     my %commblocks;
                   8020:     my $hashid=$cdom.'_'.$cnum;
                   8021:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8022:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8023:         %commblocks = %{$blocksref};
                   8024:     } else {
                   8025:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8026:         my $cachetime = 600;
                   8027:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8028:     }
                   8029:     return %commblocks;
                   8030: }
                   8031: 
1.1172.2.66  raeburn  8032: sub get_commblock_resources {
                   8033:     my ($blocks) = @_;
                   8034:     my %blockers = ();
                   8035:     return %blockers unless ($env{'request.course.id'});
                   8036:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8037:     my %commblocks;
                   8038:     if (ref($blocks) eq 'HASH') {
                   8039:         %commblocks = %{$blocks};
                   8040:     } else {
                   8041:         %commblocks = &get_comm_blocks();
                   8042:     }
1.1172.2.66  raeburn  8043:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8044:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8045:     return %blockers unless (ref($navmap));
                   8046:     my $now = time;
1.1162    raeburn  8047:     foreach my $block (keys(%commblocks)) {
                   8048:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8049:             my ($start,$end) = ($1,$2);
                   8050:             if ($start <= $now && $end >= $now) {
                   8051:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8052:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8053:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8054:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8055:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8056:                             }
                   8057:                         }
                   8058:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8059:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8060:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8061:                             }
                   8062:                         }
                   8063:                     }
                   8064:                 }
                   8065:             }
                   8066:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8067:             my $item = $1;
1.1163    raeburn  8068:             my @to_test;
1.1162    raeburn  8069:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8070:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8071:                     my @interval;
                   8072:                     my $type = 'map';
                   8073:                     if ($item eq 'course') {
                   8074:                         $type = 'course';
                   8075:                         @interval=&EXT("resource.0.interval");
                   8076:                     } else {
                   8077:                         if ($item =~ /___\d+___/) {
                   8078:                             $type = 'resource';
                   8079:                             @interval=&EXT("resource.0.interval",$item);
                   8080:                             if (ref($navmap)) {
                   8081:                                 my $res = $navmap->getBySymb($item);
                   8082:                                 push(@to_test,$res);
                   8083:                             }
1.1162    raeburn  8084:                         } else {
1.1172.2.66  raeburn  8085:                             my $mapsymb = &symbread($item,1);
                   8086:                             if ($mapsymb) {
                   8087:                                 if (ref($navmap)) {
                   8088:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8089:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8090:                                     foreach my $res (@to_test) {
                   8091:                                         my $symb = $res->symb();
                   8092:                                         next if ($symb eq $mapsymb);
                   8093:                                         if ($symb ne '') {
                   8094:                                             @interval=&EXT("resource.0.interval",$symb);
                   8095:                                             if ($interval[1] eq 'map') {
                   8096:                                                 last;
1.1162    raeburn  8097:                                             }
                   8098:                                         }
                   8099:                                     }
                   8100:                                 }
                   8101:                             }
                   8102:                         }
1.1172.2.66  raeburn  8103:                     }
1.1172.2.93.4  1(raebur 8104:7):                     if ($interval[0] =~ /^(\d+)/) {
                   8105:7):                         my $timelimit = $1;
1.1172.2.66  raeburn  8106:                         my $first_access;
                   8107:                         if ($type eq 'resource') {
                   8108:                             $first_access=&get_first_access($interval[1],$item);
                   8109:                         } elsif ($type eq 'map') {
                   8110:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8111:                         } else {
                   8112:                             $first_access=&get_first_access($interval[1]);
                   8113:                         }
                   8114:                         if ($first_access) {
1.1172.2.93.4  1(raebur 8115:7):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8116:                             if ($timesup > $now) {
                   8117:                                 my $activeblock;
                   8118:                                 foreach my $res (@to_test) {
                   8119:                                     if ($res->answerable()) {
                   8120:                                         $activeblock = 1;
                   8121:                                         last;
                   8122:                                     }
                   8123:                                 }
                   8124:                                 if ($activeblock) {
                   8125:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8126:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8127:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8128:                                          }
                   8129:                                     }
                   8130:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8131:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8132:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8133:                                         }
1.1162    raeburn  8134:                                     }
                   8135:                                 }
                   8136:                             }
                   8137:                         }
                   8138:                     }
                   8139:                 }
                   8140:             }
                   8141:         }
                   8142:     }
1.1172.2.66  raeburn  8143:     return %blockers;
1.1162    raeburn  8144: }
                   8145: 
1.1172.2.66  raeburn  8146: sub has_comm_blocking {
                   8147:     my ($priv,$symb,$uri,$blocks) = @_;
                   8148:     my @blockers;
                   8149:     return unless ($env{'request.course.id'});
                   8150:     return unless ($priv eq 'bre');
                   8151:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8152:     return if ($env{'request.state'} eq 'construct');
                   8153:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8154:     return unless (keys(%cachedblockers) > 0);
                   8155:     my (%possibles,@symbs);
                   8156:     if (!$symb) {
                   8157:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8158:     }
1.1172.2.66  raeburn  8159:     if ($symb) {
                   8160:         @symbs = ($symb);
                   8161:     } elsif (keys(%possibles)) {
                   8162:         @symbs = keys(%possibles);
                   8163:     }
                   8164:     my $noblock;
                   8165:     foreach my $symb (@symbs) {
                   8166:         last if ($noblock);
                   8167:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8168:         foreach my $block (keys(%cachedblockers)) {
                   8169:             if ($block =~ /^firstaccess____(.+)$/) {
                   8170:                 my $item = $1;
                   8171:                 if (($item eq $map) || ($item eq $symb)) {
                   8172:                     $noblock = 1;
                   8173:                     last;
                   8174:                 }
1.1162    raeburn  8175:             }
1.1172.2.66  raeburn  8176:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8177:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8178:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8179:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8180:                             push(@blockers,$block);
                   8181:                         }
                   8182:                     }
                   8183:                 }
                   8184:             }
                   8185:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8186:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8187:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8188:                         push(@blockers,$block);
                   8189:                     }
                   8190:                 }
1.1162    raeburn  8191:             }
                   8192:         }
                   8193:     }
1.1172.2.66  raeburn  8194:     return if ($noblock);
                   8195:     return @blockers;
                   8196: }
1.1162    raeburn  8197: }
                   8198: 
1.1172.2.66  raeburn  8199: # -------------------------------- Deversion and split uri into path an filename
                   8200: 
1.1133    foxr     8201: #
1.1172.2.66  raeburn  8202: #   Removes the version from a URI and
1.1133    foxr     8203: #   splits it in to its filename and path to the filename.
                   8204: #   Seems like File::Basename could have done this more clearly.
                   8205: #   Parameters:
                   8206: #      $uri   - input URI
                   8207: #   Returns:
                   8208: #     Two element list consisting of 
                   8209: #     $pathname  - the URI up to and excluding the trailing /
                   8210: #     $filename  - The part of the URI following the last /
                   8211: #  NOTE:
                   8212: #    Another realization of this is simply:
                   8213: #    use File::Basename;
                   8214: #    ...
                   8215: #    $uri = shift;
                   8216: #    $filename = basename($uri);
                   8217: #    $path     = dirname($uri);
                   8218: #    return ($filename, $path);
                   8219: #
                   8220: #     The implementation below is probably faster however.
                   8221: #
1.710     albertel 8222: sub split_uri_for_cond {
                   8223:     my $uri=&deversion(&declutter(shift));
                   8224:     my @uriparts=split(/\//,$uri);
                   8225:     my $filename=pop(@uriparts);
                   8226:     my $pathname=join('/',@uriparts);
                   8227:     return ($pathname,$filename);
                   8228: }
1.232     www      8229: # --------------------------------------------------- Is a resource on the map?
                   8230: 
                   8231: sub is_on_map {
1.710     albertel 8232:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8233:     #Trying to find the conditional for the file
1.620     albertel 8234:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8235: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8236:     if ($match) {
1.289     bowersj2 8237: 	return (1,$1);
                   8238:     } else {
1.434     www      8239: 	return (0,0);
1.289     bowersj2 8240:     }
1.12      www      8241: }
                   8242: 
1.427     www      8243: # --------------------------------------------------------- Get symb from alias
                   8244: 
                   8245: sub get_symb_from_alias {
                   8246:     my $symb=shift;
                   8247:     my ($map,$resid,$url)=&decode_symb($symb);
                   8248: # Already is a symb
                   8249:     if ($url) { return $symb; }
                   8250: # Must be an alias
                   8251:     my $aliassymb='';
                   8252:     my %bighash;
1.620     albertel 8253:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8254:                             &GDBM_READER(),0640)) {
                   8255:         my $rid=$bighash{'mapalias_'.$symb};
                   8256: 	if ($rid) {
                   8257: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8258: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8259: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8260: 	}
                   8261:         untie %bighash;
                   8262:     }
                   8263:     return $aliassymb;
                   8264: }
                   8265: 
1.12      www      8266: # ----------------------------------------------------------------- Define Role
                   8267: 
                   8268: sub definerole {
                   8269:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8270:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8271:     foreach my $role (split(':',$sysrole)) {
                   8272: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8273:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8274:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8275: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8276:                return "refused:s:$crole&$cqual"; 
                   8277:             }
                   8278:         }
1.191     harris41 8279:     }
1.800     albertel 8280:     foreach my $role (split(':',$domrole)) {
                   8281: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8282:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8283:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8284: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8285:                return "refused:d:$crole&$cqual"; 
                   8286:             }
                   8287:         }
1.191     harris41 8288:     }
1.800     albertel 8289:     foreach my $role (split(':',$courole)) {
                   8290: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8291:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8292:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8293: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8294:                return "refused:c:$crole&$cqual"; 
                   8295:             }
                   8296:         }
1.191     harris41 8297:     }
1.1172.2.84  raeburn  8298:     my $uhome;
                   8299:     if (($uname ne '') && ($udom ne '')) {
                   8300:         $uhome = &homeserver($uname,$udom);
                   8301:         return $uhome if ($uhome eq 'no_host');
                   8302:     } else {
                   8303:         $uname = $env{'user.name'};
                   8304:         $udom = $env{'user.domain'};
                   8305:         $uhome = $env{'user.home'};
                   8306:     }
1.620     albertel 8307:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8308:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8309:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8310:     return reply($command,$uhome);
1.12      www      8311:   } else {
                   8312:     return 'refused';
                   8313:   }
1.105     harris41 8314: }
                   8315: 
                   8316: # ---------------- Make a metadata query against the network of library servers
                   8317: 
                   8318: sub metadata_query {
1.1172.2.33  raeburn  8319:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8320:     my %rhash;
1.845     albertel 8321:     my %libserv = &all_library();
1.244     matthew  8322:     my @server_list = (defined($server_array) ? @$server_array
                   8323:                                               : keys(%libserv) );
                   8324:     for my $server (@server_list) {
1.1172.2.33  raeburn  8325:         my $domains = '';
                   8326:         if (ref($domains_hash) eq 'HASH') {
                   8327:             $domains = $domains_hash->{$server};    
                   8328:         }
1.118     harris41 8329: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8330: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8331: 	    $rhash{$server}=$reply;
                   8332: 	}
                   8333: 	else {
                   8334: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8335: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8336: 			     $server);
                   8337: 	    $rhash{$server}=$reply;
                   8338: 	}
1.112     harris41 8339:     }
1.118     harris41 8340:     return \%rhash;
1.240     www      8341: }
                   8342: 
                   8343: # ----------------------------------------- Send log queries and wait for reply
                   8344: 
                   8345: sub log_query {
                   8346:     my ($uname,$udom,$query,%filters)=@_;
                   8347:     my $uhome=&homeserver($uname,$udom);
                   8348:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8349:     my $uhost=&hostname($uhome);
1.800     albertel 8350:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8351:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8352:                        $uhome);
1.479     albertel 8353:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8354:     return get_query_reply($queryid);
                   8355: }
                   8356: 
1.818     raeburn  8357: # -------------------------- Update MySQL table for portfolio file
                   8358: 
                   8359: sub update_portfolio_table {
1.821     raeburn  8360:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8361:     if ($group ne '') {
                   8362:         $file_name =~s /^\Q$group\E//;
                   8363:     }
1.818     raeburn  8364:     my $homeserver = &homeserver($uname,$udom);
                   8365:     my $queryid=
1.821     raeburn  8366:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8367:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8368:     my $reply = &get_query_reply($queryid);
                   8369:     return $reply;
                   8370: }
                   8371: 
1.899     raeburn  8372: # -------------------------- Update MySQL allusers table
                   8373: 
                   8374: sub update_allusers_table {
                   8375:     my ($uname,$udom,$names) = @_;
                   8376:     my $homeserver = &homeserver($uname,$udom);
                   8377:     my $queryid=
                   8378:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8379:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8380:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8381:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8382:                'generation='.&escape($names->{'generation'}).'%%'.
                   8383:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8384:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8385:     return;
1.899     raeburn  8386: }
                   8387: 
1.508     raeburn  8388: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8389: 
                   8390: sub fetch_enrollment_query {
1.511     raeburn  8391:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8392:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8393:     my $maxtries = 1;
1.508     raeburn  8394:     if ($context eq 'automated') {
                   8395:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8396:         $sleep = 2;
                   8397:         $loopmax = 100;
1.547     raeburn  8398:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8399:     } else {
                   8400:         $homeserver = &homeserver($cnum,$dom);
                   8401:     }
1.838     albertel 8402:     my $host=&hostname($homeserver);
1.506     raeburn  8403:     my $cmd = '';
1.1000    raeburn  8404:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8405:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8406:     }
                   8407:     $cmd =~ s/%%$//;
                   8408:     $cmd = &escape($cmd);
                   8409:     my $query = 'fetchenrollment';
1.620     albertel 8410:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8411:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8412:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8413:         return 'error: '.$queryid;
                   8414:     }
1.1172.2.93  raeburn  8415:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8416:     my $tries = 1;
                   8417:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8418:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8419:         $tries ++;
                   8420:     }
1.526     raeburn  8421:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8422:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8423:     } else {
1.901     albertel 8424:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8425:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8426:             foreach my $line (@responses) {
                   8427:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8428:                 $$replyref{$key} = $value;
                   8429:             }
                   8430:         } else {
1.1117    foxr     8431:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8432:             foreach my $line (@responses) {
                   8433:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8434:                 $$replyref{$key} = $value;
                   8435:                 if ($value > 0) {
1.800     albertel 8436:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8437:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8438:                         my $destname = $pathname.'/'.$filename;
                   8439:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8440:                         if ($xml_classlist =~ /^error/) {
                   8441:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8442:                         } else {
1.1172.2.93.4  7(raebur 8443:7):                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8444:                                 print FILE &unescape($xml_classlist);
                   8445:                                 close(FILE);
1.526     raeburn  8446:                             } else {
                   8447:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8448:                             }
                   8449:                         }
                   8450:                     }
                   8451:                 }
                   8452:             }
                   8453:         }
                   8454:         return 'ok';
                   8455:     }
                   8456:     return 'error';
                   8457: }
                   8458: 
1.242     www      8459: sub get_query_reply {
1.1172.2.79  raeburn  8460:     my ($queryid,$sleep,$loopmax) = @_;
                   8461:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8462:         $sleep = 0.2;
                   8463:     }
                   8464:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8465:         $loopmax = 100;
                   8466:     }
1.1117    foxr     8467:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8468:     my $reply='';
1.1172.2.79  raeburn  8469:     for (1..$loopmax) {
                   8470: 	sleep($sleep);
1.240     www      8471:         if (-e $replyfile.'.end') {
1.1172.2.93.4  7(raebur 8472:7): 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8473: 		$reply = join('',<$fh>);
                   8474: 		close($fh);
1.240     www      8475: 	   } else { return 'error: reply_file_error'; }
1.242     www      8476:            return &unescape($reply);
                   8477: 	}
1.240     www      8478:     }
1.242     www      8479:     return 'timeout:'.$queryid;
1.240     www      8480: }
                   8481: 
                   8482: sub courselog_query {
1.241     www      8483: #
                   8484: # possible filters:
                   8485: # url: url or symb
                   8486: # username
                   8487: # domain
                   8488: # action: view, submit, grade
                   8489: # start: timestamp
                   8490: # end: timestamp
                   8491: #
1.240     www      8492:     my (%filters)=@_;
1.620     albertel 8493:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8494:     if ($filters{'url'}) {
                   8495: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8496:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8497:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8498:     }
1.620     albertel 8499:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8500:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8501:     return &log_query($cname,$cdom,'courselog',%filters);
                   8502: }
                   8503: 
                   8504: sub userlog_query {
1.858     raeburn  8505: #
                   8506: # possible filters:
                   8507: # action: log check role
                   8508: # start: timestamp
                   8509: # end: timestamp
                   8510: #
1.240     www      8511:     my ($uname,$udom,%filters)=@_;
                   8512:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8513: }
                   8514: 
1.506     raeburn  8515: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8516: 
                   8517: sub auto_run {
1.508     raeburn  8518:     my ($cnum,$cdom) = @_;
1.876     raeburn  8519:     my $response = 0;
                   8520:     my $settings;
                   8521:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8522:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8523:         $settings = $domconfig{'autoenroll'};
                   8524:         if ($settings->{'run'} eq '1') {
                   8525:             $response = 1;
                   8526:         }
                   8527:     } else {
1.934     raeburn  8528:         my $homeserver;
                   8529:         if (&is_course($cdom,$cnum)) {
                   8530:             $homeserver = &homeserver($cnum,$cdom);
                   8531:         } else {
                   8532:             $homeserver = &domain($cdom,'primary');
                   8533:         }
                   8534:         if ($homeserver ne 'no_host') {
                   8535:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8536:         }
1.876     raeburn  8537:     }
1.506     raeburn  8538:     return $response;
                   8539: }
1.776     albertel 8540: 
1.506     raeburn  8541: sub auto_get_sections {
1.508     raeburn  8542:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8543:     my $homeserver;
                   8544:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8545:         $homeserver = &homeserver($cnum,$cdom);
                   8546:     }
                   8547:     if (!defined($homeserver)) { 
                   8548:         if ($cdom =~ /^$match_domain$/) {
                   8549:             $homeserver = &domain($cdom,'primary');
                   8550:         }
                   8551:     }
                   8552:     my @secs;
                   8553:     if (defined($homeserver)) {
                   8554:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8555:         unless ($response eq 'refused') {
                   8556:             @secs = split(/:/,$response);
                   8557:         }
1.506     raeburn  8558:     }
                   8559:     return @secs;
                   8560: }
1.776     albertel 8561: 
1.506     raeburn  8562: sub auto_new_course {
1.1099    raeburn  8563:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8564:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8565:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8566:     return $response;
                   8567: }
1.776     albertel 8568: 
1.506     raeburn  8569: sub auto_validate_courseID {
1.508     raeburn  8570:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8571:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8572:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8573:     return $response;
                   8574: }
1.776     albertel 8575: 
1.1007    raeburn  8576: sub auto_validate_instcode {
1.1020    raeburn  8577:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8578:     my ($homeserver,$response);
                   8579:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8580:         $homeserver = &homeserver($cnum,$cdom);
                   8581:     }
                   8582:     if (!defined($homeserver)) {
                   8583:         if ($cdom =~ /^$match_domain$/) {
                   8584:             $homeserver = &domain($cdom,'primary');
                   8585:         }
                   8586:     }
1.1065    raeburn  8587:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8588:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8589:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8590:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8591: }
                   8592: 
1.506     raeburn  8593: sub auto_create_password {
1.873     raeburn  8594:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8595:     my ($homeserver,$response);
1.506     raeburn  8596:     my $create_passwd = 0;
                   8597:     my $authchk = '';
1.873     raeburn  8598:     if ($udom =~ /^$match_domain$/) {
                   8599:         $homeserver = &domain($udom,'primary');
                   8600:     }
                   8601:     if ($homeserver eq '') {
                   8602:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8603:             $homeserver = &homeserver($cnum,$cdom);
                   8604:         }
                   8605:     }
                   8606:     if ($homeserver eq '') {
                   8607:         $authchk = 'nodomain';
1.506     raeburn  8608:     } else {
1.873     raeburn  8609:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8610:         if ($response eq 'refused') {
                   8611:             $authchk = 'refused';
                   8612:         } else {
1.901     albertel 8613:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8614:         }
1.506     raeburn  8615:     }
                   8616:     return ($authparam,$create_passwd,$authchk);
                   8617: }
                   8618: 
1.706     raeburn  8619: sub auto_photo_permission {
                   8620:     my ($cnum,$cdom,$students) = @_;
                   8621:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8622:     my ($outcome,$perm_reqd,$conditions) = 
                   8623: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8624:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8625: 	return (undef,undef);
                   8626:     }
1.706     raeburn  8627:     return ($outcome,$perm_reqd,$conditions);
                   8628: }
                   8629: 
                   8630: sub auto_checkphotos {
                   8631:     my ($uname,$udom,$pid) = @_;
                   8632:     my $homeserver = &homeserver($uname,$udom);
                   8633:     my ($result,$resulttype);
                   8634:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8635: 				   &escape($uname).':'.&escape($pid),
                   8636: 				   $homeserver));
1.709     albertel 8637:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8638: 	return (undef,undef);
                   8639:     }
1.706     raeburn  8640:     if ($outcome) {
                   8641:         ($result,$resulttype) = split(/:/,$outcome);
                   8642:     } 
                   8643:     return ($result,$resulttype);
                   8644: }
                   8645: 
                   8646: sub auto_photochoice {
                   8647:     my ($cnum,$cdom) = @_;
                   8648:     my $homeserver = &homeserver($cnum,$cdom);
                   8649:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8650: 						       &escape($cdom),
                   8651: 						       $homeserver)));
1.709     albertel 8652:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8653: 	return (undef,undef);
                   8654:     }
1.706     raeburn  8655:     return ($update,$comment);
                   8656: }
                   8657: 
                   8658: sub auto_photoupdate {
                   8659:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8660:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8661:     my $host=&hostname($homeserver);
1.706     raeburn  8662:     my $cmd = '';
                   8663:     my $maxtries = 1;
1.800     albertel 8664:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8665:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8666:     }
                   8667:     $cmd =~ s/%%$//;
                   8668:     $cmd = &escape($cmd);
                   8669:     my $query = 'institutionalphotos';
                   8670:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8671:     unless ($queryid=~/^\Q$host\E\_/) {
                   8672:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8673:         return 'error: '.$queryid;
                   8674:     }
                   8675:     my $reply = &get_query_reply($queryid);
                   8676:     my $tries = 1;
                   8677:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8678:         $reply = &get_query_reply($queryid);
                   8679:         $tries ++;
                   8680:     }
                   8681:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8682:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8683:     } else {
                   8684:         my @responses = split(/:/,$reply);
                   8685:         my $outcome = shift(@responses); 
                   8686:         foreach my $item (@responses) {
                   8687:             my ($key,$value) = split(/=/,$item);
                   8688:             $$photo{$key} = $value;
                   8689:         }
                   8690:         return $outcome;
                   8691:     }
                   8692:     return 'error';
                   8693: }
                   8694: 
1.521     raeburn  8695: sub auto_instcode_format {
1.793     albertel 8696:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8697: 	$cat_order) = @_;
1.521     raeburn  8698:     my $courses = '';
1.772     raeburn  8699:     my @homeservers;
1.521     raeburn  8700:     if ($caller eq 'global') {
1.841     albertel 8701: 	my %servers = &get_servers($codedom,'library');
                   8702: 	foreach my $tryserver (keys(%servers)) {
                   8703: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8704: 		push(@homeservers,$tryserver);
                   8705: 	    }
1.584     raeburn  8706:         }
1.1022    raeburn  8707:     } elsif ($caller eq 'requests') {
                   8708:         if ($codedom =~ /^$match_domain$/) {
                   8709:             my $chome = &domain($codedom,'primary');
                   8710:             unless ($chome eq 'no_host') {
                   8711:                 push(@homeservers,$chome);
                   8712:             }
                   8713:         }
1.521     raeburn  8714:     } else {
1.772     raeburn  8715:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8716:     }
1.793     albertel 8717:     foreach my $code (keys(%{$instcodes})) {
                   8718:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8719:     }
                   8720:     chop($courses);
1.772     raeburn  8721:     my $ok_response = 0;
                   8722:     my $response;
                   8723:     while (@homeservers > 0 && $ok_response == 0) {
                   8724:         my $server = shift(@homeservers); 
                   8725:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8726:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8727:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8728: 		split(/:/,$response);
1.772     raeburn  8729:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8730:             push(@{$codetitles},&str2array($codetitles_str));
                   8731:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8732:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8733:             $ok_response = 1;
                   8734:         }
                   8735:     }
                   8736:     if ($ok_response) {
1.521     raeburn  8737:         return 'ok';
1.772     raeburn  8738:     } else {
                   8739:         return $response;
1.521     raeburn  8740:     }
                   8741: }
                   8742: 
1.792     raeburn  8743: sub auto_instcode_defaults {
                   8744:     my ($domain,$returnhash,$code_order) = @_;
                   8745:     my @homeservers;
1.841     albertel 8746: 
                   8747:     my %servers = &get_servers($domain,'library');
                   8748:     foreach my $tryserver (keys(%servers)) {
                   8749: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8750: 	    push(@homeservers,$tryserver);
                   8751: 	}
1.792     raeburn  8752:     }
1.841     albertel 8753: 
1.792     raeburn  8754:     my $response;
1.841     albertel 8755:     foreach my $server (@homeservers) {
1.792     raeburn  8756:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8757:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8758: 	
                   8759: 	foreach my $pair (split(/\&/,$response)) {
                   8760: 	    my ($name,$value)=split(/\=/,$pair);
                   8761: 	    if ($name eq 'code_order') {
                   8762: 		@{$code_order} = split(/\&/,&unescape($value));
                   8763: 	    } else {
                   8764: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8765: 	    }
                   8766: 	}
                   8767: 	return 'ok';
1.792     raeburn  8768:     }
1.841     albertel 8769: 
                   8770:     return $response;
1.1003    raeburn  8771: }
                   8772: 
                   8773: sub auto_possible_instcodes {
1.1007    raeburn  8774:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8775:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8776:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8777:         return;
                   8778:     }
1.1003    raeburn  8779:     my (@homeservers,$uhome);
                   8780:     if (defined(&domain($domain,'primary'))) {
                   8781:         $uhome=&domain($domain,'primary');
                   8782:         push(@homeservers,&domain($domain,'primary'));
                   8783:     } else {
                   8784:         my %servers = &get_servers($domain,'library');
                   8785:         foreach my $tryserver (keys(%servers)) {
                   8786:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8787:                 push(@homeservers,$tryserver);
                   8788:             }
                   8789:         }
                   8790:     }
                   8791:     my $response;
                   8792:     foreach my $server (@homeservers) {
                   8793:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8794:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8795:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8796:             split(':',$response);
                   8797:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8798:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8799:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8800:             my ($name,$value)=split('=',$item);
                   8801:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8802:         }
                   8803:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8804:             my ($name,$value)=split('=',$item);
                   8805:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8806:         }
                   8807:         return 'ok';
                   8808:     }
                   8809:     return $response;
                   8810: }
1.792     raeburn  8811: 
1.1010    raeburn  8812: sub auto_courserequest_checks {
                   8813:     my ($dom) = @_;
1.1020    raeburn  8814:     my ($homeserver,%validations);
                   8815:     if ($dom =~ /^$match_domain$/) {
                   8816:         $homeserver = &domain($dom,'primary');
                   8817:     }
                   8818:     unless ($homeserver eq 'no_host') {
                   8819:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8820:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8821:             my @items = split(/&/,$response);
                   8822:             foreach my $item (@items) {
                   8823:                 my ($key,$value) = split('=',$item);
                   8824:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8825:             }
                   8826:         }
                   8827:     }
1.1010    raeburn  8828:     return %validations; 
                   8829: }
                   8830: 
1.1020    raeburn  8831: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8832:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8833:     my ($homeserver,$response);
                   8834:     if ($dom =~ /^$match_domain$/) {
                   8835:         $homeserver = &domain($dom,'primary');
                   8836:     }
1.1172.2.43  raeburn  8837:     unless ($homeserver eq 'no_host') {
                   8838:         my $customdata;
                   8839:         if (ref($custominfo) eq 'HASH') {
                   8840:             $customdata = &freeze_escape($custominfo);
                   8841:         }
1.1020    raeburn  8842:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8843:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8844:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8845:                                     $customdata,$homeserver));
1.1020    raeburn  8846:     }
                   8847:     return $response;
                   8848: }
                   8849: 
1.777     albertel 8850: sub auto_validate_class_sec {
1.918     raeburn  8851:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8852:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8853:     my $ownerlist;
                   8854:     if (ref($owners) eq 'ARRAY') {
                   8855:         $ownerlist = join(',',@{$owners});
                   8856:     } else {
                   8857:         $ownerlist = $owners;
                   8858:     }
1.773     raeburn  8859:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8860:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8861:     return $response;
                   8862: }
                   8863: 
1.1172.2.93.4  10(raebu 8864:18): sub auto_validate_instclasses {
                   8865:18):     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8866:18):     my ($homeserver,%validations);
                   8867:18):     $homeserver = &homeserver($cnum,$cdom);
                   8868:18):     unless ($homeserver eq 'no_host') {
                   8869:18):         my $ownerlist;
                   8870:18):         if (ref($owners) eq 'ARRAY') {
                   8871:18):             $ownerlist = join(',',@{$owners});
                   8872:18):         } else {
                   8873:18):             $ownerlist = $owners;
                   8874:18):         }
                   8875:18):         if (ref($classesref) eq 'HASH') {
                   8876:18):             my $classes = &freeze_escape($classesref);
                   8877:18):             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8878:18):                                 ':'.$cdom.':'.$classes,$homeserver);
                   8879:18):             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8880:18):                 my @items = split(/&/,$response);
                   8881:18):                 foreach my $item (@items) {
                   8882:18):                     my ($key,$value) = split('=',$item);
                   8883:18):                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8884:18):                 }
                   8885:18):             }
                   8886:18):         }
                   8887:18):     }
                   8888:18):     return %validations;
                   8889:18): }
                   8890:18): 
1.1172.2.38  raeburn  8891: sub auto_crsreq_update {
                   8892:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8893:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8894:     my ($homeserver,%crsreqresponse);
                   8895:     if ($cdom =~ /^$match_domain$/) {
                   8896:         $homeserver = &domain($cdom,'primary');
                   8897:     }
                   8898:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8899:         my $info;
                   8900:         if (ref($inbound) eq 'HASH') {
                   8901:             $info = &freeze_escape($inbound);
                   8902:         }
                   8903:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8904:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8905:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8906:                             &escape($title).':'.&escape($code).':'.
                   8907:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8908:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8909:             my @items = split(/&/,$response);
                   8910:             foreach my $item (@items) {
                   8911:                 my ($key,$value) = split('=',$item);
                   8912:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8913:             }
                   8914:         }
                   8915:     }
                   8916:     return \%crsreqresponse;
                   8917: }
                   8918: 
1.1172.2.78  raeburn  8919: sub auto_export_grades {
                   8920:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8921:     my ($homeserver,%exportresponse);
                   8922:     if ($cdom =~ /^$match_domain$/) {
                   8923:         $homeserver = &domain($cdom,'primary');
                   8924:     }
                   8925:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8926:         my $info;
                   8927:         if (ref($inforef) eq 'HASH') {
                   8928:             $info = &freeze_escape($inforef);
                   8929:         }
                   8930:         if (ref($gradesref) eq 'HASH') {
                   8931:             my $grades = &freeze_escape($gradesref);
                   8932:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8933:                                 $info.':'.$grades,$homeserver);
                   8934:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8935:                 my @items = split(/&/,$response);
                   8936:                 foreach my $item (@items) {
                   8937:                     my ($key,$value) = split('=',$item);
                   8938:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8939:                 }
                   8940:             }
                   8941:         }
                   8942:     }
                   8943:     return \%exportresponse;
                   8944: }
                   8945: 
1.1172.2.68  raeburn  8946: sub check_instcode_cloning {
                   8947:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8948:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8949:         return;
                   8950:     }
                   8951:     my $canclone;
                   8952:     if (@{$code_order} > 0) {
                   8953:         my $instcoderegexp ='^';
                   8954:         my @clonecodes = split(/\&/,$cloner);
                   8955:         foreach my $item (@{$code_order}) {
                   8956:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8957:                 foreach my $pair (@clonecodes) {
                   8958:                     my ($key,$val) = split(/\=/,$pair,2);
                   8959:                     $val = &unescape($val);
                   8960:                     if ($key eq $item) {
                   8961:                         $instcoderegexp .= '('.$val.')';
                   8962:                         last;
                   8963:                     }
                   8964:                 }
                   8965:             } else {
                   8966:                 $instcoderegexp .= $codedefaults->{$item};
                   8967:             }
                   8968:         }
                   8969:         $instcoderegexp .= '$';
                   8970:         my (@from,@to);
                   8971:         eval {
                   8972:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8973:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8974:         };
                   8975:         if ((@from > 0) && (@to > 0)) {
                   8976:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8977:             if (!@diffs) {
                   8978:                 $canclone = 1;
                   8979:             }
                   8980:         }
                   8981:     }
                   8982:     return $canclone;
                   8983: }
                   8984: 
                   8985: sub default_instcode_cloning {
                   8986:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8987:     my (%codedefaults,@code_order,$canclone);
                   8988:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8989:         %codedefaults = %{$codedefaultsref};
                   8990:         @code_order = @{$codeorderref};
                   8991:     } elsif ($clonedom) {
                   8992:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8993:     }
                   8994:     if (($domdefclone) && (@code_order)) {
                   8995:         my @clonecodes = split(/\+/,$domdefclone);
                   8996:         my $instcoderegexp ='^';
                   8997:         foreach my $item (@code_order) {
                   8998:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8999:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9000:             } else {
                   9001:                 $instcoderegexp .= $codedefaults{$item};
                   9002:             }
                   9003:         }
                   9004:         $instcoderegexp .= '$';
                   9005:         my (@from,@to);
                   9006:         eval {
                   9007:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9008:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9009:         };
                   9010:         if ((@from > 0) && (@to > 0)) {
                   9011:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9012:             if (!@diffs) {
                   9013:                 $canclone = 1;
                   9014:             }
                   9015:         }
                   9016:     }
                   9017:     return $canclone;
                   9018: }
                   9019: 
1.679     raeburn  9020: # ------------------------------------------------------- Course Group routines
                   9021: 
                   9022: sub get_coursegroups {
1.809     raeburn  9023:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9024:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9025: }
                   9026: 
1.679     raeburn  9027: sub modify_coursegroup {
                   9028:     my ($cdom,$cnum,$groupsettings) = @_;
                   9029:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9030: }
                   9031: 
1.809     raeburn  9032: sub toggle_coursegroup_status {
                   9033:     my ($cdom,$cnum,$group,$action) = @_;
                   9034:     my ($from_namespace,$to_namespace);
                   9035:     if ($action eq 'delete') {
                   9036:         $from_namespace = 'coursegroups';
                   9037:         $to_namespace = 'deleted_groups';
                   9038:     } else {
                   9039:         $from_namespace = 'deleted_groups';
                   9040:         $to_namespace = 'coursegroups';
                   9041:     }
                   9042:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9043:     if (my $tmp = &error(%curr_group)) {
                   9044:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9045:         return ('read error',$tmp);
                   9046:     } else {
                   9047:         my %savedsettings = %curr_group; 
1.809     raeburn  9048:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9049:         my $deloutcome;
                   9050:         if ($result eq 'ok') {
1.809     raeburn  9051:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9052:         } else {
                   9053:             return ('write error',$result);
                   9054:         }
                   9055:         if ($deloutcome eq 'ok') {
                   9056:             return 'ok';
                   9057:         } else {
                   9058:             return ('delete error',$deloutcome);
                   9059:         }
                   9060:     }
                   9061: }
                   9062: 
1.679     raeburn  9063: sub modify_group_roles {
1.957     raeburn  9064:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9065:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9066:     my $role = 'gr/'.&escape($userprivs);
                   9067:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9068:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9069:     if ($result eq 'ok') {
                   9070:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9071:     }
1.679     raeburn  9072:     return $result;
                   9073: }
                   9074: 
                   9075: sub modify_coursegroup_membership {
                   9076:     my ($cdom,$cnum,$membership) = @_;
                   9077:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9078:     return $result;
                   9079: }
                   9080: 
1.682     raeburn  9081: sub get_active_groups {
                   9082:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9083:     my $now = time;
                   9084:     my %groups = ();
                   9085:     foreach my $key (keys(%env)) {
1.811     albertel 9086:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9087:             my ($start,$end) = split(/\./,$env{$key});
                   9088:             if (($end!=0) && ($end<$now)) { next; }
                   9089:             if (($start!=0) && ($start>$now)) { next; }
                   9090:             if ($1 eq $cdom && $2 eq $cnum) {
                   9091:                 $groups{$3} = $env{$key} ;
                   9092:             }
                   9093:         }
                   9094:     }
                   9095:     return %groups;
                   9096: }
                   9097: 
1.683     raeburn  9098: sub get_group_membership {
                   9099:     my ($cdom,$cnum,$group) = @_;
                   9100:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9101: }
                   9102: 
                   9103: sub get_users_groups {
                   9104:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9105:     my @usersgroups;
1.683     raeburn  9106:     my $cachetime=1800;
                   9107: 
                   9108:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9109:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9110:     if (defined($cached)) {
1.734     albertel 9111:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9112:     } else {  
                   9113:         $grouplist = '';
1.816     raeburn  9114:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9115:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9116:         my $access_end = $env{'course.'.$courseid.
                   9117:                               '.default_enrollment_end_date'};
                   9118:         my $now = time;
                   9119:         foreach my $key (keys(%roleshash)) {
                   9120:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9121:                 my $group = $1;
                   9122:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9123:                     my $start = $2;
                   9124:                     my $end = $1;
                   9125:                     if ($start == -1) { next; } # deleted from group
                   9126:                     if (($start!=0) && ($start>$now)) { next; }
                   9127:                     if (($end!=0) && ($end<$now)) {
                   9128:                         if ($access_end && $access_end < $now) {
                   9129:                             if ($access_end - $end < 86400) {
                   9130:                                 push(@usersgroups,$group);
1.733     raeburn  9131:                             }
                   9132:                         }
1.817     raeburn  9133:                         next;
1.733     raeburn  9134:                     }
1.817     raeburn  9135:                     push(@usersgroups,$group);
1.683     raeburn  9136:                 }
                   9137:             }
                   9138:         }
1.817     raeburn  9139:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9140:         $grouplist = join(':',@usersgroups);
                   9141:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9142:     }
1.733     raeburn  9143:     return @usersgroups;
1.683     raeburn  9144: }
                   9145: 
                   9146: sub devalidate_getgroups_cache {
                   9147:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9148:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9149: 
1.683     raeburn  9150:     my $hashid="$udom:$uname:$courseid";
                   9151:     &devalidate_cache_new('getgroups',$hashid);
                   9152: }
                   9153: 
1.12      www      9154: # ------------------------------------------------------------------ Plain Text
                   9155: 
                   9156: sub plaintext {
1.988     raeburn  9157:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9158:     if ($short =~ m{^cr/}) {
1.758     albertel 9159: 	return (split('/',$short))[-1];
                   9160:     }
1.742     raeburn  9161:     if (!defined($cid)) {
                   9162:         $cid = $env{'request.course.id'};
                   9163:     }
                   9164:     my %rolenames = (
1.1008    raeburn  9165:                       Course    => 'std',
                   9166:                       Community => 'alt1',
1.742     raeburn  9167:                     );
1.1037    raeburn  9168:     if ($cid ne '') {
                   9169:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9170:             unless ($forcedefault) {
                   9171:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9172:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9173:                 return &Apache::lonlocal::mt($roletext);
                   9174:             }
                   9175:         }
                   9176:     }
                   9177:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9178:         (defined($rolenames{$type})) && 
                   9179:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9180:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9181:     } elsif ($cid ne '') {
                   9182:         my $crstype = $env{'course.'.$cid.'.type'};
                   9183:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9184:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9185:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9186:         }
1.742     raeburn  9187:     }
1.1037    raeburn  9188:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9189: }
                   9190: 
                   9191: # ----------------------------------------------------------------- Assign Role
                   9192: 
                   9193: sub assignrole {
1.957     raeburn  9194:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9195:         $context)=@_;
1.21      www      9196:     my $mrole;
                   9197:     if ($role =~ /^cr\//) {
1.393     www      9198:         my $cwosec=$url;
1.811     albertel 9199:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9200: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9201:            my $refused = 1;
                   9202:            if ($context eq 'requestcourses') {
                   9203:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9204:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9205:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9206:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9207:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9208:                            if ($crsenv{'internal.courseowner'} eq
                   9209:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9210:                                $refused = '';
                   9211:                            }
                   9212:                        }
                   9213:                    }
                   9214:                }
                   9215:            }
                   9216:            if ($refused) {
                   9217:                &logthis('Refused custom assignrole: '.
                   9218:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9219:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9220:                return 'refused';
                   9221:            }
1.104     www      9222:         }
1.21      www      9223:         $mrole='cr';
1.678     raeburn  9224:     } elsif ($role =~ /^gr\//) {
                   9225:         my $cwogrp=$url;
1.811     albertel 9226:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9227:         unless (&allowed('mdg',$cwogrp)) {
                   9228:             &logthis('Refused group assignrole: '.
                   9229:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9230:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9231:             return 'refused';
                   9232:         }
                   9233:         $mrole='gr';
1.21      www      9234:     } else {
1.82      www      9235:         my $cwosec=$url;
1.811     albertel 9236:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9237:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9238:             my $refused;
                   9239:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9240:                 if (!(&allowed('c'.$role,$url))) {
                   9241:                     $refused = 1;
                   9242:                 }
                   9243:             } else {
                   9244:                 $refused = 1;
                   9245:             }
1.947     raeburn  9246:             if ($refused) {
1.1045    raeburn  9247:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9248:                 if (!$selfenroll && $context eq 'course') {
                   9249:                     my %crsenv;
                   9250:                     if ($role eq 'cc' || $role eq 'co') {
                   9251:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9252:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9253:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9254:                                 if ($crsenv{'internal.courseowner'} eq 
                   9255:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9256:                                     $refused = '';
                   9257:                                 }
                   9258:                             }
                   9259:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9260:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9261:                                 if ($crsenv{'internal.courseowner'} eq 
                   9262:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9263:                                     $refused = '';
                   9264:                                 }
                   9265:                             }
                   9266:                         }
                   9267:                     }
                   9268:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9269:                     $refused = '';
1.1017    raeburn  9270:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9271:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9272:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9273:                         my $wrongcc;
                   9274:                         if ($cnum =~ /^$match_community$/) {
                   9275:                             $wrongcc = 1 if ($role eq 'cc');
                   9276:                         } else {
                   9277:                             $wrongcc = 1 if ($role eq 'co');
                   9278:                         }
                   9279:                         unless ($wrongcc) {
                   9280:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9281:                             if ($crsenv{'internal.courseowner'} eq 
                   9282:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9283:                                 $refused = '';
                   9284:                             }
1.1017    raeburn  9285:                         }
                   9286:                     }
1.1172.2.9  raeburn  9287:                 } elsif ($context eq 'requestauthor') {
                   9288:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9289:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9290:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9291:                             $refused = '';
                   9292:                         } else {
                   9293:                             my %domdefaults = &get_domain_defaults($udom);
                   9294:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9295:                                 my $checkbystatus;
                   9296:                                 if ($env{'user.adv'}) {
                   9297:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9298:                                     if ($disposition eq 'automatic') {
                   9299:                                         $refused = '';
                   9300:                                     } elsif ($disposition eq '') {
                   9301:                                         $checkbystatus = 1;
                   9302:                                     }
                   9303:                                 } else {
                   9304:                                     $checkbystatus = 1;
                   9305:                                 }
                   9306:                                 if ($checkbystatus) {
                   9307:                                     if ($env{'environment.inststatus'}) {
                   9308:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9309:                                         foreach my $type (@inststatuses) {
                   9310:                                             if (($type ne '') &&
                   9311:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9312:                                                 $refused = '';
                   9313:                                             }
                   9314:                                         }
                   9315:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9316:                                         $refused = '';
                   9317:                                     }
                   9318:                                 }
                   9319:                             }
                   9320:                         }
                   9321:                     }
1.1017    raeburn  9322:                 }
                   9323:                 if ($refused) {
1.947     raeburn  9324:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9325:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9326: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9327:                     return 'refused';
                   9328:                 }
1.932     raeburn  9329:             }
1.1131    raeburn  9330:         } elsif ($role eq 'au') {
                   9331:             if ($url ne '/'.$udom.'/') {
                   9332:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9333:                          ' to assign author role for '.$uname.':'.$udom.
                   9334:                          ' in domain: '.$url.' refused (wrong domain).');
                   9335:                 return 'refused';
                   9336:             }
1.104     www      9337:         }
1.21      www      9338:         $mrole=$role;
                   9339:     }
1.620     albertel 9340:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9341:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9342:     if ($end) { $command.='_'.$end; }
1.21      www      9343:     if ($start) {
                   9344: 	if ($end) { 
1.81      www      9345:            $command.='_'.$start; 
1.21      www      9346:         } else {
1.81      www      9347:            $command.='_0_'.$start;
1.21      www      9348:         }
                   9349:     }
1.739     raeburn  9350:     my $origstart = $start;
                   9351:     my $origend = $end;
1.957     raeburn  9352:     my $delflag;
1.357     www      9353: # actually delete
                   9354:     if ($deleteflag) {
1.373     www      9355: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9356: # modify command to delete the role
1.620     albertel 9357:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9358:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9359: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9360: # set start and finish to negative values for userrolelog
                   9361:            $start=-1;
                   9362:            $end=-1;
1.957     raeburn  9363:            $delflag = 1;
1.357     www      9364:         }
                   9365:     }
                   9366: # send command
1.349     www      9367:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9368: # log new user role if status is ok
1.349     www      9369:     if ($answer eq 'ok') {
1.663     raeburn  9370: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9371:         if (($role eq 'cc') || ($role eq 'in') ||
                   9372:             ($role eq 'ep') || ($role eq 'ad') ||
                   9373:             ($role eq 'ta') || ($role eq 'st') ||
                   9374:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9375:             ($role eq 'co')) {
1.1172.2.13  raeburn  9376: # for course roles, perform group memberships changes triggered by role change.
                   9377:             unless ($role =~ /^gr/) {
                   9378:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9379:                                                  $origstart,$selfenroll,$context);
                   9380:             }
1.1172.2.9  raeburn  9381:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9382:                            $selfenroll,$context);
                   9383:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9384:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9385:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9386:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9387:                            $context);
                   9388:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9389:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9390:                              $context);
                   9391:         }
1.1053    raeburn  9392:         if ($role eq 'cc') {
                   9393:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9394:         }
1.349     www      9395:     }
                   9396:     return $answer;
1.169     harris41 9397: }
                   9398: 
1.1053    raeburn  9399: sub autoupdate_coowners {
                   9400:     my ($url,$end,$start,$uname,$udom) = @_;
                   9401:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9402:     if (($cdom ne '') && ($cnum ne '')) {
                   9403:         my $now = time;
                   9404:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9405:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9406:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9407:             my $instcode = $coursehash{'internal.coursecode'};
                   9408:             if ($instcode ne '') {
1.1056    raeburn  9409:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9410:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9411:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9412:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9413:                         if ($result eq 'valid') {
                   9414:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9415:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9416:                                     push(@newcoowners,$coowner);
                   9417:                                 }
                   9418:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9419:                                     push(@newcoowners,$uname.':'.$udom);
                   9420:                                 }
                   9421:                                 @newcoowners = sort(@newcoowners);
                   9422:                             } else {
                   9423:                                 push(@newcoowners,$uname.':'.$udom);
                   9424:                             }
                   9425:                         } else {
                   9426:                             if ($coursehash{'internal.co-owners'}) {
                   9427:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9428:                                     unless ($coowner eq $uname.':'.$udom) {
                   9429:                                         push(@newcoowners,$coowner);
                   9430:                                     }
                   9431:                                 }
                   9432:                                 unless (@newcoowners > 0) {
                   9433:                                     $delcoowners = 1;
                   9434:                                     $coowners = '';
                   9435:                                 }
                   9436:                             }
                   9437:                         }
                   9438:                         if (@newcoowners || $delcoowners) {
                   9439:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9440:                                             $delcoowners,@newcoowners);
                   9441:                         }
                   9442:                     }
                   9443:                 }
                   9444:             }
                   9445:         }
                   9446:     }
                   9447: }
                   9448: 
                   9449: sub store_coowners {
                   9450:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9451:     my $cid = $cdom.'_'.$cnum;
                   9452:     my ($coowners,$delresult,$putresult);
                   9453:     if (@newcoowners) {
                   9454:         $coowners = join(',',@newcoowners);
                   9455:         my %coownershash = (
                   9456:                             'internal.co-owners' => $coowners,
                   9457:                            );
                   9458:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9459:         if ($putresult eq 'ok') {
                   9460:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9461:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9462:             }
                   9463:         }
                   9464:     }
                   9465:     if ($delcoowners) {
                   9466:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9467:         if ($delresult eq 'ok') {
                   9468:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9469:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9470:             }
                   9471:         }
                   9472:     }
                   9473:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9474:         my %crsinfo =
                   9475:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9476:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9477:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9478:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9479:         }
                   9480:     }
                   9481: }
                   9482: 
1.169     harris41 9483: # -------------------------------------------------- Modify user authentication
1.197     www      9484: # Overrides without validation
                   9485: 
1.169     harris41 9486: sub modifyuserauth {
                   9487:     my ($udom,$uname,$umode,$upass)=@_;
                   9488:     my $uhome=&homeserver($uname,$udom);
1.197     www      9489:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9490:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9491:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9492:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9493:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9494: 		     &escape($upass),$uhome);
1.620     albertel 9495:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9496:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9497:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9498:     &log($udom,,$uname,$uhome,
1.620     albertel 9499:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9500:                                      $env{'user.name'}.', '.$umode.
1.197     www      9501:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9502:     unless ($reply eq 'ok') {
1.197     www      9503:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9504: 	return 'error: '.$reply;
                   9505:     }   
1.170     harris41 9506:     return 'ok';
1.80      www      9507: }
                   9508: 
1.81      www      9509: # --------------------------------------------------------------- Modify a user
1.80      www      9510: 
1.81      www      9511: sub modifyuser {
1.206     matthew  9512:     my ($udom,    $uname, $uid,
                   9513:         $umode,   $upass, $first,
                   9514:         $middle,  $last,  $gene,
1.1058    raeburn  9515:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9516:     $udom= &LONCAPA::clean_domain($udom);
                   9517:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9518:     my $showcandelete = 'none';
                   9519:     if (ref($candelete) eq 'ARRAY') {
                   9520:         if (@{$candelete} > 0) {
                   9521:             $showcandelete = join(', ',@{$candelete});
                   9522:         }
                   9523:     }
1.81      www      9524:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9525:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9526: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9527:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9528:                                      ' desiredhome not specified'). 
1.620     albertel 9529:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9530:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9531:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9532:     my $newuser;
                   9533:     if ($uhome eq 'no_host') {
                   9534:         $newuser = 1;
                   9535:     }
1.80      www      9536: # ----------------------------------------------------------------- Create User
1.406     albertel 9537:     if (($uhome eq 'no_host') && 
                   9538: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9539:         my $unhome='';
1.844     albertel 9540:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9541:             $unhome = $desiredhome;
1.620     albertel 9542: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9543: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9544:         } else { # load balancing routine for determining $unhome
1.81      www      9545:             my $loadm=10000000;
1.841     albertel 9546: 	    my %servers = &get_servers($udom,'library');
                   9547: 	    foreach my $tryserver (keys(%servers)) {
                   9548: 		my $answer=reply('load',$tryserver);
                   9549: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9550: 		    $loadm=$answer;
                   9551: 		    $unhome=$tryserver;
                   9552: 		}
1.80      www      9553: 	    }
                   9554:         }
                   9555:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9556: 	    return 'error: unable to find a home server for '.$uname.
                   9557:                    ' in domain '.$udom;
1.80      www      9558:         }
                   9559:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9560:                          &escape($upass),$unhome);
                   9561: 	unless ($reply eq 'ok') {
                   9562:             return 'error: '.$reply;
                   9563:         }   
1.230     stredwic 9564:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9565:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9566: 	    return 'error: unable verify users home machine.';
1.80      www      9567:         }
1.209     matthew  9568:     }   # End of creation of new user
1.80      www      9569: # ---------------------------------------------------------------------- Add ID
                   9570:     if ($uid) {
                   9571:        $uid=~tr/A-Z/a-z/;
                   9572:        my %uidhash=&idrget($udom,$uname);
1.196     www      9573:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9574:          && (!$forceid)) {
1.80      www      9575: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9576: 	      return 'error: user id "'.$uid.'" does not match '.
                   9577:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9578:           }
                   9579:        } else {
                   9580: 	  &idput($udom,($uname => $uid));
                   9581:        }
                   9582:     }
                   9583: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9584:     my @tmp=&get('environment',
1.899     raeburn  9585: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9586:                     'permanentemail','inststatus'],
1.134     albertel 9587: 		   $udom,$uname);
1.1075    raeburn  9588:     my (%names,%oldnames);
1.313     matthew  9589:     if ($tmp[0] =~ m/^error:.*/) { 
                   9590:         %names=(); 
                   9591:     } else {
                   9592:         %names = @tmp;
1.1075    raeburn  9593:         %oldnames = %names;
1.313     matthew  9594:     }
1.388     www      9595: #
1.1058    raeburn  9596: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9597: # of users did not contain them), do not overwrite existing values
                   9598: # unless field is in $candelete array ref.  
                   9599: #
                   9600: 
                   9601:     my @fields = ('firstname','middlename','lastname','generation',
                   9602:                   'permanentemail','id');
                   9603:     my %newvalues;
                   9604:     if (ref($candelete) eq 'ARRAY') {
                   9605:         foreach my $field (@fields) {
                   9606:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9607:                 if ($field eq 'firstname') {
                   9608:                     $names{$field} = $first;
                   9609:                 } elsif ($field eq 'middlename') {
                   9610:                     $names{$field} = $middle;
                   9611:                 } elsif ($field eq 'lastname') {
                   9612:                     $names{$field} = $last;
                   9613:                 } elsif ($field eq 'generation') { 
                   9614:                     $names{$field} = $gene;
                   9615:                 } elsif ($field eq 'permanentemail') {
                   9616:                     $names{$field} = $email;
                   9617:                 } elsif ($field eq 'id') {
                   9618:                     $names{$field}  = $uid;
                   9619:                 }
                   9620:             }
                   9621:         }
                   9622:     }
1.388     www      9623:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9624:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9625:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9626:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9627:     if ($email) {
                   9628:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9629:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9630:     }
1.899     raeburn  9631:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9632:     if (defined($inststatus)) {
                   9633:         $names{'inststatus'} = '';
                   9634:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9635:         if (ref($usertypes) eq 'HASH') {
                   9636:             my @okstatuses; 
                   9637:             foreach my $item (split(/:/,$inststatus)) {
                   9638:                 if (defined($usertypes->{$item})) {
                   9639:                     push(@okstatuses,$item);  
                   9640:                 }
                   9641:             }
                   9642:             if (@okstatuses) {
                   9643:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9644:             }
                   9645:         }
                   9646:     }
1.1075    raeburn  9647:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9648:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9649:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9650:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9651:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9652:     } else {
                   9653:         $logmsg .= ' during self creation';
                   9654:     }
1.1075    raeburn  9655:     my $changed;
                   9656:     if ($newuser) {
                   9657:         $changed = 1;
                   9658:     } else {
                   9659:         foreach my $field (@fields) {
                   9660:             if ($names{$field} ne $oldnames{$field}) {
                   9661:                 $changed = 1;
                   9662:                 last;
                   9663:             }
                   9664:         }
                   9665:     }
                   9666:     unless ($changed) {
                   9667:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9668:         &logthis($logmsg);
                   9669:         return 'ok';
                   9670:     }
                   9671:     my $reply = &put('environment', \%names, $udom,$uname);
                   9672:     if ($reply ne 'ok') { 
                   9673:         return 'error: '.$reply;
                   9674:     }
1.1087    raeburn  9675:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9676:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9677:     }
1.1075    raeburn  9678:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9679:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9680:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9681:     &logthis($logmsg);
1.134     albertel 9682:     return 'ok';
1.80      www      9683: }
                   9684: 
1.81      www      9685: # -------------------------------------------------------------- Modify student
1.80      www      9686: 
1.81      www      9687: sub modifystudent {
                   9688:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9689:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9690:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9691:     if (!$cid) {
1.620     albertel 9692: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9693: 	    return 'not_in_class';
                   9694: 	}
1.80      www      9695:     }
                   9696: # --------------------------------------------------------------- Make the user
1.81      www      9697:     my $reply=&modifyuser
1.209     matthew  9698: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9699:          $desiredhome,$email,$inststatus);
1.80      www      9700:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9701:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9702:     # student's environment
1.297     matthew  9703:     $uid = undef if (!$forceid);
1.455     albertel 9704:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9705: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9706:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9707:     return $reply;
                   9708: }
                   9709: 
                   9710: sub modify_student_enrollment {
1.1172.2.23  raeburn  9711:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9712:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9713:     my ($cdom,$cnum,$chome);
                   9714:     if (!$cid) {
1.620     albertel 9715: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9716: 	    return 'not_in_class';
                   9717: 	}
1.620     albertel 9718: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9719: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9720:     } else {
                   9721: 	($cdom,$cnum)=split(/_/,$cid);
                   9722:     }
1.620     albertel 9723:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9724:     if (!$chome) {
1.457     raeburn  9725: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9726:     }
1.455     albertel 9727:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9728:     # Make sure the user exists
1.81      www      9729:     my $uhome=&homeserver($uname,$udom);
                   9730:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9731: 	return 'error: no such user';
                   9732:     }
1.297     matthew  9733:     # Get student data if we were not given enough information
                   9734:     if (!defined($first)  || $first  eq '' || 
                   9735:         !defined($last)   || $last   eq '' || 
                   9736:         !defined($uid)    || $uid    eq '' || 
                   9737:         !defined($middle) || $middle eq '' || 
                   9738:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9739:         # They did not supply us with enough data to enroll the student, so
                   9740:         # we need to pick up more information.
1.297     matthew  9741:         my %tmp = &get('environment',
1.294     matthew  9742:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9743:                        ,$udom,$uname);
                   9744: 
1.800     albertel 9745:         #foreach my $key (keys(%tmp)) {
                   9746:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9747:         #}
1.294     matthew  9748:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9749:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9750:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9751:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9752:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9753:     }
1.556     albertel 9754:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9755:     my $user = "$uname:$udom";
                   9756:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9757:     my $reply=cput('classlist',
1.1148    raeburn  9758: 		   {$user => 
1.1172.2.76  raeburn  9759: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9760: 		   $cdom,$cnum);
1.1148    raeburn  9761:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9762:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9763:     } else { 
1.81      www      9764: 	return 'error: '.$reply;
                   9765:     }
1.297     matthew  9766:     # Add student role to user
1.83      www      9767:     my $uurl='/'.$cid;
1.81      www      9768:     $uurl=~s/\_/\//g;
                   9769:     if ($usec) {
                   9770: 	$uurl.='/'.$usec;
                   9771:     }
1.1148    raeburn  9772:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9773:                              $selfenroll,$context);
                   9774:     if ($result ne 'ok') {
                   9775:         if ($old_entry{$user} ne '') {
                   9776:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9777:         } else {
                   9778:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9779:         }
                   9780:     }
                   9781:     return $result; 
1.21      www      9782: }
                   9783: 
1.556     albertel 9784: sub format_name {
                   9785:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9786:     my $name;
                   9787:     if ($first ne 'lastname') {
                   9788: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9789:     } else {
                   9790: 	if ($lastname=~/\S/) {
                   9791: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9792: 	    $name=~s/\s+,/,/;
                   9793: 	} else {
                   9794: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9795: 	}
                   9796:     }
                   9797:     $name=~s/^\s+//;
                   9798:     $name=~s/\s+$//;
                   9799:     $name=~s/\s+/ /g;
                   9800:     return $name;
                   9801: }
                   9802: 
1.84      www      9803: # ------------------------------------------------- Write to course preferences
                   9804: 
                   9805: sub writecoursepref {
                   9806:     my ($courseid,%prefs)=@_;
                   9807:     $courseid=~s/^\///;
                   9808:     $courseid=~s/\_/\//g;
                   9809:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9810:     my $chome=homeserver($cnum,$cdomain);
                   9811:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9812: 	return 'error: no such course';
                   9813:     }
                   9814:     my $cstring='';
1.800     albertel 9815:     foreach my $pref (keys(%prefs)) {
                   9816: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9817:     }
1.84      www      9818:     $cstring=~s/\&$//;
                   9819:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9820: }
                   9821: 
                   9822: # ---------------------------------------------------------- Make/modify course
                   9823: 
                   9824: sub createcourse {
1.741     raeburn  9825:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.93.4  13(raebu 9826:20):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      9827:     $url=&declutter($url);
                   9828:     my $cid='';
1.1028    raeburn  9829:     if ($context eq 'requestcourses') {
                   9830:         my $can_create = 0;
                   9831:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9832:         if ($udom eq $ownerdom) {
1.1172.2.93.4  13(raebu 9833:20):             my $reload;
                   9834:20):             if (($callercontext eq 'auto') &&
                   9835:20):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   9836:20):                 $reload = 'reload';
                   9837:20):             }
                   9838:20):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  9839:                                   $context)) {
                   9840:                 $can_create = 1;
                   9841:             }
                   9842:         } else {
                   9843:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9844:                                            $category);
                   9845:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9846:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9847:                 if (@curr > 0) {
                   9848:                     my @options = qw(approval validate autolimit);
                   9849:                     my $optregex = join('|',@options);
                   9850:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9851:                         $can_create = 1;
                   9852:                     }
                   9853:                 }
                   9854:             }
                   9855:         }
                   9856:         if ($can_create) {
                   9857:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9858:                 unless (&allowed('ccc',$udom)) {
                   9859:                     return 'refused'; 
                   9860:                 }
1.1017    raeburn  9861:             }
                   9862:         } else {
                   9863:             return 'refused';
                   9864:         }
1.1028    raeburn  9865:     } elsif (!&allowed('ccc',$udom)) {
                   9866:         return 'refused';
1.84      www      9867:     }
1.1011    raeburn  9868: # --------------------------------------------------------------- Get Unique ID
                   9869:     my $uname;
                   9870:     if ($cnum =~ /^$match_courseid$/) {
                   9871:         my $chome=&homeserver($cnum,$udom,'true');
                   9872:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9873:             $uname = $cnum;
                   9874:         } else {
1.1038    raeburn  9875:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9876:         }
                   9877:     } else {
1.1038    raeburn  9878:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9879:     }
                   9880:     return $uname if ($uname =~ /^error/);
                   9881: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9882:     if (!defined($course_server)) {
                   9883:         if (defined(&domain($udom,'primary'))) {
                   9884:             $course_server = &domain($udom,'primary');
                   9885:         } else {
                   9886:             $course_server = $env{'user.home'}; 
                   9887:         }
                   9888:     }
                   9889:     my %host_servers =
                   9890:         &Apache::lonnet::get_servers($udom,'library');
                   9891:     unless ($host_servers{$course_server}) {
                   9892:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9893:     }
1.84      www      9894: # ------------------------------------------------------------- Make the course
                   9895:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9896:                       $course_server);
1.84      www      9897:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9898:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9899:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9900: 	return 'error: no such course';
                   9901:     }
1.271     www      9902: # ----------------------------------------------------------------- Course made
1.516     raeburn  9903: # log existence
1.1029    raeburn  9904:     my $now = time;
1.918     raeburn  9905:     my $newcourse = {
                   9906:                     $udom.'_'.$uname => {
1.921     raeburn  9907:                                      description => $description,
                   9908:                                      inst_code   => $inst_code,
                   9909:                                      owner       => $course_owner,
                   9910:                                      type        => $crstype,
1.1029    raeburn  9911:                                      creator     => $env{'user.name'}.':'.
                   9912:                                                     $env{'user.domain'},
                   9913:                                      created     => $now,
                   9914:                                      context     => $context,
1.918     raeburn  9915:                                                 },
                   9916:                     };
1.921     raeburn  9917:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9918: # set toplevel url
1.271     www      9919:     my $topurl=$url;
                   9920:     unless ($nonstandard) {
                   9921: # ------------------------------------------ For standard courses, make top url
                   9922:         my $mapurl=&clutter($url);
1.278     www      9923:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9924:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9925: <map>
                   9926: <resource id="1" type="start"></resource>
                   9927: <resource id="2" src="$mapurl"></resource>
                   9928: <resource id="3" type="finish"></resource>
                   9929: <link index="1" from="1" to="2"></link>
                   9930: <link index="2" from="2" to="3"></link>
                   9931: </map>
                   9932: ENDINITMAP
                   9933:         $topurl=&declutter(
1.638     albertel 9934:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9935:                           );
                   9936:     }
                   9937: # ----------------------------------------------------------- Write preferences
1.84      www      9938:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9939:                      ('description'              => $description,
                   9940:                       'url'                      => $topurl,
                   9941:                       'internal.creator'         => $env{'user.name'}.':'.
                   9942:                                                     $env{'user.domain'},
                   9943:                       'internal.created'         => $now,
                   9944:                       'internal.creationcontext' => $context)
                   9945:                     );
1.84      www      9946:     return '/'.$udom.'/'.$uname;
                   9947: }
                   9948: 
1.1011    raeburn  9949: # ------------------------------------------------------------------- Create ID
                   9950: sub generate_coursenum {
1.1038    raeburn  9951:     my ($udom,$crstype) = @_;
1.1011    raeburn  9952:     my $domdesc = &domain($udom);
                   9953:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9954:     my $first;
                   9955:     if ($crstype eq 'Community') {
                   9956:         $first = '0';
                   9957:     } else {
                   9958:         $first = int(1+rand(9)); 
                   9959:     } 
                   9960:     my $uname=$first.
1.1011    raeburn  9961:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9962:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9963:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9964: # ----------------------------------------------- Make sure that does not exist
                   9965:     my $uhome=&homeserver($uname,$udom,'true');
                   9966:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9967:         if ($crstype eq 'Community') {
                   9968:             $first = '0';
                   9969:         } else {
                   9970:             $first = int(1+rand(9));
                   9971:         }
                   9972:         $uname=$first.
1.1011    raeburn  9973:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9974:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9975:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9976:         $uhome=&homeserver($uname,$udom,'true');
                   9977:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9978:             return 'error: unable to generate unique course-ID';
                   9979:         }
                   9980:     }
                   9981:     return $uname;
                   9982: }
                   9983: 
1.813     albertel 9984: sub is_course {
1.1167    droeschl 9985:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9986:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9987: 
                   9988:     return unless $cdom and $cnum;
                   9989: 
                   9990:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9991:         '.');
                   9992: 
1.1172.2.23  raeburn  9993:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9994:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9995: }
                   9996: 
1.1015    raeburn  9997: sub store_userdata {
                   9998:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9999:     my $result;
1.1016    raeburn  10000:     if ($datakey ne '') {
1.1013    raeburn  10001:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10002:             if ($udom eq '' || $uname eq '') {
                   10003:                 $udom = $env{'user.domain'};
                   10004:                 $uname = $env{'user.name'};
                   10005:             }
                   10006:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10007:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10008:                 $result = 'error: no_host';
                   10009:             } else {
                   10010:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10011:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10012: 
                   10013:                 my $namevalue='';
                   10014:                 foreach my $key (keys(%{$storehash})) {
                   10015:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10016:                 }
                   10017:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10018:                 unless ($namespace eq 'courserequests') {
                   10019:                     $datakey = &escape($datakey);
                   10020:                 }
1.1105    raeburn  10021:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10022:                                   $namevalue,$uhome);
1.1013    raeburn  10023:             }
                   10024:         } else {
                   10025:             $result = 'error: data to store was not a hash reference'; 
                   10026:         }
                   10027:     } else {
                   10028:         $result= 'error: invalid requestkey'; 
                   10029:     }
                   10030:     return $result;
                   10031: }
                   10032: 
1.21      www      10033: # ---------------------------------------------------------- Assign Custom Role
                   10034: 
                   10035: sub assigncustomrole {
1.957     raeburn  10036:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10037:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10038:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10039: }
                   10040: 
                   10041: # ----------------------------------------------------------------- Revoke Role
                   10042: 
                   10043: sub revokerole {
1.957     raeburn  10044:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10045:     my $now=time;
1.965     raeburn  10046:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10047: }
                   10048: 
                   10049: # ---------------------------------------------------------- Revoke Custom Role
                   10050: 
                   10051: sub revokecustomrole {
1.957     raeburn  10052:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10053:     my $now=time;
1.357     www      10054:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10055:            $deleteflag,$selfenroll,$context);
1.17      www      10056: }
                   10057: 
1.533     banghart 10058: # ------------------------------------------------------------ Disk usage
1.535     albertel 10059: sub diskusage {
1.955     raeburn  10060:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10061:     $directorypath =~ s/\/$//;
                   10062:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10063:                        .&escape($getpropath).':'.&escape($uname).':'
                   10064:                        .&escape($udom),homeserver($uname,$udom));
                   10065:     if ($listing eq 'unknown_cmd') {
                   10066:         if ($getpropath) {
                   10067:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10068:         }
                   10069:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10070:     }
1.514     albertel 10071:     return $listing;
1.512     banghart 10072: }
                   10073: 
1.566     banghart 10074: sub is_locked {
1.1096    raeburn  10075:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10076:     my @check;
                   10077:     my $is_locked;
1.1093    raeburn  10078:     push (@check,$file_name);
1.613     albertel 10079:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10080: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10081:     my ($tmp)=keys(%locked);
                   10082:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10083:     
1.566     banghart 10084:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10085:         $is_locked = 'false';
                   10086:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10087:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10088:                $is_locked = 'true';
1.1096    raeburn  10089:                if (ref($which) eq 'ARRAY') {
                   10090:                    push(@{$which},$entry);
                   10091:                } else {
                   10092:                    last;
                   10093:                }
1.745     raeburn  10094:            }
                   10095:        }
1.566     banghart 10096:     } else {
                   10097:         $is_locked = 'false';
                   10098:     }
1.1093    raeburn  10099:     return $is_locked;
1.566     banghart 10100: }
                   10101: 
1.759     albertel 10102: sub declutter_portfile {
                   10103:     my ($file) = @_;
1.833     albertel 10104:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10105:     return $file;
                   10106: }
                   10107: 
1.559     banghart 10108: # ------------------------------------------------------------- Mark as Read Only
                   10109: 
                   10110: sub mark_as_readonly {
                   10111:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10112:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10113:     my ($tmp)=keys(%current_permissions);
                   10114:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10115:     foreach my $file (@{$files}) {
1.759     albertel 10116: 	$file = &declutter_portfile($file);
1.561     banghart 10117:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10118:     }
1.613     albertel 10119:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10120:     return;
                   10121: }
                   10122: 
1.572     banghart 10123: # ------------------------------------------------------------Save Selected Files
                   10124: 
                   10125: sub save_selected_files {
                   10126:     my ($user, $path, @files) = @_;
                   10127:     my $filename = $user."savedfiles";
1.573     banghart 10128:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.93.4  7(raebur 10129:7):     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10130:     foreach my $file (@files) {
1.620     albertel 10131:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10132:     }
                   10133:     foreach my $file (@other_files) {
1.574     banghart 10134:         print (OUT $file."\n");
1.572     banghart 10135:     }
1.574     banghart 10136:     close (OUT);
1.572     banghart 10137:     return 'ok';
                   10138: }
                   10139: 
1.574     banghart 10140: sub clear_selected_files {
                   10141:     my ($user) = @_;
                   10142:     my $filename = $user."savedfiles";
1.1172.2.93.4  7(raebur 10143:7):     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10144:     print (OUT undef);
                   10145:     close (OUT);
                   10146:     return ("ok");    
                   10147: }
                   10148: 
1.572     banghart 10149: sub files_in_path {
                   10150:     my ($user, $path) = @_;
                   10151:     my $filename = $user."savedfiles";
                   10152:     my %return_files;
1.1172.2.93.4  7(raebur 10153:7):     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10154:     while (my $line_in = <IN>) {
1.574     banghart 10155:         chomp ($line_in);
                   10156:         my @paths_and_file = split (m!/!, $line_in);
                   10157:         my $file_part = pop (@paths_and_file);
                   10158:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10159:         $path_part.='/';
                   10160:         my $path_and_file = $path_part.$file_part;
                   10161:         if ($path_part eq $path) {
                   10162:             $return_files{$file_part}= 'selected';
                   10163:         }
                   10164:     }
1.574     banghart 10165:     close (IN);
                   10166:     return (\%return_files);
1.572     banghart 10167: }
                   10168: 
                   10169: # called in portfolio select mode, to show files selected NOT in current directory
                   10170: sub files_not_in_path {
                   10171:     my ($user, $path) = @_;
                   10172:     my $filename = $user."savedfiles";
                   10173:     my @return_files;
                   10174:     my $path_part;
1.1172.2.93.4  7(raebur 10175:7):     open(IN,'<',LONCAPA::tempdir().$filename);
1.800     albertel 10176:     while (my $line = <IN>) {
1.572     banghart 10177:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10178:         my @paths_and_file = split(m|/|, $line);
                   10179:         my $file_part = pop(@paths_and_file);
                   10180:         chomp($file_part);
                   10181:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10182:         $path_part .= '/';
                   10183:         my $path_and_file = $path_part.$file_part;
                   10184:         if ($path_part ne $path) {
1.800     albertel 10185:             push(@return_files, ($path_and_file));
1.572     banghart 10186:         }
                   10187:     }
1.800     albertel 10188:     close(OUT);
1.574     banghart 10189:     return (@return_files);
1.572     banghart 10190: }
                   10191: 
1.745     raeburn  10192: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10193: 
1.745     raeburn  10194: sub get_portfile_permissions {
                   10195:     my ($domain,$user) = @_;
1.613     albertel 10196:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10197:     my ($tmp)=keys(%current_permissions);
                   10198:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10199:     return \%current_permissions;
                   10200: }
                   10201: 
                   10202: #---------------------------------------------Get portfolio file access controls
                   10203: 
1.749     raeburn  10204: sub get_access_controls {
1.745     raeburn  10205:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10206:     my %access;
                   10207:     my $real_file = $file;
                   10208:     $file =~ s/\.meta$//;
1.745     raeburn  10209:     if (defined($file)) {
1.749     raeburn  10210:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10211:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10212:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10213:             }
                   10214:         }
1.745     raeburn  10215:     } else {
1.749     raeburn  10216:         foreach my $key (keys(%{$current_permissions})) {
                   10217:             if ($key =~ /\0accesscontrol$/) {
                   10218:                 if (defined($group)) {
                   10219:                     if ($key !~ m-^\Q$group\E/-) {
                   10220:                         next;
                   10221:                     }
                   10222:                 }
                   10223:                 my ($fullpath) = split(/\0/,$key);
                   10224:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10225:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10226:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10227:                     }
                   10228:                 }
                   10229:             }
                   10230:         }
                   10231:     }
                   10232:     return %access;
                   10233: }
                   10234: 
                   10235: sub modify_access_controls {
                   10236:     my ($file_name,$changes,$domain,$user)=@_;
                   10237:     my ($outcome,$deloutcome);
                   10238:     my %store_permissions;
                   10239:     my %new_values;
                   10240:     my %new_control;
                   10241:     my %translation;
                   10242:     my @deletions = ();
                   10243:     my $now = time;
                   10244:     if (exists($$changes{'activate'})) {
                   10245:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10246:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10247:             my $numnew = scalar(@newitems);
                   10248:             for (my $i=0; $i<$numnew; $i++) {
                   10249:                 my $newkey = $newitems[$i];
                   10250:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10251:                 if ($newkey =~ /^\d+:/) { 
                   10252:                     $newkey =~ s/^(\d+)/$newid/;
                   10253:                     $translation{$1} = $newid;
                   10254:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10255:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10256:                     $translation{$1} = $newid;
                   10257:                 }
1.749     raeburn  10258:                 $new_values{$file_name."\0".$newkey} = 
                   10259:                                           $$changes{'activate'}{$newitems[$i]};
                   10260:                 $new_control{$newkey} = $now;
                   10261:             }
                   10262:         }
                   10263:     }
                   10264:     my %todelete;
                   10265:     my %changed_items;
                   10266:     foreach my $action ('delete','update') {
                   10267:         if (exists($$changes{$action})) {
                   10268:             if (ref($$changes{$action}) eq 'HASH') {
                   10269:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10270:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10271:                     if ($action eq 'delete') { 
                   10272:                         $todelete{$itemnum} = 1;
                   10273:                     } else {
                   10274:                         $changed_items{$itemnum} = $key;
                   10275:                     }
                   10276:                 }
1.745     raeburn  10277:             }
                   10278:         }
1.749     raeburn  10279:     }
                   10280:     # get lock on access controls for file.
                   10281:     my $lockhash = {
                   10282:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10283:                                                        ':'.$env{'user.domain'},
                   10284:                    }; 
                   10285:     my $tries = 0;
                   10286:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10287:    
1.1172.2.79  raeburn  10288:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10289:         $tries ++;
1.1172.2.79  raeburn  10290:         sleep(0.1);
1.749     raeburn  10291:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10292:     }
                   10293:     if ($gotlock eq 'ok') {
                   10294:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10295:         my ($tmp)=keys(%curr_permissions);
                   10296:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10297:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10298:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10299:             if (ref($curr_controls) eq 'HASH') {
                   10300:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10301:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10302:                     if (defined($todelete{$itemnum})) {
                   10303:                         push(@deletions,$file_name."\0".$control_item);
                   10304:                     } else {
                   10305:                         if (defined($changed_items{$itemnum})) {
                   10306:                             $new_control{$changed_items{$itemnum}} = $now;
                   10307:                             push(@deletions,$file_name."\0".$control_item);
                   10308:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10309:                         } else {
                   10310:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10311:                         }
                   10312:                     }
1.745     raeburn  10313:                 }
                   10314:             }
                   10315:         }
1.970     raeburn  10316:         my ($group);
                   10317:         if (&is_course($domain,$user)) {
                   10318:             ($group,my $file) = split(/\//,$file_name,2);
                   10319:         }
1.749     raeburn  10320:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10321:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10322:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10323:         #  remove lock
                   10324:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10325:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10326:         my $sqlresult =
1.970     raeburn  10327:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10328:                                     $group);
1.749     raeburn  10329:     } else {
                   10330:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10331:     }
1.749     raeburn  10332:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10333: }
                   10334: 
1.827     raeburn  10335: sub make_public_indefinitely {
                   10336:     my ($requrl) = @_;
                   10337:     my $now = time;
                   10338:     my $action = 'activate';
                   10339:     my $aclnum = 0;
                   10340:     if (&is_portfolio_url($requrl)) {
                   10341:         my (undef,$udom,$unum,$file_name,$group) =
                   10342:             &parse_portfolio_url($requrl);
                   10343:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10344:         my %access_controls = &get_access_controls($current_perms,
                   10345:                                                    $group,$file_name);
                   10346:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10347:             my ($num,$scope,$end,$start) = 
                   10348:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10349:             if ($scope eq 'public') {
                   10350:                 if ($start <= $now && $end == 0) {
                   10351:                     $action = 'none';
                   10352:                 } else {
                   10353:                     $action = 'update';
                   10354:                     $aclnum = $num;
                   10355:                 }
                   10356:                 last;
                   10357:             }
                   10358:         }
                   10359:         if ($action eq 'none') {
                   10360:              return 'ok';
                   10361:         } else {
                   10362:             my %changes;
                   10363:             my $newend = 0;
                   10364:             my $newstart = $now;
                   10365:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10366:             $changes{$action}{$newkey} = {
                   10367:                 type => 'public',
                   10368:                 time => {
                   10369:                     start => $newstart,
                   10370:                     end   => $newend,
                   10371:                 },
                   10372:             };
                   10373:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10374:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10375:             return $outcome;
                   10376:         }
                   10377:     } else {
                   10378:         return 'invalid';
                   10379:     }
                   10380: }
                   10381: 
1.745     raeburn  10382: #------------------------------------------------------Get Marked as Read Only
                   10383: 
                   10384: sub get_marked_as_readonly {
                   10385:     my ($domain,$user,$what,$group) = @_;
                   10386:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10387:     my @readonly_files;
1.629     banghart 10388:     my $cmp1=$what;
                   10389:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10390:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10391:         if (defined($group)) {
                   10392:             if ($file_name !~ m-^\Q$group\E/-) {
                   10393:                 next;
                   10394:             }
                   10395:         }
1.561     banghart 10396:         if (ref($value) eq "ARRAY"){
                   10397:             foreach my $stored_what (@{$value}) {
1.629     banghart 10398:                 my $cmp2=$stored_what;
1.759     albertel 10399:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10400:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10401:                 }
1.629     banghart 10402:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10403:                     push(@readonly_files, $file_name);
1.745     raeburn  10404:                     last;
1.563     banghart 10405:                 } elsif (!defined($what)) {
                   10406:                     push(@readonly_files, $file_name);
1.745     raeburn  10407:                     last;
1.561     banghart 10408:                 }
                   10409:             }
1.745     raeburn  10410:         }
1.561     banghart 10411:     }
                   10412:     return @readonly_files;
                   10413: }
1.577     banghart 10414: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10415: 
1.577     banghart 10416: sub get_marked_as_readonly_hash {
1.745     raeburn  10417:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10418:     my %readonly_files;
1.745     raeburn  10419:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10420:         if (defined($group)) {
                   10421:             if ($file_name !~ m-^\Q$group\E/-) {
                   10422:                 next;
                   10423:             }
                   10424:         }
1.577     banghart 10425:         if (ref($value) eq "ARRAY"){
                   10426:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10427:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10428:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10429:                         if ($lock_descriptor eq 'graded') {
                   10430:                             $readonly_files{$file_name} = 'graded';
                   10431:                         } elsif ($lock_descriptor eq 'handback') {
                   10432:                             $readonly_files{$file_name} = 'handback';
                   10433:                         } else {
                   10434:                             if (!exists($readonly_files{$file_name})) {
                   10435:                                 $readonly_files{$file_name} = 'locked';
                   10436:                             }
                   10437:                         }
1.745     raeburn  10438:                     }
1.750     banghart 10439:                 } 
1.577     banghart 10440:             }
                   10441:         } 
                   10442:     }
                   10443:     return %readonly_files;
                   10444: }
1.559     banghart 10445: # ------------------------------------------------------------ Unmark as Read Only
                   10446: 
                   10447: sub unmark_as_readonly {
1.629     banghart 10448:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10449:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10450:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10451:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10452:     my $symb_crs = $what;
                   10453:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10454:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10455:     my ($tmp)=keys(%current_permissions);
                   10456:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10457:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10458:     foreach my $file (@readonly_files) {
1.759     albertel 10459: 	my $clean_file = &declutter_portfile($file);
                   10460: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10461: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10462:         my @new_locks;
                   10463:         my @del_keys;
                   10464:         if (ref($current_locks) eq "ARRAY"){
                   10465:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10466:                 my $compare=$locker;
1.749     raeburn  10467:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10468:                     $compare=join('',@{$locker});
1.746     raeburn  10469:                     if ($compare ne $symb_crs) {
                   10470:                         push(@new_locks, $locker);
                   10471:                     }
1.563     banghart 10472:                 }
                   10473:             }
1.650     albertel 10474:             if (scalar(@new_locks) > 0) {
1.563     banghart 10475:                 $current_permissions{$file} = \@new_locks;
                   10476:             } else {
                   10477:                 push(@del_keys, $file);
1.613     albertel 10478:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10479:                 delete($current_permissions{$file});
1.563     banghart 10480:             }
                   10481:         }
1.561     banghart 10482:     }
1.613     albertel 10483:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10484:     return;
                   10485: }
1.512     banghart 10486: 
1.17      www      10487: # ------------------------------------------------------------ Directory lister
                   10488: 
                   10489: sub dirlist {
1.955     raeburn  10490:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10491:     $uri=~s/^\///;
                   10492:     $uri=~s/\/$//;
1.253     stredwic 10493:     my ($udom, $uname);
1.955     raeburn  10494:     if ($getuserdir) {
1.253     stredwic 10495:         $udom = $userdomain;
                   10496:         $uname = $username;
1.955     raeburn  10497:     } else {
                   10498:         (undef,$udom,$uname)=split(/\//,$uri);
                   10499:         if(defined($userdomain)) {
                   10500:             $udom = $userdomain;
                   10501:         }
                   10502:         if(defined($username)) {
                   10503:             $uname = $username;
                   10504:         }
1.253     stredwic 10505:     }
1.955     raeburn  10506:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10507: 
1.955     raeburn  10508:     $dirRoot = $perlvar{'lonDocRoot'};
                   10509:     if (defined($getpropath)) {
                   10510:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10511:         $dirRoot =~ s/\/$//;
1.955     raeburn  10512:     } elsif (defined($getuserdir)) {
                   10513:         my $subdir=$uname.'__';
                   10514:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10515:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10516:                    ."/$udom/$subdir/$uname";
                   10517:     } elsif (defined($alternateRoot)) {
                   10518:         $dirRoot = $alternateRoot;
1.751     banghart 10519:     }
1.253     stredwic 10520: 
                   10521:     if($udom) {
                   10522:         if($uname) {
1.1135    raeburn  10523:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10524:             if ($uhome eq 'no_host') {
                   10525:                 return ([],'no_host');
                   10526:             }
1.955     raeburn  10527:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10528:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10529:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10530:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10531:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10532:             } else {
                   10533:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10534:             }
1.605     matthew  10535:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10536:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10537:                 @listing_results = split(/:/,$listing);
                   10538:             } else {
                   10539:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10540:             }
1.1135    raeburn  10541:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10542:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10543:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10544:                 return ([],$listing);
                   10545:             } else {
                   10546:                 return (\@listing_results);
1.1135    raeburn  10547:             }
1.955     raeburn  10548:         } elsif(!$alternateRoot) {
1.1136    raeburn  10549:             my (%allusers,%listerror);
1.841     albertel 10550: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10551:  	    foreach my $tryserver (keys(%servers)) {
                   10552:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10553:                                   &escape($udom),$tryserver);
                   10554:                 if ($listing eq 'unknown_cmd') {
                   10555: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10556: 				      $udom, $tryserver);
                   10557:                 } else {
                   10558:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10559:                 }
1.841     albertel 10560: 		if ($listing eq 'unknown_cmd') {
                   10561: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10562: 				      $udom, $tryserver);
                   10563: 		    @listing_results = split(/:/,$listing);
                   10564: 		} else {
                   10565: 		    @listing_results =
                   10566: 			map { &unescape($_); } split(/:/,$listing);
                   10567: 		}
1.1136    raeburn  10568:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10569:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10570:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10571:                     $listerror{$tryserver} = $listing;
                   10572:                 } else {
1.841     albertel 10573: 		    foreach my $line (@listing_results) {
                   10574: 			my ($entry) = split(/&/,$line,2);
                   10575: 			$allusers{$entry} = 1;
                   10576: 		    }
                   10577: 		}
1.253     stredwic 10578:             }
1.1136    raeburn  10579:             my @alluserslist=();
1.800     albertel 10580:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10581:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10582:             }
1.1172.2.80  raeburn  10583:             if (!%listerror) {
                   10584:                 # no errors
                   10585:                 return (\@alluserslist);
                   10586:             } elsif (scalar(keys(%servers)) == 1) {
                   10587:                 # one library server, one error
                   10588:                 my ($key) = keys(%listerror);
                   10589:                 return (\@alluserslist, $listerror{$key});
                   10590:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10591:                 # con_lost indicates that we might miss data from at least one
                   10592:                 # library server
                   10593:                 return (\@alluserslist, 'con_lost');
                   10594:             } else {
                   10595:                 # multiple library servers and no con_lost -> data should be
                   10596:                 # complete.
                   10597:                 return (\@alluserslist);
                   10598:             }
                   10599: 
1.253     stredwic 10600:         } else {
1.1136    raeburn  10601:             return ([],'missing username');
1.253     stredwic 10602:         }
1.955     raeburn  10603:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10604:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10605:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10606:         return (\@all_domains);
1.955     raeburn  10607:     } else {
1.1136    raeburn  10608:         return ([],'missing domain');
1.275     stredwic 10609:     }
                   10610: }
                   10611: 
                   10612: # --------------------------------------------- GetFileTimestamp
                   10613: # This function utilizes dirlist and returns the date stamp for
                   10614: # when it was last modified.  It will also return an error of -1
                   10615: # if an error occurs
                   10616: 
                   10617: sub GetFileTimestamp {
1.955     raeburn  10618:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10619:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10620:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10621:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10622:                                     undef,$getuserdir);
                   10623:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10624:         return -1;
                   10625:     }
                   10626:     if (ref($fileref) eq 'ARRAY') {
                   10627:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10628:         # @stats contains first the filename, then the stat output
                   10629:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10630:     } else {
                   10631:         return -1;
1.253     stredwic 10632:     }
1.26      www      10633: }
                   10634: 
1.712     albertel 10635: sub stat_file {
                   10636:     my ($uri) = @_;
1.787     albertel 10637:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10638: 
1.955     raeburn  10639:     my ($udom,$uname,$file);
1.712     albertel 10640:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10641: 	($udom,$uname,$file) =
1.811     albertel 10642: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10643: 	$file = 'userfiles/'.$file;
                   10644:     }
                   10645:     if ($uri =~ m-^/res/-) {
                   10646: 	($udom,$uname) = 
1.807     albertel 10647: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10648: 	$file = $uri;
                   10649:     }
                   10650: 
                   10651:     if (!$udom || !$uname || !$file) {
                   10652: 	# unable to handle the uri
                   10653: 	return ();
                   10654:     }
1.956     raeburn  10655:     my $getpropath;
                   10656:     if ($file =~ /^userfiles\//) {
                   10657:         $getpropath = 1;
                   10658:     }
1.1136    raeburn  10659:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10660:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10661:         return ();
                   10662:     } else {
                   10663:         if (ref($listref) eq 'ARRAY') {
                   10664:             my @stats = split('&',$listref->[0]);
                   10665: 	    shift(@stats); #filename is first
                   10666: 	    return @stats;
                   10667:         }
1.712     albertel 10668:     }
                   10669:     return ();
                   10670: }
                   10671: 
1.26      www      10672: # -------------------------------------------------------- Value of a Condition
                   10673: 
1.713     albertel 10674: # gets the value of a specific preevaluated condition
                   10675: #    stored in the string  $env{user.state.<cid>}
                   10676: # or looks up a condition reference in the bighash and if if hasn't
                   10677: # already been evaluated recurses into docondval to get the value of
                   10678: # the condition, then memoizing it to 
                   10679: #   $env{user.state.<cid>.<condition>}
1.40      www      10680: sub directcondval {
                   10681:     my $number=shift;
1.620     albertel 10682:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10683: 	&Apache::lonuserstate::evalstate();
                   10684:     }
1.713     albertel 10685:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10686: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10687:     } elsif ($number =~ /^_/) {
                   10688: 	my $sub_condition;
                   10689: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10690: 		&GDBM_READER(),0640)) {
                   10691: 	    $sub_condition=$bighash{'conditions'.$number};
                   10692: 	    untie(%bighash);
                   10693: 	}
                   10694: 	my $value = &docondval($sub_condition);
1.949     raeburn  10695: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10696: 	return $value;
                   10697:     }
1.620     albertel 10698:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10699:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10700:     } else {
                   10701:        return 2;
                   10702:     }
                   10703: }
                   10704: 
1.713     albertel 10705: # get the collection of conditions for this resource
1.26      www      10706: sub condval {
                   10707:     my $condidx=shift;
1.54      www      10708:     my $allpathcond='';
1.713     albertel 10709:     foreach my $cond (split(/\|/,$condidx)) {
                   10710: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10711: 	    $allpathcond.=
                   10712: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10713: 	}
1.191     harris41 10714:     }
1.54      www      10715:     $allpathcond=~s/\|$//;
1.713     albertel 10716:     return &docondval($allpathcond);
                   10717: }
                   10718: 
                   10719: #evaluates an expression of conditions
                   10720: sub docondval {
                   10721:     my ($allpathcond) = @_;
                   10722:     my $result=0;
                   10723:     if ($env{'request.course.id'}
                   10724: 	&& defined($allpathcond)) {
                   10725: 	my $operand='|';
                   10726: 	my @stack;
                   10727: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10728: 	    if ($chunk eq '(') {
                   10729: 		push @stack,($operand,$result);
                   10730: 	    } elsif ($chunk eq ')') {
                   10731: 		my $before=pop @stack;
                   10732: 		if (pop @stack eq '&') {
                   10733: 		    $result=$result>$before?$before:$result;
                   10734: 		} else {
                   10735: 		    $result=$result>$before?$result:$before;
                   10736: 		}
                   10737: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10738: 		$operand=$chunk;
                   10739: 	    } else {
                   10740: 		my $new=directcondval($chunk);
                   10741: 		if ($operand eq '&') {
                   10742: 		    $result=$result>$new?$new:$result;
                   10743: 		} else {
                   10744: 		    $result=$result>$new?$result:$new;
                   10745: 		}
                   10746: 	    }
                   10747: 	}
1.26      www      10748:     }
                   10749:     return $result;
1.421     albertel 10750: }
                   10751: 
                   10752: # ---------------------------------------------------- Devalidate courseresdata
                   10753: 
                   10754: sub devalidatecourseresdata {
                   10755:     my ($coursenum,$coursedomain)=@_;
                   10756:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10757:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10758: }
                   10759: 
1.763     www      10760: 
1.200     www      10761: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10762: #
                   10763: #  Parameters:
                   10764: #      $coursenum    - Number of the course.
                   10765: #      $coursedomain - Domain at which the course was created.
                   10766: #  Returns:
                   10767: #     A hash of the course parameters along (I think) with timestamps
                   10768: #     and version info.
1.877     foxr     10769: 
1.624     albertel 10770: sub get_courseresdata {
                   10771:     my ($coursenum,$coursedomain)=@_;
1.200     www      10772:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10773:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10774:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10775:     my %dumpreply;
1.417     albertel 10776:     unless (defined($cached)) {
1.624     albertel 10777: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10778: 	$result=\%dumpreply;
1.251     albertel 10779: 	my ($tmp) = keys(%dumpreply);
                   10780: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10781: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10782: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10783: 	    return $tmp;
1.416     albertel 10784: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10785: 	    $result=undef;
1.599     albertel 10786: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10787: 	}
                   10788:     }
1.624     albertel 10789:     return $result;
                   10790: }
                   10791: 
1.633     albertel 10792: sub devalidateuserresdata {
                   10793:     my ($uname,$udom)=@_;
                   10794:     my $hashid="$udom:$uname";
                   10795:     &devalidate_cache_new('userres',$hashid);
                   10796: }
                   10797: 
1.624     albertel 10798: sub get_userresdata {
                   10799:     my ($uname,$udom)=@_;
                   10800:     #most student don\'t have any data set, check if there is some data
                   10801:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10802: 
                   10803:     my $hashid="$udom:$uname";
                   10804:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10805:     if (!defined($cached)) {
                   10806: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10807: 	$result=\%resourcedata;
                   10808: 	&do_cache_new('userres',$hashid,$result,600);
                   10809:     }
                   10810:     my ($tmp)=keys(%$result);
                   10811:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10812: 	return $result;
                   10813:     }
                   10814:     #error 2 occurs when the .db doesn't exist
                   10815:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10816:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10817: 	    &logthis("<font color=\"blue\">WARNING:".
                   10818: 		     " Trying to get resource data for ".
                   10819: 		     $uname." at ".$udom.": ".
                   10820: 		     $tmp."</font>");
                   10821:         }
1.624     albertel 10822:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10823: 	#&EXT_cache_set($udom,$uname);
                   10824: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10825: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10826:     }
                   10827:     return $tmp;
                   10828: }
1.879     foxr     10829: #----------------------------------------------- resdata - return resource data
                   10830: #  Purpose:
                   10831: #    Return resource data for either users or for a course.
                   10832: #  Parameters:
                   10833: #     $name      - Course/user name.
                   10834: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.93.4  1(raebur 10835:7): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     10836: #     @which     - Array of names of resources desired.
                   10837: #  Returns:
                   10838: #     The value of the first reasource in @which that is found in the
                   10839: #     resource hash.
                   10840: #  Exceptional Conditions:
                   10841: #     If the $type passed in is not valid (not the string 'course' or 
                   10842: #     'user', an undefined  reference is returned.
                   10843: #     If none of the resources are found, an undef is returned
1.624     albertel 10844: sub resdata {
                   10845:     my ($name,$domain,$type,@which)=@_;
                   10846:     my $result;
                   10847:     if ($type eq 'course') {
                   10848: 	$result=&get_courseresdata($name,$domain);
                   10849:     } elsif ($type eq 'user') {
                   10850: 	$result=&get_userresdata($name,$domain);
                   10851:     }
                   10852:     if (!ref($result)) { return $result; }    
1.251     albertel 10853:     foreach my $item (@which) {
1.1172.2.93.4  1(raebur 10854:7):         if (ref($item) eq 'ARRAY') {
                   10855:7): 	    if (defined($result->{$item->[0]})) {
                   10856:7): 	        return [$result->{$item->[0]},$item->[1]];
                   10857:7): 	    }
                   10858:7):         }
1.250     albertel 10859:     }
1.291     albertel 10860:     return undef;
1.200     www      10861: }
                   10862: 
1.1172.2.93.4  2(raebur 10863:7): sub get_domain_ltitools {
                   10864:7):     my ($cdom) = @_;
                   10865:7):     my %ltitools;
                   10866:7):     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10867:7):     if (defined($cached)) {
                   10868:7):         if (ref($result) eq 'HASH') {
                   10869:7):             %ltitools = %{$result};
                   10870:7):         }
                   10871:7):     } else {
                   10872:7):         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10873:7):         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10874:7):             %ltitools = %{$domconfig{'ltitools'}};
                   10875:7):             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
                   10876:7):             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
                   10877:7):                 foreach my $id (keys(%ltitools)) {
                   10878:7):                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
                   10879:7):                         foreach my $item ('key','secret') {
                   10880:7):                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
                   10881:7):                         }
                   10882:7):                     }
                   10883:7):                 }
                   10884:7):             }
                   10885:7):         }
                   10886:7):         my $cachetime = 24*60*60;
                   10887:7):         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10888:7):     }
                   10889:7):     return %ltitools;
                   10890:7): }
                   10891:7): 
1.1172.2.31  raeburn  10892: sub get_numsuppfiles {
                   10893:     my ($cnum,$cdom,$ignorecache)=@_;
                   10894:     my $hashid=$cnum.':'.$cdom;
                   10895:     my ($suppcount,$cached);
                   10896:     unless ($ignorecache) {
                   10897:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10898:     }
                   10899:     unless (defined($cached)) {
                   10900:         my $chome=&homeserver($cnum,$cdom);
                   10901:         unless ($chome eq 'no_host') {
                   10902:             ($suppcount,my $errors) = (0,0);
                   10903:             my $suppmap = 'supplemental.sequence';
                   10904:             ($suppcount,$errors) =
                   10905:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10906:         }
                   10907:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10908:     }
                   10909:     return $suppcount;
                   10910: }
                   10911: 
1.379     matthew  10912: #
                   10913: # EXT resource caching routines
                   10914: #
                   10915: 
                   10916: sub clear_EXT_cache_status {
1.383     albertel 10917:     &delenv('cache.EXT.');
1.379     matthew  10918: }
                   10919: 
                   10920: sub EXT_cache_status {
                   10921:     my ($target_domain,$target_user) = @_;
1.383     albertel 10922:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10923:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10924:         # We know already the user has no data
                   10925:         return 1;
                   10926:     } else {
                   10927:         return 0;
                   10928:     }
                   10929: }
                   10930: 
                   10931: sub EXT_cache_set {
                   10932:     my ($target_domain,$target_user) = @_;
1.383     albertel 10933:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10934:     #&appenv({$cachename => time});
1.379     matthew  10935: }
                   10936: 
1.28      www      10937: # --------------------------------------------------------- Value of a Variable
1.58      www      10938: sub EXT {
1.715     albertel 10939: 
1.1172.2.28  raeburn  10940:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10941:     unless ($varname) { return ''; }
1.218     albertel 10942:     #get real user name/domain, courseid and symb
                   10943:     my $courseid;
1.359     albertel 10944:     my $publicuser;
1.427     www      10945:     if ($symbparm) {
                   10946: 	$symbparm=&get_symb_from_alias($symbparm);
                   10947:     }
1.218     albertel 10948:     if (!($uname && $udom)) {
1.790     albertel 10949:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10950:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10951:     } else {
1.620     albertel 10952: 	$courseid=$env{'request.course.id'};
1.218     albertel 10953:     }
1.48      www      10954:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10955:     my $rest;
1.320     albertel 10956:     if (defined($therest[0])) {
1.48      www      10957:        $rest=join('.',@therest);
                   10958:     } else {
                   10959:        $rest='';
                   10960:     }
1.320     albertel 10961: 
1.57      www      10962:     my $qualifierrest=$qualifier;
                   10963:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10964:     my $spacequalifierrest=$space;
                   10965:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10966:     if ($realm eq 'user') {
1.48      www      10967: # --------------------------------------------------------------- user.resource
                   10968: 	if ($space eq 'resource') {
1.651     albertel 10969: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10970: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10971: 		 &&
1.744     albertel 10972: 		 ($symbparm eq &symbread()) ) {	
                   10973: 		# if we are in the middle of processing the resource the
                   10974: 		# get the value we are planning on committing
                   10975:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10976:                     return $Apache::lonhomework::results{$qualifierrest};
                   10977:                 } else {
                   10978:                     return $Apache::lonhomework::history{$qualifierrest};
                   10979:                 }
1.335     albertel 10980: 	    } else {
1.359     albertel 10981: 		my %restored;
1.620     albertel 10982: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10983: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10984: 		} else {
                   10985: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10986: 		}
1.335     albertel 10987: 		return $restored{$qualifierrest};
                   10988: 	    }
1.48      www      10989: # ----------------------------------------------------------------- user.access
                   10990:         } elsif ($space eq 'access') {
1.218     albertel 10991: 	    # FIXME - not supporting calls for a specific user
1.48      www      10992:             return &allowed($qualifier,$rest);
                   10993: # ------------------------------------------ user.preferences, user.environment
                   10994:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10995: 	    if (($uname eq $env{'user.name'}) &&
                   10996: 		($udom eq $env{'user.domain'})) {
                   10997: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10998: 	    } else {
1.359     albertel 10999: 		my %returnhash;
                   11000: 		if (!$publicuser) {
                   11001: 		    %returnhash=&userenvironment($udom,$uname,
                   11002: 						 $qualifierrest);
                   11003: 		}
1.218     albertel 11004: 		return $returnhash{$qualifierrest};
                   11005: 	    }
1.48      www      11006: # ----------------------------------------------------------------- user.course
                   11007:         } elsif ($space eq 'course') {
1.218     albertel 11008: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11009:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11010: # ------------------------------------------------------------------- user.role
                   11011:         } elsif ($space eq 'role') {
1.218     albertel 11012: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11013:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11014:             if ($qualifier eq 'value') {
                   11015: 		return $role;
                   11016:             } elsif ($qualifier eq 'extent') {
                   11017:                 return $where;
                   11018:             }
                   11019: # ----------------------------------------------------------------- user.domain
                   11020:         } elsif ($space eq 'domain') {
1.218     albertel 11021:             return $udom;
1.48      www      11022: # ------------------------------------------------------------------- user.name
                   11023:         } elsif ($space eq 'name') {
1.218     albertel 11024:             return $uname;
1.48      www      11025: # ---------------------------------------------------- Any other user namespace
1.29      www      11026:         } else {
1.359     albertel 11027: 	    my %reply;
                   11028: 	    if (!$publicuser) {
                   11029: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11030: 	    }
                   11031: 	    return $reply{$qualifierrest};
1.48      www      11032:         }
1.236     www      11033:     } elsif ($realm eq 'query') {
                   11034: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11035:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11036: 						[$spacequalifierrest]);
1.620     albertel 11037: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11038:    } elsif ($realm eq 'request') {
1.48      www      11039: # ------------------------------------------------------------- request.browser
                   11040:         if ($space eq 'browser') {
1.1145    bisitz   11041:             return $env{'browser.'.$qualifier};
1.57      www      11042: # ------------------------------------------------------------ request.filename
                   11043:         } else {
1.620     albertel 11044:             return $env{'request.'.$spacequalifierrest};
1.29      www      11045:         }
1.28      www      11046:     } elsif ($realm eq 'course') {
1.48      www      11047: # ---------------------------------------------------------- course.description
1.620     albertel 11048:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11049:     } elsif ($realm eq 'resource') {
1.165     www      11050: 
1.620     albertel 11051: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11052: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11053: 	}
1.693     albertel 11054: 
1.1172.2.30  raeburn  11055:         if ($qualifier eq '') {
                   11056: 	    if ($space eq 'title') {
                   11057: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11058: 	        return &gettitle($symbparm);
                   11059: 	    }
1.693     albertel 11060: 	
1.1172.2.30  raeburn  11061: 	    if ($space eq 'map') {
                   11062: 	        my ($map) = &decode_symb($symbparm);
                   11063: 	        return &symbread($map);
                   11064: 	    }
                   11065:             if ($space eq 'maptitle') {
                   11066:                 my ($map) = &decode_symb($symbparm);
                   11067:                 return &gettitle($map);
                   11068:             }
                   11069: 	    if ($space eq 'filename') {
                   11070: 	        if ($symbparm) {
                   11071: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11072: 	        }
                   11073: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11074: 	    }
1.1172.2.30  raeburn  11075: 
                   11076:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11077:                 if ($space eq 'visibleparts') {
                   11078:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11079:                     my $item;
                   11080:                     if (ref($navmap)) {
                   11081:                         my $res = $navmap->getBySymb($symbparm);
                   11082:                         my $parts = $res->parts();
                   11083:                         if (ref($parts) eq 'ARRAY') {
                   11084:                             $item = join(',',@{$parts});
                   11085:                         }
                   11086:                         undef($navmap);
                   11087:                     }
                   11088:                     return $item;
                   11089:                 }
                   11090:             }
                   11091:         }
1.693     albertel 11092: 
                   11093: 	my ($section, $group, @groups);
1.593     albertel 11094: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11095:         if (($courseid eq '') && ($cid)) {
                   11096:             $courseid = $cid;
                   11097:         }
                   11098: 	if (($symbparm && $courseid) && 
                   11099: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11100: 
1.218     albertel 11101: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11102: 
1.60      www      11103: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11104: 	    my $symbp=$symbparm;
1.735     albertel 11105: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11106: 
                   11107: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11108: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11109: 
1.620     albertel 11110: 	    if (($env{'user.name'} eq $uname) &&
                   11111: 		($env{'user.domain'} eq $udom)) {
                   11112: 		$section=$env{'request.course.sec'};
1.733     raeburn  11113:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11114:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11115: 	    } else {
1.539     albertel 11116: 		if (! defined($usection)) {
1.551     albertel 11117: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11118: 		} else {
                   11119: 		    $section = $usection;
                   11120: 		}
1.733     raeburn  11121:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11122: 	    }
                   11123: 
                   11124: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11125: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11126: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11127: 
1.593     albertel 11128: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11129: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11130: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11131: 
1.60      www      11132: # ----------------------------------------------------------- first, check user
1.624     albertel 11133: 
                   11134: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11135: 				       ([$courselevelr,'resource'],
                   11136: 					[$courselevelm,'map'     ],
                   11137: 					[$courselevel, 'course'  ]));
1.931     albertel 11138: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11139: 
1.594     albertel 11140: # ------------------------------------------------ second, check some of course
1.684     raeburn  11141:             my $coursereply;
1.691     raeburn  11142:             if (@groups > 0) {
                   11143:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11144:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11145:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11146:             }
1.96      www      11147: 
1.684     raeburn  11148: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11149: 				  $env{'course.'.$courseid.'.domain'},
                   11150: 				  'course',
                   11151: 				  ([$seclevelr,   'resource'],
                   11152: 				   [$seclevelm,   'map'     ],
                   11153: 				   [$seclevel,    'course'  ],
                   11154: 				   [$courselevelr,'resource']));
                   11155: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11156: 
1.60      www      11157: # ------------------------------------------------------ third, check map parms
1.218     albertel 11158: 	    my %parmhash=();
                   11159: 	    my $thisparm='';
                   11160: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11161: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11162: 		    &GDBM_READER(),0640)) {
1.218     albertel 11163: 		$thisparm=$parmhash{$symbparm};
                   11164: 		untie(%parmhash);
                   11165: 	    }
1.927     albertel 11166: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11167: 	}
1.594     albertel 11168: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11169: 
1.218     albertel 11170: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11171: 	my $filename;
                   11172: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11173: 	if ($symbparm) {
1.409     www      11174: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11175: 	} else {
1.620     albertel 11176: 	    $filename=$env{'request.filename'};
1.282     albertel 11177: 	}
                   11178: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11179: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11180: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11181: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11182: 
1.927     albertel 11183: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11184: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11185: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11186: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11187: 				     $env{'course.'.$courseid.'.domain'},
                   11188: 				     'course',
1.927     albertel 11189: 				     ([$courselevelm,'map'   ],
                   11190: 				      [$courselevel, 'course']));
                   11191: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11192: 	}
1.145     www      11193: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11194: 	unless ($space eq '0') {
1.336     albertel 11195: 	    my @parts=split(/_/,$space);
                   11196: 	    my $id=pop(@parts);
                   11197: 	    my $part=join('_',@parts);
                   11198: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11199: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11200: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11201: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11202: 	}
1.395     albertel 11203: 	if ($recurse) { return undef; }
                   11204: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11205: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11206: # ---------------------------------------------------- Any other user namespace
                   11207:     } elsif ($realm eq 'environment') {
                   11208: # ----------------------------------------------------------------- environment
1.620     albertel 11209: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11210: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11211: 	} else {
1.770     albertel 11212: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11213: 		return '';
                   11214: 	    }
1.219     albertel 11215: 	    my %returnhash=&userenvironment($udom,$uname,
                   11216: 					    $spacequalifierrest);
                   11217: 	    return $returnhash{$spacequalifierrest};
                   11218: 	}
1.28      www      11219:     } elsif ($realm eq 'system') {
1.48      www      11220: # ----------------------------------------------------------------- system.time
                   11221: 	if ($space eq 'time') {
                   11222: 	    return time;
                   11223:         }
1.696     albertel 11224:     } elsif ($realm eq 'server') {
                   11225: # ----------------------------------------------------------------- system.time
                   11226: 	if ($space eq 'name') {
                   11227: 	    return $ENV{'SERVER_NAME'};
                   11228:         }
1.28      www      11229:     }
1.48      www      11230:     return '';
1.61      www      11231: }
                   11232: 
1.927     albertel 11233: sub get_reply {
                   11234:     my ($reply_value) = @_;
1.940     raeburn  11235:     if (ref($reply_value) eq 'ARRAY') {
                   11236:         if (wantarray) {
                   11237: 	    return @$reply_value;
                   11238:         }
                   11239:         return $reply_value->[0];
                   11240:     } else {
                   11241:         return $reply_value;
1.927     albertel 11242:     }
                   11243: }
                   11244: 
1.691     raeburn  11245: sub check_group_parms {
                   11246:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11247:     my @groupitems = ();
                   11248:     my $resultitem;
1.927     albertel 11249:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11250:     foreach my $group (@{$groups}) {
                   11251:         foreach my $level (@levels) {
1.927     albertel 11252:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11253:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11254:         }
                   11255:     }
                   11256:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11257:                             $env{'course.'.$courseid.'.domain'},
                   11258:                                      'course',@groupitems);
                   11259:     return $coursereply;
                   11260: }
                   11261: 
                   11262: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11263:     my ($courseid,@groups) = @_;
                   11264:     @groups = sort(@groups);
1.691     raeburn  11265:     return @groups;
                   11266: }
                   11267: 
1.395     albertel 11268: sub packages_tab_default {
                   11269:     my ($uri,$varname)=@_;
                   11270:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11271: 
                   11272:     my (@extension,@specifics,$do_default);
                   11273:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11274: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11275: 	if ($pack_type eq 'default') {
                   11276: 	    $do_default=1;
                   11277: 	} elsif ($pack_type eq 'extension') {
                   11278: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11279: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11280: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11281: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11282: 	}
                   11283:     }
                   11284:     # first look for a package that matches the requested part id
                   11285:     foreach my $package (@specifics) {
                   11286: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11287: 	next if ($pack_part ne $part);
                   11288: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11289: 	    return $packagetab{"$pack_type&$name&default"};
                   11290: 	}
                   11291:     }
                   11292:     # look for any possible matching non extension_ package
                   11293:     foreach my $package (@specifics) {
                   11294: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11295: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11296: 	    return $packagetab{"$pack_type&$name&default"};
                   11297: 	}
1.585     albertel 11298: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11299: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11300: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11301: 	}
                   11302:     }
1.738     albertel 11303:     # look for any posible extension_ match
                   11304:     foreach my $package (@extension) {
                   11305: 	my ($package,$pack_type)=@{$package};
                   11306: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11307: 	    return $packagetab{"$pack_type&$name&default"};
                   11308: 	}
                   11309: 	if (defined($packagetab{$package."&$name&default"})) {
                   11310: 	    return $packagetab{$package."&$name&default"};
                   11311: 	}
                   11312:     }
                   11313:     # look for a global default setting
                   11314:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11315: 	return $packagetab{"default&$name&default"};
                   11316:     }
1.395     albertel 11317:     return undef;
                   11318: }
                   11319: 
1.334     albertel 11320: sub add_prefix_and_part {
                   11321:     my ($prefix,$part)=@_;
                   11322:     my $keyroot;
                   11323:     if (defined($prefix) && $prefix !~ /^__/) {
                   11324: 	# prefix that has a part already
                   11325: 	$keyroot=$prefix;
                   11326:     } elsif (defined($prefix)) {
                   11327: 	# prefix that is missing a part
                   11328: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11329:     } else {
                   11330: 	# no prefix at all
                   11331: 	if (defined($part)) { $keyroot='_'.$part; }
                   11332:     }
                   11333:     return $keyroot;
                   11334: }
                   11335: 
1.71      www      11336: # ---------------------------------------------------------------- Get metadata
                   11337: 
1.599     albertel 11338: my %metaentry;
1.1070    www      11339: my %importedpartids;
1.1172.2.93.4  8(raebur 11340:8): my %importedrespids;
1.71      www      11341: sub metadata {
1.176     www      11342:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11343:     $uri=&declutter($uri);
1.288     albertel 11344:     # if it is a non metadata possible uri return quickly
1.529     albertel 11345:     if (($uri eq '') || 
                   11346: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.93.4  2(raebur 11347:7): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11348:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11349: 	return undef;
                   11350:     }
1.1172.2.49  raeburn  11351:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11352: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11353: 	return undef;
1.288     albertel 11354:     }
1.73      www      11355:     my $filename=$uri;
                   11356:     $uri=~s/\.meta$//;
1.172     www      11357: #
                   11358: # Is the metadata already cached?
1.177     www      11359: # Look at timestamp of caching
1.172     www      11360: # Everything is cached by the main uri, libraries are never directly cached
                   11361: #
1.428     albertel 11362:     if (!defined($liburi)) {
1.599     albertel 11363: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11364: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11365:     }
                   11366:     {
1.1069    www      11367: # Imported parts would go here
1.1172.2.93.4  8(raebur 11368:8):         my @origfiletagids=();
1.1069    www      11369:         my $importedparts=0;
1.1172.2.93.4  8(raebur 11370:8): 
                   11371:8): # Imported responseids would go here
                   11372:8):         my $importedresponses=0;
1.172     www      11373: #
                   11374: # Is this a recursive call for a library?
                   11375: #
1.599     albertel 11376: #	if (! exists($metacache{$uri})) {
                   11377: #	    $metacache{$uri}={};
                   11378: #	}
1.924     albertel 11379: 	my $cachetime = 60*60;
1.171     www      11380:         if ($liburi) {
                   11381: 	    $liburi=&declutter($liburi);
                   11382:             $filename=$liburi;
1.401     bowersj2 11383:         } else {
1.599     albertel 11384: 	    &devalidate_cache_new('meta',$uri);
                   11385: 	    undef(%metaentry);
1.401     bowersj2 11386: 	}
1.140     www      11387:         my %metathesekeys=();
1.73      www      11388:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11389: 	my $metastring;
1.1140    www      11390: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11391: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11392: 	    $metastring = 
1.929     albertel 11393: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11394: 					  ('grade_target' => 'meta'));
                   11395: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11396: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11397:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11398: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11399: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11400: 	    $metastring=&getfile($file);
1.489     albertel 11401: 	}
1.208     albertel 11402:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11403:         my $token;
1.140     www      11404:         undef %metathesekeys;
1.71      www      11405:         while ($token=$parser->get_token) {
1.339     albertel 11406: 	    if ($token->[0] eq 'S') {
                   11407: 		if (defined($token->[2]->{'package'})) {
1.172     www      11408: #
                   11409: # This is a package - get package info
                   11410: #
1.339     albertel 11411: 		    my $package=$token->[2]->{'package'};
                   11412: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11413: 		    if (defined($token->[2]->{'id'})) { 
                   11414: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11415: 		    }
1.599     albertel 11416: 		    if ($metaentry{':packages'}) {
                   11417: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11418: 		    } else {
1.599     albertel 11419: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11420: 		    }
1.736     albertel 11421: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11422: 			my $part=$keyroot;
                   11423: 			$part=~s/^\_//;
1.736     albertel 11424: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11425: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11426: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11427: 			    # ignore package.tab specified default values
                   11428:                             # here &package_tab_default() will fetch those
                   11429: 			    if ($subp eq 'default') { next; }
1.736     albertel 11430: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11431: 			    my $unikey;
                   11432: 			    if ($pack =~ /_0$/) {
                   11433: 				$unikey='parameter_0_'.$name;
                   11434: 				$part=0;
                   11435: 			    } else {
                   11436: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11437: 			    }
1.339     albertel 11438: 			    if ($subp eq 'display') {
                   11439: 				$value.=' [Part: '.$part.']';
                   11440: 			    }
1.599     albertel 11441: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11442: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11443: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11444: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11445: 			    }
1.599     albertel 11446: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11447: 				$metaentry{':'.$unikey}=
                   11448: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11449: 			    }
1.339     albertel 11450: 			}
                   11451: 		    }
                   11452: 		} else {
1.172     www      11453: #
                   11454: # This is not a package - some other kind of start tag
1.339     albertel 11455: #
                   11456: 		    my $entry=$token->[1];
1.1068    www      11457: 		    my $unikey='';
1.175     www      11458: 
1.339     albertel 11459: 		    if ($entry eq 'import') {
1.175     www      11460: #
                   11461: # Importing a library here
1.339     albertel 11462: #
1.1067    www      11463:                         my $location=$parser->get_text('/import');
                   11464:                         my $dir=$filename;
                   11465:                         $dir=~s|[^/]*$||;
                   11466:                         $location=&filelocation($dir,$location);
1.1172.2.93.4  8(raebur 11467:8): 
                   11468:8):                         my $importid=$token->[2]->{'id'};
1.1068    www      11469:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.93.4  8(raebur 11470:8): #
                   11471:8): # Check metadata for imported file to
                   11472:8): # see if it contained response items
                   11473:8): #
          9(raebur 11474:8):                         my %currmetaentry = %metaentry;
          8(raebur 11475:8):                         my $libresponseorder = &metadata($location,'responseorder');
                   11476:8):                         my $origfile;
                   11477:8):                         if ($libresponseorder ne '') {
                   11478:8):                             if ($#origfiletagids<0) {
                   11479:8):                                 undef(%importedrespids);
                   11480:8):                                 undef(%importedpartids);
                   11481:8):                             }
                   11482:8):                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11483:8):                             if (@{$importedrespids{$importid}} > 0) {
                   11484:8):                                 $importedresponses = 1;
                   11485:8): # We need to get the original file and the imported file to get the response order correct
                   11486:8): # Load and inspect original file
                   11487:8):                                 if ($#origfiletagids<0) {
                   11488:8):                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11489:8):                                     $origfile=&getfile($origfilelocation);
                   11490:8):                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11491:8):                                 }
                   11492:8):                             }
                   11493:8):                         }
          9(raebur 11494:8): # Do not overwrite contents of %metaentry hash for resource itself with 
                   11495:8): # hash populated for imported library file
                   11496:8):                         %metaentry = %currmetaentry;
                   11497:8):                         undef(%currmetaentry);
1.1068    www      11498:                         if ($importmode eq 'problem') {
1.1069    www      11499: # Import as problem/response
1.1068    www      11500:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11501:                         } elsif ($importmode eq 'part') {
                   11502: # Import as part(s)
1.1069    www      11503:                            $importedparts=1;
                   11504: # We need to get the original file and the imported file to get the part order correct
                   11505: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.93.4  8(raebur 11506:8): # Load and inspect original file if we didn't do that already
          9(raebur 11507:8):                            if ($#origfiletagids<0) {
          8(raebur 11508:8):                                undef(%importedrespids);
                   11509:8):                                undef(%importedpartids);
                   11510:8):                                if ($origfile eq '') {
                   11511:8):                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11512:8):                                    $origfile=&getfile($origfilelocation);
                   11513:8):                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11514:8):                                }
1.1070    www      11515:                            }
                   11516: 
1.1069    www      11517: # Load and inspect imported file
                   11518:                            my $impfile=&getfile($location);
                   11519:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11520:                            if ($#impfilepartids>=0) {
                   11521: # This problem had parts
1.1070    www      11522:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11523:                            } else {
                   11524: # Importing by turning a single problem into a problem part
                   11525: # It gets the import-tags ID as part-ID
                   11526:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11527:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11528:                            }
1.1068    www      11529:                         } else {
                   11530: # Normal import
                   11531:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11532:                            if (defined($token->[2]->{'id'})) {
                   11533:                               $unikey.='_'.$token->[2]->{'id'};
                   11534:                            }
1.1067    www      11535:                         }
                   11536: 
1.339     albertel 11537: 			if ($depthcount<20) {
1.736     albertel 11538: 			    my $metadata = 
                   11539: 				&metadata($uri,'keys', $location,$unikey,
                   11540: 					  $depthcount+1);
                   11541: 			    foreach my $meta (split(',',$metadata)) {
                   11542: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11543: 				$metathesekeys{$meta}=1;
1.339     albertel 11544: 			    }
1.1068    www      11545: 			
                   11546:                         }
1.1067    www      11547: 		    } else {
                   11548: #
                   11549: # Not importing, some other kind of non-package, non-library start tag
                   11550: # 
                   11551:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11552:                         if (defined($token->[2]->{'id'})) {
                   11553:                             $unikey.='_'.$token->[2]->{'id'};
                   11554:                         }
1.339     albertel 11555: 			if (defined($token->[2]->{'name'})) { 
                   11556: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11557: 			}
                   11558: 			$metathesekeys{$unikey}=1;
1.736     albertel 11559: 			foreach my $param (@{$token->[3]}) {
                   11560: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11561: 				$token->[2]->{$param};
1.339     albertel 11562: 			}
                   11563: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11564: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11565: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11566: 		 # only ws inside the tag, and not in default, so use default
                   11567: 		 # as value
1.599     albertel 11568: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11569: 			} elsif ( $internaltext =~ /\S/ ) {
                   11570: 		  # something interesting inside the tag
                   11571: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11572: 			} else {
1.908     albertel 11573: 		  # no interesting values, don't set a default
1.339     albertel 11574: 			}
1.172     www      11575: # end of not-a-package not-a-library import
1.339     albertel 11576: 		    }
1.172     www      11577: # end of not-a-package start tag
1.339     albertel 11578: 		}
1.172     www      11579: # the next is the end of "start tag"
1.339     albertel 11580: 	    }
                   11581: 	}
1.483     albertel 11582: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11583: 	$extension = lc($extension);
                   11584: 	if ($extension eq 'htm') { $extension='html'; }
                   11585: 
1.737     albertel 11586: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11587: 	    #no specific packages #how's our extension
                   11588: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11589: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11590: 					 \%metathesekeys);
                   11591: 	}
1.883     albertel 11592: 
                   11593: 	if (!exists($metaentry{':packages'})
                   11594: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11595: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11596: 		#no specific packages well let's get default then
                   11597: 		if ($key!~/^default&/) { next; }
1.488     albertel 11598: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11599: 					     \%metathesekeys);
                   11600: 	    }
                   11601: 	}
1.338     www      11602: # are there custom rights to evaluate
1.599     albertel 11603: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11604: 
1.338     www      11605:     #
                   11606:     # Importing a rights file here
1.339     albertel 11607:     #
                   11608: 	    unless ($depthcount) {
1.599     albertel 11609: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11610: 		my $dir=$filename;
                   11611: 		$dir=~s|[^/]*$||;
                   11612: 		$location=&filelocation($dir,$location);
1.736     albertel 11613: 		my $rights_metadata =
                   11614: 		    &metadata($uri,'keys',$location,'_rights',
                   11615: 			      $depthcount+1);
                   11616: 		foreach my $rights (split(',',$rights_metadata)) {
                   11617: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11618: 		    $metathesekeys{$rights}=1;
1.339     albertel 11619: 		}
                   11620: 	    }
                   11621: 	}
1.737     albertel 11622: 	# uniqifiy package listing
                   11623: 	my %seen;
                   11624: 	my @uniq_packages =
                   11625: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11626: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11627: 
1.1172.2.93.4  8(raebur 11628:8):         if (($importedresponses) || ($importedparts)) {
                   11629:8):             if ($importedparts) {
1.1070    www      11630: # We had imported parts and need to rebuild partorder
1.1172.2.93.4  8(raebur 11631:8):                 $metaentry{':partorder'}='';
                   11632:8):                 $metathesekeys{'partorder'}=1;
                   11633:8):             }
                   11634:8):             if ($importedresponses) {
                   11635:8): # We had imported responses and need to rebuild responseorder
                   11636:8):                 $metaentry{':responseorder'}='';
                   11637:8):                 $metathesekeys{'responseorder'}=1;
                   11638:8):             }
                   11639:8):             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11640:8):                 my $origid = $origfiletagids[$index+1];
                   11641:8):                 if ($origfiletagids[$index] eq 'part') {
                   11642:8): # Original part, part of the problem
                   11643:8):                     if ($importedparts) {
                   11644:8):                         $metaentry{':partorder'}.=','.$origid;
                   11645:8):                     }
                   11646:8):                 } elsif ($origfiletagids[$index] eq 'import') {
                   11647:8):                     if ($importedparts) {
                   11648:8): # We have imported parts at this position
                   11649:8):                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11650:8):                     }
                   11651:8):                     if ($importedresponses) {
                   11652:8): # We have imported responses at this position
                   11653:8):                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11654:8):                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11655:8):                         }
                   11656:8):                     }
                   11657:8):                 } else {
                   11658:8): # Original response item, part of the problem
                   11659:8):                     if ($importedresponses) {
                   11660:8):                         $metaentry{':responseorder'}.=','.$origid;
                   11661:8):                     }
                   11662:8):                 }
                   11663:8):             }
                   11664:8):             if ($importedparts) {
                   11665:8):                 $metaentry{':partorder'}=~s/^\,//;
                   11666:8):             }
                   11667:8):             if ($importedresponses) {
                   11668:8):                 $metaentry{':responseorder'}=~s/^\,//;
                   11669:8):             }
1.1070    www      11670:         }
                   11671: 
1.737     albertel 11672: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11673: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11674: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11675: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11676: # this is the end of "was not already recently cached
1.71      www      11677:     }
1.599     albertel 11678:     return $metaentry{':'.$what};
1.261     albertel 11679: }
                   11680: 
1.488     albertel 11681: sub metadata_create_package_def {
1.483     albertel 11682:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11683:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11684:     if ($subp eq 'default') { next; }
                   11685:     
1.599     albertel 11686:     if (defined($metaentry{':packages'})) {
                   11687: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11688:     } else {
1.599     albertel 11689: 	$metaentry{':packages'}=$package;
1.483     albertel 11690:     }
                   11691:     my $value=$packagetab{$key};
                   11692:     my $unikey;
                   11693:     $unikey='parameter_0_'.$name;
1.599     albertel 11694:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11695:     $$metathesekeys{$unikey}=1;
1.599     albertel 11696:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11697: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11698:     }
1.599     albertel 11699:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11700: 	$metaentry{':'.$unikey}=
                   11701: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11702:     }
                   11703: }
                   11704: 
1.261     albertel 11705: sub metadata_generate_part0 {
                   11706:     my ($metadata,$metacache,$uri) = @_;
                   11707:     my %allnames;
1.737     albertel 11708:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11709: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11710: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11711: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11712: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11713: 	    $allnames{$name}=$part;
                   11714: 	  }
                   11715: 	}
                   11716:     }
                   11717:     foreach my $name (keys(%allnames)) {
                   11718:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11719:       my $key=":parameter_0_$name";
1.261     albertel 11720:       $$metacache{"$key.part"}='0';
                   11721:       $$metacache{"$key.name"}=$name;
1.428     albertel 11722:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11723: 					   $allnames{$name}.'_'.$name.
                   11724: 					   '.type'};
1.428     albertel 11725:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11726: 			     '.display'};
1.644     www      11727:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11728:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11729:       $$metacache{"$key.display"}=$olddis;
                   11730:     }
1.71      www      11731: }
                   11732: 
1.764     albertel 11733: # ------------------------------------------------------ Devalidate title cache
                   11734: 
                   11735: sub devalidate_title_cache {
                   11736:     my ($url)=@_;
                   11737:     if (!$env{'request.course.id'}) { return; }
                   11738:     my $symb=&symbread($url);
                   11739:     if (!$symb) { return; }
                   11740:     my $key=$env{'request.course.id'}."\0".$symb;
                   11741:     &devalidate_cache_new('title',$key);
                   11742: }
                   11743: 
1.1014    droeschl 11744: # ------------------------------------------------- Get the title of a course
                   11745: 
                   11746: sub current_course_title {
                   11747:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11748: }
1.301     www      11749: # ------------------------------------------------- Get the title of a resource
                   11750: 
                   11751: sub gettitle {
                   11752:     my $urlsymb=shift;
                   11753:     my $symb=&symbread($urlsymb);
1.534     albertel 11754:     if ($symb) {
1.620     albertel 11755: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11756: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11757: 	if (defined($cached)) { 
                   11758: 	    return $result;
                   11759: 	}
1.534     albertel 11760: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11761: 	my $title='';
1.907     albertel 11762: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11763: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11764: 	} else {
                   11765: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11766: 		    &GDBM_READER(),0640)) {
                   11767: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11768: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11769: 		untie(%bighash);
                   11770: 	    }
1.534     albertel 11771: 	}
                   11772: 	$title=~s/\&colon\;/\:/gs;
                   11773: 	if ($title) {
1.1159    www      11774: # Remember both $symb and $title for dynamic metadata
                   11775:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11776:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11777: # Cache this title and then return it
1.599     albertel 11778: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11779: 	}
                   11780: 	$urlsymb=$url;
                   11781:     }
                   11782:     my $title=&metadata($urlsymb,'title');
                   11783:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11784:     return $title;
1.301     www      11785: }
1.613     albertel 11786: 
1.614     albertel 11787: sub get_slot {
                   11788:     my ($which,$cnum,$cdom)=@_;
                   11789:     if (!$cnum || !$cdom) {
1.790     albertel 11790: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11791: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11792: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11793:     }
1.703     albertel 11794:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11795:     my %slotinfo;
                   11796:     if (exists($remembered{$key})) {
                   11797: 	$slotinfo{$which} = $remembered{$key};
                   11798:     } else {
                   11799: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11800: 	&Apache::lonhomework::showhash(%slotinfo);
                   11801: 	my ($tmp)=keys(%slotinfo);
                   11802: 	if ($tmp=~/^error:/) { return (); }
                   11803: 	$remembered{$key} = $slotinfo{$which};
                   11804:     }
1.616     albertel 11805:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11806: 	return %{$slotinfo{$which}};
                   11807:     }
                   11808:     return $slotinfo{$which};
1.614     albertel 11809: }
1.1150    raeburn  11810: 
                   11811: sub get_reservable_slots {
                   11812:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11813:     my $now = time;
                   11814:     my $reservable_info;
                   11815:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11816:     if (exists($remembered{$key})) {
                   11817:         $reservable_info = $remembered{$key};
                   11818:     } else {
                   11819:         my %resv;
                   11820:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11821:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11822:         $reservable_info = \%resv;
                   11823:         $remembered{$key} = $reservable_info;
                   11824:     }
                   11825:     return $reservable_info;
                   11826: }
                   11827: 
                   11828: sub get_course_slots {
                   11829:     my ($cnum,$cdom) = @_;
                   11830:     my $hashid=$cnum.':'.$cdom;
                   11831:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11832:     if (defined($cached)) {
                   11833:         if (ref($result) eq 'HASH') {
                   11834:             return %{$result};
                   11835:         }
                   11836:     } else {
                   11837:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11838:         my ($tmp) = keys(%slots);
                   11839:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11840:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11841:             return %slots;
                   11842:         }
                   11843:     }
                   11844:     return;
                   11845: }
                   11846: 
                   11847: sub devalidate_slots_cache {
                   11848:     my ($cnum,$cdom)=@_;
                   11849:     my $hashid=$cnum.':'.$cdom;
                   11850:     &devalidate_cache_new('allslots',$hashid);
                   11851: }
                   11852: 
1.1172.2.8  raeburn  11853: sub get_coursechange {
                   11854:     my ($cdom,$cnum) = @_;
                   11855:     if ($cdom eq '' || $cnum eq '') {
                   11856:         return unless ($env{'request.course.id'});
                   11857:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11858:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11859:     }
                   11860:     my $hashid=$cdom.'_'.$cnum;
                   11861:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11862:     if ((defined($cached)) && ($change ne '')) {
                   11863:         return $change;
                   11864:     } else {
                   11865:         my %crshash;
                   11866:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11867:         if ($crshash{'internal.contentchange'} eq '') {
                   11868:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11869:             if ($change eq '') {
                   11870:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11871:                 $change = $crshash{'internal.created'};
                   11872:             }
                   11873:         } else {
                   11874:             $change = $crshash{'internal.contentchange'};
                   11875:         }
                   11876:         my $cachetime = 600;
                   11877:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11878:     }
                   11879:     return $change;
                   11880: }
                   11881: 
                   11882: sub devalidate_coursechange_cache {
                   11883:     my ($cnum,$cdom)=@_;
                   11884:     my $hashid=$cnum.':'.$cdom;
                   11885:     &devalidate_cache_new('crschange',$hashid);
                   11886: }
                   11887: 
1.31      www      11888: # ------------------------------------------------- Update symbolic store links
                   11889: 
                   11890: sub symblist {
                   11891:     my ($mapname,%newhash)=@_;
1.438     www      11892:     $mapname=&deversion(&declutter($mapname));
1.31      www      11893:     my %hash;
1.620     albertel 11894:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11895:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11896:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11897: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11898: 		next if ($url eq 'last_known'
                   11899: 			 && $env{'form.no_update_last_known'});
                   11900: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11901: 						    $newhash{$url}->[1],
                   11902: 						    $newhash{$url}->[0]);
1.191     harris41 11903:             }
1.31      www      11904:             if (untie(%hash)) {
                   11905: 		return 'ok';
                   11906:             }
                   11907:         }
                   11908:     }
                   11909:     return 'error';
1.212     www      11910: }
                   11911: 
                   11912: # --------------------------------------------------------------- Verify a symb
                   11913: 
                   11914: sub symbverify {
1.1172.2.11  raeburn  11915:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11916:     my $thisfn=$thisurl;
1.439     www      11917:     $thisfn=&declutter($thisfn);
1.215     www      11918: # direct jump to resource in page or to a sequence - will construct own symbs
                   11919:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11920: # check URL part
1.409     www      11921:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11922: 
1.431     www      11923:     unless ($url eq $thisfn) { return 0; }
1.213     www      11924: 
1.216     www      11925:     $symb=&symbclean($symb);
1.510     www      11926:     $thisurl=&deversion($thisurl);
1.439     www      11927:     $thisfn=&deversion($thisfn);
1.213     www      11928: 
                   11929:     my %bighash;
                   11930:     my $okay=0;
1.431     www      11931: 
1.620     albertel 11932:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11933:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11934:         my $noclutter;
1.1032    raeburn  11935:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11936:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11937:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11938:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11939:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11940:                 $noclutter = 1;
                   11941:             }
                   11942:         }
                   11943:         my $ids;
                   11944:         if ($noclutter) {
                   11945:             $ids=$bighash{'ids_'.$thisurl};
                   11946:         } else {
                   11947:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11948:         }
1.1102    raeburn  11949:         unless ($ids) {
1.1172.2.13  raeburn  11950:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11951:             $ids=$bighash{$idkey};
1.216     www      11952:         }
                   11953:         if ($ids) {
                   11954: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11955:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11956:                 $symb =~ s/\?.+$//;
                   11957:             }
1.800     albertel 11958: 	    foreach my $id (split(/\,/,$ids)) {
                   11959: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11960:                if (
                   11961:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11962:    eq $symb) {
1.1172.2.11  raeburn  11963:                    if (ref($encstate)) {
                   11964:                        $$encstate = $bighash{'encrypted_'.$id};
                   11965:                    }
1.1172.2.13  raeburn  11966:                    if (($env{'request.role.adv'}) ||
                   11967:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11968:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11969:                        $okay=1;
                   11970:                        last;
                   11971:                    }
                   11972:                }
                   11973:            }
1.216     www      11974:         }
1.213     www      11975: 	untie(%bighash);
                   11976:     }
                   11977:     return $okay;
1.31      www      11978: }
                   11979: 
1.210     www      11980: # --------------------------------------------------------------- Clean-up symb
                   11981: 
                   11982: sub symbclean {
                   11983:     my $symb=shift;
1.568     albertel 11984:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11985: # remove version from map
                   11986:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11987: 
1.210     www      11988: # remove version from URL
                   11989:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11990: 
1.507     www      11991: # remove wrapper
                   11992: 
1.510     www      11993:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11994:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11995:     return $symb;
1.409     www      11996: }
                   11997: 
                   11998: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11999: 
                   12000: sub encode_symb {
                   12001:     my ($map,$resid,$url)=@_;
                   12002:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12003: }
1.409     www      12004: 
                   12005: sub decode_symb {
1.568     albertel 12006:     my $symb=shift;
                   12007:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12008:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12009:     return (&fixversion($map),$resid,&fixversion($url));
                   12010: }
                   12011: 
                   12012: sub fixversion {
                   12013:     my $fn=shift;
1.609     banghart 12014:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12015:     my %bighash;
                   12016:     my $uri=&clutter($fn);
1.620     albertel 12017:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12018: # is this cached?
1.599     albertel 12019:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12020:     if (defined($cached)) { return $result; }
                   12021: # unfortunately not cached, or expired
1.620     albertel 12022:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12023: 	    &GDBM_READER(),0640)) {
                   12024:  	if ($bighash{'version_'.$uri}) {
                   12025:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12026:  	    unless (($version eq 'mostrecent') || 
                   12027: 		    ($version==&getversion($uri))) {
1.440     www      12028:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12029:  	    }
                   12030:  	}
                   12031:  	untie %bighash;
1.413     www      12032:     }
1.599     albertel 12033:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12034: }
                   12035: 
                   12036: sub deversion {
                   12037:     my $url=shift;
                   12038:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12039:     return $url;
1.210     www      12040: }
                   12041: 
1.31      www      12042: # ------------------------------------------------------ Return symb list entry
                   12043: 
                   12044: sub symbread {
1.1172.2.66  raeburn  12045:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  12046:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  12047:     if (defined($env{$cache_str})) {
                   12048:         if ($ignorecachednull) {
                   12049:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12050:         } else {
                   12051:             return $env{$cache_str};
                   12052:         }
                   12053:     }
1.242     www      12054: # no filename provided? try from environment
1.1172.2.54  raeburn  12055:     unless ($thisfn) {
1.620     albertel 12056:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  12057:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12058:         }
                   12059:         $thisfn=$env{'request.filename'};
1.44      www      12060:     }
1.569     albertel 12061:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12062: # is that filename actually a symb? Verify, clean, and return
                   12063:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12064: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12065: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12066: 	}
1.242     www      12067:     }
1.44      www      12068:     $thisfn=declutter($thisfn);
1.31      www      12069:     my %hash;
1.37      www      12070:     my %bighash;
                   12071:     my $syval='';
1.620     albertel 12072:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12073:         my $targetfn = $thisfn;
1.609     banghart 12074:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12075:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12076:         }
1.687     albertel 12077: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12078: 	    $targetfn=$1;
                   12079: 	}
1.620     albertel 12080:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12081:                       &GDBM_READER(),0640)) {
1.481     raeburn  12082: 	    $syval=$hash{$targetfn};
1.37      www      12083:             untie(%hash);
                   12084:         }
                   12085: # ---------------------------------------------------------- There was an entry
                   12086:         if ($syval) {
1.601     albertel 12087: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12088: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12089: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12090: 		    #return $env{$cache_str}='';
1.601     albertel 12091: 		#}    
                   12092: 		#$syval.=$1;
                   12093: 	    #}
1.37      www      12094:         } else {
                   12095: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12096:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12097:                             &GDBM_READER(),0640)) {
1.37      www      12098: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12099:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12100:               unless ($ids) { 
                   12101:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12102:               }
                   12103:               unless ($ids) {
                   12104: # alias?
                   12105: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12106:               }
1.37      www      12107:               if ($ids) {
                   12108: # ------------------------------------------------------------------- Has ID(s)
                   12109:                  my @possibilities=split(/\,/,$ids);
1.39      www      12110:                  if ($#possibilities==0) {
                   12111: # ----------------------------------------------- There is only one possibility
1.37      www      12112: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12113: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12114: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12115:                      if (ref($possibles) eq 'HASH') {
                   12116:                          $possibles->{$syval} = 1;
                   12117:                      }
                   12118:                      if ($checkforblock) {
                   12119:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12120:                          if (@blockers) {
                   12121:                              $syval = '';
                   12122:                              return;
                   12123:                          }
                   12124:                      }
                   12125:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12126: # ------------------------------------------ There is more than one possibility
                   12127:                      my $realpossible=0;
1.800     albertel 12128:                      foreach my $id (@possibilities) {
                   12129: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12130:                          my $canaccess;
                   12131:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12132:                              $canaccess = 1;
                   12133:                          } else {
                   12134:                              $canaccess = &allowed('bre',$file);
                   12135:                          }
                   12136:                          if ($canaccess) {
                   12137:          		     my ($mapid,$resid)=split(/\./,$id);
                   12138:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12139:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12140:                                                              $resid,$thisfn);
                   12141:                                  if (ref($possibles) eq 'HASH') {
                   12142:                                      $possibles->{$syval} = 1;
                   12143:                                  }
                   12144:                                  if ($checkforblock) {
                   12145:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12146:                                      unless (@blockers > 0) {
                   12147:                                          $syval = $poss_syval;
                   12148:                                          $realpossible++;
                   12149:                                      }
                   12150:                                  } else {
                   12151:                                      $syval = $poss_syval;
                   12152:                                      $realpossible++;
                   12153:                                  }
                   12154:                              }
1.39      www      12155: 			 }
1.191     harris41 12156:                      }
1.39      www      12157: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12158:                  } else {
                   12159:                      $syval='';
1.37      www      12160:                  }
                   12161: 	      }
1.1172.2.66  raeburn  12162:               untie(%bighash);
1.481     raeburn  12163:            }
1.31      www      12164:         }
1.62      www      12165:         if ($syval) {
1.620     albertel 12166: 	    return $env{$cache_str}=$syval;
1.62      www      12167:         }
1.31      www      12168:     }
1.949     raeburn  12169:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12170:     return $env{$cache_str}='';
1.31      www      12171: }
                   12172: 
                   12173: # ---------------------------------------------------------- Return random seed
                   12174: 
1.32      www      12175: sub numval {
                   12176:     my $txt=shift;
                   12177:     $txt=~tr/A-J/0-9/;
                   12178:     $txt=~tr/a-j/0-9/;
                   12179:     $txt=~tr/K-T/0-9/;
                   12180:     $txt=~tr/k-t/0-9/;
                   12181:     $txt=~tr/U-Z/0-5/;
                   12182:     $txt=~tr/u-z/0-5/;
                   12183:     $txt=~s/\D//g;
1.564     albertel 12184:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12185:     return int($txt);
1.368     albertel 12186: }
                   12187: 
1.484     albertel 12188: sub numval2 {
                   12189:     my $txt=shift;
                   12190:     $txt=~tr/A-J/0-9/;
                   12191:     $txt=~tr/a-j/0-9/;
                   12192:     $txt=~tr/K-T/0-9/;
                   12193:     $txt=~tr/k-t/0-9/;
                   12194:     $txt=~tr/U-Z/0-5/;
                   12195:     $txt=~tr/u-z/0-5/;
                   12196:     $txt=~s/\D//g;
                   12197:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12198:     my $total;
                   12199:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12200:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12201:     return int($total);
                   12202: }
                   12203: 
1.575     albertel 12204: sub numval3 {
                   12205:     use integer;
                   12206:     my $txt=shift;
                   12207:     $txt=~tr/A-J/0-9/;
                   12208:     $txt=~tr/a-j/0-9/;
                   12209:     $txt=~tr/K-T/0-9/;
                   12210:     $txt=~tr/k-t/0-9/;
                   12211:     $txt=~tr/U-Z/0-5/;
                   12212:     $txt=~tr/u-z/0-5/;
                   12213:     $txt=~s/\D//g;
                   12214:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12215:     my $total;
                   12216:     foreach my $val (@txts) { $total+=$val; }
                   12217:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12218:     return $total;
                   12219: }
                   12220: 
1.675     albertel 12221: sub digest {
                   12222:     my ($data)=@_;
                   12223:     my $digest=&Digest::MD5::md5($data);
                   12224:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12225:     my ($e,$f);
                   12226:     {
                   12227:         use integer;
                   12228:         $e=($a+$b);
                   12229:         $f=($c+$d);
                   12230:         if ($_64bit) {
                   12231:             $e=(($e<<32)>>32);
                   12232:             $f=(($f<<32)>>32);
                   12233:         }
                   12234:     }
                   12235:     if (wantarray) {
                   12236: 	return ($e,$f);
                   12237:     } else {
                   12238: 	my $g;
                   12239: 	{
                   12240: 	    use integer;
                   12241: 	    $g=($e+$f);
                   12242: 	    if ($_64bit) {
                   12243: 		$g=(($g<<32)>>32);
                   12244: 	    }
                   12245: 	}
                   12246: 	return $g;
                   12247:     }
                   12248: }
                   12249: 
1.368     albertel 12250: sub latest_rnd_algorithm_id {
1.675     albertel 12251:     return '64bit5';
1.366     albertel 12252: }
1.32      www      12253: 
1.503     albertel 12254: sub get_rand_alg {
                   12255:     my ($courseid)=@_;
1.790     albertel 12256:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12257:     if ($courseid) {
1.620     albertel 12258: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12259:     }
                   12260:     return &latest_rnd_algorithm_id();
                   12261: }
                   12262: 
1.562     albertel 12263: sub validCODE {
                   12264:     my ($CODE)=@_;
                   12265:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12266:     return 0;
                   12267: }
                   12268: 
1.491     albertel 12269: sub getCODE {
1.620     albertel 12270:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12271:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12272: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12273: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12274: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12275:     }
                   12276:     return undef;
                   12277: }
1.1133    foxr     12278: #
                   12279: #  Determines the random seed for a specific context:
                   12280: #
                   12281: # parameters:
                   12282: #   symb      - in course context the symb for the seed.
                   12283: #   course_id - The course id of the form domain_coursenum.
                   12284: #   domain    - Domain for the user.
                   12285: #   course    - Course for the user.
                   12286: #   cenv      - environment of the course.
                   12287: #
                   12288: # NOTE:
                   12289: #   All parameters are picked out of the environment if missing
                   12290: #   or not defined.
                   12291: #   If a symb cannot be determined the current time is used instead.
                   12292: #
                   12293: #  For a given well defined symb, courside, domain, username,
                   12294: #  and course environment, the seed is reproducible.
                   12295: #
1.31      www      12296: sub rndseed {
1.1133    foxr     12297:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12298:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12299:     if (!defined($symb)) {
1.366     albertel 12300: 	unless ($symb=$wsymb) { return time; }
                   12301:     }
1.1146    foxr     12302:     if (!defined $courseid) { 
                   12303: 	$courseid=$wcourseid; 
                   12304:     }
                   12305:     if (!defined $domain) { $domain=$wdomain; }
                   12306:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12307: 
                   12308:     my $which;
                   12309:     if (defined($cenv->{'rndseed'})) {
                   12310: 	$which = $cenv->{'rndseed'};
                   12311:     } else {
                   12312: 	$which =&get_rand_alg($courseid);
                   12313:     }
1.491     albertel 12314:     if (defined(&getCODE())) {
1.675     albertel 12315: 	if ($which eq '64bit5') {
                   12316: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12317: 	} elsif ($which eq '64bit4') {
1.575     albertel 12318: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12319: 	} else {
                   12320: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12321: 	}
1.675     albertel 12322:     } elsif ($which eq '64bit5') {
                   12323: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12324:     } elsif ($which eq '64bit4') {
                   12325: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12326:     } elsif ($which eq '64bit3') {
                   12327: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12328:     } elsif ($which eq '64bit2') {
                   12329: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12330:     } elsif ($which eq '64bit') {
                   12331: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12332:     }
                   12333:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12334: }
                   12335: 
                   12336: sub rndseed_32bit {
                   12337:     my ($symb,$courseid,$domain,$username)=@_;
                   12338:     {
                   12339: 	use integer;
                   12340: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12341: 	my $symbseed=numval($symb) << 22;
                   12342: 	my $namechck=unpack("%32C*",$username) << 17;
                   12343: 	my $nameseed=numval($username) << 12;
                   12344: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12345: 	my $courseseed=unpack("%32C*",$courseid);
                   12346: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12347: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12348: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12349: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12350: 	return $num;
                   12351:     }
                   12352: }
                   12353: 
                   12354: sub rndseed_64bit {
                   12355:     my ($symb,$courseid,$domain,$username)=@_;
                   12356:     {
                   12357: 	use integer;
                   12358: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12359: 	my $symbseed=numval($symb) << 10;
                   12360: 	my $namechck=unpack("%32S*",$username);
                   12361: 	
                   12362: 	my $nameseed=numval($username) << 21;
                   12363: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12364: 	my $courseseed=unpack("%32S*",$courseid);
                   12365: 	
                   12366: 	my $num1=$symbchck+$symbseed+$namechck;
                   12367: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12368: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12369: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12370: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12371: 	return "$num1,$num2";
1.155     albertel 12372:     }
1.366     albertel 12373: }
                   12374: 
1.443     albertel 12375: sub rndseed_64bit2 {
                   12376:     my ($symb,$courseid,$domain,$username)=@_;
                   12377:     {
                   12378: 	use integer;
                   12379: 	# strings need to be an even # of cahracters long, it it is odd the
                   12380:         # last characters gets thrown away
                   12381: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12382: 	my $symbseed=numval($symb) << 10;
                   12383: 	my $namechck=unpack("%32S*",$username.' ');
                   12384: 	
                   12385: 	my $nameseed=numval($username) << 21;
1.501     albertel 12386: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12387: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12388: 	
                   12389: 	my $num1=$symbchck+$symbseed+$namechck;
                   12390: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12391: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12392: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12393: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12394: 	return "$num1,$num2";
                   12395:     }
                   12396: }
                   12397: 
                   12398: sub rndseed_64bit3 {
                   12399:     my ($symb,$courseid,$domain,$username)=@_;
                   12400:     {
                   12401: 	use integer;
                   12402: 	# strings need to be an even # of cahracters long, it it is odd the
                   12403:         # last characters gets thrown away
                   12404: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12405: 	my $symbseed=numval2($symb) << 10;
                   12406: 	my $namechck=unpack("%32S*",$username.' ');
                   12407: 	
                   12408: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12409: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12410: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12411: 	
                   12412: 	my $num1=$symbchck+$symbseed+$namechck;
                   12413: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12414: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12415: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12416: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12417: 	
1.503     albertel 12418: 	return "$num1:$num2";
1.443     albertel 12419:     }
                   12420: }
                   12421: 
1.575     albertel 12422: sub rndseed_64bit4 {
                   12423:     my ($symb,$courseid,$domain,$username)=@_;
                   12424:     {
                   12425: 	use integer;
                   12426: 	# strings need to be an even # of cahracters long, it it is odd the
                   12427:         # last characters gets thrown away
                   12428: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12429: 	my $symbseed=numval3($symb) << 10;
                   12430: 	my $namechck=unpack("%32S*",$username.' ');
                   12431: 	
                   12432: 	my $nameseed=numval3($username) << 21;
                   12433: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12434: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12435: 	
                   12436: 	my $num1=$symbchck+$symbseed+$namechck;
                   12437: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12438: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12439: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12440: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12441: 	
1.575     albertel 12442: 	return "$num1:$num2";
                   12443:     }
                   12444: }
                   12445: 
1.675     albertel 12446: sub rndseed_64bit5 {
                   12447:     my ($symb,$courseid,$domain,$username)=@_;
                   12448:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12449:     return "$num1:$num2";
                   12450: }
                   12451: 
1.366     albertel 12452: sub rndseed_CODE_64bit {
                   12453:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12454:     {
1.366     albertel 12455: 	use integer;
1.443     albertel 12456: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12457: 	my $symbseed=numval2($symb);
1.491     albertel 12458: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12459: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12460: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12461: 	my $num1=$symbseed+$CODEchck;
                   12462: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12463: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12464: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12465: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12466: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12467: 	return "$num1:$num2";
1.366     albertel 12468:     }
                   12469: }
                   12470: 
1.575     albertel 12471: sub rndseed_CODE_64bit4 {
                   12472:     my ($symb,$courseid,$domain,$username)=@_;
                   12473:     {
                   12474: 	use integer;
                   12475: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12476: 	my $symbseed=numval3($symb);
                   12477: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12478: 	my $CODEseed=numval3(&getCODE());
                   12479: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12480: 	my $num1=$symbseed+$CODEchck;
                   12481: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12482: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12483: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12484: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12485: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12486: 	return "$num1:$num2";
                   12487:     }
                   12488: }
                   12489: 
1.675     albertel 12490: sub rndseed_CODE_64bit5 {
                   12491:     my ($symb,$courseid,$domain,$username)=@_;
                   12492:     my $code = &getCODE();
                   12493:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12494:     return "$num1:$num2";
                   12495: }
                   12496: 
1.366     albertel 12497: sub setup_random_from_rndseed {
                   12498:     my ($rndseed)=@_;
1.503     albertel 12499:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12500: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12501:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12502:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12503:         } else {
                   12504:             &Math::Random::random_set_seed($num1,$num2);
                   12505:         }
1.366     albertel 12506:     } else {
                   12507: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12508:     }
1.36      albertel 12509: }
                   12510: 
1.474     albertel 12511: sub latest_receipt_algorithm_id {
1.835     albertel 12512:     return 'receipt3';
1.474     albertel 12513: }
                   12514: 
1.480     www      12515: sub recunique {
                   12516:     my $fucourseid=shift;
                   12517:     my $unique;
1.835     albertel 12518:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12519: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12520: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12521:     } else {
                   12522: 	$unique=$perlvar{'lonReceipt'};
                   12523:     }
                   12524:     return unpack("%32C*",$unique);
                   12525: }
                   12526: 
                   12527: sub recprefix {
                   12528:     my $fucourseid=shift;
                   12529:     my $prefix;
1.835     albertel 12530:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12531: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12532: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12533:     } else {
                   12534: 	$prefix=$perlvar{'lonHostID'};
                   12535:     }
                   12536:     return unpack("%32C*",$prefix);
                   12537: }
                   12538: 
1.76      www      12539: sub ireceipt {
1.474     albertel 12540:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12541: 
                   12542:     my $return =&recprefix($fucourseid).'-';
                   12543: 
                   12544:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12545: 	$env{'request.state'} eq 'construct') {
                   12546: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12547: 	return $return;
                   12548:     }
                   12549: 
1.76      www      12550:     my $cuname=unpack("%32C*",$funame);
                   12551:     my $cudom=unpack("%32C*",$fudom);
                   12552:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12553:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12554:     my $cunique=&recunique($fucourseid);
1.474     albertel 12555:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12556:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12557: 
1.790     albertel 12558: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12559: 			       
                   12560: 	$return.= ($cunique%$cuname+
                   12561: 		   $cunique%$cudom+
                   12562: 		   $cusymb%$cuname+
                   12563: 		   $cusymb%$cudom+
                   12564: 		   $cucourseid%$cuname+
                   12565: 		   $cucourseid%$cudom+
                   12566: 		   $cpart%$cuname+
                   12567: 		   $cpart%$cudom);
                   12568:     } else {
                   12569: 	$return.= ($cunique%$cuname+
                   12570: 		   $cunique%$cudom+
                   12571: 		   $cusymb%$cuname+
                   12572: 		   $cusymb%$cudom+
                   12573: 		   $cucourseid%$cuname+
                   12574: 		   $cucourseid%$cudom);
                   12575:     }
                   12576:     return $return;
1.76      www      12577: }
                   12578: 
                   12579: sub receipt {
1.474     albertel 12580:     my ($part)=@_;
1.790     albertel 12581:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12582:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12583: }
1.260     ng       12584: 
1.790     albertel 12585: sub whichuser {
                   12586:     my ($passedsymb)=@_;
                   12587:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12588:     if (defined($env{'form.grade_symb'})) {
                   12589: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12590: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12591: 	if (!$allowed &&
                   12592: 	    exists($env{'request.course.sec'}) &&
                   12593: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12594: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12595: 			      '/'.$env{'request.course.sec'});
                   12596: 	}
                   12597: 	if ($allowed) {
                   12598: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12599: 	    $courseid=$tmp_courseid;
                   12600: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12601: 	    ($name)=&get_env_multiple('form.grade_username');
                   12602: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12603: 	}
                   12604:     }
                   12605:     if (!$passedsymb) {
                   12606: 	$symb=&symbread();
                   12607:     } else {
                   12608: 	$symb=$passedsymb;
                   12609:     }
                   12610:     $courseid=$env{'request.course.id'};
                   12611:     $domain=$env{'user.domain'};
                   12612:     $name=$env{'user.name'};
                   12613:     if ($name eq 'public' && $domain eq 'public') {
                   12614: 	if (!defined($env{'form.username'})) {
                   12615: 	    $env{'form.username'}.=time.rand(10000000);
                   12616: 	}
                   12617: 	$name.=$env{'form.username'};
                   12618:     }
                   12619:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12620: 
                   12621: }
                   12622: 
1.36      albertel 12623: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12624: # returns either the contents of the file or 
                   12625: # -1 if the file doesn't exist
1.481     raeburn  12626: #
                   12627: # if the target is a file that was uploaded via DOCS, 
                   12628: # a check will be made to see if a current copy exists on the local server,
                   12629: # if it does this will be served, otherwise a copy will be retrieved from
                   12630: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12631: # the local server.   
1.472     albertel 12632: 
1.36      albertel 12633: sub getfile {
1.538     albertel 12634:     my ($file) = @_;
1.609     banghart 12635:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12636:     &repcopy($file);
                   12637:     return &readfile($file);
                   12638: }
                   12639: 
                   12640: sub repcopy_userfile {
                   12641:     my ($file)=@_;
1.1142    raeburn  12642:     my $londocroot = $perlvar{'lonDocRoot'};
                   12643:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12644:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12645:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12646: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12647:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12648:     if (-e "$file") {
1.828     www      12649: # we already have a local copy, check it out
1.538     albertel 12650: 	my @fileinfo = stat($file);
1.828     www      12651: 	my $rtncode;
                   12652: 	my $info;
1.538     albertel 12653: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12654: 	if ($lwpresp ne 'ok') {
1.828     www      12655: # there is no such file anymore, even though we had a local copy
1.482     albertel 12656: 	    if ($rtncode eq '404') {
1.538     albertel 12657: 		unlink($file);
1.482     albertel 12658: 	    }
                   12659: 	    return -1;
                   12660: 	}
                   12661: 	if ($info < $fileinfo[9]) {
1.828     www      12662: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12663: 	    return 'ok';
1.828     www      12664: 	} else {
                   12665: # the file is outdated, get rid of it
                   12666: 	    unlink($file);
1.482     albertel 12667: 	}
1.828     www      12668:     }
                   12669: # one way or the other, at this point, we don't have the file
                   12670: # construct the correct path for the file
                   12671:     my @parts = ($cdom,$cnum); 
                   12672:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12673: 	push @parts, split(/\//,$1);
                   12674:     }
                   12675:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12676:     foreach my $part (@parts) {
                   12677: 	$path .= '/'.$part;
                   12678: 	if (!-e $path) {
                   12679: 	    mkdir($path,0770);
1.482     albertel 12680: 	}
                   12681:     }
1.828     www      12682: # now the path exists for sure
                   12683: # get a user agent
                   12684:     my $ua=new LWP::UserAgent;
                   12685:     my $transferfile=$file.'.in.transfer';
                   12686: # FIXME: this should flock
                   12687:     if (-e $transferfile) { return 'ok'; }
                   12688:     my $request;
                   12689:     $uri=~s/^\///;
1.980     raeburn  12690:     my $homeserver = &homeserver($cnum,$cdom);
                   12691:     my $protocol = $protocol{$homeserver};
                   12692:     $protocol = 'http' if ($protocol ne 'https');
                   12693:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12694:     my $response=$ua->request($request,$transferfile);
                   12695: # did it work?
                   12696:     if ($response->is_error()) {
                   12697: 	unlink($transferfile);
                   12698: 	&logthis("Userfile repcopy failed for $uri");
                   12699: 	return -1;
                   12700:     }
                   12701: # worked, rename the transfer file
                   12702:     rename($transferfile,$file);
1.607     raeburn  12703:     return 'ok';
1.481     raeburn  12704: }
                   12705: 
1.517     albertel 12706: sub tokenwrapper {
                   12707:     my $uri=shift;
1.980     raeburn  12708:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12709:     $uri=~s|^/||;
1.620     albertel 12710:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12711:     my $token=$1;
1.552     albertel 12712:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12713:     if ($udom && $uname && $file) {
                   12714: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12715:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12716:         my $homeserver = &homeserver($uname,$udom);
                   12717:         my $protocol = $protocol{$homeserver};
                   12718:         $protocol = 'http' if ($protocol ne 'https');
                   12719:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12720:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12721:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12722:     } else {
                   12723:         return '/adm/notfound.html';
                   12724:     }
                   12725: }
                   12726: 
1.828     www      12727: # call with reqtype HEAD: get last modification time
                   12728: # call with reqtype GET: get the file contents
                   12729: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12730: #
1.481     raeburn  12731: sub getuploaded {
                   12732:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12733:     $uri=~s/^\///;
1.980     raeburn  12734:     my $homeserver = &homeserver($cnum,$cdom);
                   12735:     my $protocol = $protocol{$homeserver};
                   12736:     $protocol = 'http' if ($protocol ne 'https');
                   12737:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12738:     my $ua=new LWP::UserAgent;
                   12739:     my $request=new HTTP::Request($reqtype,$uri);
                   12740:     my $response=$ua->request($request);
                   12741:     $$rtncode = $response->code;
1.482     albertel 12742:     if (! $response->is_success()) {
                   12743: 	return 'failed';
                   12744:     }      
                   12745:     if ($reqtype eq 'HEAD') {
1.486     www      12746: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12747:     } elsif ($reqtype eq 'GET') {
                   12748: 	$$info = $response->content;
1.472     albertel 12749:     }
1.482     albertel 12750:     return 'ok';
1.36      albertel 12751: }
                   12752: 
1.481     raeburn  12753: sub readfile {
                   12754:     my $file = shift;
                   12755:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12756:     my $fh;
1.1172.2.93.4  7(raebur 12757:7):     open($fh,"<",$file);
1.481     raeburn  12758:     my $a='';
1.800     albertel 12759:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12760:     return $a;
                   12761: }
                   12762: 
1.36      albertel 12763: sub filelocation {
1.590     banghart 12764:     my ($dir,$file) = @_;
                   12765:     my $location;
                   12766:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12767: 
                   12768:     if ($file =~ m-^/adm/-) {
                   12769: 	$file=~s-^/adm/wrapper/-/-;
                   12770: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12771:     }
1.882     albertel 12772: 
1.1139    www      12773:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12774:         $location = $file;
1.609     banghart 12775:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12776:         my ($udom,$uname,$filename)=
1.811     albertel 12777:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12778:         my $home=&homeserver($uname,$udom);
                   12779:         my $is_me=0;
                   12780:         my @ids=&current_machine_ids();
                   12781:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12782:         if ($is_me) {
1.1117    foxr     12783:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12784:         } else {
                   12785:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12786:   	      $udom.'/'.$uname.'/'.$filename;
                   12787:         }
1.882     albertel 12788:     } elsif ($file =~ m-^/adm/-) {
                   12789: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12790:     } else {
                   12791:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12792:         $file=~s:^/(res|priv)/:/:;
                   12793:         my $space=$1;
1.590     banghart 12794:         if ( !( $file =~ m:^/:) ) {
                   12795:             $location = $dir. '/'.$file;
                   12796:         } else {
1.1142    raeburn  12797:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12798:         }
1.59      albertel 12799:     }
1.590     banghart 12800:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12801:     while ($location=~m{/\.\./}) {
                   12802: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12803: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12804: 	} else {
                   12805: 	    $location=~ s{/\.\./}{/}g;
                   12806: 	}
                   12807:     } #remove dir/..
1.590     banghart 12808:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12809:     return $location;
1.46      www      12810: }
1.36      albertel 12811: 
1.46      www      12812: sub hreflocation {
                   12813:     my ($dir,$file)=@_;
1.980     raeburn  12814:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12815: 	$file=filelocation($dir,$file);
1.700     albertel 12816:     } elsif ($file=~m-^/adm/-) {
                   12817: 	$file=~s-^/adm/wrapper/-/-;
                   12818: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12819:     }
                   12820:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12821: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12822:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12823: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12824: 	        {/uploaded/$1/$2/}x;
1.46      www      12825:     }
1.913     albertel 12826:     if ($file=~ m{^/userfiles/}) {
                   12827: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12828:     }
1.462     albertel 12829:     return $file;
1.465     albertel 12830: }
                   12831: 
1.1139    www      12832: 
                   12833: 
                   12834: 
                   12835: 
1.465     albertel 12836: sub current_machine_domains {
1.853     albertel 12837:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12838: }
                   12839: 
                   12840: sub machine_domains {
                   12841:     my ($hostname) = @_;
1.465     albertel 12842:     my @domains;
1.838     albertel 12843:     my %hostname = &all_hostnames();
1.465     albertel 12844:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12845: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12846: 	if ($hostname eq $name) {
1.844     albertel 12847: 	    push(@domains,&host_domain($id));
1.465     albertel 12848: 	}
                   12849:     }
                   12850:     return @domains;
                   12851: }
                   12852: 
                   12853: sub current_machine_ids {
1.853     albertel 12854:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12855: }
                   12856: 
                   12857: sub machine_ids {
                   12858:     my ($hostname) = @_;
                   12859:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12860:     my @ids;
1.888     albertel 12861:     my %name_to_host = &all_names();
1.889     albertel 12862:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12863: 	return @{ $name_to_host{$hostname} };
                   12864:     }
                   12865:     return;
1.31      www      12866: }
                   12867: 
1.824     raeburn  12868: sub additional_machine_domains {
                   12869:     my @domains;
1.1172.2.93.4  7(raebur 12870:7):     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  12871:     while( my $line = <$fh>) {
                   12872:         $line =~ s/\s//g;
                   12873:         push(@domains,$line);
                   12874:     }
                   12875:     return @domains;
                   12876: }
                   12877: 
                   12878: sub default_login_domain {
                   12879:     my $domain = $perlvar{'lonDefDomain'};
                   12880:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12881:     foreach my $posdom (&current_machine_domains(),
                   12882:                         &additional_machine_domains()) {
                   12883:         if (lc($posdom) eq lc($testdomain)) {
                   12884:             $domain=$posdom;
                   12885:             last;
                   12886:         }
                   12887:     }
                   12888:     return $domain;
                   12889: }
                   12890: 
1.31      www      12891: # ------------------------------------------------------------- Declutters URLs
                   12892: 
                   12893: sub declutter {
                   12894:     my $thisfn=shift;
1.569     albertel 12895:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12896:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12897:         $thisfn=~s{^/home/httpd/html}{};
                   12898:     }
1.31      www      12899:     $thisfn=~s/^\///;
1.697     albertel 12900:     $thisfn=~s|^adm/wrapper/||;
                   12901:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12902:     $thisfn=~s/^res\///;
1.1172    bisitz   12903:     $thisfn=~s/^priv\///;
1.1032    raeburn  12904:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12905:         $thisfn=~s/\?.+$//;
                   12906:     }
1.268     www      12907:     return $thisfn;
                   12908: }
                   12909: 
                   12910: # ------------------------------------------------------------- Clutter up URLs
                   12911: 
                   12912: sub clutter {
                   12913:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12914:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12915: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12916:        $thisfn='/res'.$thisfn; 
                   12917:     }
1.1031    raeburn  12918:     if ($thisfn !~m|^/adm|) {
                   12919: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12920: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12921: 	} else {
                   12922: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12923: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12924: 	    if ($embstyle eq 'ssi'
                   12925: 		|| ($embstyle eq 'hdn')
                   12926: 		|| ($embstyle eq 'rat')
                   12927: 		|| ($embstyle eq 'prv')
                   12928: 		|| ($embstyle eq 'ign')) {
                   12929: 		#do nothing with these
                   12930: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12931: 		|| ($embstyle eq 'emb')
                   12932: 		|| ($embstyle eq 'wrp')) {
                   12933: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12934: 	    } elsif ($embstyle eq 'unk'
                   12935: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12936: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12937: 	    } else {
1.718     www      12938: #		&logthis("Got a blank emb style");
1.695     albertel 12939: 	    }
1.694     albertel 12940: 	}
1.1172.2.93.4  2(raebur 12941:7):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   12942:7):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12943:     }
1.31      www      12944:     return $thisfn;
1.12      www      12945: }
                   12946: 
1.787     albertel 12947: sub clutter_with_no_wrapper {
                   12948:     my $uri = &clutter(shift);
                   12949:     if ($uri =~ m-^/adm/-) {
                   12950: 	$uri =~ s-^/adm/wrapper/-/-;
                   12951: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12952:     }
                   12953:     return $uri;
                   12954: }
                   12955: 
1.557     albertel 12956: sub freeze_escape {
                   12957:     my ($value)=@_;
                   12958:     if (ref($value)) {
                   12959: 	$value=&nfreeze($value);
                   12960: 	return '__FROZEN__'.&escape($value);
                   12961:     }
                   12962:     return &escape($value);
                   12963: }
                   12964: 
1.11      www      12965: 
1.557     albertel 12966: sub thaw_unescape {
                   12967:     my ($value)=@_;
                   12968:     if ($value =~ /^__FROZEN__/) {
                   12969: 	substr($value,0,10,undef);
                   12970: 	$value=&unescape($value);
                   12971: 	return &thaw($value);
                   12972:     }
                   12973:     return &unescape($value);
                   12974: }
                   12975: 
1.436     albertel 12976: sub correct_line_ends {
                   12977:     my ($result)=@_;
                   12978:     $$result =~s/\r\n/\n/mg;
                   12979:     $$result =~s/\r/\n/mg;
1.415     albertel 12980: }
1.1       albertel 12981: # ================================================================ Main Program
                   12982: 
1.184     www      12983: sub goodbye {
1.204     albertel 12984:    &logthis("Starting Shut down");
1.443     albertel 12985: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12986:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12987: #converted
1.599     albertel 12988: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12989:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12990: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12991: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12992: #1.1 only
1.870     albertel 12993: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12994: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12995: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12996: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12997:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12998:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12999:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13000:    &flushcourselogs();
                   13001:    &logthis("Shutting down");
                   13002: }
                   13003: 
1.852     albertel 13004: sub get_dns {
1.1172.2.17  raeburn  13005:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13006:     if (!$ignore_cache) {
                   13007: 	my ($content,$cached)=
                   13008: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13009: 	if ($cached) {
1.1172.2.17  raeburn  13010: 	    &$func($content,$hashref);
1.869     albertel 13011: 	    return;
                   13012: 	}
                   13013:     }
                   13014: 
                   13015:     my %alldns;
1.1172.2.93.4  7(raebur 13016:7):     open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13017:     foreach my $dns (<$config>) {
                   13018: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  13019:         my $line = $1;
                   13020:         my ($host,$protocol) = split(/:/,$line);
                   13021:         if ($protocol ne 'https') {
                   13022:             $protocol = 'http';
                   13023:         }
                   13024: 	$alldns{$host} = $protocol;
1.869     albertel 13025:     }
                   13026:     while (%alldns) {
1.1172.2.52  raeburn  13027: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13028: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13029:         $ua->timeout(30);
1.979     raeburn  13030: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13031: 	my $response=$ua->request($request);
1.979     raeburn  13032:         delete($alldns{$dns});
1.852     albertel 13033: 	next if ($response->is_error());
                   13034: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13035:         unless ($nocache) {
1.1172.2.23  raeburn  13036: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13037:         }
                   13038: 	&$func(\@content,$hashref);
1.869     albertel 13039: 	return;
1.852     albertel 13040:     }
                   13041:     close($config);
1.871     albertel 13042:     my $which = (split('/',$url))[3];
                   13043:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.93.4  7(raebur 13044:7):     open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 13045:     my @content = <$config>;
1.1172.2.17  raeburn  13046:     &$func(\@content,$hashref);
                   13047:     return;
                   13048: }
                   13049: 
                   13050: # ------------------------------------------------------Get DNS checksums file
                   13051: sub parse_dns_checksums_tab {
                   13052:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13053:     my $lonhost = $perlvar{'lonHostID'};
                   13054:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13055:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13056:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13057:     my $webconfdir = '/etc/httpd/conf';
                   13058:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13059:         $webconfdir = '/etc/apache2';
                   13060:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13061:         if ($1 >= 10) {
                   13062:             $webconfdir = '/etc/apache2';
                   13063:         }
                   13064:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13065:         if ($1 >= 10.0) {
                   13066:             $webconfdir = '/etc/apache2';
                   13067:         }
                   13068:     }
1.1172.2.17  raeburn  13069:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13070:     my (%chksum,%revnum);
                   13071:     if (ref($lines) eq 'ARRAY') {
                   13072:         chomp(@{$lines});
1.1172.2.34  raeburn  13073:         my $version = shift(@{$lines});
                   13074:         if ($version eq $release) {
1.1172.2.17  raeburn  13075:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13076:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13077:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13078:                     if ($webconfdir eq '/etc/apache2') {
                   13079:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13080:                     }
                   13081:                 }
1.1172.2.34  raeburn  13082:                 $chksum{$file} = $shasum;
                   13083:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13084:             }
                   13085:             if (ref($hashref) eq 'HASH') {
                   13086:                 %{$hashref} = (
                   13087:                                 sums     => \%chksum,
                   13088:                                 versions => \%revnum,
                   13089:                               );
                   13090:             }
                   13091:         }
                   13092:     }
1.869     albertel 13093:     return;
1.852     albertel 13094: }
1.1172.2.17  raeburn  13095: 
                   13096: sub fetch_dns_checksums {
                   13097:     my %checksums;
1.1172.2.34  raeburn  13098:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13099:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13100:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13101:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13102:              \%checksums);
                   13103:     return \%checksums;
                   13104: }
                   13105: 
1.327     albertel 13106: # ------------------------------------------------------------ Read domain file
                   13107: {
1.852     albertel 13108:     my $loaded;
1.846     albertel 13109:     my %domain;
                   13110: 
1.852     albertel 13111:     sub parse_domain_tab {
                   13112: 	my ($lines) = @_;
                   13113: 	foreach my $line (@$lines) {
                   13114: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13115: 
1.846     albertel 13116: 	    chomp($line);
1.852     albertel 13117: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13118: 	    my %this_domain;
                   13119: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13120: 			       'lang_def', 'city', 'longi', 'lati',
                   13121: 			       'primary') {
                   13122: 		$this_domain{$field} = shift(@elements);
                   13123: 	    }
                   13124: 	    $domain{$name} = \%this_domain;
1.852     albertel 13125: 	}
                   13126:     }
1.864     albertel 13127: 
                   13128:     sub reset_domain_info {
                   13129: 	undef($loaded);
                   13130: 	undef(%domain);
                   13131:     }
                   13132: 
1.852     albertel 13133:     sub load_domain_tab {
1.1172.2.70  raeburn  13134: 	my ($ignore_cache,$nocache) = @_;
                   13135: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13136: 	my $fh;
1.1172.2.93.4  7(raebur 13137:7): 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13138: 	    my @lines = <$fh>;
                   13139: 	    &parse_domain_tab(\@lines);
1.448     albertel 13140: 	}
1.852     albertel 13141: 	close($fh);
                   13142: 	$loaded = 1;
1.327     albertel 13143:     }
1.846     albertel 13144: 
                   13145:     sub domain {
1.852     albertel 13146: 	&load_domain_tab() if (!$loaded);
                   13147: 
1.846     albertel 13148: 	my ($name,$what) = @_;
                   13149: 	return if ( !exists($domain{$name}) );
                   13150: 
                   13151: 	if (!$what) {
                   13152: 	    return $domain{$name}{'description'};
                   13153: 	}
                   13154: 	return $domain{$name}{$what};
                   13155:     }
1.974     raeburn  13156: 
                   13157:     sub domain_info {
                   13158:         &load_domain_tab() if (!$loaded);
                   13159:         return %domain;
                   13160:     }
                   13161: 
1.327     albertel 13162: }
                   13163: 
                   13164: 
1.1       albertel 13165: # ------------------------------------------------------------- Read hosts file
                   13166: {
1.838     albertel 13167:     my %hostname;
1.844     albertel 13168:     my %hostdom;
1.845     albertel 13169:     my %libserv;
1.852     albertel 13170:     my $loaded;
1.888     albertel 13171:     my %name_to_host;
1.1074    raeburn  13172:     my %internetdom;
1.1107    raeburn  13173:     my %LC_dns_serv;
1.852     albertel 13174: 
                   13175:     sub parse_hosts_tab {
                   13176: 	my ($file) = @_;
                   13177: 	foreach my $configline (@$file) {
                   13178: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13179:             chomp($configline);
                   13180: 	    if ($configline =~ /^\^/) {
                   13181:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13182:                     $LC_dns_serv{$1} = 1;
                   13183:                 }
                   13184:                 next;
                   13185:             }
1.1074    raeburn  13186: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13187: 	    $name=~s/\s//g;
                   13188: 	    if ($id && $domain && $role && $name) {
1.1172.2.93.4  3(raebur 13189:7):                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13190:7):                     my $curr = $hostname{$id};
                   13191:7):                     my $skip;
                   13192:7):                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13193:7):                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13194:7):                             $skip = 1;
                   13195:7):                         } else {
                   13196:7):                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13197:7):                         }
                   13198:7):                     }
                   13199:7):                     unless ($skip) {
                   13200:7):                         push(@{$name_to_host{$name}},$id);
                   13201:7):                     }
                   13202:7):                 } else {
                   13203:7):                     push(@{$name_to_host{$name}},$id);
                   13204:7):                 }
1.852     albertel 13205: 		$hostname{$id}=$name;
                   13206: 		$hostdom{$id}=$domain;
                   13207: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13208:                 if (defined($protocol)) {
                   13209:                     if ($protocol eq 'https') {
                   13210:                         $protocol{$id} = $protocol;
                   13211:                     } else {
                   13212:                         $protocol{$id} = 'http'; 
                   13213:                     }
1.968     raeburn  13214:                 } else {
1.969     raeburn  13215:                     $protocol{$id} = 'http';
1.968     raeburn  13216:                 }
1.1074    raeburn  13217:                 if (defined($intdom)) {
                   13218:                     $internetdom{$id} = $intdom;
                   13219:                 }
1.852     albertel 13220: 	    }
                   13221: 	}
                   13222:     }
1.864     albertel 13223:     
                   13224:     sub reset_hosts_info {
1.897     albertel 13225: 	&purge_remembered();
1.864     albertel 13226: 	&reset_domain_info();
                   13227: 	&reset_hosts_ip_info();
1.892     albertel 13228: 	undef(%name_to_host);
1.864     albertel 13229: 	undef(%hostname);
                   13230: 	undef(%hostdom);
                   13231: 	undef(%libserv);
                   13232: 	undef($loaded);
                   13233:     }
1.1       albertel 13234: 
1.852     albertel 13235:     sub load_hosts_tab {
1.1172.2.70  raeburn  13236: 	my ($ignore_cache,$nocache) = @_;
                   13237: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.93.4  7(raebur 13238:7): 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13239: 	my @config = <$config>;
                   13240: 	&parse_hosts_tab(\@config);
                   13241: 	close($config);
                   13242: 	$loaded=1;
1.1       albertel 13243:     }
1.852     albertel 13244: 
1.838     albertel 13245:     sub hostname {
1.852     albertel 13246: 	&load_hosts_tab() if (!$loaded);
                   13247: 
1.838     albertel 13248: 	my ($lonid) = @_;
                   13249: 	return $hostname{$lonid};
                   13250:     }
1.845     albertel 13251: 
1.838     albertel 13252:     sub all_hostnames {
1.852     albertel 13253: 	&load_hosts_tab() if (!$loaded);
                   13254: 
1.838     albertel 13255: 	return %hostname;
                   13256:     }
1.845     albertel 13257: 
1.888     albertel 13258:     sub all_names {
1.1172.2.70  raeburn  13259:         my ($ignore_cache,$nocache) = @_;
                   13260: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13261: 
                   13262: 	return %name_to_host;
                   13263:     }
                   13264: 
1.974     raeburn  13265:     sub all_host_domain {
                   13266:         &load_hosts_tab() if (!$loaded);
                   13267:         return %hostdom;
                   13268:     }
                   13269: 
1.845     albertel 13270:     sub is_library {
1.852     albertel 13271: 	&load_hosts_tab() if (!$loaded);
                   13272: 
1.845     albertel 13273: 	return exists($libserv{$_[0]});
                   13274:     }
                   13275: 
                   13276:     sub all_library {
1.852     albertel 13277: 	&load_hosts_tab() if (!$loaded);
                   13278: 
1.845     albertel 13279: 	return %libserv;
                   13280:     }
                   13281: 
1.1062    droeschl 13282:     sub unique_library {
                   13283: 	#2x reverse removes all hostnames that appear more than once
                   13284:         my %unique = reverse &all_library();
                   13285:         return reverse %unique;
                   13286:     }
                   13287: 
1.841     albertel 13288:     sub get_servers {
1.852     albertel 13289: 	&load_hosts_tab() if (!$loaded);
                   13290: 
1.841     albertel 13291: 	my ($domain,$type) = @_;
                   13292: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13293: 	                                          : %hostname;
                   13294: 	my %result;
1.842     albertel 13295: 	if (ref($domain) eq 'ARRAY') {
                   13296: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13297: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13298: 		    $result{$host} = $hostname;
                   13299: 		}
                   13300: 	    }
                   13301: 	} else {
                   13302: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13303: 		if ($hostdom{$host} eq $domain) {
                   13304: 		    $result{$host} = $hostname;
                   13305: 		}
1.841     albertel 13306: 	    }
                   13307: 	}
                   13308: 	return %result;
                   13309:     }
1.845     albertel 13310: 
1.1062    droeschl 13311:     sub get_unique_servers {
                   13312:         my %unique = reverse &get_servers(@_);
                   13313: 	return reverse %unique;
                   13314:     }
                   13315: 
1.844     albertel 13316:     sub host_domain {
1.852     albertel 13317: 	&load_hosts_tab() if (!$loaded);
                   13318: 
1.844     albertel 13319: 	my ($lonid) = @_;
                   13320: 	return $hostdom{$lonid};
                   13321:     }
                   13322: 
1.841     albertel 13323:     sub all_domains {
1.852     albertel 13324: 	&load_hosts_tab() if (!$loaded);
                   13325: 
1.841     albertel 13326: 	my %seen;
                   13327: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13328: 	return @uniq;
                   13329:     }
1.1074    raeburn  13330: 
                   13331:     sub internet_dom {
                   13332:         &load_hosts_tab() if (!$loaded);
                   13333: 
                   13334:         my ($lonid) = @_;
                   13335:         return $internetdom{$lonid};
                   13336:     }
1.1107    raeburn  13337: 
                   13338:     sub is_LC_dns {
                   13339:         &load_hosts_tab() if (!$loaded);
                   13340: 
                   13341:         my ($hostname) = @_;
                   13342:         return exists($LC_dns_serv{$hostname});
                   13343:     }
                   13344: 
1.1       albertel 13345: }
                   13346: 
1.847     albertel 13347: { 
                   13348:     my %iphost;
1.856     albertel 13349:     my %name_to_ip;
                   13350:     my %lonid_to_ip;
1.869     albertel 13351: 
1.847     albertel 13352:     sub get_hosts_from_ip {
                   13353: 	my ($ip) = @_;
                   13354: 	my %iphosts = &get_iphost();
                   13355: 	if (ref($iphosts{$ip})) {
                   13356: 	    return @{$iphosts{$ip}};
                   13357: 	}
                   13358: 	return;
1.839     albertel 13359:     }
1.864     albertel 13360:     
                   13361:     sub reset_hosts_ip_info {
                   13362: 	undef(%iphost);
                   13363: 	undef(%name_to_ip);
                   13364: 	undef(%lonid_to_ip);
                   13365:     }
1.856     albertel 13366: 
                   13367:     sub get_host_ip {
                   13368: 	my ($lonid) = @_;
                   13369: 	if (exists($lonid_to_ip{$lonid})) {
                   13370: 	    return $lonid_to_ip{$lonid};
                   13371: 	}
                   13372: 	my $name=&hostname($lonid);
                   13373:    	my $ip = gethostbyname($name);
                   13374: 	return if (!$ip || length($ip) ne 4);
                   13375: 	$ip=inet_ntoa($ip);
                   13376: 	$name_to_ip{$name}   = $ip;
                   13377: 	$lonid_to_ip{$lonid} = $ip;
                   13378: 	return $ip;
                   13379:     }
1.847     albertel 13380:     
                   13381:     sub get_iphost {
1.1172.2.70  raeburn  13382: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13383: 
1.869     albertel 13384: 	if (!$ignore_cache) {
                   13385: 	    if (%iphost) {
                   13386: 		return %iphost;
                   13387: 	    }
                   13388: 	    my ($ip_info,$cached)=
                   13389: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13390: 	    if ($cached) {
                   13391: 		%iphost      = %{$ip_info->[0]};
                   13392: 		%name_to_ip  = %{$ip_info->[1]};
                   13393: 		%lonid_to_ip = %{$ip_info->[2]};
                   13394: 		return %iphost;
                   13395: 	    }
                   13396: 	}
1.894     albertel 13397: 
                   13398: 	# get yesterday's info for fallback
                   13399: 	my %old_name_to_ip;
                   13400: 	my ($ip_info,$cached)=
                   13401: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13402: 	if ($cached) {
                   13403: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13404: 	}
                   13405: 
1.1172.2.70  raeburn  13406: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13407: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13408: 	    my $ip;
                   13409: 	    if (!exists($name_to_ip{$name})) {
                   13410: 		$ip = gethostbyname($name);
                   13411: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13412: 		    if (defined($old_name_to_ip{$name})) {
                   13413: 			$ip = $old_name_to_ip{$name};
                   13414: 			&logthis("Can't find $name defaulting to old $ip");
                   13415: 		    } else {
                   13416: 			&logthis("Name $name no IP found");
                   13417: 			next;
                   13418: 		    }
                   13419: 		} else {
                   13420: 		    $ip=inet_ntoa($ip);
1.847     albertel 13421: 		}
                   13422: 		$name_to_ip{$name} = $ip;
                   13423: 	    } else {
                   13424: 		$ip = $name_to_ip{$name};
1.653     albertel 13425: 	    }
1.888     albertel 13426: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13427: 		$lonid_to_ip{$id} = $ip;
                   13428: 	    }
                   13429: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13430: 	}
1.1172.2.70  raeburn  13431:         unless ($nocache) {
                   13432: 	    &do_cache_new('iphost','iphost',
                   13433: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13434: 		          48*60*60);
                   13435:         }
1.869     albertel 13436: 
1.847     albertel 13437: 	return %iphost;
1.598     albertel 13438:     }
                   13439: 
1.992     raeburn  13440:     #
                   13441:     #  Given a DNS returns the loncapa host name for that DNS 
                   13442:     # 
                   13443:     sub host_from_dns {
                   13444:         my ($dns) = @_;
                   13445:         my @hosts;
                   13446:         my $ip;
                   13447: 
1.993     raeburn  13448:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13449:             $ip = $name_to_ip{$dns};
                   13450:         }
                   13451:         if (!$ip) {
                   13452:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13453:             if (length($ip) == 4) { 
                   13454: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13455:             }
                   13456:         }
                   13457:         if ($ip) {
                   13458: 	    @hosts = get_hosts_from_ip($ip);
                   13459: 	    return $hosts[0];
                   13460:         }
                   13461:         return undef;
1.986     foxr     13462:     }
1.992     raeburn  13463: 
1.1074    raeburn  13464:     sub get_internet_names {
                   13465:         my ($lonid) = @_;
                   13466:         return if ($lonid eq '');
                   13467:         my ($idnref,$cached)=
                   13468:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13469:         if ($cached) {
                   13470:             return $idnref;
                   13471:         }
                   13472:         my $ip = &get_host_ip($lonid);
                   13473:         my @hosts = &get_hosts_from_ip($ip);
                   13474:         my %iphost = &get_iphost();
                   13475:         my (@idns,%seen);
                   13476:         foreach my $id (@hosts) {
                   13477:             my $dom = &host_domain($id);
                   13478:             my $prim_id = &domain($dom,'primary');
                   13479:             my $prim_ip = &get_host_ip($prim_id);
                   13480:             next if ($seen{$prim_ip});
                   13481:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13482:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13483:                     my $intdom = &internet_dom($id);
                   13484:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13485:                         push(@idns,$intdom);
                   13486:                     }
                   13487:                 }
                   13488:             }
                   13489:             $seen{$prim_ip} = 1;
                   13490:         }
1.1172.2.23  raeburn  13491:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13492:     }
                   13493: 
1.986     foxr     13494: }
                   13495: 
1.1079    raeburn  13496: sub all_loncaparevs {
1.1172.2.39  raeburn  13497:     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  13498: }
                   13499: 
1.1172.2.27  raeburn  13500: # ------------------------------------------------------- Read loncaparev table
                   13501: {
                   13502:     sub load_loncaparevs {
                   13503:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.93.4  7(raebur 13504:7):             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13505:                 while (my $configline=<$config>) {
                   13506:                     chomp($configline);
                   13507:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13508:                     $loncaparevs{$hostid}=$loncaparev;
                   13509:                 }
                   13510:                 close($config);
                   13511:             }
                   13512:         }
                   13513:     }
                   13514: }
                   13515: 
                   13516: # ----------------------------------------------------- Read serverhostID table
                   13517: {
                   13518:     sub load_serverhomeIDs {
                   13519:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.93.4  7(raebur 13520:7):             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13521:                 while (my $configline=<$config>) {
                   13522:                     chomp($configline);
                   13523:                     my ($name,$id)=split(/:/,$configline);
                   13524:                     $serverhomeIDs{$name}=$id;
                   13525:                 }
                   13526:                 close($config);
                   13527:             }
                   13528:         }
                   13529:     }
                   13530: }
                   13531: 
                   13532: 
1.862     albertel 13533: BEGIN {
                   13534: 
                   13535: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13536:     unless ($readit) {
                   13537: {
                   13538:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13539:     %perlvar = (%perlvar,%{$configvars});
                   13540: }
                   13541: 
                   13542: 
1.1       albertel 13543: # ------------------------------------------------------ Read spare server file
                   13544: {
1.1172.2.93.4  7(raebur 13545:7):     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13546: 
                   13547:     while (my $configline=<$config>) {
                   13548:        chomp($configline);
1.284     matthew  13549:        if ($configline) {
1.784     albertel 13550: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13551: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13552: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13553:        }
                   13554:     }
1.448     albertel 13555:     close($config);
1.1       albertel 13556: }
1.11      www      13557: # ------------------------------------------------------------ Read permissions
                   13558: {
1.1172.2.93.4  7(raebur 13559:7):     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13560: 
                   13561:     while (my $configline=<$config>) {
1.448     albertel 13562: 	chomp($configline);
                   13563: 	if ($configline) {
                   13564: 	    my ($role,$perm)=split(/ /,$configline);
                   13565: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13566: 	}
1.11      www      13567:     }
1.448     albertel 13568:     close($config);
1.11      www      13569: }
                   13570: 
                   13571: # -------------------------------------------- Read plain texts for permissions
                   13572: {
1.1172.2.93.4  7(raebur 13573:7):     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13574: 
                   13575:     while (my $configline=<$config>) {
1.448     albertel 13576: 	chomp($configline);
                   13577: 	if ($configline) {
1.742     raeburn  13578: 	    my ($short,@plain)=split(/:/,$configline);
                   13579:             %{$prp{$short}} = ();
                   13580: 	    if (@plain > 0) {
                   13581:                 $prp{$short}{'std'} = $plain[0];
                   13582:                 for (my $i=1; $i<@plain; $i++) {
                   13583:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13584:                 }
                   13585:             }
1.448     albertel 13586: 	}
1.135     www      13587:     }
1.448     albertel 13588:     close($config);
1.135     www      13589: }
                   13590: 
                   13591: # ---------------------------------------------------------- Read package table
                   13592: {
1.1172.2.93.4  7(raebur 13593:7):     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13594: 
                   13595:     while (my $configline=<$config>) {
1.483     albertel 13596: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13597: 	chomp($configline);
                   13598: 	my ($short,$plain)=split(/:/,$configline);
                   13599: 	my ($pack,$name)=split(/\&/,$short);
                   13600: 	if ($plain ne '') {
                   13601: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13602: 	    $packagetab{$short}=$plain; 
                   13603: 	}
1.11      www      13604:     }
1.448     albertel 13605:     close($config);
1.329     matthew  13606: }
                   13607: 
1.1172.2.27  raeburn  13608: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13609: 
1.1172.2.27  raeburn  13610: &load_loncaparevs();
                   13611: 
                   13612: # ------------------------------------------------------- Read serverhostID table
                   13613: 
                   13614: &load_serverhomeIDs();
1.1074    raeburn  13615: 
1.1172.2.27  raeburn  13616: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13617: {
                   13618:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13619:     if (-e $file) {
                   13620:         my $parser = HTML::LCParser->new($file);
                   13621:         while (my $token = $parser->get_token()) {
                   13622:             if ($token->[0] eq 'S') {
                   13623:                 my $item = $token->[1];
                   13624:                 my $name = $token->[2]{'name'};
                   13625:                 my $value = $token->[2]{'value'};
                   13626:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13627:                     my $release = $parser->get_text();
                   13628:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13629:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13630:                 }
                   13631:             }
                   13632:         }
                   13633:     }
1.1073    raeburn  13634: }
                   13635: 
1.1138    raeburn  13636: # ---------------------------------------------------------- Read managers table
                   13637: {
                   13638:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.93.4  7(raebur 13639:7):         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13640:             while (my $configline=<$config>) {
                   13641:                 chomp($configline);
                   13642:                 next if ($configline =~ /^\#/);
                   13643:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13644:                     $managerstab{$configline} = 1;
                   13645:                 }
                   13646:             }
                   13647:             close($config);
                   13648:         }
                   13649:     }
                   13650: }
                   13651: 
1.329     matthew  13652: # ------------- set up temporary directory
                   13653: {
1.1117    foxr     13654:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13655: 
1.11      www      13656: }
                   13657: 
1.794     albertel 13658: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13659: 				'compress_threshold'=> 20_000,
                   13660:  			        });
1.185     www      13661: 
1.281     www      13662: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13663: $dumpcount=0;
1.958     www      13664: $locknum=0;
1.22      www      13665: 
1.163     harris41 13666: &logtouch();
1.672     albertel 13667: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13668: $readit=1;
1.564     albertel 13669:     {
                   13670: 	use integer;
                   13671: 	my $test=(2**32)+1;
1.568     albertel 13672: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13673: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13674:     }
1.195     www      13675: }
1.1       albertel 13676: }
1.179     www      13677: 
1.1       albertel 13678: 1;
1.191     harris41 13679: __END__
                   13680: 
1.243     albertel 13681: =pod
                   13682: 
1.191     harris41 13683: =head1 NAME
                   13684: 
1.243     albertel 13685: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13686: 
                   13687: =head1 SYNOPSIS
                   13688: 
1.243     albertel 13689: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13690: 
                   13691:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13692: 
1.243     albertel 13693: Common parameters:
                   13694: 
                   13695: =over 4
                   13696: 
                   13697: =item *
                   13698: 
                   13699: $uname : an internal username (if $cname expecting a course Id specifically)
                   13700: 
                   13701: =item *
                   13702: 
                   13703: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13704: 
                   13705: =item *
                   13706: 
                   13707: $symb : a resource instance identifier
                   13708: 
                   13709: =item *
                   13710: 
                   13711: $namespace : the name of a .db file that contains the data needed or
                   13712: being set.
                   13713: 
                   13714: =back
                   13715: 
1.394     bowersj2 13716: =head1 OVERVIEW
1.191     harris41 13717: 
1.394     bowersj2 13718: lonnet provides subroutines which interact with the
                   13719: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13720: about classes, users, and resources.
1.243     albertel 13721: 
                   13722: For many of these objects you can also use this to store data about
                   13723: them or modify them in various ways.
1.191     harris41 13724: 
1.394     bowersj2 13725: =head2 Symbs
1.191     harris41 13726: 
1.394     bowersj2 13727: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13728: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13729: map, the resource number of the resource in the map, and the URL of
                   13730: the resource itself. The latter is somewhat redundant, but might help
                   13731: if maps change.
                   13732: 
                   13733: An example is
                   13734: 
                   13735:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13736: 
                   13737: The respective map entry is
                   13738: 
                   13739:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13740:   title="Problem 2">
                   13741:  </resource>
                   13742: 
                   13743: Symbs are used by the random number generator, as well as to store and
                   13744: restore data specific to a certain instance of for example a problem.
                   13745: 
                   13746: =head2 Storing And Retrieving Data
                   13747: 
                   13748: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13749: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13750: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13751: is is the non-critical message twin of cstore. These functions are for
                   13752: handlers to store a perl hash to a user's permanent data space in an
                   13753: easy manner, and to retrieve it again on another call. It is expected
                   13754: that a handler would use this once at the beginning to retrieve data,
                   13755: and then again once at the end to send only the new data back.
                   13756: 
                   13757: The data is stored in the user's data directory on the user's
                   13758: homeserver under the ID of the course.
                   13759: 
                   13760: The hash that is returned by restore will have all of the previous
                   13761: value for all of the elements of the hash.
                   13762: 
                   13763: Example:
                   13764: 
                   13765:  #creating a hash
                   13766:  my %hash;
                   13767:  $hash{'foo'}='bar';
                   13768: 
                   13769:  #storing it
                   13770:  &Apache::lonnet::cstore(\%hash);
                   13771: 
                   13772:  #changing a value
                   13773:  $hash{'foo'}='notbar';
                   13774: 
                   13775:  #adding a new value
                   13776:  $hash{'bar'}='foo';
                   13777:  &Apache::lonnet::cstore(\%hash);
                   13778: 
                   13779:  #retrieving the hash
                   13780:  my %history=&Apache::lonnet::restore();
                   13781: 
                   13782:  #print the hash
                   13783:  foreach my $key (sort(keys(%history))) {
                   13784:    print("\%history{$key} = $history{$key}");
                   13785:  }
                   13786: 
                   13787: Will print out:
1.191     harris41 13788: 
1.394     bowersj2 13789:  %history{1:foo} = bar
                   13790:  %history{1:keys} = foo:timestamp
                   13791:  %history{1:timestamp} = 990455579
                   13792:  %history{2:bar} = foo
                   13793:  %history{2:foo} = notbar
                   13794:  %history{2:keys} = foo:bar:timestamp
                   13795:  %history{2:timestamp} = 990455580
                   13796:  %history{bar} = foo
                   13797:  %history{foo} = notbar
                   13798:  %history{timestamp} = 990455580
                   13799:  %history{version} = 2
                   13800: 
                   13801: Note that the special hash entries C<keys>, C<version> and
                   13802: C<timestamp> were added to the hash. C<version> will be equal to the
                   13803: total number of versions of the data that have been stored. The
                   13804: C<timestamp> attribute will be the UNIX time the hash was
                   13805: stored. C<keys> is available in every historical section to list which
                   13806: keys were added or changed at a specific historical revision of a
                   13807: hash.
                   13808: 
                   13809: B<Warning>: do not store the hash that restore returns directly. This
                   13810: will cause a mess since it will restore the historical keys as if the
                   13811: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13812: 
1.394     bowersj2 13813: Calling convention:
1.191     harris41 13814: 
1.1172.2.27  raeburn  13815:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13816:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13817: 
1.394     bowersj2 13818: For more detailed information, see lonnet specific documentation.
1.191     harris41 13819: 
1.394     bowersj2 13820: =head1 RETURN MESSAGES
1.191     harris41 13821: 
1.394     bowersj2 13822: =over 4
1.191     harris41 13823: 
1.394     bowersj2 13824: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13825: 
1.394     bowersj2 13826: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13827: when the connection is brought back up
1.191     harris41 13828: 
1.394     bowersj2 13829: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13830: for later delivery
1.191     harris41 13831: 
1.967     bisitz   13832: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13833: 
1.394     bowersj2 13834: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13835: that was requested
1.191     harris41 13836: 
1.243     albertel 13837: =back
1.191     harris41 13838: 
1.243     albertel 13839: =head1 PUBLIC SUBROUTINES
1.191     harris41 13840: 
1.243     albertel 13841: =head2 Session Environment Functions
1.191     harris41 13842: 
1.243     albertel 13843: =over 4
1.191     harris41 13844: 
1.394     bowersj2 13845: =item * 
                   13846: X<appenv()>
1.949     raeburn  13847: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13848: the user envirnoment file, and will be restored for each access this
1.620     albertel 13849: user makes during this session, also modifies the %env for the current
1.949     raeburn  13850: process. Optional rolesarrayref - if defined contains a reference to an array
                   13851: of roles which are exempt from the restriction on modifying user.role entries 
                   13852: in the user's environment.db and in %env.    
1.191     harris41 13853: 
                   13854: =item *
1.394     bowersj2 13855: X<delenv()>
1.987     raeburn  13856: B<delenv($delthis,$regexp)>: removes all items from the session
                   13857: environment file that begin with $delthis. If the 
                   13858: optional second arg - $regexp - is true, $delthis is treated as a 
                   13859: regular expression, otherwise \Q$delthis\E is used. 
                   13860: The values are also deleted from the current processes %env.
1.191     harris41 13861: 
1.795     albertel 13862: =item * get_env_multiple($name) 
                   13863: 
                   13864: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13865: values may be defined and end up as an array ref.
                   13866: 
                   13867: returns an array of values
                   13868: 
1.243     albertel 13869: =back
                   13870: 
                   13871: =head2 User Information
1.191     harris41 13872: 
1.243     albertel 13873: =over 4
1.191     harris41 13874: 
                   13875: =item *
1.394     bowersj2 13876: X<queryauthenticate()>
                   13877: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13878: authentication scheme
                   13879: 
                   13880: =item *
1.394     bowersj2 13881: X<authenticate()>
1.1073    raeburn  13882: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13883: authenticate user from domain's lib servers (first use the current
                   13884: one). C<$upass> should be the users password.
1.1073    raeburn  13885: $checkdefauth is optional (value is 1 if a check should be made to
                   13886:    authenticate user using default authentication method, and allow
                   13887:    account creation if username does not have account in the domain).
                   13888: $clientcancheckhost is optional (value is 1 if checking whether the
                   13889:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13890: 
                   13891: =item *
1.394     bowersj2 13892: X<homeserver()>
                   13893: B<homeserver($uname,$udom)>: find the server which has
                   13894: the user's directory and files (there must be only one), this caches
                   13895: the answer, and also caches if there is a borken connection.
1.191     harris41 13896: 
                   13897: =item *
1.394     bowersj2 13898: X<idget()>
                   13899: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13900: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13901: username, and only 1 username per ID in a specific domain) (returns
                   13902: hash: id=>name,id=>name)
1.191     harris41 13903: 
                   13904: =item *
1.394     bowersj2 13905: X<idrget()>
                   13906: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13907: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13908: 
                   13909: =item *
1.394     bowersj2 13910: X<idput()>
                   13911: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13912: 
                   13913: =item *
1.394     bowersj2 13914: X<rolesinit()>
1.1169    droeschl 13915: B<rolesinit($udom,$username)>: get user privileges.
                   13916: returns user role, first access and timer interval hashes
1.243     albertel 13917: 
                   13918: =item *
1.1171    droeschl 13919: X<privileged()>
                   13920: B<privileged($username,$domain)>: returns a true if user has a
                   13921: privileged and active role (i.e. su or dc), false otherwise.
                   13922: 
                   13923: =item *
1.551     albertel 13924: X<getsection()>
                   13925: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13926: course $cname, return section name/number or '' for "not in course"
                   13927: and '-1' for "no section"
                   13928: 
                   13929: =item *
1.394     bowersj2 13930: X<userenvironment()>
                   13931: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13932: passed in @what from the requested user's environment, returns a hash
                   13933: 
1.858     raeburn  13934: =item * 
                   13935: X<userlog_query()>
1.859     albertel 13936: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13937: activity.log file. %filters defines filters applied when parsing the
                   13938: log file. These can be start or end timestamps, or the type of action
                   13939: - log to look for Login or Logout events, check for Checkin or
                   13940: Checkout, role for role selection. The response is in the form
                   13941: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13942: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13943: 
1.243     albertel 13944: =back
                   13945: 
                   13946: =head2 User Roles
                   13947: 
                   13948: =over 4
                   13949: 
                   13950: =item *
                   13951: 
1.1172.2.65  raeburn  13952: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13953: returns codes for allowed actions.
                   13954: 
                   13955: The first argument is required, all others are optional.
                   13956: 
                   13957: $priv is the privilege being checked.
                   13958: $uri contains additional information about what is being checked for access (e.g.,
                   13959: URL, course ID etc.).
                   13960: $symb is the unique resource instance identifier in a course; if needed,
                   13961: but not provided, it will be retrieved via a call to &symbread().
                   13962: $role is the role for which a priv is being checked (only used if priv is evb).
                   13963: $clientip is the user's IP address (only used when checking for access to portfolio
                   13964: files).
                   13965: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13966: prevents recursive calls to &allowed.
                   13967: 
1.243     albertel 13968:  F: full access
                   13969:  U,I,K: authentication modes (cxx only)
                   13970:  '': forbidden
                   13971:  1: user needs to choose course
                   13972:  2: browse allowed
1.766     albertel 13973:  A: passphrase authentication needed
1.1172.2.65  raeburn  13974:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13975: 
                   13976: =item *
                   13977: 
1.1172.2.13  raeburn  13978: constructaccess($url,$setpriv) : check for access to construction space URL
                   13979: 
                   13980: See if the owner domain and name in the URL match those in the
                   13981: expected environment.  If so, return three element list
                   13982: ($ownername,$ownerdomain,$ownerhome).
                   13983: 
                   13984: Otherwise return the null string.
                   13985: 
                   13986: If second argument 'setpriv' is true, it assigns the privileges,
                   13987: and returns the same three element list, unless the owner has
                   13988: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13989: in which case the null string is returned.
                   13990: 
                   13991: =item *
                   13992: 
1.1172.2.84  raeburn  13993: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13994: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13995: for system, domain, and course level. $uname and $udom are optional (current
                   13996: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13997: 
                   13998: =item *
                   13999: 
1.988     raeburn  14000: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14001: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14002: $type is Course (default) or Community.
1.988     raeburn  14003: If $forcedefault evaluates to true, text returned will be default 
                   14004: text for $type. Otherwise, if this is a course, the text returned 
                   14005: will be a custom name for the role (if defined in the course's 
                   14006: environment).  If no custom name is defined the default is returned.
                   14007:    
1.832     raeburn  14008: =item *
                   14009: 
1.1172.2.23  raeburn  14010: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14011: All arguments are optional. Returns a hash of a roles, either for
                   14012: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14013: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14014: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14015: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14016: For each key, value is set to colon-separated start and end times for
                   14017: the role.  If no username and domain are specified, will default to
1.934     raeburn  14018: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14019: of role statuses (active, future or previous), roles 
                   14020: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14021: to restrict the list of roles reported. If no array ref is 
                   14022: provided for types, will default to return only active roles.
1.834     albertel 14023: 
1.1172.2.13  raeburn  14024: =item *
                   14025: 
                   14026: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14027: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14028: 
                   14029: Additional optional arguments are: $type (if role checking is to be restricted
                   14030: to certain user status types -- previous (expired roles), active (currently
                   14031: available roles) or future (roles available in the future), and
                   14032: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14033: have active Domain Coordinator role in course's domain or in additional
                   14034: domains (specified in 'Domains to check for privileged users' in course
                   14035: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14036: 
                   14037: =item *
                   14038: 
                   14039: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14040: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14041: $possdomains and $possroles are optional array refs -- to domains to check and
                   14042: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14043: users' roles.db to check for a dc or su role in any domain. This can be
                   14044: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14045: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14046: this then allows &privileged_by_domain() to be used, which caches the identity
                   14047: of privileged users, eliminating the need for repeated calls to &dump().
                   14048: 
                   14049: =item *
                   14050: 
                   14051: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14052: where the outer hash keys are domains specified in the $possdomains array ref,
                   14053: next inner hash keys are privileged roles specified in the $roles array ref,
                   14054: and the innermost hash contains key = value pairs for username:domain = end:start
                   14055: for active or future "privileged" users with that role in that domain. To avoid
                   14056: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14057: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14058: 
1.243     albertel 14059: =back
                   14060: 
                   14061: =head2 User Modification
                   14062: 
                   14063: =over 4
                   14064: 
                   14065: =item *
                   14066: 
1.957     raeburn  14067: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14068: user for the level given by URL.  Optional start and end dates (leave empty
                   14069: string or zero for "no date")
1.191     harris41 14070: 
                   14071: =item *
                   14072: 
1.243     albertel 14073: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14074: change a users, password, possible return values are: ok,
                   14075: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14076: refused
1.191     harris41 14077: 
                   14078: =item *
                   14079: 
1.243     albertel 14080: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14081: 
                   14082: =item *
                   14083: 
1.1058    raeburn  14084: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14085:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14086: 
                   14087: will update user information (firstname,middlename,lastname,generation,
                   14088: permanentemail), and if forceid is true, student/employee ID also.
                   14089: A user's institutional affiliation(s) can also be updated.
                   14090: User information fields will not be overwritten with empty entries 
                   14091: unless the field is included in the $candelete array reference.
                   14092: This array is included when a single user is modified via "Manage Users",
                   14093: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14094: 
                   14095: =item *
                   14096: 
1.286     matthew  14097: modifystudent
                   14098: 
1.957     raeburn  14099: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14100: The course id is resolved based on the current user's environment.  
                   14101: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14102: associated with a course.
                   14103: 
1.297     matthew  14104: This call is essentially a wrapper for lonnet::modifyuser and
                   14105: lonnet::modify_student_enrollment
1.286     matthew  14106: 
                   14107: Inputs: 
                   14108: 
                   14109: =over 4
                   14110: 
1.957     raeburn  14111: =item B<$udom> Student's loncapa domain
1.286     matthew  14112: 
1.957     raeburn  14113: =item B<$uname> Student's loncapa login name
1.286     matthew  14114: 
1.964     bisitz   14115: =item B<$uid> Student/Employee ID
1.286     matthew  14116: 
1.957     raeburn  14117: =item B<$umode> Student's authentication mode
1.286     matthew  14118: 
1.957     raeburn  14119: =item B<$upass> Student's password
1.286     matthew  14120: 
1.957     raeburn  14121: =item B<$first> Student's first name
1.286     matthew  14122: 
1.957     raeburn  14123: =item B<$middle> Student's middle name
1.286     matthew  14124: 
1.957     raeburn  14125: =item B<$last> Student's last name
1.286     matthew  14126: 
1.957     raeburn  14127: =item B<$gene> Student's generation
1.286     matthew  14128: 
1.957     raeburn  14129: =item B<$usec> Student's section in course
1.286     matthew  14130: 
                   14131: =item B<$end> Unix time of the roles expiration
                   14132: 
                   14133: =item B<$start> Unix time of the roles start date
                   14134: 
                   14135: =item B<$forceid> If defined, allow $uid to be changed
                   14136: 
                   14137: =item B<$desiredhome> server to use as home server for student
                   14138: 
1.957     raeburn  14139: =item B<$email> Student's permanent e-mail address
                   14140: 
                   14141: =item B<$type> Type of enrollment (auto or manual)
                   14142: 
1.963     raeburn  14143: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14144: 
                   14145: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14146: 
1.963     raeburn  14147: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14148: 
1.963     raeburn  14149: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14150: 
1.1172.2.19  raeburn  14151: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14152: 
                   14153: =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  14154: 
1.286     matthew  14155: =back
1.297     matthew  14156: 
                   14157: =item *
                   14158: 
                   14159: modify_student_enrollment
                   14160: 
1.1172.2.31  raeburn  14161: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14162: 'role.request.course' must be defined for this function to proceed.
                   14163: 
                   14164: Inputs:
                   14165: 
                   14166: =over 4
                   14167: 
1.1172.2.31  raeburn  14168: =item $udom, student's domain
1.297     matthew  14169: 
1.1172.2.31  raeburn  14170: =item $uname, student's name
1.297     matthew  14171: 
1.1172.2.31  raeburn  14172: =item $uid, student's user id
1.297     matthew  14173: 
1.1172.2.31  raeburn  14174: =item $first, student's first name
1.297     matthew  14175: 
                   14176: =item $middle
                   14177: 
                   14178: =item $last
                   14179: 
                   14180: =item $gene
                   14181: 
                   14182: =item $usec
                   14183: 
                   14184: =item $end
                   14185: 
                   14186: =item $start
                   14187: 
1.957     raeburn  14188: =item $type
                   14189: 
                   14190: =item $locktype
                   14191: 
                   14192: =item $cid
                   14193: 
                   14194: =item $selfenroll
                   14195: 
                   14196: =item $context
                   14197: 
1.1172.2.19  raeburn  14198: =item $credits, number of credits student will earn from this class
                   14199: 
1.1172.2.76  raeburn  14200: =item $instsec, institutional course section code for student
                   14201: 
1.297     matthew  14202: =back
                   14203: 
1.191     harris41 14204: 
                   14205: =item *
                   14206: 
1.243     albertel 14207: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14208: custom role; give a custom role to a user for the level given by URL.  Specify
                   14209: name and domain of role author, and role name
1.191     harris41 14210: 
                   14211: =item *
                   14212: 
1.243     albertel 14213: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14214: 
                   14215: =item *
                   14216: 
1.243     albertel 14217: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14218: 
                   14219: =back
                   14220: 
                   14221: =head2 Course Infomation
                   14222: 
                   14223: =over 4
1.191     harris41 14224: 
                   14225: =item *
                   14226: 
1.1118    foxr     14227: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14228: specified course id, including all environment settings for the
                   14229: course, the description of the course will be in the hash under the
                   14230: key 'description'
1.191     harris41 14231: 
1.1118    foxr     14232: $options is an optional parameter that if supplied is a hash reference that controls
                   14233: what how this function works.  It has the following key/values:
                   14234: 
                   14235: =over 4
                   14236: 
                   14237: =item freshen_cache
                   14238: 
                   14239: If defined, and the environment cache for the course is valid, it is 
                   14240: returned in the returned hash.
                   14241: 
                   14242: =item one_time
                   14243: 
                   14244: If defined, the last cache time is set to _now_
                   14245: 
                   14246: =item user
                   14247: 
                   14248: If defined, the supplied username is used instead of the current user.
                   14249: 
                   14250: 
                   14251: =back
                   14252: 
1.191     harris41 14253: =item *
                   14254: 
1.624     albertel 14255: resdata($name,$domain,$type,@which) : request for current parameter
                   14256: setting for a specific $type, where $type is either 'course' or 'user',
                   14257: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14258: answers for 10 minutes.
1.243     albertel 14259: 
1.877     foxr     14260: =item *
                   14261: 
                   14262: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14263: data base, returning a hash that is keyed by the resource name and has
                   14264: values that are the resource value.  I believe that the timestamps and
                   14265: versions are also returned.
                   14266: 
1.1172.2.31  raeburn  14267: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14268: supplemental content area. This routine caches the number of files for
                   14269: 10 minutes.
                   14270: 
1.243     albertel 14271: =back
                   14272: 
                   14273: =head2 Course Modification
                   14274: 
                   14275: =over 4
1.191     harris41 14276: 
                   14277: =item *
                   14278: 
1.243     albertel 14279: writecoursepref($courseid,%prefs) : write preferences (environment
                   14280: database) for a course
1.191     harris41 14281: 
                   14282: =item *
                   14283: 
1.1011    raeburn  14284: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14285: 
                   14286: =item *
                   14287: 
1.1038    raeburn  14288: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14289: 
1.1167    droeschl 14290: =item *
                   14291: 
                   14292: is_course($courseid), is_course($cdom, $cnum)
                   14293: 
                   14294: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14295: two component version $cdom, $cnum. It checks if the specified course exists.
                   14296: 
                   14297: Returns:
                   14298:     undef if the course doesn't exist, otherwise
                   14299:     in scalar context the combined courseid.
                   14300:     in list context the two components of the course identifier, domain and 
                   14301:     courseid.    
                   14302: 
1.243     albertel 14303: =back
                   14304: 
1.1172.2.93.4  12(raebu 14305:19): =head2 Bubblesheet Configuration
                   14306:19): 
                   14307:19): =over 4
                   14308:19): 
                   14309:19): =item *
                   14310:19): 
                   14311:19): get_scantron_config($which)
                   14312:19): 
                   14313:19): $which - the name of the configuration to parse from the file.
                   14314:19): 
                   14315:19): Parses and returns the bubblesheet configuration line selected as a
                   14316:19): hash of configuration file fields.
                   14317:19): 
                   14318:19): 
                   14319:19): Returns:
                   14320:19):     If the named configuration is not in the file, an empty
                   14321:19):     hash is returned.
                   14322:19): 
                   14323:19):     a hash with the fields
                   14324:19):       name         - internal name for the this configuration setup
                   14325:19):       description  - text to display to operator that describes this config
                   14326:19):       CODElocation - if 0 or the string 'none'
                   14327:19):                           - no CODE exists for this config
                   14328:19):                      if -1 || the string 'letter'
                   14329:19):                           - a CODE exists for this config and is
                   14330:19):                             a string of letters
                   14331:19):                      Unsupported value (but planned for future support)
                   14332:19):                           if a positive integer
                   14333:19):                                - The CODE exists as the first n items from
                   14334:19):                                  the question section of the form
                   14335:19):                           if the string 'number'
                   14336:19):                                - The CODE exists for this config and is
                   14337:19):                                  a string of numbers
                   14338:19):       CODEstart   - (only matter if a CODE exists) column in the line where
                   14339:19):                      the CODE starts
                   14340:19):       CODElength  - length of the CODE
                   14341:19):       IDstart     - column where the student/employee ID starts
                   14342:19):       IDlength    - length of the student/employee ID info
                   14343:19):       Qstart      - column where the information from the bubbled
                   14344:19):                     'questions' start
                   14345:19):       Qlength     - number of columns comprising a single bubble line from
                   14346:19):                     the sheet. (usually either 1 or 10)
                   14347:19):       Qon         - either a single character representing the character used
                   14348:19):                     to signal a bubble was chosen in the positional setup, or
                   14349:19):                     the string 'letter' if the letter of the chosen bubble is
                   14350:19):                     in the final, or 'number' if a number representing the
                   14351:19):                     chosen bubble is in the file (1->A 0->J)
                   14352:19):       Qoff        - the character used to represent that a bubble was
                   14353:19):                     left blank
                   14354:19):       PaperID     - if the scanning process generates a unique number for each
                   14355:19):                     sheet scanned the column that this ID number starts in
                   14356:19):       PaperIDlength - number of columns that comprise the unique ID number
                   14357:19):                       for the sheet of paper
                   14358:19):       FirstName   - column that the first name starts in
                   14359:19):       FirstNameLength - number of columns that the first name spans
                   14360:19):       LastName    - column that the last name starts in
                   14361:19):       LastNameLength - number of columns that the last name spans
                   14362:19):       BubblesPerRow - number of bubbles available in each row used to
                   14363:19):                       bubble an answer. (If not specified, 10 assumed).
                   14364:19): 
                   14365:19): 
                   14366:19): =item *
                   14367:19): 
                   14368:19): get_scantronformat_file($cdom)
                   14369:19): 
                   14370:19): $cdom - the course's domain (optional); if not supplied, uses
                   14371:19): domain for current $env{'request.course.id'}.
                   14372:19): 
                   14373:19): Returns an array containing lines from the scantron format file for
                   14374:19): the domain of the course.
                   14375:19): 
                   14376:19): If a url for a custom.tab file is listed in domain's configuration.db,
                   14377:19): lines are from this file.
                   14378:19): 
                   14379:19): Otherwise, if a default.tab has been published in RES space by the
                   14380:19): domainconfig user, lines are from this file.
                   14381:19): 
                   14382:19): Otherwise, fall back to getting lines from the legacy file on the
                   14383:19): local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14384:19): 
                   14385:19): =back
                   14386:19): 
1.243     albertel 14387: =head2 Resource Subroutines
                   14388: 
                   14389: =over 4
1.191     harris41 14390: 
                   14391: =item *
                   14392: 
1.243     albertel 14393: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14394: 
                   14395: =item *
                   14396: 
1.243     albertel 14397: repcopy($filename) : subscribes to the requested file, and attempts to
                   14398: replicate from the owning library server, Might return
1.607     raeburn  14399: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14400: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14401: resource. Expects the local filesystem pathname
                   14402: (/home/httpd/html/res/....)
                   14403: 
                   14404: =back
                   14405: 
                   14406: =head2 Resource Information
                   14407: 
                   14408: =over 4
1.191     harris41 14409: 
                   14410: =item *
                   14411: 
1.1172.2.28  raeburn  14412: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14413: and returns the value of a variety of different possible values,
                   14414: $varname should be a request string, and the other parameters can be
                   14415: used to specify who and what one is asking about. Ordinarily, $cid 
                   14416: does not need to be specified, as it is retrived from 
                   14417: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14418: within lonuserstate::loadmap() when initializing a course, before
                   14419: $env{'request.course.id'} has been set, so it needs to be provided
                   14420: in that one case.
1.243     albertel 14421: 
                   14422: Possible values for $varname are environment.lastname (or other item
                   14423: from the envirnment hash), user.name (or someother aspect about the
                   14424: user), resource.0.maxtries (or some other part and parameter of a
                   14425: resource)
1.204     albertel 14426: 
                   14427: =item *
                   14428: 
1.243     albertel 14429: directcondval($number) : get current value of a condition; reads from a state
                   14430: string
1.204     albertel 14431: 
                   14432: =item *
                   14433: 
1.243     albertel 14434: condval($condidx) : value of condition index based on state
1.204     albertel 14435: 
                   14436: =item *
                   14437: 
1.243     albertel 14438: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14439: resource's metadata, $what should be either a specific key, or either
                   14440: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14441: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14442: 
                   14443: this function automatically caches all requests
1.191     harris41 14444: 
                   14445: =item *
                   14446: 
1.243     albertel 14447: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14448: network of library servers; returns file handle of where SQL and regex results
                   14449: will be stored for query
1.191     harris41 14450: 
                   14451: =item *
                   14452: 
1.1172.2.66  raeburn  14453: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14454: return symbolic list entry (all arguments optional).
                   14455: 
                   14456: Args: filename is the filename (including path) for the file for which a symb
                   14457: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14458: to check access status if more than one resource was found in the bighash
                   14459: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14460: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14461: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14462: cause possible symbs to be checked to determine if they are subject to content
                   14463: blocking, if so they will not be included as possible symbs; possibles is a
                   14464: ref to a hash, which, as a side effect, will be populated with all possible
                   14465: symbs (content blocking not tested).
                   14466: 
1.243     albertel 14467: returns the data handle
1.191     harris41 14468: 
                   14469: =item *
                   14470: 
1.1172.2.17  raeburn  14471: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14472: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14473: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14474: on failure, user must be in a course, as it assumes the existence of
                   14475: the course initial hash, and uses $env('request.course.id'}.  The third
                   14476: arg is an optional reference to a scalar.  If this arg is passed in the
                   14477: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14478: encrypted; otherwise it will be null.
1.243     albertel 14479: 
1.191     harris41 14480: =item *
                   14481: 
1.243     albertel 14482: symbclean($symb) : removes versions numbers from a symb, returns the
                   14483: cleaned symb
1.191     harris41 14484: 
                   14485: =item *
                   14486: 
1.243     albertel 14487: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14488: course map, user must be in a course for it to work.
1.191     harris41 14489: 
                   14490: =item *
                   14491: 
1.243     albertel 14492: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14493: 
                   14494: =item *
                   14495: 
1.243     albertel 14496: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14497: a random seed, all arguments are optional, if they aren't sent it uses the
                   14498: environment to derive them. Note: if symb isn't sent and it can't get one
                   14499: from &symbread it will use the current time as its return value
1.191     harris41 14500: 
                   14501: =item *
                   14502: 
1.243     albertel 14503: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14504: unfakeable, receipt
1.191     harris41 14505: 
                   14506: =item *
                   14507: 
1.620     albertel 14508: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14509: 
                   14510: =item *
                   14511: 
1.243     albertel 14512: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14513: 
                   14514: =item *
                   14515: 
1.243     albertel 14516: 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 14517: 
                   14518: =item *
                   14519: 
1.243     albertel 14520: 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 14521: 
                   14522: =item *
                   14523: 
1.243     albertel 14524: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14525: 
                   14526: =item *
                   14527: 
1.243     albertel 14528: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14529: forcing spreadsheet to reevaluate the resource scores next time.
                   14530: 
1.1172.2.13  raeburn  14531: =item *
                   14532: 
                   14533: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14534: when viewing in course context.
                   14535: 
                   14536:  input: six args -- filename (decluttered), course number, course domain,
                   14537:                     url, symb (if registered) and group (if this is a
                   14538:                     group item -- e.g., bulletin board, group page etc.).
                   14539: 
                   14540:  output: array of five scalars --
                   14541:          $cfile -- url for file editing if editable on current server
                   14542:          $home -- homeserver of resource (i.e., for author if published,
                   14543:                                           or course if uploaded.).
                   14544:          $switchserver --  1 if server switch will be needed.
                   14545:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14546:          $forceview -- 1 if icon/link should be to go to view mode
                   14547: 
                   14548: =item *
                   14549: 
                   14550: is_course_upload($file,$cnum,$cdom)
                   14551: 
                   14552: Used in course context to determine if current file was uploaded to
                   14553: the course (i.e., would be found in /userfiles/docs on the course's
                   14554: homeserver.
                   14555: 
                   14556:   input: 3 args -- filename (decluttered), course number and course domain.
                   14557:   output: boolean -- 1 if file was uploaded.
                   14558: 
1.243     albertel 14559: =back
                   14560: 
                   14561: =head2 Storing/Retreiving Data
                   14562: 
                   14563: =over 4
1.191     harris41 14564: 
                   14565: =item *
                   14566: 
1.1172.2.64  raeburn  14567: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14568: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14569: the remaining args aren't required and if they aren't passed or are '' they will
                   14570: be derived from the env (with the exception of $laststore, which is an
                   14571: optional arg used when a user's submission is stored in grading).
                   14572: $laststore is $version=$timestamp, where $version is the most recent version
                   14573: number retrieved for the corresponding $symb in the $namespace db file, and
                   14574: $timestamp is the timestamp for that transaction (UNIX time).
                   14575: $laststore is currently only passed when cstore() is called by
                   14576: structuretags::finalize_storage().
1.191     harris41 14577: 
                   14578: =item *
                   14579: 
1.1172.2.64  raeburn  14580: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14581: but uses critical subroutine
1.191     harris41 14582: 
                   14583: =item *
                   14584: 
1.243     albertel 14585: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14586: all args are optional
1.191     harris41 14587: 
                   14588: =item *
                   14589: 
1.717     albertel 14590: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14591: dumps the complete (or key matching regexp) namespace into a hash
                   14592: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14593: normally &store()ed into
                   14594: 
                   14595: $range should be either an integer '100' (give me the first 100
                   14596:                                            matching records)
                   14597:               or be  two integers sperated by a - with no spaces
                   14598:                  '30-50' (give me the 30th through the 50th matching
                   14599:                           records)
                   14600: 
                   14601: 
                   14602: =item *
                   14603: 
1.1172.2.59  raeburn  14604: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14605: replaces a &store() version of data with a replacement set of data
                   14606: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14607: reference. If $tolog is true, the transaction is logged in the courselog
                   14608: with an action=PUTSTORE.
1.717     albertel 14609: 
                   14610: =item *
                   14611: 
1.243     albertel 14612: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14613: works very similar to store/cstore, but all data is stored in a
                   14614: temporary location and can be reset using tmpreset, $storehash should
                   14615: be a hash reference, returns nothing on success
1.191     harris41 14616: 
                   14617: =item *
                   14618: 
1.243     albertel 14619: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14620: similar to restore, but all data is stored in a temporary location and
                   14621: can be reset using tmpreset. Returns a hash of values on success,
                   14622: error string otherwise.
1.191     harris41 14623: 
                   14624: =item *
                   14625: 
1.243     albertel 14626: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14627: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14628: 
                   14629: =item *
                   14630: 
1.243     albertel 14631: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14632: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14633: 
                   14634: =item *
                   14635: 
1.243     albertel 14636: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14637: namesp ($udom and $uname are optional)
1.191     harris41 14638: 
                   14639: =item *
                   14640: 
1.702     albertel 14641: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14642: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14643: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14644: 
1.702     albertel 14645: $range should be either an integer '100' (give me the first 100
                   14646:                                            matching records)
                   14647:               or be  two integers sperated by a - with no spaces
                   14648:                  '30-50' (give me the 30th through the 50th matching
                   14649:                           records)
1.449     matthew  14650: =item *
                   14651: 
                   14652: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14653: $store can be a scalar, an array reference, or if the amount to be 
                   14654: incremented is > 1, a hash reference.
                   14655: 
                   14656: ($udom and $uname are optional)
1.191     harris41 14657: 
                   14658: =item *
                   14659: 
1.243     albertel 14660: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14661: ($udom and $uname are optional)
1.191     harris41 14662: 
                   14663: =item *
                   14664: 
1.243     albertel 14665: cput($namespace,$storehash,$udom,$uname) : critical put
                   14666: ($udom and $uname are optional)
1.191     harris41 14667: 
                   14668: =item *
                   14669: 
1.748     albertel 14670: newput($namespace,$storehash,$udom,$uname) :
                   14671: 
                   14672: Attempts to store the items in the $storehash, but only if they don't
                   14673: currently exist, if this succeeds you can be certain that you have 
                   14674: successfully created a new key value pair in the $namespace db.
                   14675: 
                   14676: 
                   14677: Args:
                   14678:  $namespace: name of database to store values to
                   14679:  $storehash: hashref to store to the db
                   14680:  $udom: (optional) domain of user containing the db
                   14681:  $uname: (optional) name of user caontaining the db
                   14682: 
                   14683: Returns:
                   14684:  'ok' -> succeeded in storing all keys of $storehash
                   14685:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14686:                         least <key> already existed in the db (other
                   14687:                         requested keys may also already exist)
1.967     bisitz   14688:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14689:  'con_lost' -> unable to contact request server
                   14690:  'refused' -> action was not allowed by remote machine
                   14691: 
                   14692: 
                   14693: =item *
                   14694: 
1.243     albertel 14695: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14696: reference filled in from namesp (encrypts the return communication)
                   14697: ($udom and $uname are optional)
1.191     harris41 14698: 
                   14699: =item *
                   14700: 
1.243     albertel 14701: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14702: critical subroutine
                   14703: 
1.806     raeburn  14704: =item *
                   14705: 
1.860     raeburn  14706: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14707: array reference filled in from namespace found in domain level on either
                   14708: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14709: 
                   14710: =item *
                   14711: 
1.860     raeburn  14712: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14713: domain level either on specified domain server ($uhome) or primary domain 
                   14714: server ($udom and $uhome are optional)
1.806     raeburn  14715: 
1.943     raeburn  14716: =item * 
                   14717: 
1.1172.2.35  raeburn  14718: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14719: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14720: the target domain.
                   14721: 
                   14722: May also include additional key => value pairs for the following groups:
                   14723: 
                   14724: =over
                   14725: 
                   14726: =item
                   14727: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14728: 
                   14729: =over
                   14730: 
                   14731: =item defaultquota, authorquota
                   14732: 
                   14733: =back
                   14734: 
                   14735: =item
                   14736: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14737: portfolio for users).
                   14738: 
                   14739: =over
                   14740: 
                   14741: =item
                   14742: aboutme, blog, webdav, portfolio
                   14743: 
                   14744: =back
                   14745: 
                   14746: =item
                   14747: requestcourses: ability to request courses, and how requests are processed.
                   14748: 
                   14749: =over
                   14750: 
                   14751: =item
1.1172.2.37  raeburn  14752: official, unofficial, community, textbook
1.1172.2.35  raeburn  14753: 
                   14754: =back
                   14755: 
                   14756: =item
                   14757: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14758: 
                   14759: =over
                   14760: 
                   14761: =item
1.1172.2.44  raeburn  14762: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  14763: 
                   14764: =back
                   14765: 
                   14766: =item
                   14767: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14768: for course's uploaded content.
                   14769: 
                   14770: =over
                   14771: 
                   14772: =item
1.1172.2.68  raeburn  14773: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   14774: communityquota, textbookquota
1.1172.2.35  raeburn  14775: 
                   14776: =back
                   14777: 
                   14778: =item
                   14779: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14780: on your servers.
                   14781: 
                   14782: =over
                   14783: 
                   14784: =item
                   14785: remotesessions, hostedsessions
                   14786: 
                   14787: =back
                   14788: 
                   14789: =back
                   14790: 
                   14791: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14792: utility to create a configuration.db file on a domain's primary library server
                   14793: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14794: -- corresponding values are authentication type (internal, krb4, krb5,
                   14795: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   14796: will be available. Values are retrieved from cache (if current), unless the
                   14797: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14798: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14799: 
                   14800: Typical usage:
1.943     raeburn  14801: 
1.1172.2.35  raeburn  14802: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14803: 
1.243     albertel 14804: =back
                   14805: 
                   14806: =head2 Network Status Functions
                   14807: 
                   14808: =over 4
1.191     harris41 14809: 
                   14810: =item *
                   14811: 
1.1137    raeburn  14812: dirlist() : return directory list based on URI (first arg).
                   14813: 
                   14814: Inputs: 1 required, 5 optional.
                   14815: 
                   14816: =over
                   14817: 
                   14818: =item 
                   14819: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14820: 
                   14821: =item
                   14822: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14823: 
                   14824: =item
                   14825: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14826: 
                   14827: =item
                   14828: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14829: 
                   14830: =item
                   14831: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14832: 
                   14833: =item 
                   14834: $alternateRoot - path to prepend in place of path from $uri.
                   14835: 
                   14836: =back
                   14837: 
                   14838: Returns: Array of up to two items.
                   14839: 
                   14840: =over
                   14841: 
                   14842: a reference to an array of files/subdirectories
                   14843: 
                   14844: =over
                   14845: 
                   14846: Each element in the array of files/subdirectories is a & separated list of
                   14847: item name and the result of running stat on the item.  If dirlist was requested
                   14848: for a file instead of a directory, the item name will be ''. For a directory 
                   14849: listing, if the item is a metadata file, the element will end &N&M 
                   14850: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14851: default copyright set (1).  
                   14852: 
                   14853: =back
                   14854: 
                   14855: a scalar containing error condition (if encountered).
                   14856: 
                   14857: =over
                   14858: 
                   14859: =item 
                   14860: no_host (no homeserver identified for $username:$domain).
                   14861: 
                   14862: =item 
                   14863: no_such_host (server contacted for listing not identified as valid host).
                   14864: 
                   14865: =item 
                   14866: con_lost (connection to remote server failed).
                   14867: 
                   14868: =item 
                   14869: refused (invalid $username:$domain received on lond side).
                   14870: 
                   14871: =item 
                   14872: no_such_dir (directory at specified path on lond side does not exist). 
                   14873: 
                   14874: =item 
                   14875: empty (directory at specified path on lond side is empty).
                   14876: 
                   14877: =over
                   14878: 
                   14879: This is currently not encountered because the &ls3, &ls2, 
                   14880: &ls (_handler) routines on the lond side do not filter out
                   14881: . and .. from a directory listing. 
                   14882: 
                   14883: =back
                   14884: 
                   14885: =back
                   14886: 
                   14887: =back
1.191     harris41 14888: 
                   14889: =item *
                   14890: 
1.243     albertel 14891: spareserver() : find server with least workload from spare.tab
                   14892: 
1.986     foxr     14893: 
                   14894: =item *
                   14895: 
                   14896: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14897: if there is no corresponding loncapa host.
                   14898: 
1.243     albertel 14899: =back
                   14900: 
1.986     foxr     14901: 
1.243     albertel 14902: =head2 Apache Request
                   14903: 
                   14904: =over 4
1.191     harris41 14905: 
                   14906: =item *
                   14907: 
1.243     albertel 14908: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14909: localhost, posts hash
                   14910: 
                   14911: =back
                   14912: 
                   14913: =head2 Data to String to Data
                   14914: 
                   14915: =over 4
1.191     harris41 14916: 
                   14917: =item *
                   14918: 
1.243     albertel 14919: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14920: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14921: 
                   14922: =item *
                   14923: 
1.243     albertel 14924: hashref2str($hashref) : convert a hashref into a string complete with
                   14925: escaping and '=' and '&' separators, supports elements that are
                   14926: arrayrefs and hashrefs
1.191     harris41 14927: 
                   14928: =item *
                   14929: 
1.243     albertel 14930: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14931: with escaping and '&' separators, supports elements that are arrayrefs
                   14932: and hashrefs
1.191     harris41 14933: 
                   14934: =item *
                   14935: 
1.243     albertel 14936: str2hash($string) : convert string to hash using unescaping and
                   14937: splitting on '=' and '&', supports elements that are arrayrefs and
                   14938: hashrefs
1.191     harris41 14939: 
                   14940: =item *
                   14941: 
1.243     albertel 14942: str2array($string) : convert string to hash using unescaping and
                   14943: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14944: 
                   14945: =back
                   14946: 
                   14947: =head2 Logging Routines
                   14948: 
                   14949: 
                   14950: These routines allow one to make log messages in the lonnet.log and
                   14951: lonnet.perm logfiles.
1.191     harris41 14952: 
1.1119    foxr     14953: =over 4
                   14954: 
1.191     harris41 14955: =item *
                   14956: 
1.243     albertel 14957: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14958: 
                   14959: =item *
                   14960: 
1.243     albertel 14961: logthis() : append message to the normal lonnet.log file, it gets
                   14962: preiodically rolled over and deleted.
1.191     harris41 14963: 
                   14964: =item *
                   14965: 
1.243     albertel 14966: logperm() : append a permanent message to lonnet.perm.log, this log
                   14967: file never gets deleted by any automated portion of the system, only
                   14968: messages of critical importance should go in here.
                   14969: 
1.1119    foxr     14970: 
1.243     albertel 14971: =back
                   14972: 
                   14973: =head2 General File Helper Routines
                   14974: 
                   14975: =over 4
1.191     harris41 14976: 
                   14977: =item *
                   14978: 
1.481     raeburn  14979: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14980: (a) files in /uploaded
                   14981:   (i) If a local copy of the file exists - 
                   14982:       compares modification date of local copy with last-modified date for 
                   14983:       definitive version stored on home server for course. If local copy is 
                   14984:       stale, requests a new version from the home server and stores it. 
                   14985:       If the original has been removed from the home server, then local copy 
                   14986:       is unlinked.
                   14987:   (ii) If local copy does not exist -
                   14988:       requests the file from the home server and stores it. 
                   14989:   
                   14990:   If $caller is 'uploadrep':  
                   14991:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14992:     for request for files originally uploaded via DOCS. 
                   14993:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14994:   
                   14995:   Otherwise:
                   14996:      This indicates a call from the content generation phase of the request.
                   14997:      -  returns the entire contents of the file or -1.
                   14998:      
                   14999: (b) files in /res
                   15000:    - returns the entire contents of a file or -1; 
                   15001:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15002: 
1.712     albertel 15003: 
                   15004: =item *
                   15005: 
                   15006: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15007:                   reference
                   15008: 
                   15009: returns either a stat() list of data about the file or an empty list
                   15010: if the file doesn't exist or couldn't find out about it (connection
                   15011: problems or user unknown)
                   15012: 
1.191     harris41 15013: =item *
                   15014: 
1.243     albertel 15015: filelocation($dir,$file) : returns file system location of a file
                   15016: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15017: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15018: and a file of ../bob will become /a/bob)
1.191     harris41 15019: 
                   15020: =item *
                   15021: 
                   15022: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15023: filelocation except for hrefs
                   15024: 
                   15025: =item *
                   15026: 
1.1172.2.49  raeburn  15027: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15028: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15029: 
1.243     albertel 15030: =back
                   15031: 
1.608     albertel 15032: =head2 Usererfile file routines (/uploaded*)
                   15033: 
                   15034: =over 4
                   15035: 
                   15036: =item *
                   15037: 
                   15038: userfileupload(): main rotine for putting a file in a user or course's
                   15039:                   filespace, arguments are,
                   15040: 
1.620     albertel 15041:  formname - required - this is the name of the element in $env where the
1.608     albertel 15042:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15043:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15044:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15045:  context - if coursedoc, store the file in the course of the active role
                   15046:              of the current user; 
                   15047:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15048:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15049:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15050:          if undefined, it will be placed in "unknown"
                   15051: 
                   15052:  (This routine calls clean_filename() to remove any dangerous
                   15053:  characters from the filename, and then calls finuserfileupload() to
                   15054:  complete the transaction)
                   15055: 
                   15056:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15057:  and /adm/notfound.html if unsuccessful
                   15058: 
                   15059: =item *
                   15060: 
                   15061: clean_filename(): routine for cleaing a filename up for storage in
                   15062:                  userfile space, argument is:
                   15063: 
                   15064:  filename - proposed filename
                   15065: 
                   15066: returns: the new clean filename
                   15067: 
                   15068: =item *
                   15069: 
1.1090    raeburn  15070: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15071: userspace, probably shouldn't be called directly
                   15072: 
                   15073:   docuname: username or courseid of destination for the file
                   15074:   docudom: domain of user/course of destination for the file
                   15075:   formname: same as for userfileupload()
1.1090    raeburn  15076:   fname: filename (including subdirectories) for the file
                   15077:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.93.4  12(raebu 15078:19):           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15079:   allfiles: reference to hash used to store objects found by parser
                   15080:   codebase: reference to hash used for codebases of java objects found by parser
                   15081:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15082:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15083:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15084:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15085:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15086:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15087:   mimetype: reference to scalar to accommodate mime type determined
                   15088:             from File::MMagic if $parser = parse.
1.608     albertel 15089: 
                   15090:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15091:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15092:  was 'overwrite').
                   15093:  
1.608     albertel 15094: 
                   15095: =item *
                   15096: 
                   15097: renameuserfile(): renames an existing userfile to a new name
                   15098: 
                   15099:   Args:
                   15100:    docuname: username or courseid of destination for the file
                   15101:    docudom: domain of user/course of destination for the file
                   15102:    old: current file name (including any subdirs under userfiles)
                   15103:    new: desired file name (including any subdirs under userfiles)
                   15104: 
                   15105: =item *
                   15106: 
                   15107: mkdiruserfile(): creates a directory is a userfiles dir
                   15108: 
                   15109:   Args:
                   15110:    docuname: username or courseid of destination for the file
                   15111:    docudom: domain of user/course of destination for the file
                   15112:    dir: dir to create (including any subdirs under userfiles)
                   15113: 
                   15114: =item *
                   15115: 
                   15116: removeuserfile(): removes a file that exists in userfiles
                   15117: 
                   15118:   Args:
                   15119:    docuname: username or courseid of destination for the file
                   15120:    docudom: domain of user/course of destination for the file
                   15121:    fname: filname to delete (including any subdirs under userfiles)
                   15122: 
                   15123: =item *
                   15124: 
                   15125: removeuploadedurl(): convience function for removeuserfile()
                   15126: 
                   15127:   Args:
                   15128:    url:  a full /uploaded/... url to delete
                   15129: 
1.747     albertel 15130: =item * 
                   15131: 
                   15132: get_portfile_permissions():
                   15133:   Args:
                   15134:     domain: domain of user or course contain the portfolio files
                   15135:     user: name of user or num of course contain the portfolio files
                   15136:   Returns:
                   15137:     hashref of a dump of the proper file_permissions.db
                   15138:    
                   15139: 
                   15140: =item * 
                   15141: 
                   15142: get_access_controls():
                   15143: 
                   15144: Args:
                   15145:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15146:   group: (optional) the group you want the files associated with
                   15147:   file: (optional) the file you want access info on
                   15148: 
                   15149: Returns:
1.749     raeburn  15150:     a hash (keys are file names) of hashes containing
                   15151:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15152:         values are XML containing access control settings (see below) 
1.747     albertel 15153: 
                   15154: Internal notes:
                   15155: 
1.749     raeburn  15156:  access controls are stored in file_permissions.db as key=value pairs.
                   15157:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15158:         where scope -> public,guest,course,group,domains or users.
                   15159:               end -> UNIX time for end of access (0 -> no end date)
                   15160:               start -> UNIX time for start of access
                   15161: 
                   15162:     value -> XML description of access control
                   15163:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15164:             <start></start>
                   15165:             <end></end>
                   15166: 
                   15167:             <password></password>  for scope type = guest
                   15168: 
                   15169:             <domain></domain>     for scope type = course or group
                   15170:             <number></number>
                   15171:             <roles id="">
                   15172:              <role></role>
                   15173:              <access></access>
                   15174:              <section></section>
                   15175:              <group></group>
                   15176:             </roles>
                   15177: 
                   15178:             <dom></dom>         for scope type = domains
                   15179: 
                   15180:             <users>             for scope type = users
                   15181:              <user>
                   15182:               <uname></uname>
                   15183:               <udom></udom>
                   15184:              </user>
                   15185:             </users>
                   15186:            </scope> 
                   15187:               
                   15188:  Access data is also aggregated for each file in an additional key=value pair:
                   15189:  key -> path to file/file_name\0accesscontrol 
                   15190:  value -> reference to hash
                   15191:           hash contains key = value pairs
                   15192:           where key = uniqueID:scope_end_start
                   15193:                 value = UNIX time record was last updated
                   15194: 
                   15195:           Used to improve speed of look-ups of access controls for each file.  
                   15196:  
                   15197:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15198: 
1.1172.2.13  raeburn  15199: =item *
                   15200: 
1.749     raeburn  15201: modify_access_controls():
                   15202: 
                   15203: Modifies access controls for a portfolio file
                   15204: Args
                   15205: 1. file name
                   15206: 2. reference to hash of required changes,
                   15207: 3. domain
                   15208: 4. username
                   15209:   where domain,username are the domain of the portfolio owner 
                   15210:   (either a user or a course) 
                   15211: 
                   15212: Returns:
                   15213: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15214: 2. result of deletions ('ok' or 'error', with error message).
                   15215: 3. reference to hash of any new or updated access controls.
                   15216: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15217:    key = integer (inbound ID)
1.1172.2.13  raeburn  15218:    value = uniqueID
                   15219: 
                   15220: =item *
                   15221: 
                   15222: get_timebased_id():
                   15223: 
                   15224: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15225: course via the Course Editor (e.g., folders, composite pages,
                   15226: group bulletin boards).
                   15227: 
                   15228: Args: (first three required; six others optional)
                   15229: 
                   15230: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15231:    docssequence, or name of group
                   15232: 
                   15233: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15234:    e.g., num, boardids
                   15235: 
                   15236: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15237:    file will be named nohist_namespace.db
                   15238: 
                   15239: 4. cdom: domain of course; default is current course domain from %env
                   15240: 
                   15241: 5. cnum: course number; default is current course number from %env
                   15242: 
                   15243: 6. idtype: set to concat if an additional digit is to be appended to the
                   15244:    unix timestamp to form the suffix, if the plain timestamp is already
                   15245:    in use.  Default is to not do this, but simply increment the unix
                   15246:    timestamp by 1 until a unique key is obtained.
                   15247: 
                   15248: 7. who: holder of locking key; defaults to user:domain for user.
                   15249: 
                   15250: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15251:    retrying); default is 3.
                   15252: 
                   15253: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15254: 
                   15255: Returns:
                   15256: 
                   15257: 1. suffix obtained (numeric)
                   15258: 
                   15259: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15260: 
                   15261: 3. error: contains (localized) error message if an error occurred.
                   15262: 
1.747     albertel 15263: 
1.608     albertel 15264: =back
                   15265: 
1.243     albertel 15266: =head2 HTTP Helper Routines
                   15267: 
                   15268: =over 4
                   15269: 
1.191     harris41 15270: =item *
                   15271: 
                   15272: escape() : unpack non-word characters into CGI-compatible hex codes
                   15273: 
                   15274: =item *
                   15275: 
                   15276: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15277: 
1.243     albertel 15278: =back
                   15279: 
                   15280: =head1 PRIVATE SUBROUTINES
                   15281: 
                   15282: =head2 Underlying communication routines (Shouldn't call)
                   15283: 
                   15284: =over 4
                   15285: 
                   15286: =item *
                   15287: 
                   15288: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15289: 
                   15290: =item *
                   15291: 
                   15292: reply() : uses subreply to send a message to remote machine, logs all failures
                   15293: 
                   15294: =item *
                   15295: 
                   15296: critical() : passes a critical message to another server; if cannot
                   15297: get through then place message in connection buffer directory and
                   15298: returns con_delayed, if incapable of saving message, returns
                   15299: con_failed
                   15300: 
                   15301: =item *
                   15302: 
                   15303: reconlonc() : tries to reconnect lonc client processes.
                   15304: 
                   15305: =back
                   15306: 
                   15307: =head2 Resource Access Logging
                   15308: 
                   15309: =over 4
                   15310: 
                   15311: =item *
                   15312: 
                   15313: flushcourselogs() : flush (save) buffer logs and access logs
                   15314: 
                   15315: =item *
                   15316: 
                   15317: courselog($what) : save message for course in hash
                   15318: 
                   15319: =item *
                   15320: 
                   15321: courseacclog($what) : save message for course using &courselog().  Perform
                   15322: special processing for specific resource types (problems, exams, quizzes, etc).
                   15323: 
1.191     harris41 15324: =item *
                   15325: 
                   15326: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15327: as a PerlChildExitHandler
1.243     albertel 15328: 
                   15329: =back
                   15330: 
                   15331: =head2 Other
                   15332: 
                   15333: =over 4
                   15334: 
                   15335: =item *
                   15336: 
                   15337: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15338: 
                   15339: =back
                   15340: 
                   15341: =cut
1.877     foxr     15342: 

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