Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.127
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.127! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.126 2020/09/28 13:56:29 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
1.1172.2.107 raeburn 77: use CGI::Cookie;
1.977 amueller 78:
1.1172.2.104 raeburn 79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138 raeburn 80: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114 raeburn 81: %managerstab $passwdmin);
1.871 albertel 82:
83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
84: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
85: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 86: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 87:
1.1 albertel 88: use IO::Socket;
1.31 www 89: use GDBM_File;
1.208 albertel 90: use HTML::LCParser;
1.88 www 91: use Fcntl qw(:flock);
1.870 albertel 92: use Storable qw(thaw nfreeze);
1.1172.2.79 raeburn 93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 94: use Cache::Memcached;
1.676 albertel 95: use Digest::MD5;
1.790 albertel 96: use Math::Random;
1.1024 raeburn 97: use File::MMagic;
1.807 albertel 98: use LONCAPA qw(:DEFAULT :match);
1.740 www 99: use LONCAPA::Configuration;
1.1160 www 100: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 101: use LONCAPA::Lond;
1.1172.2.110 raeburn 102: use LONCAPA::transliterate;
1.1117 foxr 103:
1.1090 raeburn 104: use File::Copy;
1.676 albertel 105:
1.195 www 106: my $readit;
1.1172.2.79 raeburn 107: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 108:
1.619 albertel 109: require Exporter;
110:
111: our @ISA = qw (Exporter);
112: our @EXPORT = qw(%env);
113:
1.1172.2.9 raeburn 114: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 115: {
116: my $logid;
1.1172.2.9 raeburn 117: sub write_log {
118: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
119: if ($context eq 'course') {
120: if (($cnum eq '') || ($cdom eq '')) {
121: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
122: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
123: }
1.957 raeburn 124: }
1.1172.2.13 raeburn 125: $logid ++;
1.957 raeburn 126: my $now = time();
127: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 128: my $logentry = {
129: $id => {
130: 'exe_uname' => $env{'user.name'},
131: 'exe_udom' => $env{'user.domain'},
132: 'exe_time' => $now,
133: 'exe_ip' => $ENV{'REMOTE_ADDR'},
134: 'delflag' => $delflag,
135: 'logentry' => $storehash,
136: 'uname' => $uname,
137: 'udom' => $udom,
138: }
139: };
140: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 141: }
142: }
1.1 albertel 143:
1.163 harris41 144: sub logtouch {
145: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 146: unless (-e "$execdir/logs/lonnet.log") {
1.1172.2.96 raeburn 147: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 148: close $fh;
149: }
150: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
151: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
152: }
153:
1.1 albertel 154: sub logthis {
155: my $message=shift;
156: my $execdir=$perlvar{'lonDaemons'};
157: my $now=time;
158: my $local=localtime($now);
1.1172.2.96 raeburn 159: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 160: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
161: print $fh $logstring;
1.448 albertel 162: close($fh);
163: }
1.1 albertel 164: return 1;
165: }
166:
167: sub logperm {
168: my $message=shift;
169: my $execdir=$perlvar{'lonDaemons'};
170: my $now=time;
171: my $local=localtime($now);
1.1172.2.96 raeburn 172: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 173: print $fh "$now:$message:$local\n";
174: close($fh);
175: }
1.1 albertel 176: return 1;
177: }
178:
1.850 albertel 179: sub create_connection {
1.853 albertel 180: my ($hostname,$lonid) = @_;
1.851 albertel 181: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 182: Type => SOCK_STREAM,
183: Timeout => 10);
184: return 0 if (!$client);
1.890 albertel 185: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 186: my $result = <$client>;
187: chomp($result);
188: return 1 if ($result eq 'done');
189: return 0;
190: }
191:
1.983 raeburn 192: sub get_server_timezone {
193: my ($cnum,$cdom) = @_;
194: my $home=&homeserver($cnum,$cdom);
195: if ($home ne 'no_host') {
196: my $cachetime = 24*3600;
197: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
198: if (defined($cached)) {
199: return $timezone;
200: } else {
201: my $timezone = &reply('servertimezone',$home);
202: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
203: }
204: }
205: }
1.850 albertel 206:
1.1106 raeburn 207: sub get_server_distarch {
208: my ($lonhost,$ignore_cache) = @_;
209: if (defined($lonhost)) {
210: if (!defined(&hostname($lonhost))) {
211: return;
212: }
213: my $cachetime = 12*3600;
214: if (!$ignore_cache) {
215: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
216: if (defined($cached)) {
217: return $distarch;
218: }
219: }
220: my $rep = &reply('serverdistarch',$lonhost);
221: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
222: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
223: $rep eq '') {
224: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
225: }
226: }
227: return;
228: }
229:
1.993 raeburn 230: sub get_server_loncaparev {
1.1073 raeburn 231: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 232: if (defined($lonhost)) {
233: if (!defined(&hostname($lonhost))) {
234: undef($lonhost);
235: }
236: }
237: if (!defined($lonhost)) {
238: if (defined(&domain($dom,'primary'))) {
239: $lonhost=&domain($dom,'primary');
240: if ($lonhost eq 'no_host') {
241: undef($lonhost);
242: }
243: }
244: }
245: if (defined($lonhost)) {
1.1073 raeburn 246: my $cachetime = 12*3600;
247: if (!$ignore_cache) {
248: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
249: if (defined($cached)) {
250: return $loncaparev;
251: }
252: }
253: my ($answer,$loncaparev);
254: my @ids=¤t_machine_ids();
255: if (grep(/^\Q$lonhost\E$/,@ids)) {
256: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 257: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 258: $loncaparev = $1;
259: }
260: } else {
261: $answer = &reply('serverloncaparev',$lonhost);
262: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
263: if ($caller eq 'loncron') {
264: my $ua=new LWP::UserAgent;
1.1082 raeburn 265: $ua->timeout(4);
1.1172.2.120 raeburn 266: my $hostname = &hostname($lonhost);
1.1073 raeburn 267: my $protocol = $protocol{$lonhost};
268: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 269: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 270: my $request=new HTTP::Request('GET',$url);
271: my $response=$ua->request($request);
272: unless ($response->is_error()) {
273: my $content = $response->content;
1.1081 raeburn 274: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 275: $loncaparev = $1;
276: }
277: }
278: } else {
279: $loncaparev = $loncaparevs{$lonhost};
280: }
1.1081 raeburn 281: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 282: $loncaparev = $1;
283: }
1.993 raeburn 284: }
1.1073 raeburn 285: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 286: }
287: }
288:
1.1074 raeburn 289: sub get_server_homeID {
290: my ($hostname,$ignore_cache,$caller) = @_;
291: unless ($ignore_cache) {
292: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
293: if (defined($cached)) {
294: return $serverhomeID;
295: }
296: }
297: my $cachetime = 12*3600;
298: my $serverhomeID;
299: if ($caller eq 'loncron') {
300: my @machine_ids = &machine_ids($hostname);
301: foreach my $id (@machine_ids) {
302: my $response = &reply('serverhomeID',$id);
303: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
304: $serverhomeID = $response;
305: last;
306: }
307: }
308: if ($serverhomeID eq '') {
309: $serverhomeID = $machine_ids[-1];
310: }
311: } else {
312: $serverhomeID = $serverhomeIDs{$hostname};
313: }
314: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
315: }
316:
1.1121 raeburn 317: sub get_remote_globals {
318: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 319: my ($result,%returnhash,%whatneeded);
320: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 321: foreach my $what (sort(keys(%{$whathash}))) {
322: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 323: my ($response,$cached);
1.1121 raeburn 324: unless ($ignore_cache) {
1.1125 raeburn 325: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 326: }
327: if (defined($cached)) {
1.1125 raeburn 328: $returnhash{$what} = $response;
1.1121 raeburn 329: } else {
1.1125 raeburn 330: $whatneeded{$what} = 1;
1.1121 raeburn 331: }
332: }
1.1125 raeburn 333: if (keys(%whatneeded) == 0) {
334: $result = 'ok';
335: } else {
1.1121 raeburn 336: my $requested = &freeze_escape(\%whatneeded);
337: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 338: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
339: ($rep eq 'unknown_cmd')) {
340: $result = $rep;
341: } else {
342: $result = 'ok';
1.1121 raeburn 343: my @pairs=split(/\&/,$rep);
1.1125 raeburn 344: foreach my $item (@pairs) {
345: my ($key,$value)=split(/=/,$item,2);
346: my $what = &unescape($key);
347: my $hashid = $lonhost.'-'.$what;
348: $returnhash{$what}=&thaw_unescape($value);
349: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 350: }
351: }
352: }
353: }
1.1125 raeburn 354: return ($result,\%returnhash);
1.1121 raeburn 355: }
356:
1.1124 raeburn 357: sub remote_devalidate_cache {
1.1172.2.35 raeburn 358: my ($lonhost,$cachekeys) = @_;
359: my $items;
360: return unless (ref($cachekeys) eq 'ARRAY');
361: my $cachestr = join('&',@{$cachekeys});
362: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 363: }
364:
1.1 albertel 365: # -------------------------------------------------- Non-critical communication
366: sub subreply {
367: my ($cmd,$server)=@_;
1.838 albertel 368: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 369: #
370: # With loncnew process trimming, there's a timing hole between lonc server
371: # process exit and the master server picking up the listen on the AF_UNIX
372: # socket. In that time interval, a lock file will exist:
373:
374: my $lockfile=$peerfile.".lock";
375: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 376: sleep(0.1);
1.549 foxr 377: }
378: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 379: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 380: #
1.550 foxr 381: # We'll give the connection a few tries before abandoning it. If
382: # connection is not possible, we'll con_lost back to the client.
383: #
384: my $client;
385: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
386: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
387: Type => SOCK_STREAM,
388: Timeout => 10);
1.869 albertel 389: if ($client) {
1.550 foxr 390: last; # Connected!
1.850 albertel 391: } else {
1.853 albertel 392: &create_connection(&hostname($server),$server);
1.550 foxr 393: }
1.1172.2.79 raeburn 394: sleep(0.1); # Try again later if failed connection.
1.550 foxr 395: }
396: my $answer;
397: if ($client) {
1.704 albertel 398: print $client "sethost:$server:$cmd\n";
1.550 foxr 399: $answer=<$client>;
400: if (!$answer) { $answer="con_lost"; }
401: chomp($answer);
402: } else {
403: $answer = 'con_lost'; # Failed connection.
404: }
1.1 albertel 405: return $answer;
406: }
407:
408: sub reply {
409: my ($cmd,$server)=@_;
1.838 albertel 410: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 411: my $answer=subreply($cmd,$server);
1.65 www 412: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111 raeburn 413: my $logged = $cmd;
414: if ($cmd =~ /^encrypt:([^:]+):/) {
415: my $subcmd = $1;
416: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
417: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
418: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
419: (undef,undef,my @rest) = split(/:/,$cmd);
420: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
421: splice(@rest,2,1,'Hidden');
422: } elsif ($subcmd eq 'passwd') {
423: splice(@rest,2,2,('Hidden','Hidden'));
424: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
425: ($subcmd eq 'autoexportgrades')) {
426: splice(@rest,3,1,'Hidden');
427: }
428: $logged = join(':',('encrypt:'.$subcmd,@rest));
429: }
430: }
431: &logthis("<font color=\"blue\">WARNING:".
432: " $logged to $server returned $answer</font>");
1.12 www 433: }
1.1 albertel 434: return $answer;
435: }
436:
437: # ----------------------------------------------------------- Send USR1 to lonc
438:
439: sub reconlonc {
1.891 albertel 440: my ($lonid) = @_;
441: if ($lonid) {
1.1172.2.72 raeburn 442: my $hostname = &hostname($lonid);
1.891 albertel 443: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
444: if ($hostname && -e $peerfile) {
445: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
446: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
447: Type => SOCK_STREAM,
448: Timeout => 10);
449: if ($client) {
450: print $client ("reset_retries\n");
451: my $answer=<$client>;
452: #reset just this one.
453: }
454: }
455: return;
456: }
457:
1.836 www 458: &logthis("Trying to reconnect lonc");
1.1 albertel 459: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96 raeburn 460: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 461: my $loncpid=<$fh>;
462: chomp($loncpid);
463: if (kill 0 => $loncpid) {
464: &logthis("lonc at pid $loncpid responding, sending USR1");
465: kill USR1 => $loncpid;
466: sleep 1;
1.836 www 467: } else {
1.12 www 468: &logthis(
1.672 albertel 469: "<font color=\"blue\">WARNING:".
1.12 www 470: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 471: }
472: } else {
1.836 www 473: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 474: }
475: }
476:
477: # ------------------------------------------------------ Critical communication
1.12 www 478:
1.1 albertel 479: sub critical {
480: my ($cmd,$server)=@_;
1.838 albertel 481: unless (&hostname($server)) {
1.672 albertel 482: &logthis("<font color=\"blue\">WARNING:".
1.89 www 483: " Critical message to unknown server ($server)</font>");
484: return 'no_such_host';
485: }
1.1 albertel 486: my $answer=reply($cmd,$server);
487: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 488: &reconlonc($server);
1.589 albertel 489: my $answer=reply($cmd,$server);
1.1 albertel 490: if ($answer eq 'con_lost') {
491: my $now=time;
492: my $middlename=$cmd;
1.5 www 493: $middlename=substr($middlename,0,16);
1.1 albertel 494: $middlename=~s/\W//g;
495: my $dfilename=
1.305 www 496: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
497: $dumpcount++;
1.1 albertel 498: {
1.448 albertel 499: my $dfh;
1.1172.2.96 raeburn 500: if (open($dfh,">",$dfilename)) {
1.448 albertel 501: print $dfh "$cmd\n";
502: close($dfh);
503: }
1.1 albertel 504: }
1.1172.2.79 raeburn 505: sleep 1;
1.1 albertel 506: my $wcmd='';
507: {
1.448 albertel 508: my $dfh;
1.1172.2.96 raeburn 509: if (open($dfh,"<",$dfilename)) {
1.448 albertel 510: $wcmd=<$dfh>;
511: close($dfh);
512: }
1.1 albertel 513: }
514: chomp($wcmd);
1.7 www 515: if ($wcmd eq $cmd) {
1.672 albertel 516: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 517: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 518: &logperm("D:$server:$cmd");
519: return 'con_delayed';
520: } else {
1.672 albertel 521: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 522: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 523: &logperm("F:$server:$cmd");
524: return 'con_failed';
525: }
526: }
527: }
528: return $answer;
1.405 albertel 529: }
530:
1.755 albertel 531: # ------------------------------------------- check if return value is an error
532:
533: sub error {
534: my ($result) = @_;
1.756 albertel 535: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 536: if ($2 == 2) { return undef; }
537: return $1;
538: }
539: return undef;
540: }
541:
1.783 albertel 542: sub convert_and_load_session_env {
543: my ($lonidsdir,$handle)=@_;
544: my @profile;
545: {
1.917 albertel 546: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
547: if (!$opened) {
1.915 albertel 548: return 0;
549: }
1.783 albertel 550: flock($idf,LOCK_SH);
551: @profile=<$idf>;
552: close($idf);
553: }
554: my %temp_env;
555: foreach my $line (@profile) {
1.786 albertel 556: if ($line !~ m/=/) {
557: return 0;
558: }
1.783 albertel 559: chomp($line);
560: my ($envname,$envvalue)=split(/=/,$line,2);
561: $temp_env{&unescape($envname)} = &unescape($envvalue);
562: }
563: unlink("$lonidsdir/$handle.id");
564: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
565: 0640)) {
566: %disk_env = %temp_env;
567: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
568: untie(%disk_env);
569: }
1.786 albertel 570: return 1;
1.783 albertel 571: }
572:
1.374 www 573: # ------------------------------------------- Transfer profile into environment
1.780 albertel 574: my $env_loaded;
575: sub transfer_profile_to_env {
1.788 albertel 576: my ($lonidsdir,$handle,$force_transfer) = @_;
577: if (!$force_transfer && $env_loaded) { return; }
1.374 www 578:
1.720 albertel 579: if (!defined($lonidsdir)) {
580: $lonidsdir = $perlvar{'lonIDsDir'};
581: }
582: if (!defined($handle)) {
583: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
584: }
585:
1.786 albertel 586: my $convert;
587: {
1.917 albertel 588: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
589: if (!$opened) {
1.915 albertel 590: return;
591: }
1.786 albertel 592: flock($idf,LOCK_SH);
593: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
594: &GDBM_READER(),0640)) {
595: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
596: untie(%disk_env);
597: } else {
598: $convert = 1;
599: }
600: }
601: if ($convert) {
602: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
603: &logthis("Failed to load session, or convert session.");
604: }
1.374 www 605: }
1.783 albertel 606:
1.786 albertel 607: my %remove;
1.783 albertel 608: while ( my $envname = each(%env) ) {
1.433 matthew 609: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
610: if ($time < time-300) {
1.783 albertel 611: $remove{$key}++;
1.433 matthew 612: }
613: }
614: }
1.783 albertel 615:
1.619 albertel 616: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 617: $env_loaded=1;
1.783 albertel 618: foreach my $expired_key (keys(%remove)) {
1.433 matthew 619: &delenv($expired_key);
1.374 www 620: }
1.1 albertel 621: }
622:
1.916 albertel 623: # ---------------------------------------------------- Check for valid session
624: sub check_for_valid_session {
1.1172.2.96 raeburn 625: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 626: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108 raeburn 627: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155 raeburn 628: if ($name eq 'lonDAV') {
629: $lonidsdir=$r->dir_config('lonDAVsessDir');
630: } else {
631: $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108 raeburn 632: if ($name eq '') {
633: $name = 'lonID';
634: }
635: }
636: if ($name eq 'lonID') {
637: $secure = 'lonSID';
638: $linkname = 'lonLinkID';
639: $pubname = 'lonPubID';
640: if (exists($cookies{$secure})) {
641: $lonid=$cookies{$secure};
642: } elsif (exists($cookies{$name})) {
643: $lonid=$cookies{$name};
644: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
645: $lonid=$cookies{$linkname};
646: } elsif (exists($cookies{$pubname})) {
647: $lonid=$cookies{$pubname};
648: }
649: } else {
650: $lonid=$cookies{$name};
651: }
652: return undef if (!$lonid);
653:
654: my $handle=&LONCAPA::clean_handle($lonid->value);
655: if (-l "$lonidsdir/$handle.id") {
656: my $link = readlink("$lonidsdir/$handle.id");
657: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
658: $handle = $1;
659: }
1.1155 raeburn 660: }
1.1172.2.96 raeburn 661: if (!-e "$lonidsdir/$handle.id") {
662: if ((ref($domref)) && ($name eq 'lonID') &&
663: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
664: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
665: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
666: $$domref = $possudom;
667: }
668: }
669: return undef;
670: }
1.916 albertel 671:
1.917 albertel 672: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
673: return undef if (!$opened);
1.916 albertel 674:
675: flock($idf,LOCK_SH);
676: my %disk_env;
677: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
678: &GDBM_READER(),0640)) {
679: return undef;
680: }
681:
682: if (!defined($disk_env{'user.name'})
683: || !defined($disk_env{'user.domain'})) {
1.1172.2.107 raeburn 684: untie(%disk_env);
1.916 albertel 685: return undef;
686: }
1.1172.2.18 raeburn 687:
1.1172.2.36 raeburn 688: if (ref($userhashref) eq 'HASH') {
689: $userhashref->{'name'} = $disk_env{'user.name'};
690: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 691: }
1.1172.2.107 raeburn 692: untie(%disk_env);
1.1172.2.18 raeburn 693:
1.916 albertel 694: return $handle;
695: }
696:
1.830 albertel 697: sub timed_flock {
698: my ($file,$lock_type) = @_;
699: my $failed=0;
700: eval {
701: local $SIG{__DIE__}='DEFAULT';
702: local $SIG{ALRM}=sub {
703: $failed=1;
704: die("failed lock");
705: };
706: alarm(13);
707: flock($file,$lock_type);
708: alarm(0);
709: };
710: if ($failed) {
711: return undef;
712: } else {
713: return 1;
714: }
715: }
716:
1.1172.2.107 raeburn 717: sub get_sessionfile_vars {
718: my ($handle,$lonidsdir,$storearr) = @_;
719: my %returnhash;
720: unless (ref($storearr) eq 'ARRAY') {
721: return %returnhash;
722: }
723: if (-l "$lonidsdir/$handle.id") {
724: my $link = readlink("$lonidsdir/$handle.id");
725: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
726: $handle = $1;
727: }
728: }
729: if ((-e "$lonidsdir/$handle.id") &&
730: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
731: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
732: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
733: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
734: flock($idf,LOCK_SH);
735: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
736: &GDBM_READER(),0640)) {
737: foreach my $item (@{$storearr}) {
738: $returnhash{$item} = $disk_env{$item};
739: }
740: untie(%disk_env);
741: }
742: }
743: }
744: }
745: return %returnhash;
746: }
747:
1.5 www 748: # ---------------------------------------------------------- Append Environment
749:
750: sub appenv {
1.949 raeburn 751: my ($newenv,$roles) = @_;
752: if (ref($newenv) eq 'HASH') {
753: foreach my $key (keys(%{$newenv})) {
754: my $refused = 0;
755: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
756: $refused = 1;
757: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 758: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 759: if (grep(/^\Q$role\E$/,@{$roles})) {
760: $refused = 0;
761: }
762: }
763: }
764: if ($refused) {
765: &logthis("<font color=\"blue\">WARNING: ".
766: "Attempt to modify environment ".$key." to ".$newenv->{$key}
767: .'</font>');
768: delete($newenv->{$key});
769: } else {
770: $env{$key}=$newenv->{$key};
771: }
772: }
1.1172.2.96 raeburn 773: my $lonids = $perlvar{'lonIDsDir'};
774: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
775: my $opened = open(my $env_file,'+<',$env{'user.environment'});
776: if ($opened
777: && &timed_flock($env_file,LOCK_EX)
778: &&
779: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
780: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
781: while (my ($key,$value) = each(%{$newenv})) {
782: $disk_env{$key} = $value;
783: }
784: untie(%disk_env);
785: }
1.35 www 786: }
1.191 harris41 787: }
1.56 www 788: return 'ok';
789: }
790: # ----------------------------------------------------- Delete from Environment
791:
792: sub delenv {
1.1104 raeburn 793: my ($delthis,$regexp,$roles) = @_;
794: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
795: my $refused = 1;
796: if (ref($roles) eq 'ARRAY') {
797: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
798: if (grep(/^\Q$role\E$/,@{$roles})) {
799: $refused = 0;
800: }
801: }
802: if ($refused) {
803: &logthis("<font color=\"blue\">WARNING: ".
804: "Attempt to delete from environment ".$delthis);
805: return 'error';
806: }
1.56 www 807: }
1.917 albertel 808: my $opened = open(my $env_file,'+<',$env{'user.environment'});
809: if ($opened
1.915 albertel 810: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 811: &&
812: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
813: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 814: foreach my $key (keys(%disk_env)) {
1.987 raeburn 815: if ($regexp) {
816: if ($key=~/^$delthis/) {
817: delete($env{$key});
818: delete($disk_env{$key});
819: }
820: } else {
821: if ($key=~/^\Q$delthis\E/) {
822: delete($env{$key});
823: delete($disk_env{$key});
824: }
825: }
1.448 albertel 826: }
1.783 albertel 827: untie(%disk_env);
1.5 www 828: }
829: return 'ok';
1.369 albertel 830: }
831:
1.790 albertel 832: sub get_env_multiple {
833: my ($name) = @_;
834: my @values;
835: if (defined($env{$name})) {
836: # exists is it an array
837: if (ref($env{$name})) {
838: @values=@{ $env{$name} };
839: } else {
840: $values[0]=$env{$name};
841: }
842: }
843: return(@values);
844: }
845:
1.958 www 846: # ------------------------------------------------------------------- Locking
847:
848: sub set_lock {
849: my ($text)=@_;
850: $locknum++;
851: my $id=$$.'-'.$locknum;
852: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
853: 'session.lock.'.$id => $text});
854: return $id;
855: }
856:
857: sub get_locks {
858: my $num=0;
859: my %texts=();
860: foreach my $lock (split(/\,/,$env{'session.locks'})) {
861: if ($lock=~/\w/) {
862: $num++;
863: $texts{$lock}=$env{'session.lock.'.$lock};
864: }
865: }
866: return ($num,%texts);
867: }
868:
869: sub remove_lock {
870: my ($id)=@_;
871: my $newlocks='';
872: foreach my $lock (split(/\,/,$env{'session.locks'})) {
873: if (($lock=~/\w/) && ($lock ne $id)) {
874: $newlocks.=','.$lock;
875: }
876: }
877: &appenv({'session.locks' => $newlocks});
878: &delenv('session.lock.'.$id);
879: }
880:
881: sub remove_all_locks {
882: my $activelocks=$env{'session.locks'};
883: foreach my $lock (split(/\,/,$env{'session.locks'})) {
884: if ($lock=~/\w/) {
885: &remove_lock($lock);
886: }
887: }
888: }
889:
890:
1.369 albertel 891: # ------------------------------------------ Find out current server userload
892: sub userload {
893: my $numusers=0;
894: {
895: opendir(LONIDS,$perlvar{'lonIDsDir'});
896: my $filename;
897: my $curtime=time;
898: while ($filename=readdir(LONIDS)) {
1.925 albertel 899: next if ($filename eq '.' || $filename eq '..');
900: next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112 raeburn 901: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 902: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 903: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 904: }
905: closedir(LONIDS);
906: }
907: my $userloadpercent=0;
908: my $maxuserload=$perlvar{'lonUserLoadLim'};
909: if ($maxuserload) {
1.371 albertel 910: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 911: }
1.372 albertel 912: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 913: return $userloadpercent;
1.283 www 914: }
915:
1.1 albertel 916: # ------------------------------ Find server with least workload from spare.tab
1.11 www 917:
1.1 albertel 918: sub spareserver {
1.1083 raeburn 919: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 920: my $spare_server;
1.370 albertel 921: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 922: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
923: : $userloadpercent;
1.1083 raeburn 924: my ($uint_dom,$remotesessions);
925: if (($udom ne '') && (&domain($udom) ne '')) {
926: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
927: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
928: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
929: $remotesessions = $udomdefaults{'remotesessions'};
930: }
1.1123 raeburn 931: my $spareshash = &this_host_spares($udom);
932: if (ref($spareshash) eq 'HASH') {
933: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 935: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
936: $try_server));
1.1123 raeburn 937: ($spare_server, $lowest_load) =
938: &compare_server_load($try_server, $spare_server, $lowest_load);
939: }
1.1083 raeburn 940: }
1.784 albertel 941:
1.1123 raeburn 942: my $found_server = ($spare_server ne '' && $lowest_load < 100);
943:
944: if (!$found_server) {
945: if (ref($spareshash->{'default'}) eq 'ARRAY') {
946: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 947: next unless (&spare_can_host($udom,$uint_dom,
948: $remotesessions,$try_server));
1.1123 raeburn 949: ($spare_server, $lowest_load) =
950: &compare_server_load($try_server, $spare_server, $lowest_load);
951: }
952: }
953: }
1.784 albertel 954: }
955:
956: if (!$want_server_name) {
1.1001 raeburn 957: if (defined($spare_server)) {
958: my $hostname = &hostname($spare_server);
1.1083 raeburn 959: if (defined($hostname)) {
1.1172.2.120 raeburn 960: my $protocol = 'http';
961: if ($protocol{$spare_server} eq 'https') {
962: $protocol = $protocol{$spare_server};
963: }
1.1001 raeburn 964: $spare_server = $protocol.'://'.$hostname;
965: }
966: }
1.784 albertel 967: }
968: return $spare_server;
969: }
970:
971: sub compare_server_load {
1.1172.2.41 raeburn 972: my ($try_server, $spare_server, $lowest_load, $required) = @_;
973:
974: if ($required) {
975: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
976: my $remoterev = &get_server_loncaparev(undef,$try_server);
977: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
978: if (($major eq '' && $minor eq '') ||
979: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
980: return ($spare_server,$lowest_load);
981: }
982: }
1.784 albertel 983:
984: my $loadans = &reply('load', $try_server);
985: my $userloadans = &reply('userload',$try_server);
986:
987: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 988: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 989: }
990:
991: my $load;
992: if ($loadans =~ /\d/) {
993: if ($userloadans =~ /\d/) {
994: #both are numbers, pick the bigger one
995: $load = ($loadans > $userloadans) ? $loadans
996: : $userloadans;
1.411 albertel 997: } else {
1.784 albertel 998: $load = $loadans;
1.411 albertel 999: }
1.784 albertel 1000: } else {
1001: $load = $userloadans;
1002: }
1003:
1004: if (($load =~ /\d/) && ($load < $lowest_load)) {
1005: $spare_server = $try_server;
1006: $lowest_load = $load;
1.370 albertel 1007: }
1.784 albertel 1008: return ($spare_server,$lowest_load);
1.202 matthew 1009: }
1.914 albertel 1010:
1011: # --------------------------- ask offload servers if user already has a session
1012: sub find_existing_session {
1013: my ($udom,$uname) = @_;
1.1123 raeburn 1014: my $spareshash = &this_host_spares($udom);
1015: if (ref($spareshash) eq 'HASH') {
1016: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1017: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1018: return $try_server if (&has_user_session($try_server, $udom, $uname));
1019: }
1020: }
1021: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1022: foreach my $try_server (@{ $spareshash->{'default'} }) {
1023: return $try_server if (&has_user_session($try_server, $udom, $uname));
1024: }
1025: }
1.914 albertel 1026: }
1027: return;
1028: }
1029:
1.1172.2.107 raeburn 1030: # check if user's browser sent load balancer cookie and server still has session
1031: # and is not overloaded.
1032: sub check_for_balancer_cookie {
1033: my ($r,$update_mtime) = @_;
1034: my ($otherserver,$cookie);
1035: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1036: if (exists($cookies{'balanceID'})) {
1037: my $balid = $cookies{'balanceID'};
1038: $cookie=&LONCAPA::clean_handle($balid->value);
1039: my $balancedir=$r->dir_config('lonBalanceDir');
1040: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1041: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1042: my ($possudom,$possuname) = ($1,$2);
1043: my $has_session = 0;
1044: if ((&domain($possudom) ne '') &&
1045: (&homeserver($possuname,$possudom) ne 'no_host')) {
1046: my $try_server;
1047: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1048: if ($opened) {
1049: flock($idf,LOCK_SH);
1050: while (my $line = <$idf>) {
1051: chomp($line);
1052: if (&hostname($line) ne '') {
1053: $try_server = $line;
1054: last;
1055: }
1056: }
1057: close($idf);
1058: if (($try_server) &&
1059: (&has_user_session($try_server,$possudom,$possuname))) {
1060: my $lowest_load = 30000;
1061: ($otherserver,$lowest_load) =
1062: &compare_server_load($try_server,undef,$lowest_load);
1063: if ($otherserver ne '' && $lowest_load < 100) {
1064: $has_session = 1;
1065: } else {
1066: undef($otherserver);
1067: }
1068: }
1069: }
1070: }
1071: if ($has_session) {
1072: if ($update_mtime) {
1073: my $atime = my $mtime = time;
1074: utime($atime,$mtime,"$balancedir/$cookie.id");
1075: }
1076: } else {
1077: unlink("$balancedir/$cookie.id");
1078: }
1079: }
1080: }
1081: }
1082: return ($otherserver,$cookie);
1083: }
1084:
1085: sub delbalcookie {
1086: my ($cookie,$balancer) =@_;
1087: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1088: my ($udom,$uname) = ($1,$2);
1089: my $uprimary_id = &domain($udom,'primary');
1090: my $uintdom = &internet_dom($uprimary_id);
1091: my $intdom = &internet_dom($balancer);
1092: my $serverhomedom = &host_domain($balancer);
1093: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1094: return &reply("delbalcookie:$cookie",$balancer);
1095: }
1096: }
1097: }
1098:
1.914 albertel 1099: # -------------------------------- ask if server already has a session for user
1100: sub has_user_session {
1101: my ($lonid,$udom,$uname) = @_;
1102: my $result = &reply(join(':','userhassession',
1103: map {&escape($_)} ($udom,$uname)),$lonid);
1104: return 1 if ($result eq 'ok');
1105:
1106: return 0;
1107: }
1108:
1.1076 raeburn 1109: # --------- determine least loaded server in a user's domain which allows login
1110:
1111: sub choose_server {
1.1172.2.47 raeburn 1112: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1113: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1114: my %servers = &get_servers($udom);
1.1076 raeburn 1115: my $lowest_load = 30000;
1.1172.2.47 raeburn 1116: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1117: if ($skiploadbal) {
1118: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1119: unless (defined($cached)) {
1120: my $cachetime = 60*60*24;
1121: my %domconfig =
1122: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1123: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1124: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1125: $cachetime);
1126: }
1127: }
1128: }
1.1076 raeburn 1129: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 1130: my $loginvia;
1.1172.2.47 raeburn 1131: if ($skiploadbal) {
1132: if (ref($balancers) eq 'HASH') {
1133: next if (exists($balancers->{$lonhost}));
1134: }
1135: }
1.1115 raeburn 1136: if ($checkloginvia) {
1137: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1138: if ($loginvia) {
1139: my ($server,$path) = split(/:/,$loginvia);
1140: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1141: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1142: if ($login_host eq $server) {
1143: $portal_path = $path;
1.1151 raeburn 1144: $isredirect = 1;
1.1116 raeburn 1145: }
1146: } else {
1147: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1148: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1149: if ($login_host eq $lonhost) {
1150: $portal_path = '';
1.1151 raeburn 1151: $isredirect = '';
1.1116 raeburn 1152: }
1153: }
1154: } else {
1.1076 raeburn 1155: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1156: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1157: }
1158: }
1159: if ($login_host ne '') {
1.1116 raeburn 1160: $hostname = &hostname($login_host);
1.1076 raeburn 1161: }
1.1172.2.88 raeburn 1162: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1163: }
1164:
1.1172.2.123 raeburn 1165: sub get_course_sessions {
1166: my ($cnum,$cdom,$lastactivity) = @_;
1167: my %servers = &internet_dom_servers($cdom);
1168: my %returnhash;
1169: foreach my $server (sort(keys(%servers))) {
1170: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1171: my @pairs=split(/\&/,$rep);
1172: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1173: foreach my $item (@pairs) {
1174: my ($key,$value)=split(/=/,$item,2);
1175: $key = &unescape($key);
1176: next if ($key =~ /^error: 2 /);
1177: if (exists($returnhash{$key})) {
1178: next if ($value < $returnhash{$key});
1179: }
1180: $returnhash{$key}=$value;
1181: }
1182: }
1183: }
1184: return %returnhash;
1185: }
1186:
1.202 matthew 1187: # --------------------------------------------- Try to change a user's password
1188:
1189: sub changepass {
1.799 raeburn 1190: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1191: $currentpass = &escape($currentpass);
1192: $newpass = &escape($newpass);
1.1030 raeburn 1193: my $lonhost = $perlvar{'lonHostID'};
1194: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1195: $server);
1196: if (! $answer) {
1197: &logthis("No reply on password change request to $server ".
1198: "by $uname in domain $udom.");
1199: } elsif ($answer =~ "^ok") {
1200: &logthis("$uname in $udom successfully changed their password ".
1201: "on $server.");
1202: } elsif ($answer =~ "^pwchange_failure") {
1203: &logthis("$uname in $udom was unable to change their password ".
1204: "on $server. The action was blocked by either lcpasswd ".
1205: "or pwchange");
1206: } elsif ($answer =~ "^non_authorized") {
1207: &logthis("$uname in $udom did not get their password correct when ".
1208: "attempting to change it on $server.");
1209: } elsif ($answer =~ "^auth_mode_error") {
1210: &logthis("$uname in $udom attempted to change their password despite ".
1211: "not being locally or internally authenticated on $server.");
1212: } elsif ($answer =~ "^unknown_user") {
1213: &logthis("$uname in $udom attempted to change their password ".
1214: "on $server but were unable to because $server is not ".
1215: "their home server.");
1216: } elsif ($answer =~ "^refused") {
1217: &logthis("$server refused to change $uname in $udom password because ".
1218: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1219: } elsif ($answer =~ "invalid_client") {
1220: &logthis("$server refused to change $uname in $udom password because ".
1221: "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113 raeburn 1222: } elsif ($answer =~ "^prioruse") {
1223: &logthis("$server refused to change $uname in $udom password because ".
1224: "the password had been used before");
1.202 matthew 1225: }
1226: return $answer;
1.1 albertel 1227: }
1228:
1.169 harris41 1229: # ----------------------- Try to determine user's current authentication scheme
1230:
1231: sub queryauthenticate {
1232: my ($uname,$udom)=@_;
1.456 albertel 1233: my $uhome=&homeserver($uname,$udom);
1234: if (!$uhome) {
1235: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1236: return 'no_host';
1237: }
1238: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1239: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1240: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1241: }
1.456 albertel 1242: return $answer;
1.169 harris41 1243: }
1244:
1.1 albertel 1245: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1246:
1.1 albertel 1247: sub authenticate {
1.1073 raeburn 1248: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1249: $upass=&escape($upass);
1250: $uname= &LONCAPA::clean_username($uname);
1.836 www 1251: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1252: my $newhome;
1.836 www 1253: if ((!$uhome) || ($uhome eq 'no_host')) {
1254: # Maybe the machine was offline and only re-appeared again recently?
1255: &reconlonc();
1256: # One more
1.952 raeburn 1257: $uhome=&homeserver($uname,$udom,1);
1258: if (($uhome eq 'no_host') && $checkdefauth) {
1259: if (defined(&domain($udom,'primary'))) {
1260: $newhome=&domain($udom,'primary');
1261: }
1262: if ($newhome ne '') {
1263: $uhome = $newhome;
1264: }
1265: }
1.836 www 1266: if ((!$uhome) || ($uhome eq 'no_host')) {
1267: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1268: return 'no_host';
1269: }
1.1 albertel 1270: }
1.1073 raeburn 1271: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1272: if ($answer eq 'authorized') {
1.952 raeburn 1273: if ($newhome) {
1274: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1275: return 'no_account_on_host';
1276: } else {
1277: &logthis("User $uname at $udom authorized by $uhome");
1278: return $uhome;
1279: }
1.471 albertel 1280: }
1281: if ($answer eq 'non_authorized') {
1282: &logthis("User $uname at $udom rejected by $uhome");
1283: return 'no_host';
1.9 www 1284: }
1.471 albertel 1285: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1286: return 'no_host';
1287: }
1288:
1.1073 raeburn 1289: sub can_host_session {
1.1074 raeburn 1290: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1291: my $canhost = 1;
1.1074 raeburn 1292: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1293: if (ref($remotesessions) eq 'HASH') {
1294: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1295: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1296: $canhost = 0;
1297: } else {
1298: $canhost = 1;
1299: }
1300: }
1301: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1302: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1303: $canhost = 1;
1304: } else {
1305: $canhost = 0;
1306: }
1307: }
1308: if ($canhost) {
1309: if ($remotesessions->{'version'} ne '') {
1310: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1311: if ($reqmajor ne '' && $reqminor ne '') {
1312: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1313: my $major = $1;
1314: my $minor = $2;
1315: if (($major < $reqmajor ) ||
1316: (($major == $reqmajor) && ($minor < $reqminor))) {
1317: $canhost = 0;
1318: }
1319: } else {
1320: $canhost = 0;
1321: }
1322: }
1323: }
1324: }
1325: }
1326: if ($canhost) {
1327: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1328: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1329: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1330: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1331: if (($uint_dom ne '') &&
1332: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1333: $canhost = 0;
1334: } else {
1335: $canhost = 1;
1336: }
1337: }
1338: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1339: if (($uint_dom ne '') &&
1340: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1341: $canhost = 1;
1342: } else {
1343: $canhost = 0;
1344: }
1345: }
1346: }
1347: }
1348: return $canhost;
1349: }
1350:
1.1083 raeburn 1351: sub spare_can_host {
1352: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1353: my $canhost=1;
1.1172.2.62 raeburn 1354: my $try_server_hostname = &hostname($try_server);
1355: my $serverhomeID = &get_server_homeID($try_server_hostname);
1356: my $serverhomedom = &host_domain($serverhomeID);
1357: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1358: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1359: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1360: $canhost = 0;
1361: }
1362: }
1363: if (($canhost) && ($uint_dom)) {
1364: my @intdoms;
1365: my $internet_names = &get_internet_names($try_server);
1366: if (ref($internet_names) eq 'ARRAY') {
1367: @intdoms = @{$internet_names};
1368: }
1369: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1370: my $remoterev = &get_server_loncaparev(undef,$try_server);
1371: $canhost = &can_host_session($udom,$try_server,$remoterev,
1372: $remotesessions,
1373: $defdomdefaults{'hostedsessions'});
1374: }
1.1083 raeburn 1375: }
1376: return $canhost;
1377: }
1378:
1.1123 raeburn 1379: sub this_host_spares {
1380: my ($dom) = @_;
1.1126 raeburn 1381: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1382: my @hosts = ¤t_machine_ids();
1383: foreach my $lonhost (@hosts) {
1384: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1385: $dom_in_use = $dom;
1386: $lonhost_in_use = $lonhost;
1.1123 raeburn 1387: last;
1388: }
1389: }
1.1126 raeburn 1390: if ($dom_in_use ne '') {
1391: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1392: }
1393: if (ref($result) ne 'HASH') {
1394: $lonhost_in_use = $perlvar{'lonHostID'};
1395: $dom_in_use = &host_domain($lonhost_in_use);
1396: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1397: if (ref($result) ne 'HASH') {
1398: $result = \%spareid;
1399: }
1400: }
1401: return $result;
1402: }
1403:
1404: sub spares_for_offload {
1405: my ($dom_in_use,$lonhost_in_use) = @_;
1406: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1407: if (defined($cached)) {
1408: return $result;
1409: } else {
1.1126 raeburn 1410: my $cachetime = 60*60*24;
1411: my %domconfig =
1412: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1413: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1414: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1415: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1416: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1417: }
1418: }
1419: }
1420: }
1.1126 raeburn 1421: return;
1.1123 raeburn 1422: }
1423:
1.1129 raeburn 1424: sub get_lonbalancer_config {
1425: my ($servers) = @_;
1426: my ($currbalancer,$currtargets);
1427: if (ref($servers) eq 'HASH') {
1428: foreach my $server (keys(%{$servers})) {
1429: my %what = (
1430: spareid => 1,
1431: perlvar => 1,
1432: );
1433: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1434: if ($result eq 'ok') {
1435: if (ref($returnhash) eq 'HASH') {
1436: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1437: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1438: $currbalancer = $server;
1439: $currtargets = {};
1440: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1441: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1442: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1443: }
1444: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1445: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1446: }
1447: }
1448: last;
1449: }
1450: }
1451: }
1452: }
1453: }
1454: }
1455: return ($currbalancer,$currtargets);
1456: }
1457:
1458: sub check_loadbalancing {
1.1172.2.88 raeburn 1459: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1460: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107 raeburn 1461: $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129 raeburn 1462: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1463: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1464: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1465: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1466: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1467: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1468: my $domneedscache;
1.1129 raeburn 1469: my $cachetime = 60*60*24;
1470:
1471: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1472: $dom_in_use = $udom;
1473: $homeintdom = 1;
1474: } else {
1475: $dom_in_use = $serverhomedom;
1476: }
1477: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1478: unless (defined($cached)) {
1479: my %domconfig =
1480: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1481: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1482: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1483: } else {
1484: $domneedscache = $dom_in_use;
1.1129 raeburn 1485: }
1486: }
1487: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1488: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1489: &check_balancer_result($result,@hosts);
1.1129 raeburn 1490: if ($is_balancer) {
1491: if (ref($currrules) eq 'HASH') {
1492: if ($homeintdom) {
1493: if ($uname ne '') {
1494: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1495: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1496: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1497: $rule_in_effect = $currrules->{'_LC_author'};
1498: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1499: $rule_in_effect = $currrules->{'_LC_adv'}
1500: }
1501: }
1502: if ($rule_in_effect eq '') {
1503: my %userenv = &userenvironment($udom,$uname,'inststatus');
1504: if ($userenv{'inststatus'} ne '') {
1505: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1506: my ($othertitle,$usertypes,$types) =
1507: &Apache::loncommon::sorted_inst_types($udom);
1508: if (ref($types) eq 'ARRAY') {
1509: foreach my $type (@{$types}) {
1510: if (grep(/^\Q$type\E$/,@statuses)) {
1511: if (exists($currrules->{$type})) {
1512: $rule_in_effect = $currrules->{$type};
1513: }
1514: }
1515: }
1516: }
1517: } else {
1518: if (exists($currrules->{'default'})) {
1519: $rule_in_effect = $currrules->{'default'};
1520: }
1521: }
1522: }
1523: } else {
1524: if (exists($currrules->{'default'})) {
1525: $rule_in_effect = $currrules->{'default'};
1526: }
1527: }
1528: } else {
1529: if ($currrules->{'_LC_external'} ne '') {
1530: $rule_in_effect = $currrules->{'_LC_external'};
1531: }
1532: }
1533: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1534: $uname,$udom);
1535: }
1536: }
1537: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1538: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1539: unless (defined($cached)) {
1540: my %domconfig =
1541: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1542: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1543: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1544: } else {
1545: $domneedscache = $serverhomedom;
1.1129 raeburn 1546: }
1547: }
1548: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1549: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1550: &check_balancer_result($result,@hosts);
1551: if ($is_balancer) {
1.1129 raeburn 1552: if (ref($currrules) eq 'HASH') {
1553: if ($currrules->{'_LC_internetdom'} ne '') {
1554: $rule_in_effect = $currrules->{'_LC_internetdom'};
1555: }
1556: }
1557: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1558: $uname,$udom);
1559: }
1560: } else {
1561: if ($perlvar{'lonBalancer'} eq 'yes') {
1562: $is_balancer = 1;
1563: $offloadto = &this_host_spares($dom_in_use);
1564: }
1.1172.2.75 raeburn 1565: unless (defined($cached)) {
1566: $domneedscache = $serverhomedom;
1567: }
1.1129 raeburn 1568: }
1569: } else {
1570: if ($perlvar{'lonBalancer'} eq 'yes') {
1571: $is_balancer = 1;
1572: $offloadto = &this_host_spares($dom_in_use);
1573: }
1.1172.2.75 raeburn 1574: unless (defined($cached)) {
1575: $domneedscache = $serverhomedom;
1576: }
1577: }
1578: if ($domneedscache) {
1579: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1580: }
1.1172.2.5 raeburn 1581: if ($is_balancer) {
1582: my $lowest_load = 30000;
1583: if (ref($offloadto) eq 'HASH') {
1584: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1585: foreach my $try_server (@{$offloadto->{'primary'}}) {
1586: ($otherserver,$lowest_load) =
1587: &compare_server_load($try_server,$otherserver,$lowest_load);
1588: }
1.1129 raeburn 1589: }
1.1172.2.5 raeburn 1590: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1591:
1.1172.2.5 raeburn 1592: if (!$found_server) {
1593: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1594: foreach my $try_server (@{$offloadto->{'default'}}) {
1595: ($otherserver,$lowest_load) =
1596: &compare_server_load($try_server,$otherserver,$lowest_load);
1597: }
1598: }
1599: }
1600: } elsif (ref($offloadto) eq 'ARRAY') {
1601: if (@{$offloadto} == 1) {
1602: $otherserver = $offloadto->[0];
1603: } elsif (@{$offloadto} > 1) {
1604: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1605: ($otherserver,$lowest_load) =
1606: &compare_server_load($try_server,$otherserver,$lowest_load);
1607: }
1608: }
1609: }
1.1172.2.88 raeburn 1610: unless ($caller eq 'login') {
1611: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1612: $is_balancer = 0;
1613: if ($uname ne '' && $udom ne '') {
1614: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1615: &appenv({'user.loadbalexempt' => $lonhost,
1616: 'user.loadbalcheck.time' => time});
1617: }
1.1172.2.5 raeburn 1618: }
1.1129 raeburn 1619: }
1620: }
1.1172.2.107 raeburn 1621: unless ($homeintdom) {
1622: undef($setcookie);
1623: }
1.1129 raeburn 1624: }
1.1172.2.107 raeburn 1625: return ($is_balancer,$otherserver,$setcookie);
1.1129 raeburn 1626: }
1627:
1.1172.2.12 raeburn 1628: sub check_balancer_result {
1629: my ($result,@hosts) = @_;
1.1172.2.107 raeburn 1630: my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1631: if (ref($result) eq 'HASH') {
1632: if ($result->{'lonhost'} ne '') {
1633: my $currbalancer = $result->{'lonhost'};
1634: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1635: $is_balancer = 1;
1636: $currtargets = $result->{'targets'};
1637: $currrules = $result->{'rules'};
1638: }
1639: } else {
1640: foreach my $key (keys(%{$result})) {
1641: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1642: (ref($result->{$key}) eq 'HASH')) {
1643: $is_balancer = 1;
1644: $currrules = $result->{$key}{'rules'};
1645: $currtargets = $result->{$key}{'targets'};
1.1172.2.107 raeburn 1646: $setcookie = $result->{$key}{'cookie'};
1.1172.2.12 raeburn 1647: last;
1648: }
1649: }
1650: }
1651: }
1.1172.2.107 raeburn 1652: return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1653: }
1654:
1.1129 raeburn 1655: sub get_loadbalancer_targets {
1656: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1657: my $offloadto;
1.1172.2.4 raeburn 1658: if ($rule_in_effect eq 'none') {
1659: return [$perlvar{'lonHostID'}];
1660: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1661: $offloadto = $currtargets;
1662: } else {
1663: if ($rule_in_effect eq 'homeserver') {
1664: my $homeserver = &homeserver($uname,$udom);
1665: if ($homeserver ne 'no_host') {
1666: $offloadto = [$homeserver];
1667: }
1668: } elsif ($rule_in_effect eq 'externalbalancer') {
1669: my %domconfig =
1670: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1671: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1672: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1673: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1674: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1675: }
1676: }
1677: } else {
1.1172.2.7 raeburn 1678: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1679: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1680: if (&hostname($remotebalancer) ne '') {
1681: $offloadto = [$remotebalancer];
1682: }
1683: }
1684: } elsif (&hostname($rule_in_effect) ne '') {
1685: $offloadto = [$rule_in_effect];
1686: }
1687: }
1688: return $offloadto;
1689: }
1690:
1.1127 raeburn 1691: sub internet_dom_servers {
1692: my ($dom) = @_;
1693: my (%uniqservers,%servers);
1694: my $primaryserver = &hostname(&domain($dom,'primary'));
1695: my @machinedoms = &machine_domains($primaryserver);
1696: foreach my $mdom (@machinedoms) {
1697: my %currservers = %servers;
1698: my %server = &get_servers($mdom);
1699: %servers = (%currservers,%server);
1700: }
1701: my %by_hostname;
1702: foreach my $id (keys(%servers)) {
1703: push(@{$by_hostname{$servers{$id}}},$id);
1704: }
1705: foreach my $hostname (sort(keys(%by_hostname))) {
1706: if (@{$by_hostname{$hostname}} > 1) {
1707: my $match = 0;
1708: foreach my $id (@{$by_hostname{$hostname}}) {
1709: if (&host_domain($id) eq $dom) {
1710: $uniqservers{$id} = $hostname;
1711: $match = 1;
1712: }
1713: }
1714: unless ($match) {
1715: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1716: }
1717: } else {
1718: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1719: }
1720: }
1721: return %uniqservers;
1722: }
1723:
1.1 albertel 1724: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1725:
1.599 albertel 1726: my %homecache;
1.1 albertel 1727: sub homeserver {
1.230 stredwic 1728: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1729: my $index="$uname:$udom";
1.426 albertel 1730:
1.599 albertel 1731: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1732:
1733: my %servers = &get_servers($udom,'library');
1734: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1735: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1736: exists($badServerCache{$tryserver}));
1.841 albertel 1737:
1738: my $answer=reply("home:$udom:$uname",$tryserver);
1739: if ($answer eq 'found') {
1740: delete($badServerCache{$tryserver});
1741: return $homecache{$index}=$tryserver;
1742: } elsif ($answer eq 'no_host') {
1743: $badServerCache{$tryserver}=1;
1744: }
1.1 albertel 1745: }
1746: return 'no_host';
1.70 www 1747: }
1748:
1749: # ------------------------------------- Find the usernames behind a list of IDs
1750:
1751: sub idget {
1752: my ($udom,@ids)=@_;
1753: my %returnhash=();
1754:
1.841 albertel 1755: my %servers = &get_servers($udom,'library');
1756: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1757: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1758: $idlist=~tr/A-Z/a-z/;
1759: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1760: my @answer=();
1761: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1762: @answer=split(/\&/,$reply);
1763: } ;
1764: my $i;
1765: for ($i=0;$i<=$#ids;$i++) {
1766: if ($answer[$i]) {
1.1172.2.73 raeburn 1767: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1768: }
1769: }
1770: }
1.70 www 1771: return %returnhash;
1772: }
1773:
1774: # ------------------------------------- Find the IDs behind a list of usernames
1775:
1776: sub idrget {
1777: my ($udom,@unames)=@_;
1778: my %returnhash=();
1.800 albertel 1779: foreach my $uname (@unames) {
1780: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1781: }
1.70 www 1782: return %returnhash;
1783: }
1784:
1785: # ------------------------------- Store away a list of names and associated IDs
1786:
1787: sub idput {
1788: my ($udom,%ids)=@_;
1789: my %servers=();
1.800 albertel 1790: foreach my $uname (keys(%ids)) {
1791: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1792: my $uhom=&homeserver($uname,$udom);
1.70 www 1793: if ($uhom ne 'no_host') {
1.800 albertel 1794: my $id=&escape($ids{$uname});
1.70 www 1795: $id=~tr/A-Z/a-z/;
1.800 albertel 1796: my $esc_unam=&escape($uname);
1.70 www 1797: if ($servers{$uhom}) {
1.800 albertel 1798: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1799: } else {
1.800 albertel 1800: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1801: }
1802: }
1.191 harris41 1803: }
1.800 albertel 1804: foreach my $server (keys(%servers)) {
1805: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1806: }
1.344 www 1807: }
1808:
1.1172.2.30 raeburn 1809: # ---------------------------------------- Delete unwanted IDs from ids.db file
1810:
1811: sub iddel {
1812: my ($udom,$idshashref,$uhome)=@_;
1813: my %result=();
1814: unless (ref($idshashref) eq 'HASH') {
1815: return %result;
1816: }
1817: my %servers=();
1818: while (my ($id,$uname) = each(%{$idshashref})) {
1819: my $uhom;
1820: if ($uhome) {
1821: $uhom = $uhome;
1822: } else {
1823: $uhom=&homeserver($uname,$udom);
1824: }
1825: if ($uhom ne 'no_host') {
1826: if ($servers{$uhom}) {
1827: $servers{$uhom}.='&'.&escape($id);
1828: } else {
1829: $servers{$uhom}=&escape($id);
1830: }
1831: }
1832: }
1833: foreach my $server (keys(%servers)) {
1834: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1835: }
1836: return %result;
1837: }
1838:
1.1023 raeburn 1839: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1840: sub dump_dom {
1.1165 droeschl 1841: my ($namespace, $udom, $regexp) = @_;
1842:
1843: $udom ||= $env{'user.domain'};
1844:
1845: return () unless $udom;
1846:
1847: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1848: }
1849:
1.1023 raeburn 1850: # ------------------------------------------ get items from domain db files
1.806 raeburn 1851:
1852: sub get_dom {
1.860 raeburn 1853: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1854: return if ($udom eq 'public');
1.806 raeburn 1855: my $items='';
1856: foreach my $item (@$storearr) {
1857: $items.=&escape($item).'&';
1858: }
1859: $items=~s/\&$//;
1.860 raeburn 1860: if (!$udom) {
1861: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1862: return if ($udom eq 'public');
1.860 raeburn 1863: if (defined(&domain($udom,'primary'))) {
1864: $uhome=&domain($udom,'primary');
1865: } else {
1.874 albertel 1866: undef($uhome);
1.860 raeburn 1867: }
1868: } else {
1869: if (!$uhome) {
1870: if (defined(&domain($udom,'primary'))) {
1871: $uhome=&domain($udom,'primary');
1872: }
1873: }
1874: }
1875: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1876: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1877: my %returnhash;
1.875 albertel 1878: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1879: return %returnhash;
1880: }
1.806 raeburn 1881: my @pairs=split(/\&/,$rep);
1882: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1883: return @pairs;
1884: }
1885: my $i=0;
1886: foreach my $item (@$storearr) {
1887: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1888: $i++;
1889: }
1890: return %returnhash;
1891: } else {
1.880 banghart 1892: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1893: }
1894: }
1895:
1896: # -------------------------------------------- put items in domain db files
1897:
1898: sub put_dom {
1.860 raeburn 1899: my ($namespace,$storehash,$udom,$uhome)=@_;
1900: if (!$udom) {
1901: $udom=$env{'user.domain'};
1902: if (defined(&domain($udom,'primary'))) {
1903: $uhome=&domain($udom,'primary');
1904: } else {
1.874 albertel 1905: undef($uhome);
1.860 raeburn 1906: }
1907: } else {
1908: if (!$uhome) {
1909: if (defined(&domain($udom,'primary'))) {
1910: $uhome=&domain($udom,'primary');
1911: }
1912: }
1913: }
1914: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1915: my $items='';
1916: foreach my $item (keys(%$storehash)) {
1917: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1918: }
1919: $items=~s/\&$//;
1920: return &reply("putdom:$udom:$namespace:$items",$uhome);
1921: } else {
1.860 raeburn 1922: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1923: }
1924: }
1925:
1.1023 raeburn 1926: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1927: sub newput_dom {
1.1023 raeburn 1928: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1929: my $result;
1930: if (!$udom) {
1931: $udom=$env{'user.domain'};
1932: }
1.1023 raeburn 1933: if ($udom) {
1934: my $uname = &get_domainconfiguser($udom);
1935: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1936: }
1937: return $result;
1938: }
1939:
1.1023 raeburn 1940: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1941: sub del_dom {
1.1023 raeburn 1942: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1943: if (ref($storearr) eq 'ARRAY') {
1944: if (!$udom) {
1945: $udom=$env{'user.domain'};
1946: }
1.1023 raeburn 1947: if ($udom) {
1948: my $uname = &get_domainconfiguser($udom);
1949: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1950: }
1951: }
1952: }
1953:
1.1023 raeburn 1954: # ----------------------------------construct domainconfig user for a domain
1955: sub get_domainconfiguser {
1956: my ($udom) = @_;
1957: return $udom.'-domainconfig';
1958: }
1959:
1.837 raeburn 1960: sub retrieve_inst_usertypes {
1961: my ($udom) = @_;
1962: my (%returnhash,@order);
1.989 raeburn 1963: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1964: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1965: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1966: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1967: } else {
1968: if (defined(&domain($udom,'primary'))) {
1969: my $uhome=&domain($udom,'primary');
1970: my $rep=&reply("inst_usertypes:$udom",$uhome);
1971: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1972: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1973: return (\%returnhash,\@order);
1974: }
1975: my ($hashitems,$orderitems) = split(/:/,$rep);
1976: my @pairs=split(/\&/,$hashitems);
1977: foreach my $item (@pairs) {
1978: my ($key,$value)=split(/=/,$item,2);
1979: $key = &unescape($key);
1980: next if ($key =~ /^error: 2 /);
1981: $returnhash{$key}=&thaw_unescape($value);
1982: }
1983: my @esc_order = split(/\&/,$orderitems);
1984: foreach my $item (@esc_order) {
1985: push(@order,&unescape($item));
1986: }
1987: } else {
1.1172.2.44 raeburn 1988: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1989: }
1.1172.2.44 raeburn 1990: return (\%returnhash,\@order);
1.837 raeburn 1991: }
1992: }
1993:
1.868 raeburn 1994: sub is_domainimage {
1995: my ($url) = @_;
1.1172.2.74 raeburn 1996: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1997: if (&domain($1) ne '') {
1998: return '1';
1999: }
2000: }
2001: return;
2002: }
2003:
1.899 raeburn 2004: sub inst_directory_query {
2005: my ($srch) = @_;
2006: my $udom = $srch->{'srchdomain'};
2007: my %results;
2008: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2009: my $outcome;
1.899 raeburn 2010: if ($homeserver ne '') {
1.1172.2.116 raeburn 2011: unless ($homeserver eq $perlvar{'lonHostID'}) {
2012: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2013: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116 raeburn 2014: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
2015: if (($major eq '' && $minor eq '') || ($major < 2) ||
2016: (($major == 2) && ($minor < 11)) ||
2017: (($major == 2) && ($minor == 11) && ($subver < 3))) {
2018: return;
2019: }
2020: }
2021: }
1.904 albertel 2022: my $queryid=&reply("querysend:instdirsearch:".
2023: &escape($srch->{'srchby'}).':'.
2024: &escape($srch->{'srchterm'}).':'.
2025: &escape($srch->{'srchtype'}),$homeserver);
2026: my $host=&hostname($homeserver);
2027: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96 raeburn 2028: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2029: return;
2030: }
2031: my $response = &get_query_reply($queryid);
2032: my $maxtries = 5;
2033: my $tries = 1;
2034: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2035: $response = &get_query_reply($queryid);
2036: $tries ++;
2037: }
2038:
2039: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2040: if ($response eq 'unavailable') {
2041: $outcome = $response;
2042: } else {
2043: $outcome = 'ok';
2044: my @matches = split(/\n/,$response);
2045: foreach my $match (@matches) {
2046: my ($key,$value) = split(/=/,$match);
2047: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2048: }
1.899 raeburn 2049: }
2050: }
2051: }
1.909 raeburn 2052: return ($outcome,%results);
1.899 raeburn 2053: }
2054:
2055: sub usersearch {
2056: my ($srch) = @_;
2057: my $dom = $srch->{'srchdomain'};
2058: my %results;
2059: my %libserv = &all_library();
2060: my $query = 'usersearch';
2061: foreach my $tryserver (keys(%libserv)) {
2062: if (&host_domain($tryserver) eq $dom) {
1.1172.2.116 raeburn 2063: unless ($tryserver eq $perlvar{'lonHostID'}) {
2064: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2065: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119 raeburn 2066: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116 raeburn 2067: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2068: (($major == 2) && ($minor < 11)) ||
2069: (($major == 2) && ($minor == 11) && ($subver < 3)));
2070: }
2071: }
1.899 raeburn 2072: my $host=&hostname($tryserver);
2073: my $queryid=
1.911 raeburn 2074: &reply("querysend:".&escape($query).':'.
2075: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2076: &escape($srch->{'srchtype'}).':'.
2077: &escape($srch->{'srchterm'}),$tryserver);
2078: if ($queryid !~/^\Q$host\E\_/) {
2079: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2080: next;
1.899 raeburn 2081: }
2082: my $reply = &get_query_reply($queryid);
2083: my $maxtries = 1;
2084: my $tries = 1;
2085: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2086: $reply = &get_query_reply($queryid);
2087: $tries ++;
2088: }
2089: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2090: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2091: } else {
1.911 raeburn 2092: my @matches;
2093: if ($reply =~ /\n/) {
2094: @matches = split(/\n/,$reply);
2095: } else {
2096: @matches = split(/\&/,$reply);
2097: }
1.899 raeburn 2098: foreach my $match (@matches) {
2099: my ($uname,$udom,%userhash);
1.911 raeburn 2100: foreach my $entry (split(/:/,$match)) {
2101: my ($key,$value) =
2102: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2103: $userhash{$key} = $value;
2104: if ($key eq 'username') {
2105: $uname = $value;
2106: } elsif ($key eq 'domain') {
2107: $udom = $value;
1.911 raeburn 2108: }
1.899 raeburn 2109: }
2110: $results{$uname.':'.$udom} = \%userhash;
2111: }
2112: }
2113: }
2114: }
2115: return %results;
2116: }
2117:
1.912 raeburn 2118: sub get_instuser {
2119: my ($udom,$uname,$id) = @_;
2120: my $homeserver = &domain($udom,'primary');
2121: my ($outcome,%results);
2122: if ($homeserver ne '') {
2123: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2124: &escape($id).':'.&escape($udom),$homeserver);
2125: my $host=&hostname($homeserver);
2126: if ($queryid !~/^\Q$host\E\_/) {
2127: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2128: return;
2129: }
2130: my $response = &get_query_reply($queryid);
2131: my $maxtries = 5;
2132: my $tries = 1;
2133: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2134: $response = &get_query_reply($queryid);
2135: $tries ++;
2136: }
2137: if (!&error($response) && $response ne 'refused') {
2138: if ($response eq 'unavailable') {
2139: $outcome = $response;
2140: } else {
2141: $outcome = 'ok';
2142: my @matches = split(/\n/,$response);
2143: foreach my $match (@matches) {
2144: my ($key,$value) = split(/=/,$match);
2145: $results{&unescape($key)} = &thaw_unescape($value);
2146: }
2147: }
2148: }
2149: }
2150: my %userinfo;
2151: if (ref($results{$uname}) eq 'HASH') {
2152: %userinfo = %{$results{$uname}};
2153: }
2154: return ($outcome,%userinfo);
2155: }
2156:
1.1172.2.69 raeburn 2157: sub get_multiple_instusers {
2158: my ($udom,$users,$caller) = @_;
2159: my ($outcome,$results);
2160: if (ref($users) eq 'HASH') {
2161: my $count = keys(%{$users});
2162: my $requested = &freeze_escape($users);
2163: my $homeserver = &domain($udom,'primary');
2164: if ($homeserver ne '') {
2165: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2166: my $host=&hostname($homeserver);
2167: if ($queryid !~/^\Q$host\E\_/) {
2168: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2169: ' for host: '.$homeserver.'in domain '.$udom);
2170: return ($outcome,$results);
2171: }
2172: my $response = &get_query_reply($queryid);
2173: my $maxtries = 5;
2174: if ($count > 100) {
2175: $maxtries = 1+int($count/20);
2176: }
2177: my $tries = 1;
2178: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2179: $response = &get_query_reply($queryid);
2180: $tries ++;
2181: }
2182: if ($response eq '') {
2183: $results = {};
2184: foreach my $key (keys(%{$users})) {
2185: my ($uname,$id);
2186: if ($caller eq 'id') {
2187: $id = $key;
2188: } else {
2189: $uname = $key;
2190: }
2191: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2192: $outcome = $resp;
2193: if ($resp eq 'ok') {
2194: %{$results} = (%{$results}, %info);
2195: } else {
2196: last;
2197: }
2198: }
2199: } elsif(!&error($response) && ($response ne 'refused')) {
2200: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2201: $outcome = $response;
2202: } else {
2203: ($outcome,my $userdata) = split(/=/,$response,2);
2204: if ($outcome eq 'ok') {
2205: $results = &thaw_unescape($userdata);
2206: }
2207: }
2208: }
2209: }
2210: }
2211: return ($outcome,$results);
2212: }
2213:
1.912 raeburn 2214: sub inst_rulecheck {
1.923 raeburn 2215: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2216: my %returnhash;
2217: if ($udom ne '') {
2218: if (ref($rules) eq 'ARRAY') {
2219: @{$rules} = map {&escape($_);} (@{$rules});
2220: my $rulestr = join(':',@{$rules});
2221: my $homeserver=&domain($udom,'primary');
2222: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2223: my $response;
2224: if ($item eq 'username') {
2225: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2226: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2227: $homeserver));
1.923 raeburn 2228: } elsif ($item eq 'id') {
2229: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2230: ':'.&escape($id).':'.$rulestr,
2231: $homeserver));
1.945 raeburn 2232: } elsif ($item eq 'selfcreate') {
2233: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2234: &escape($udom).':'.&escape($uname).
2235: ':'.$rulestr,$homeserver));
1.923 raeburn 2236: }
1.912 raeburn 2237: if ($response ne 'refused') {
2238: my @pairs=split(/\&/,$response);
2239: foreach my $item (@pairs) {
2240: my ($key,$value)=split(/=/,$item,2);
2241: $key = &unescape($key);
2242: next if ($key =~ /^error: 2 /);
2243: $returnhash{$key}=&thaw_unescape($value);
2244: }
2245: }
2246: }
2247: }
2248: }
2249: return %returnhash;
2250: }
2251:
2252: sub inst_userrules {
1.923 raeburn 2253: my ($udom,$check) = @_;
1.912 raeburn 2254: my (%ruleshash,@ruleorder);
2255: if ($udom ne '') {
2256: my $homeserver=&domain($udom,'primary');
2257: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2258: my $response;
2259: if ($check eq 'id') {
2260: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2261: $homeserver);
1.943 raeburn 2262: } elsif ($check eq 'email') {
2263: $response=&reply('instemailrules:'.&escape($udom),
2264: $homeserver);
1.923 raeburn 2265: } else {
2266: $response=&reply('instuserrules:'.&escape($udom),
2267: $homeserver);
2268: }
1.912 raeburn 2269: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2270: ($response ne 'unknown_cmd') &&
1.912 raeburn 2271: ($response ne 'no_such_host')) {
2272: my ($hashitems,$orderitems) = split(/:/,$response);
2273: my @pairs=split(/\&/,$hashitems);
2274: foreach my $item (@pairs) {
2275: my ($key,$value)=split(/=/,$item,2);
2276: $key = &unescape($key);
2277: next if ($key =~ /^error: 2 /);
2278: $ruleshash{$key}=&thaw_unescape($value);
2279: }
2280: my @esc_order = split(/\&/,$orderitems);
2281: foreach my $item (@esc_order) {
2282: push(@ruleorder,&unescape($item));
2283: }
2284: }
2285: }
2286: }
2287: return (\%ruleshash,\@ruleorder);
2288: }
2289:
1.976 raeburn 2290: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2291:
2292: sub get_domain_defaults {
1.1172.2.35 raeburn 2293: my ($domain,$ignore_cache) = @_;
2294: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2295: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2296: unless ($ignore_cache) {
2297: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2298: if (defined($cached)) {
2299: if (ref($result) eq 'HASH') {
2300: return %{$result};
2301: }
1.943 raeburn 2302: }
2303: }
2304: my %domdefaults;
2305: my %domconfig =
1.989 raeburn 2306: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2307: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2308: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2309: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2310: 'coursecategories','autoenroll',
2311: 'helpsettings'],$domain);
1.1172.2.41 raeburn 2312: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2313: if (ref($domconfig{'defaults'}) eq 'HASH') {
2314: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2315: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2316: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2317: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2318: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2319: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2320: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2321: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2322: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2323: } else {
2324: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2325: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2326: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2327: }
1.976 raeburn 2328: if (ref($domconfig{'quotas'}) eq 'HASH') {
2329: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2330: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2331: } else {
2332: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2333: }
1.1172.2.6 raeburn 2334: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2335: foreach my $item (@usertools) {
2336: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2337: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2338: }
2339: }
1.1172.2.29 raeburn 2340: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2341: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2342: }
1.976 raeburn 2343: }
1.985 raeburn 2344: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2345: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2346: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2347: }
2348: }
1.1172.2.9 raeburn 2349: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2350: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2351: }
1.989 raeburn 2352: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2353: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2354: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2355: }
2356: }
1.1047 raeburn 2357: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2358: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2359: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2360: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2361: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2362: }
1.1172.2.41 raeburn 2363: foreach my $type (@coursetypes) {
2364: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2365: unless ($type eq 'community') {
2366: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2367: }
2368: }
2369: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2370: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2371: }
1.1172.2.60 raeburn 2372: if ($domdefaults{'postsubmit'} eq 'on') {
2373: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2374: $domdefaults{$type.'postsubtimeout'} =
2375: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2376: }
2377: }
1.1172.2.30 raeburn 2378: }
1.1172.2.67 raeburn 2379: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2380: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2381: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2382: if (@clonecodes) {
2383: $domdefaults{'canclone'} = join('+',@clonecodes);
2384: }
2385: }
2386: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2387: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2388: }
1.1172.2.103 raeburn 2389: if ($domconfig{'coursedefaults'}{'texengine'}) {
2390: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2391: }
1.1047 raeburn 2392: }
1.1073 raeburn 2393: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2394: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2395: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2396: }
2397: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2398: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2399: }
1.1172.2.62 raeburn 2400: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2401: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2402: }
1.1073 raeburn 2403: }
1.1172.2.41 raeburn 2404: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2405: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2406: my @settings = ('types','registered','enroll_dates','access_dates','section',
2407: 'approval','limit');
2408: foreach my $type (@coursetypes) {
2409: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2410: my @mgrdc = ();
2411: foreach my $item (@settings) {
2412: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2413: push(@mgrdc,$item);
2414: }
2415: }
2416: if (@mgrdc) {
2417: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2418: }
2419: }
2420: }
2421: }
2422: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2423: foreach my $type (@coursetypes) {
2424: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2425: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2426: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2427: }
2428: }
2429: }
2430: }
2431: }
1.1172.2.46 raeburn 2432: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2433: $domdefaults{'catauth'} = 'std';
2434: $domdefaults{'catunauth'} = 'std';
2435: if ($domconfig{'coursecategories'}{'auth'}) {
2436: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2437: }
2438: if ($domconfig{'coursecategories'}{'unauth'}) {
2439: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2440: }
2441: }
1.1172.2.76 raeburn 2442: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2443: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2444: }
1.1172.2.89 raeburn 2445: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2446: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2447: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2448: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2449: }
2450: }
1.1172.2.23 raeburn 2451: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2452: return %domdefaults;
2453: }
2454:
1.1172.2.106 raeburn 2455: sub get_dom_cats {
2456: my ($dom) = @_;
2457: return unless (&domain($dom));
2458: my ($cats,$cached)=&is_cached_new('cats',$dom);
2459: unless (defined($cached)) {
2460: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2461: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2462: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2463: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2464: } else {
2465: $cats = {};
2466: }
2467: } else {
2468: $cats = {};
2469: }
2470: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2471: }
2472: return $cats;
2473: }
2474:
2475: sub get_dom_instcats {
2476: my ($dom) = @_;
2477: return unless (&domain($dom));
2478: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2479: unless (defined($cached)) {
2480: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2481: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2482: if ($totcodes > 0) {
2483: my $caller = 'global';
2484: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2485: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2486: $instcats = {
2487: codes => \%codes,
2488: codetitles => \@codetitles,
2489: cat_titles => \%cat_titles,
2490: cat_order => \%cat_order,
2491: };
2492: &do_cache_new('instcats',$dom,$instcats,3600);
2493: }
2494: }
2495: }
2496: return $instcats;
2497: }
2498:
2499: sub retrieve_instcodes {
2500: my ($coursecodes,$dom) = @_;
2501: my $totcodes;
2502: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2503: foreach my $course (keys(%courses)) {
2504: if (ref($courses{$course}) eq 'HASH') {
2505: if ($courses{$course}{'inst_code'} ne '') {
2506: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2507: $totcodes ++;
2508: }
2509: }
2510: }
2511: return $totcodes;
2512: }
2513:
1.1172.2.113 raeburn 2514: # --------------------------------------------- Get domain config for passwords
2515:
2516: sub get_passwdconf {
2517: my ($dom) = @_;
2518: my (%passwdconf,$gotconf,$lookup);
2519: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2520: if (defined($cached)) {
2521: if (ref($result) eq 'HASH') {
2522: %passwdconf = %{$result};
2523: $gotconf = 1;
2524: }
2525: }
2526: unless ($gotconf) {
2527: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2528: if (ref($domconfig{'passwords'}) eq 'HASH') {
2529: %passwdconf = %{$domconfig{'passwords'}};
2530: }
2531: my $cachetime = 24*60*60;
2532: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2533: }
2534: return %passwdconf;
2535: }
2536:
1.344 www 2537: # --------------------------------------------------- Assign a key to a student
2538:
2539: sub assign_access_key {
1.364 www 2540: #
2541: # a valid key looks like uname:udom#comments
2542: # comments are being appended
2543: #
1.498 www 2544: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2545: $kdom=
1.620 albertel 2546: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2547: $knum=
1.620 albertel 2548: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2549: $cdom=
1.620 albertel 2550: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2551: $cnum=
1.620 albertel 2552: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2553: $udom=$env{'user.name'} unless (defined($udom));
2554: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2555: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2556: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2557: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2558: # assigned to this person
2559: # - this should not happen,
1.345 www 2560: # unless something went wrong
2561: # the first time around
2562: # ready to assign
1.364 www 2563: $logentry=$1.'; '.$logentry;
1.496 www 2564: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2565: $kdom,$knum) eq 'ok') {
1.345 www 2566: # key now belongs to user
1.346 www 2567: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2568: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2569: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2570: return 'ok';
2571: } else {
2572: return
2573: 'error: Count not permanently assign key, will need to be re-entered later.';
2574: }
2575: } else {
2576: return 'error: Could not assign key, try again later.';
2577: }
1.364 www 2578: } elsif (!$existing{$ckey}) {
1.345 www 2579: # the key does not exist
2580: return 'error: The key does not exist';
2581: } else {
2582: # the key is somebody else's
2583: return 'error: The key is already in use';
2584: }
1.344 www 2585: }
2586:
1.364 www 2587: # ------------------------------------------ put an additional comment on a key
2588:
2589: sub comment_access_key {
2590: #
2591: # a valid key looks like uname:udom#comments
2592: # comments are being appended
2593: #
2594: my ($ckey,$cdom,$cnum,$logentry)=@_;
2595: $cdom=
1.620 albertel 2596: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2597: $cnum=
1.620 albertel 2598: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2599: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2600: if ($existing{$ckey}) {
2601: $existing{$ckey}.='; '.$logentry;
2602: # ready to assign
1.367 www 2603: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2604: $cdom,$cnum) eq 'ok') {
2605: return 'ok';
2606: } else {
2607: return 'error: Count not store comment.';
2608: }
2609: } else {
2610: # the key does not exist
2611: return 'error: The key does not exist';
2612: }
2613: }
2614:
1.344 www 2615: # ------------------------------------------------------ Generate a set of keys
2616:
2617: sub generate_access_keys {
1.364 www 2618: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2619: $cdom=
1.620 albertel 2620: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2621: $cnum=
1.620 albertel 2622: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2623: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2624: unless (($cdom) && ($cnum)) { return 0; }
2625: if ($number>10000) { return 0; }
2626: sleep(2); # make sure don't get same seed twice
2627: srand(time()^($$+($$<<15))); # from "Programming Perl"
2628: my $total=0;
2629: for (my $i=1;$i<=$number;$i++) {
2630: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2631: sprintf("%lx",int(100000*rand)).'-'.
2632: sprintf("%lx",int(100000*rand));
2633: $newkey=~s/1/g/g; # folks mix up 1 and l
2634: $newkey=~s/0/h/g; # and also 0 and O
2635: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2636: if ($existing{$newkey}) {
2637: $i--;
2638: } else {
1.364 www 2639: if (&put('accesskeys',
2640: { $newkey => '# generated '.localtime().
1.620 albertel 2641: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2642: '; '.$logentry },
2643: $cdom,$cnum) eq 'ok') {
1.344 www 2644: $total++;
2645: }
2646: }
2647: }
1.620 albertel 2648: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2649: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2650: return $total;
2651: }
2652:
2653: # ------------------------------------------------------- Validate an accesskey
2654:
2655: sub validate_access_key {
2656: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2657: $cdom=
1.620 albertel 2658: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2659: $cnum=
1.620 albertel 2660: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2661: $udom=$env{'user.domain'} unless (defined($udom));
2662: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2663: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2664: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2665: }
2666:
2667: # ------------------------------------- Find the section of student in a course
1.652 albertel 2668: sub devalidate_getsection_cache {
2669: my ($udom,$unam,$courseid)=@_;
2670: my $hashid="$udom:$unam:$courseid";
2671: &devalidate_cache_new('getsection',$hashid);
2672: }
1.298 matthew 2673:
1.815 albertel 2674: sub courseid_to_courseurl {
2675: my ($courseid) = @_;
2676: #already url style courseid
2677: return $courseid if ($courseid =~ m{^/});
2678:
2679: if (exists($env{'course.'.$courseid.'.num'})) {
2680: my $cnum = $env{'course.'.$courseid.'.num'};
2681: my $cdom = $env{'course.'.$courseid.'.domain'};
2682: return "/$cdom/$cnum";
2683: }
2684:
2685: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2686: if (exists($courseinfo{'num'})) {
2687: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2688: }
2689:
2690: return undef;
2691: }
2692:
1.298 matthew 2693: sub getsection {
2694: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2695: my $cachetime=1800;
1.551 albertel 2696:
2697: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2698: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2699: if (defined($cached)) { return $result; }
2700:
1.298 matthew 2701: my %Pending;
2702: my %Expired;
2703: #
2704: # Each role can either have not started yet (pending), be active,
2705: # or have expired.
2706: #
2707: # If there is an active role, we are done.
2708: #
2709: # If there is more than one role which has not started yet,
2710: # choose the one which will start sooner
2711: # If there is one role which has not started yet, return it.
2712: #
2713: # If there is more than one expired role, choose the one which ended last.
2714: # If there is a role which has expired, return it.
2715: #
1.815 albertel 2716: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2717: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2718: foreach my $key (keys(%roleshash)) {
1.479 albertel 2719: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2720: my $section=$1;
2721: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2722: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2723: my $now=time;
1.548 albertel 2724: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2725: $Expired{$end}=$section;
2726: next;
2727: }
1.548 albertel 2728: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2729: $Pending{$start}=$section;
2730: next;
2731: }
1.599 albertel 2732: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2733: }
2734: #
2735: # Presumedly there will be few matching roles from the above
2736: # loop and the sorting time will be negligible.
2737: if (scalar(keys(%Pending))) {
2738: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2739: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2740: }
2741: if (scalar(keys(%Expired))) {
2742: my @sorted = sort {$a <=> $b} keys(%Expired);
2743: my $time = pop(@sorted);
1.599 albertel 2744: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2745: }
1.599 albertel 2746: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2747: }
1.70 www 2748:
1.599 albertel 2749: sub save_cache {
2750: &purge_remembered();
1.722 albertel 2751: #&Apache::loncommon::validate_page();
1.620 albertel 2752: undef(%env);
1.780 albertel 2753: undef($env_loaded);
1.599 albertel 2754: }
1.452 albertel 2755:
1.599 albertel 2756: my $to_remember=-1;
2757: my %remembered;
2758: my %accessed;
2759: my $kicks=0;
2760: my $hits=0;
1.849 albertel 2761: sub make_key {
2762: my ($name,$id) = @_;
1.872 albertel 2763: if (length($id) > 65
2764: && length(&escape($id)) > 200) {
2765: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2766: }
1.849 albertel 2767: return &escape($name.':'.$id);
2768: }
2769:
1.599 albertel 2770: sub devalidate_cache_new {
2771: my ($name,$id,$debug) = @_;
2772: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2773: my $remembered_id=$name.':'.$id;
1.849 albertel 2774: $id=&make_key($name,$id);
1.599 albertel 2775: $memcache->delete($id);
1.1172.2.81 raeburn 2776: delete($remembered{$remembered_id});
2777: delete($accessed{$remembered_id});
1.599 albertel 2778: }
2779:
2780: sub is_cached_new {
2781: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2782: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2783: # keys in %remembered hash, which persists for
2784: # duration of request (no restriction on key length).
2785: if (exists($remembered{$remembered_id})) {
2786: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2787: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2788: $hits++;
1.1172.2.81 raeburn 2789: return ($remembered{$remembered_id},1);
1.599 albertel 2790: }
1.1172.2.81 raeburn 2791: $id=&make_key($name,$id);
1.599 albertel 2792: my $value = $memcache->get($id);
2793: if (!(defined($value))) {
2794: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2795: return (undef,undef);
1.416 albertel 2796: }
1.599 albertel 2797: if ($value eq '__undef__') {
2798: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2799: $value=undef;
2800: }
1.1172.2.81 raeburn 2801: &make_room($remembered_id,$value,$debug);
1.599 albertel 2802: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2803: return ($value,1);
2804: }
2805:
2806: sub do_cache_new {
2807: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2808: my $remembered_id=$name.':'.$id;
1.849 albertel 2809: $id=&make_key($name,$id);
1.599 albertel 2810: my $setvalue=$value;
2811: if (!defined($setvalue)) {
2812: $setvalue='__undef__';
2813: }
1.623 albertel 2814: if (!defined($time) ) {
2815: $time=600;
2816: }
1.599 albertel 2817: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2818: my $result = $memcache->set($id,$setvalue,$time);
2819: if (! $result) {
1.872 albertel 2820: &logthis("caching of id -> $id failed");
1.910 albertel 2821: $memcache->disconnect_all();
1.872 albertel 2822: }
1.600 albertel 2823: # need to make a copy of $value
1.1172.2.81 raeburn 2824: &make_room($remembered_id,$value,$debug);
1.599 albertel 2825: return $value;
2826: }
2827:
2828: sub make_room {
1.1172.2.81 raeburn 2829: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2830:
1.1172.2.81 raeburn 2831: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2832: : $value;
1.599 albertel 2833: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2834: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2835: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2836: my $to_kick;
2837: my $max_time=0;
2838: foreach my $other (keys(%accessed)) {
2839: if (&tv_interval($accessed{$other}) > $max_time) {
2840: $to_kick=$other;
2841: $max_time=&tv_interval($accessed{$other});
2842: }
2843: }
2844: delete($remembered{$to_kick});
2845: delete($accessed{$to_kick});
2846: $kicks++;
2847: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2848: return;
2849: }
2850:
1.599 albertel 2851: sub purge_remembered {
1.604 albertel 2852: #&logthis("Tossing ".scalar(keys(%remembered)));
2853: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2854: undef(%remembered);
2855: undef(%accessed);
1.428 albertel 2856: }
1.70 www 2857: # ------------------------------------- Read an entry from a user's environment
2858:
2859: sub userenvironment {
2860: my ($udom,$unam,@what)=@_;
1.976 raeburn 2861: my $items;
2862: foreach my $item (@what) {
2863: $items.=&escape($item).'&';
2864: }
2865: $items=~s/\&$//;
1.70 www 2866: my %returnhash=();
1.1009 raeburn 2867: my $uhome = &homeserver($unam,$udom);
2868: unless ($uhome eq 'no_host') {
2869: my @answer=split(/\&/,
2870: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2871: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2872: return %returnhash;
2873: }
1.1009 raeburn 2874: my $i;
2875: for ($i=0;$i<=$#what;$i++) {
2876: $returnhash{$what[$i]}=&unescape($answer[$i]);
2877: }
1.70 www 2878: }
2879: return %returnhash;
1.1 albertel 2880: }
2881:
1.617 albertel 2882: # ---------------------------------------------------------- Get a studentphoto
2883: sub studentphoto {
2884: my ($udom,$unam,$ext) = @_;
2885: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2886: if (defined($env{'request.course.id'})) {
1.708 raeburn 2887: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2888: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2889: return(&retrievestudentphoto($udom,$unam,$ext));
2890: } else {
2891: my ($result,$perm_reqd)=
1.707 albertel 2892: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2893: if ($result eq 'ok') {
2894: if (!($perm_reqd eq 'yes')) {
2895: return(&retrievestudentphoto($udom,$unam,$ext));
2896: }
2897: }
2898: }
2899: }
2900: } else {
2901: my ($result,$perm_reqd) =
1.707 albertel 2902: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2903: if ($result eq 'ok') {
2904: if (!($perm_reqd eq 'yes')) {
2905: return(&retrievestudentphoto($udom,$unam,$ext));
2906: }
2907: }
2908: }
2909: return '/adm/lonKaputt/lonlogo_broken.gif';
2910: }
2911:
2912: sub retrievestudentphoto {
2913: my ($udom,$unam,$ext,$type) = @_;
2914: my $home=&Apache::lonnet::homeserver($unam,$udom);
2915: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2916: if ($ret eq 'ok') {
2917: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2918: if ($type eq 'thumbnail') {
2919: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2920: }
2921: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2922: return $tokenurl;
2923: } else {
2924: if ($type eq 'thumbnail') {
2925: return '/adm/lonKaputt/genericstudent_tn.gif';
2926: } else {
2927: return '/adm/lonKaputt/lonlogo_broken.gif';
2928: }
1.617 albertel 2929: }
2930: }
2931:
1.263 www 2932: # -------------------------------------------------------------------- New chat
2933:
2934: sub chatsend {
1.724 raeburn 2935: my ($newentry,$anon,$group)=@_;
1.620 albertel 2936: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2937: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2938: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2939: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2940: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2941: &escape($newentry)).':'.$group,$chome);
1.292 www 2942: }
2943:
2944: # ------------------------------------------ Find current version of a resource
2945:
2946: sub getversion {
2947: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2948: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2949: return ¤tversion(&filelocation('',$fname));
2950: }
2951:
2952: sub currentversion {
2953: my $fname=shift;
2954: my $author=$fname;
2955: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2956: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2957: my $home=&homeserver($uname,$udom);
1.292 www 2958: if ($home eq 'no_host') {
2959: return -1;
2960: }
1.1112 www 2961: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2962: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2963: return -1;
2964: }
1.1112 www 2965: return $answer;
1.263 www 2966: }
2967:
1.1111 www 2968: #
2969: # Return special version number of resource if set by override, empty otherwise
2970: #
2971: sub usedversion {
2972: my $fname=shift;
2973: unless ($fname) { $fname=$env{'request.uri'}; }
2974: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2975: if ($urlversion) { return $urlversion; }
2976: return '';
2977: }
2978:
1.1 albertel 2979: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2980:
1.1 albertel 2981: sub subscribe {
2982: my $fname=shift;
1.761 raeburn 2983: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2984: $fname=~s/[\n\r]//g;
1.1 albertel 2985: my $author=$fname;
2986: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2987: my ($udom,$uname)=split(/\//,$author);
2988: my $home=homeserver($uname,$udom);
1.335 albertel 2989: if ($home eq 'no_host') {
2990: return 'not_found';
1.1 albertel 2991: }
2992: my $answer=reply("sub:$fname",$home);
1.64 www 2993: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2994: $answer.=' by '.$home;
2995: }
1.1 albertel 2996: return $answer;
2997: }
2998:
1.8 www 2999: # -------------------------------------------------------------- Replicate file
3000:
3001: sub repcopy {
3002: my $filename=shift;
1.23 www 3003: $filename=~s/\/+/\//g;
1.1142 raeburn 3004: my $londocroot = $perlvar{'lonDocRoot'};
3005: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3006: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3007: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3008: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3009: return &repcopy_userfile($filename);
3010: }
1.532 albertel 3011: $filename=~s/[\n\r]//g;
1.8 www 3012: my $transname="$filename.in.transfer";
1.828 www 3013: # FIXME: this should flock
1.607 raeburn 3014: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3015: my $remoteurl=subscribe($filename);
1.64 www 3016: if ($remoteurl =~ /^con_lost by/) {
3017: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3018: return 'unavailable';
1.8 www 3019: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3020: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3021: return 'not_found';
1.64 www 3022: } elsif ($remoteurl =~ /^rejected by/) {
3023: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3024: return 'forbidden';
1.20 www 3025: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3026: return 'ok';
1.8 www 3027: } else {
1.290 www 3028: my $author=$filename;
3029: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3030: my ($udom,$uname)=split(/\//,$author);
3031: my $home=homeserver($uname,$udom);
3032: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3033: my @parts=split(/\//,$filename);
3034: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3035: if ($path ne "$londocroot/res") {
1.8 www 3036: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3037: return 'bad_request';
1.8 www 3038: }
3039: my $count;
3040: for ($count=5;$count<$#parts;$count++) {
3041: $path.="/$parts[$count]";
3042: if ((-e $path)!=1) {
3043: mkdir($path,0777);
3044: }
3045: }
3046: my $ua=new LWP::UserAgent;
3047: my $request=new HTTP::Request('GET',"$remoteurl");
3048: my $response=$ua->request($request,$transname);
3049: if ($response->is_error()) {
3050: unlink($transname);
3051: my $message=$response->status_line;
1.672 albertel 3052: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3053: ." LWP get: $message: $filename</font>");
1.607 raeburn 3054: return 'unavailable';
1.8 www 3055: } else {
1.16 www 3056: if ($remoteurl!~/\.meta$/) {
3057: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3058: my $mresponse=$ua->request($mrequest,$filename.'.meta');
3059: if ($mresponse->is_error()) {
3060: unlink($filename.'.meta');
3061: &logthis(
1.672 albertel 3062: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3063: }
3064: }
1.8 www 3065: rename($transname,$filename);
1.607 raeburn 3066: return 'ok';
1.8 www 3067: }
1.290 www 3068: }
1.8 www 3069: }
1.330 www 3070: }
3071:
1.1172.2.124 raeburn 3072: # ------------------------------------------------- Unsubscribe from a resource
3073:
3074: sub unsubscribe {
3075: my ($fname) = @_;
3076: my $answer;
3077: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3078: $fname=~s/[\n\r]//g;
3079: my $author=$fname;
3080: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3081: my ($udom,$uname)=split(/\//,$author);
3082: my $home=homeserver($uname,$udom);
3083: if ($home eq 'no_host') {
3084: $answer = 'no_host';
3085: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3086: $answer = 'home';
3087: } else {
1.1172.2.125 raeburn 3088: $answer = reply("unsub:$fname",$home);
1.1172.2.124 raeburn 3089: }
3090: return $answer;
3091: }
3092:
1.330 www 3093: # ------------------------------------------------ Get server side include body
3094: sub ssi_body {
1.381 albertel 3095: my ($filelink,%form)=@_;
1.606 matthew 3096: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3097: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3098: }
1.953 www 3099: my $output='';
3100: my $response;
1.980 raeburn 3101: if ($filelink=~/^https?\:/) {
1.954 raeburn 3102: ($output,$response)=&externalssi($filelink);
1.953 www 3103: } else {
1.1004 droeschl 3104: $filelink .= $filelink=~/\?/ ? '&' : '?';
3105: $filelink .= 'inhibitmenu=yes';
1.953 www 3106: ($output,$response)=&ssi($filelink,%form);
3107: }
1.778 albertel 3108: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3109: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3110: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3111: if (wantarray) {
3112: return ($output, $response);
3113: } else {
3114: return $output;
3115: }
1.8 www 3116: }
3117:
1.15 www 3118: # --------------------------------------------------------- Server Side Include
3119:
1.782 albertel 3120: sub absolute_url {
3121: my ($host_name) = @_;
3122: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3123: if ($host_name eq '') {
3124: $host_name = $ENV{'SERVER_NAME'};
3125: }
3126: return $protocol.$host_name;
3127: }
3128:
1.942 foxr 3129: #
3130: # Server side include.
3131: # Parameters:
3132: # fn Possibly encrypted resource name/id.
3133: # form Hash that describes how the rendering should be done
3134: # and other things.
1.944 foxr 3135: # Returns:
1.950 raeburn 3136: # Scalar context: The content of the response.
3137: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3138: #
1.15 www 3139: sub ssi {
3140:
1.944 foxr 3141: my ($fn,%form)=@_;
1.1172.2.100 raeburn 3142: my ($request,$response);
1.711 albertel 3143:
3144: $form{'no_update_last_known'}=1;
1.895 albertel 3145: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3146: if (%form) {
1.782 albertel 3147: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 3148: $request->content(join('&',map {
3149: my $name = escape($_);
3150: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3151: ? join("&$name=", map {escape($_) } @{$form{$_}})
3152: : &escape($form{$_}) );
3153: } keys(%form)));
1.23 www 3154: } else {
1.782 albertel 3155: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3156: }
3157:
1.15 www 3158: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100 raeburn 3159:
1.1172.2.101 raeburn 3160: if (($env{'request.course.id'}) &&
3161: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3162: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3163: ($form{'grade_symb'} ne '') &&
3164: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3165: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100 raeburn 3166: if (LWP::UserAgent->VERSION >= 5.834) {
3167: my $ua=new LWP::UserAgent;
3168: $ua->local_address('127.0.0.1');
3169: $response = $ua->request($request);
3170: } else {
3171: {
3172: require LWP::Protocol::http;
3173: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
3174: my $ua=new LWP::UserAgent;
3175: $response = $ua->request($request);
3176: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
3177: }
3178: }
3179: } else {
3180: my $ua=new LWP::UserAgent;
3181: $response = $ua->request($request);
3182: }
1.944 foxr 3183: if (wantarray) {
1.1172.2.3 raeburn 3184: return ($response->content, $response);
1.944 foxr 3185: } else {
1.1172.2.3 raeburn 3186: return $response->content;
1.942 foxr 3187: }
1.324 www 3188: }
3189:
3190: sub externalssi {
3191: my ($url)=@_;
3192: my $ua=new LWP::UserAgent;
3193: my $request=new HTTP::Request('GET',$url);
3194: my $response=$ua->request($request);
1.954 raeburn 3195: if (wantarray) {
3196: return ($response->content, $response);
3197: } else {
3198: return $response->content;
3199: }
1.15 www 3200: }
1.254 www 3201:
1.1172.2.98 raeburn 3202: # If the local copy of a replicated resource is outdated, trigger a
3203: # connection from the homeserver to flush the delayed queue. If no update
3204: # happens, remove local copies of outdated resource (and corresponding
3205: # metadata file).
3206:
3207: sub remove_stale_resfile {
3208: my ($url) = @_;
3209: my $removed;
3210: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3211: my $audom = $1;
3212: my $auname = $2;
3213: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3214: my $homeserver = &homeserver($auname,$audom);
3215: unless (($homeserver eq 'no_host') ||
3216: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3217: my $fname = &filelocation('',$url);
3218: if (-e $fname) {
3219: my $hostname = &hostname($homeserver);
3220: if ($hostname) {
1.1172.2.120 raeburn 3221: my $protocol = $protocol{$homeserver};
3222: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98 raeburn 3223: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120 raeburn 3224: my $ua=new LWP::UserAgent;
3225: $ua->timeout(5);
1.1172.2.98 raeburn 3226: my $request=new HTTP::Request('HEAD',$uri);
3227: my $response=$ua->request($request);
3228: if ($response->is_success()) {
3229: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3230: my $locmodtime = (stat($fname))[9];
3231: if ($locmodtime < $remmodtime) {
3232: my $stale;
3233: my $answer = &reply('pong',$homeserver);
3234: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3235: sleep(0.2);
3236: $locmodtime = (stat($fname))[9];
3237: if ($locmodtime < $remmodtime) {
3238: my $posstransfer = $fname.'.in.transfer';
3239: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3240: $removed = 1;
3241: } else {
3242: $stale = 1;
3243: }
3244: } else {
3245: $removed = 1;
3246: }
3247: } else {
3248: $stale = 1;
3249: }
3250: if ($stale) {
1.1172.2.124 raeburn 3251: if (unlink($fname)) {
3252: if ($uri!~/\.meta$/) {
3253: if (-e $fname.'.meta') {
3254: unlink($fname.'.meta');
3255: }
3256: }
3257: my $unsubresult = &unsubscribe($fname);
3258: unless ($unsubresult eq 'ok') {
3259: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3260: }
3261: $removed = 1;
1.1172.2.98 raeburn 3262: }
3263: }
3264: }
3265: }
3266: }
3267: }
3268: }
3269: }
3270: }
3271: return $removed;
3272: }
3273:
1.492 albertel 3274: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3275:
3276: sub allowuploaded {
3277: my ($srcurl,$url)=@_;
3278: $url=&clutter(&declutter($url));
3279: my $dir=$url;
3280: $dir=~s/\/[^\/]+$//;
3281: my %httpref=();
3282: my $httpurl=&hreflocation('',$url);
3283: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3284: &Apache::lonnet::appenv(\%httpref);
1.254 www 3285: }
1.477 raeburn 3286:
1.1172.2.13 raeburn 3287: #
3288: # Determine if the current user should be able to edit a particular resource,
3289: # when viewing in course context.
3290: # (a) When viewing resource used to determine if "Edit" item is included in
3291: # Functions.
3292: # (b) When displaying folder contents in course editor, used to determine if
3293: # "Edit" link will be displayed alongside resource.
3294: #
3295: # input: six args -- filename (decluttered), course number, course domain,
3296: # url, symb (if registered) and group (if this is a group
3297: # item -- e.g., bulletin board, group page etc.).
3298: # output: array of five scalars --
3299: # $cfile -- url for file editing if editable on current server
3300: # $home -- homeserver of resource (i.e., for author if published,
3301: # or course if uploaded.).
3302: # $switchserver -- 1 if server switch will be needed.
3303: # $forceedit -- 1 if icon/link should be to go to edit mode
3304: # $forceview -- 1 if icon/link should be to go to view mode
3305: #
3306:
3307: sub can_edit_resource {
3308: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3309: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3310: #
3311: # For aboutme pages user can only edit his/her own.
3312: #
3313: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3314: my ($sdom,$sname) = ($1,$2);
3315: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3316: $home = $env{'user.home'};
3317: $cfile = $resurl;
3318: if ($env{'form.forceedit'}) {
3319: $forceview = 1;
3320: } else {
3321: $forceedit = 1;
3322: }
3323: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3324: } else {
3325: return;
3326: }
3327: }
3328:
3329: if ($env{'request.course.id'}) {
3330: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3331: if ($group ne '') {
3332: # if this is a group homepage or group bulletin board, check group privs
3333: my $allowed = 0;
3334: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3335: if ((&allowed('mdg',$env{'request.course.id'}.
3336: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3337: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3338: $allowed = 1;
3339: }
3340: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3341: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3342: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3343: $allowed = 1;
3344: }
3345: }
3346: if ($allowed) {
3347: $home=&homeserver($cnum,$cdom);
3348: if ($env{'form.forceedit'}) {
3349: $forceview = 1;
3350: } else {
3351: $forceedit = 1;
3352: }
3353: $cfile = $resurl;
3354: } else {
3355: return;
3356: }
3357: } else {
1.1172.2.15 raeburn 3358: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3359: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3360: return;
3361: }
3362: } elsif (!$crsedit) {
1.1172.2.13 raeburn 3363: #
3364: # No edit allowed where CC has switched to student role.
3365: #
3366: return;
3367: }
3368: }
3369: }
3370:
3371: if ($file ne '') {
3372: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3373: if (&is_course_upload($file,$cnum,$cdom)) {
3374: $uploaded = 1;
3375: $incourse = 1;
3376: if ($file =~/\.(htm|html|css|js|txt)$/) {
3377: $cfile = &hreflocation('',$file);
3378: if ($env{'form.forceedit'}) {
3379: $forceview = 1;
3380: } else {
3381: $forceedit = 1;
3382: }
3383: }
3384: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3385: $incourse = 1;
3386: if ($env{'form.forceedit'}) {
3387: $forceview = 1;
3388: } else {
3389: $forceedit = 1;
3390: }
3391: $cfile = $resurl;
3392: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3393: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3394: $incourse = 1;
3395: if ($env{'form.forceedit'}) {
3396: $forceview = 1;
3397: } else {
3398: $forceedit = 1;
3399: }
3400: $cfile = $resurl;
3401: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3402: $incourse = 1;
3403: $cfile = $resurl.'/smpedit';
3404: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3405: $incourse = 1;
3406: if ($env{'form.forceedit'}) {
3407: $forceview = 1;
3408: } else {
3409: $forceedit = 1;
3410: }
3411: $cfile = $resurl;
1.1172.2.122 raeburn 3412: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3413: my ($map,$id,$res) = &decode_symb($symb);
3414: if ($map =~ /\.page$/) {
3415: $incourse = 1;
3416: if ($env{'form.forceedit'}) {
3417: $forceview = 1;
3418: $cfile = $map;
3419: } else {
3420: $forceedit = 1;
3421: $cfile = '/adm/wrapper'.$resurl;
3422: }
3423: }
1.1172.2.15 raeburn 3424: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3425: $incourse = 1;
3426: if ($env{'form.forceedit'}) {
3427: $forceview = 1;
3428: } else {
3429: $forceedit = 1;
3430: }
3431: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3432: }
3433: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3434: my $template = '/res/lib/templates/simpleproblem.problem';
3435: if (&is_on_map($template)) {
3436: $incourse = 1;
3437: $forceview = 1;
3438: $cfile = $template;
3439: }
3440: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118 raeburn 3441: $incourse = 1;
3442: if ($env{'form.forceedit'}) {
3443: $forceview = 1;
3444: } else {
3445: $forceedit = 1;
3446: }
3447: $cfile = $resurl;
1.1172.2.13 raeburn 3448: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3449: $incourse = 1;
3450: $forceview = 1;
3451: if ($symb) {
3452: my ($map,$id,$res)=&decode_symb($symb);
3453: $env{'request.symb'} = $symb;
3454: $cfile = &clutter($res);
3455: } else {
3456: $cfile = $env{'form.suppurl'};
3457: $cfile =~ s{^http://}{};
3458: $cfile = '/adm/wrapper/ext/'.$cfile;
3459: }
1.1172.2.31 raeburn 3460: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3461: if ($env{'form.forceedit'}) {
3462: $forceview = 1;
3463: } else {
3464: $forceedit = 1;
3465: }
3466: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3467: }
3468: }
3469: if ($uploaded || $incourse) {
3470: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3471: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3472: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3473: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3474: # Check that the user has permission to edit this resource
3475: my $setpriv = 1;
3476: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3477: if (defined($cfudom)) {
3478: $home=&homeserver($cfuname,$cfudom);
3479: $cfile=$file;
3480: }
3481: }
3482: if (($cfile ne '') && (!$incourse || $uploaded) &&
3483: (($home ne '') && ($home ne 'no_host'))) {
3484: my @ids=¤t_machine_ids();
3485: unless (grep(/^\Q$home\E$/,@ids)) {
3486: $switchserver=1;
3487: }
3488: }
3489: }
3490: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3491: }
3492:
3493: sub is_course_upload {
3494: my ($file,$cnum,$cdom) = @_;
3495: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3496: $uploadpath =~ s{^\/}{};
3497: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3498: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3499: return 1;
3500: }
3501: return;
3502: }
3503:
3504: sub in_course {
3505: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3506: if ($hideprivileged) {
3507: my $skipuser;
1.1172.2.23 raeburn 3508: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3509: my @possdoms = ($cdom);
3510: if ($coursehash{'checkforpriv'}) {
3511: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3512: }
3513: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3514: $skipuser = 1;
3515: if ($coursehash{'nothideprivileged'}) {
3516: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3517: my $user;
3518: if ($item =~ /:/) {
3519: $user = $item;
3520: } else {
3521: $user = join(':',split(/[\@]/,$item));
3522: }
3523: if ($user eq $uname.':'.$udom) {
3524: undef($skipuser);
3525: last;
3526: }
3527: }
3528: }
3529: if ($skipuser) {
3530: return 0;
3531: }
3532: }
3533: }
3534: $type ||= 'any';
3535: if (!defined($cdom) || !defined($cnum)) {
3536: my $cid = $env{'request.course.id'};
3537: $cdom = $env{'course.'.$cid.'.domain'};
3538: $cnum = $env{'course.'.$cid.'.num'};
3539: }
3540: my $typesref;
3541: if (($type eq 'any') || ($type eq 'all')) {
3542: $typesref = ['active','previous','future'];
3543: } elsif ($type eq 'previous' || $type eq 'future') {
3544: $typesref = [$type];
3545: }
3546: my %roles = &get_my_roles($uname,$udom,'userroles',
3547: $typesref,undef,[$cdom]);
3548: my ($tmp) = keys(%roles);
3549: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3550: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3551: if (@course_roles > 0) {
3552: return 1;
3553: }
3554: return 0;
3555: }
3556:
1.478 albertel 3557: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3558: # input: action, courseID, current domain, intended
1.637 raeburn 3559: # path to file, source of file, instruction to parse file for objects,
3560: # ref to hash for embedded objects,
3561: # ref to hash for codebase of java objects.
1.1095 raeburn 3562: # reference to scalar to accommodate mime type determined
3563: # from File::MMagic if $parser = parse.
1.637 raeburn 3564: #
1.485 raeburn 3565: # output: url to file (if action was uploaddoc),
3566: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3567: #
1.478 albertel 3568: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3569: # course.
1.477 raeburn 3570: #
1.478 albertel 3571: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3572: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3573: # course's home server.
1.477 raeburn 3574: #
1.478 albertel 3575: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3576: # be copied from $source (current location) to
3577: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3578: # and will then be copied to
3579: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3580: # course's home server.
1.485 raeburn 3581: #
1.481 raeburn 3582: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3583: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3584: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3585: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3586: # in course's home server.
1.637 raeburn 3587: #
1.477 raeburn 3588:
3589: sub process_coursefile {
1.1095 raeburn 3590: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3591: $mimetype)=@_;
1.477 raeburn 3592: my $fetchresult;
1.638 albertel 3593: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3594: if ($action eq 'propagate') {
1.638 albertel 3595: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3596: $home);
1.481 raeburn 3597: } else {
1.477 raeburn 3598: my $fpath = '';
3599: my $fname = $file;
1.478 albertel 3600: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3601: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3602: my $filepath = &build_filepath($fpath);
1.481 raeburn 3603: if ($action eq 'copy') {
3604: if ($source eq '') {
3605: $fetchresult = 'no source file';
3606: return $fetchresult;
3607: } else {
3608: my $destination = $filepath.'/'.$fname;
3609: rename($source,$destination);
3610: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3611: $home);
1.481 raeburn 3612: }
3613: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 3614: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3615: print $fh $env{'form.'.$source};
1.481 raeburn 3616: close($fh);
1.637 raeburn 3617: if ($parser eq 'parse') {
1.1024 raeburn 3618: my $mm = new File::MMagic;
1.1095 raeburn 3619: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3620: if ($type eq 'text/html') {
1.1024 raeburn 3621: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3622: unless ($parse_result eq 'ok') {
3623: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3624: }
1.637 raeburn 3625: }
1.1095 raeburn 3626: if (ref($mimetype)) {
3627: $$mimetype = $type;
3628: }
1.637 raeburn 3629: }
1.477 raeburn 3630: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3631: $home);
1.481 raeburn 3632: if ($fetchresult eq 'ok') {
3633: return '/uploaded/'.$fpath.'/'.$fname;
3634: } else {
3635: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3636: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3637: return '/adm/notfound.html';
3638: }
1.477 raeburn 3639: }
3640: }
1.485 raeburn 3641: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3642: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3643: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3644: }
3645: return $fetchresult;
3646: }
3647:
1.637 raeburn 3648: sub build_filepath {
3649: my ($fpath) = @_;
3650: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3651: unless ($fpath eq '') {
3652: my @parts=split('/',$fpath);
3653: foreach my $part (@parts) {
3654: $filepath.= '/'.$part;
3655: if ((-e $filepath)!=1) {
3656: mkdir($filepath,0777);
3657: }
3658: }
3659: }
3660: return $filepath;
3661: }
3662:
3663: sub store_edited_file {
1.638 albertel 3664: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3665: my $file = $primary_url;
3666: $file =~ s#^/uploaded/$docudom/$docuname/##;
3667: my $fpath = '';
3668: my $fname = $file;
3669: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3670: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3671: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 3672: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3673: print $fh $content;
3674: close($fh);
1.638 albertel 3675: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3676: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3677: $home);
1.637 raeburn 3678: if ($$fetchresult eq 'ok') {
3679: return '/uploaded/'.$fpath.'/'.$fname;
3680: } else {
1.638 albertel 3681: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3682: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3683: return '/adm/notfound.html';
3684: }
3685: }
3686:
1.531 albertel 3687: sub clean_filename {
1.831 albertel 3688: my ($fname,$args)=@_;
1.315 www 3689: # Replace Windows backslashes by forward slashes
1.257 www 3690: $fname=~s/\\/\//g;
1.831 albertel 3691: if (!$args->{'keep_path'}) {
3692: # Get rid of everything but the actual filename
3693: $fname=~s/^.*\/([^\/]+)$/$1/;
3694: }
1.315 www 3695: # Replace spaces by underscores
3696: $fname=~s/\s+/\_/g;
1.1172.2.110 raeburn 3697: # Transliterate non-ascii text to ascii
3698: my $lang = &Apache::lonlocal::current_language();
3699: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 3700: # Replace all other weird characters by nothing
1.831 albertel 3701: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3702: # Replace all .\d. sequences with _\d. so they no longer look like version
3703: # numbers
3704: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3705: return $fname;
3706: }
1.1172.2.110 raeburn 3707:
1.1051 raeburn 3708: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3709: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3710: # image with the same aspect ratio as the original, but with dimensions which do
3711: # not exceed $resizewidth and $resizeheight.
3712:
1.984 neumanie 3713: sub resizeImage {
1.1051 raeburn 3714: my ($img_path,$resizewidth,$resizeheight) = @_;
3715: my $ima = Image::Magick->new;
3716: my $resized;
3717: if (-e $img_path) {
3718: $ima->Read($img_path);
3719: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3720: my $width = $ima->Get('width');
3721: my $height = $ima->Get('height');
3722: if ($width > $resizewidth) {
3723: my $factor = $width/$resizewidth;
3724: my $newheight = $height/$factor;
3725: $ima->Scale(width=>$resizewidth,height=>$newheight);
3726: $resized = 1;
3727: }
3728: }
3729: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3730: my $width = $ima->Get('width');
3731: my $height = $ima->Get('height');
3732: if ($height > $resizeheight) {
3733: my $factor = $height/$resizeheight;
3734: my $newwidth = $width/$factor;
3735: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3736: $resized = 1;
3737: }
3738: }
3739: if ($resized) {
3740: $ima->Write($img_path);
3741: }
3742: }
3743: return;
1.977 amueller 3744: }
3745:
1.608 albertel 3746: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3747: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3748: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3749: # $context - possible values: coursedoc, existingfile, overwrite,
1.1172.2.109 raeburn 3750: # canceloverwrite, scantron or ''.
1.1090 raeburn 3751: # if 'coursedoc': upload to the current course
3752: # if 'existingfile': write file to tmp/overwrites directory
3753: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3754: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3755: # $subdir - directory in userfile to store the file into
1.1172.2.109 raeburn 3756: # $parser - instruction to parse file for objects ($parser = parse) or
3757: # if context is 'scantron', $parser is hashref of csv column mapping
3758: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3759: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 3760: # $allfiles - reference to hash for embedded objects
3761: # $codebase - reference to hash for codebase of java objects
3762: # $desuname - username for permanent storage of uploaded file
3763: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3764: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3765: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3766: # $resizewidth - width (pixels) to which to resize uploaded image
3767: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3768: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3769: # from File::MMagic.
1.858 raeburn 3770: #
1.686 albertel 3771: # output: url of file in userspace, or error: <message>
3772: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3773:
1.531 albertel 3774: sub userfileupload {
1.1090 raeburn 3775: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3776: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3777: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3778: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3779: $fname=&clean_filename($fname);
1.1090 raeburn 3780: # See if there is anything left
1.257 www 3781: unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110 raeburn 3782: # If filename now begins with a . prepend unix timestamp _ milliseconds
3783: if ($fname =~ /^\./) {
3784: my ($s,$usec) = &gettimeofday();
3785: while (length($usec) < 6) {
3786: $usec = '0'.$usec;
3787: }
3788: $fname = $s.'_'.substr($usec,0,3).$fname;
3789: }
1.1090 raeburn 3790: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3791: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3792: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3793: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3794: my $now = time;
1.1090 raeburn 3795: my $filepath;
1.1095 raeburn 3796: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3797: $filepath = 'tmp/helprequests/'.$now;
3798: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3799: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3800: '_'.$env{'user.domain'}.'/pending';
3801: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3802: my ($docuname,$docudom);
1.1172.2.96 raeburn 3803: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3804: $docudom = $destudom;
3805: } else {
3806: $docudom = $env{'user.domain'};
3807: }
1.1172.2.96 raeburn 3808: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3809: $docuname = $destuname;
3810: } else {
3811: $docuname = $env{'user.name'};
3812: }
3813: if (exists($env{'form.group'})) {
3814: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3815: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3816: }
3817: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3818: if ($context eq 'canceloverwrite') {
3819: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3820: if (-e $tempfile) {
3821: my @info = stat($tempfile);
3822: if ($info[9] eq $env{'form.timestamp'}) {
3823: unlink($tempfile);
3824: }
3825: }
3826: return;
1.523 raeburn 3827: }
3828: }
1.1090 raeburn 3829: # Create the directory if not present
1.741 raeburn 3830: my @parts=split(/\//,$filepath);
3831: my $fullpath = $perlvar{'lonDaemons'};
3832: for (my $i=0;$i<@parts;$i++) {
3833: $fullpath .= '/'.$parts[$i];
3834: if ((-e $fullpath)!=1) {
3835: mkdir($fullpath,0777);
3836: }
3837: }
1.1172.2.96 raeburn 3838: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3839: print $fh $env{'form.'.$formname};
3840: close($fh);
1.1090 raeburn 3841: if ($context eq 'existingfile') {
3842: my @info = stat($fullpath.'/'.$fname);
3843: return ($fullpath.'/'.$fname,$info[9]);
3844: } else {
3845: return $fullpath.'/'.$fname;
3846: }
1.523 raeburn 3847: }
1.995 raeburn 3848: if ($subdir eq 'scantron') {
3849: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3850: } else {
1.995 raeburn 3851: $fname="$subdir/$fname";
3852: }
1.1090 raeburn 3853: if ($context eq 'coursedoc') {
1.638 albertel 3854: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3855: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3856: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3857: return &finishuserfileupload($docuname,$docudom,
3858: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3859: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3860: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3861: } else {
1.1172.2.21 raeburn 3862: if ($env{'form.folder'}) {
3863: $fname=$env{'form.folder'}.'/'.$fname;
3864: }
1.638 albertel 3865: return &process_coursefile('uploaddoc',$docuname,$docudom,
3866: $fname,$formname,$parser,
1.1095 raeburn 3867: $allfiles,$codebase,$mimetype);
1.481 raeburn 3868: }
1.719 banghart 3869: } elsif (defined($destuname)) {
3870: my $docuname=$destuname;
3871: my $docudom=$destudom;
1.860 raeburn 3872: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3873: $parser,$allfiles,$codebase,
1.1051 raeburn 3874: $thumbwidth,$thumbheight,
1.1095 raeburn 3875: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3876: } else {
1.638 albertel 3877: my $docuname=$env{'user.name'};
3878: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3879: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3880: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3881: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3882: }
1.860 raeburn 3883: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3884: $parser,$allfiles,$codebase,
1.1051 raeburn 3885: $thumbwidth,$thumbheight,
1.1095 raeburn 3886: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3887: }
1.271 www 3888: }
3889:
3890: sub finishuserfileupload {
1.860 raeburn 3891: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3892: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3893: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3894: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3895:
1.860 raeburn 3896: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3897: $file=$fname;
3898: if ($fname=~m|/|) {
3899: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3900: $path.=$fnamepath.'/';
3901: }
1.259 www 3902: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3903: my $count;
3904: for ($count=4;$count<=$#parts;$count++) {
3905: $filepath.="/$parts[$count]";
3906: if ((-e $filepath)!=1) {
3907: mkdir($filepath,0777);
3908: }
3909: }
1.984 neumanie 3910:
1.258 www 3911: # Save the file
3912: {
1.1172.2.96 raeburn 3913: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 3914: &logthis('Failed to create '.$filepath.'/'.$file);
3915: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3916: return '/adm/notfound.html';
3917: }
1.1090 raeburn 3918: if ($context eq 'overwrite') {
1.1117 foxr 3919: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3920: my $target = $filepath.'/'.$file;
3921: if (-e $source) {
3922: my @info = stat($source);
3923: if ($info[9] eq $env{'form.timestamp'}) {
3924: unless (&File::Copy::move($source,$target)) {
3925: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3926: return "Moving from $source failed";
3927: }
3928: } else {
3929: return "Temporary file: $source had unexpected date/time for last modification";
3930: }
3931: } else {
3932: return "Temporary file: $source missing";
3933: }
3934: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3935: &logthis('Failed to write to '.$filepath.'/'.$file);
3936: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3937: return '/adm/notfound.html';
3938: }
1.570 albertel 3939: close(FH);
1.1051 raeburn 3940: if ($resizewidth && $resizeheight) {
3941: my $mm = new File::MMagic;
3942: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3943: if ($mime_type =~ m{^image/}) {
3944: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3945: }
1.977 amueller 3946: }
1.258 www 3947: }
1.1152 raeburn 3948: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3949: if (ref($mimetype)) {
3950: if ($$mimetype eq '') {
3951: my $mm = new File::MMagic;
3952: my $type = $mm->checktype_filename($filepath.'/'.$file);
3953: $$mimetype = $type;
3954: }
3955: }
3956: }
1.1172.2.109 raeburn 3957: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 3958: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3959: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3960: $allfiles,$codebase);
3961: unless ($parse_result eq 'ok') {
3962: &logthis('Failed to parse '.$filepath.$file.
3963: ' for embedded media: '.$parse_result);
3964: }
1.637 raeburn 3965: }
1.1172.2.109 raeburn 3966: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
3967: my $format = $env{'form.scantron_format'};
3968: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 3969: }
1.860 raeburn 3970: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3971: my $input = $filepath.'/'.$file;
3972: my $output = $filepath.'/'.'tn-'.$file;
3973: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96 raeburn 3974: my @args = ('convert','-sample',$thumbsize,$input,$output);
3975: system({$args[0]} @args);
1.860 raeburn 3976: if (-e $filepath.'/'.'tn-'.$file) {
3977: $fetchthumb = 1;
3978: }
3979: }
1.858 raeburn 3980:
1.259 www 3981: # Notify homeserver to grep it
3982: #
1.984 neumanie 3983: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3984: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3985: if ($fetchresult eq 'ok') {
1.860 raeburn 3986: if ($fetchthumb) {
3987: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3988: if ($thumbresult ne 'ok') {
3989: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3990: $docuhome.': '.$thumbresult);
3991: }
3992: }
1.259 www 3993: #
1.258 www 3994: # Return the URL to it
1.494 albertel 3995: return '/uploaded/'.$path.$file;
1.263 www 3996: } else {
1.494 albertel 3997: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3998: ': '.$fetchresult);
1.263 www 3999: return '/adm/notfound.html';
1.858 raeburn 4000: }
1.493 albertel 4001: }
4002:
1.637 raeburn 4003: sub extract_embedded_items {
1.961 raeburn 4004: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4005: my @state = ();
1.1164 raeburn 4006: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4007: my %javafiles = (
4008: codebase => '',
4009: code => '',
4010: archive => ''
4011: );
4012: my %mediafiles = (
4013: src => '',
4014: movie => '',
4015: );
1.648 raeburn 4016: my $p;
4017: if ($content) {
4018: $p = HTML::LCParser->new($content);
4019: } else {
1.961 raeburn 4020: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4021: }
1.641 albertel 4022: while (my $t=$p->get_token()) {
1.640 albertel 4023: if ($t->[0] eq 'S') {
4024: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4025: push(@state, $tagname);
1.648 raeburn 4026: if (lc($tagname) eq 'allow') {
4027: &add_filetype($allfiles,$attr->{'src'},'src');
4028: }
1.640 albertel 4029: if (lc($tagname) eq 'img') {
4030: &add_filetype($allfiles,$attr->{'src'},'src');
4031: }
1.886 albertel 4032: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 4033: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4034: &add_filetype($allfiles,$attr->{'href'},'href');
4035: }
1.886 albertel 4036: }
1.645 raeburn 4037: if (lc($tagname) eq 'script') {
1.1164 raeburn 4038: my $src;
1.645 raeburn 4039: if ($attr->{'archive'} =~ /\.jar$/i) {
4040: &add_filetype($allfiles,$attr->{'archive'},'archive');
4041: } else {
1.1164 raeburn 4042: if ($attr->{'src'} ne '') {
4043: $src = $attr->{'src'};
4044: &add_filetype($allfiles,$src,'src');
4045: }
4046: }
4047: my $text = $p->get_trimmed_text();
4048: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4049: my @swfargs = split(/,/,$1);
4050: foreach my $item (@swfargs) {
4051: $item =~ s/["']//g;
4052: $item =~ s/^\s+//;
4053: $item =~ s/\s+$//;
4054: }
4055: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4056: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4057: push(@{$related{$swfargs[0]}},$swfargs[2]);
4058: } else {
4059: $related{$swfargs[0]} = [$swfargs[2]];
4060: }
4061: }
1.645 raeburn 4062: }
4063: }
4064: if (lc($tagname) eq 'link') {
4065: if (lc($attr->{'rel'}) eq 'stylesheet') {
4066: &add_filetype($allfiles,$attr->{'href'},'href');
4067: }
4068: }
1.640 albertel 4069: if (lc($tagname) eq 'object' ||
4070: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4071: foreach my $item (keys(%javafiles)) {
4072: $javafiles{$item} = '';
4073: }
1.1164 raeburn 4074: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4075: $lastids{lc($tagname)} = $attr->{'id'};
4076: }
1.640 albertel 4077: }
4078: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4079: my $name = lc($attr->{'name'});
4080: foreach my $item (keys(%javafiles)) {
4081: if ($name eq $item) {
4082: $javafiles{$item} = $attr->{'value'};
4083: last;
4084: }
4085: }
1.1164 raeburn 4086: my $pathfrom;
1.640 albertel 4087: foreach my $item (keys(%mediafiles)) {
4088: if ($name eq $item) {
1.1164 raeburn 4089: $pathfrom = $attr->{'value'};
4090: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4091: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4092: last;
4093: }
4094: }
1.1164 raeburn 4095: if ($name eq 'flashvars') {
4096: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4097: }
4098: if ($pathfrom ne '') {
4099: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4100: $pathfrom);
4101: }
1.640 albertel 4102: }
4103: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4104: foreach my $item (keys(%javafiles)) {
4105: if ($attr->{$item}) {
4106: $javafiles{$item} = $attr->{$item};
4107: last;
4108: }
4109: }
4110: foreach my $item (keys(%mediafiles)) {
4111: if ($attr->{$item}) {
4112: &add_filetype($allfiles,$attr->{$item},$item);
4113: last;
4114: }
4115: }
1.1164 raeburn 4116: if (lc($tagname) eq 'embed') {
4117: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4118: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4119: $attr->{'src'});
4120: }
4121: }
1.640 albertel 4122: }
1.1172.2.35 raeburn 4123: if (lc($tagname) eq 'iframe') {
4124: my $src = $attr->{'src'} ;
4125: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4126: &add_filetype($allfiles,$src,'src');
4127: } elsif ($src =~ m{^/}) {
4128: if ($env{'request.course.id'}) {
4129: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4130: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4131: my $url = &hreflocation('',$fullpath);
4132: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4133: my $relpath = $1;
4134: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4135: &add_filetype($allfiles,$1,'src');
4136: }
4137: }
4138: }
4139: }
4140: }
1.1164 raeburn 4141: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 4142: pop(@state);
1.1164 raeburn 4143: }
1.640 albertel 4144: } elsif ($t->[0] eq 'E') {
4145: my ($tagname) = ($t->[1]);
4146: if ($javafiles{'codebase'} ne '') {
4147: $javafiles{'codebase'} .= '/';
4148: }
4149: if (lc($tagname) eq 'applet' ||
4150: lc($tagname) eq 'object' ||
4151: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4152: ) {
4153: foreach my $item (keys(%javafiles)) {
4154: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4155: my $file=$javafiles{'codebase'}.$javafiles{$item};
4156: &add_filetype($allfiles,$file,$item);
4157: }
4158: }
4159: }
4160: pop @state;
4161: }
4162: }
1.1164 raeburn 4163: foreach my $id (sort(keys(%flashvars))) {
4164: if ($shockwave{$id} ne '') {
4165: my @pairs = split(/\&/,$flashvars{$id});
4166: foreach my $pair (@pairs) {
4167: my ($key,$value) = split(/\=/,$pair);
4168: if ($key eq 'thumb') {
4169: &add_filetype($allfiles,$value,$key);
4170: } elsif ($key eq 'content') {
4171: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4172: my ($ext) = ($value =~ /\.([^.]+)$/);
4173: if ($ext ne '') {
4174: &add_filetype($allfiles,$path.$value,$ext);
4175: }
4176: }
4177: }
4178: }
4179: }
1.637 raeburn 4180: return 'ok';
4181: }
4182:
1.639 albertel 4183: sub add_filetype {
4184: my ($allfiles,$file,$type)=@_;
4185: if (exists($allfiles->{$file})) {
4186: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4187: push(@{$allfiles->{$file}}, &escape($type));
4188: }
4189: } else {
4190: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4191: }
4192: }
4193:
1.1164 raeburn 4194: sub embedded_dependency {
4195: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4196: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4197: if (($identifier ne '') &&
4198: (ref($related->{$identifier}) eq 'ARRAY') &&
4199: ($pathfrom ne '')) {
4200: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4201: foreach my $dep (@{$related->{$identifier}}) {
4202: &add_filetype($allfiles,$path.$dep,'object');
4203: }
4204: }
4205: }
4206: return;
4207: }
4208:
1.1172.2.109 raeburn 4209: sub bubblesheet_converter {
4210: my ($cdom,$fullpath,$config,$format) = @_;
4211: if ((&domain($cdom) ne '') &&
4212: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4213: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4214: my (%csvcols,%csvoptions);
4215: if (ref($config->{'fields'}) eq 'HASH') {
4216: %csvcols = %{$config->{'fields'}};
4217: }
4218: if (ref($config->{'options'}) eq 'HASH') {
4219: %csvoptions = %{$config->{'options'}};
4220: }
4221: my %csvbynum = reverse(%csvcols);
4222: my %scantronconf = &get_scantron_config($format,$cdom);
4223: if (keys(%scantronconf)) {
4224: my %bynum = (
4225: $scantronconf{CODEstart} => 'CODEstart',
4226: $scantronconf{IDstart} => 'IDstart',
4227: $scantronconf{PaperID} => 'PaperID',
4228: $scantronconf{FirstName} => 'FirstName',
4229: $scantronconf{LastName} => 'LastName',
4230: $scantronconf{Qstart} => 'Qstart',
4231: );
4232: my @ordered;
4233: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4234: push(@ordered,$bynum{$item});
4235: }
4236: my %mapstart = (
4237: CODEstart => 'CODE',
4238: IDstart => 'ID',
4239: PaperID => 'PaperID',
4240: FirstName => 'FirstName',
4241: LastName => 'LastName',
4242: Qstart => 'FirstQuestion',
4243: );
4244: my %maplength = (
4245: CODEstart => 'CODElength',
4246: IDstart => 'IDlength',
4247: PaperID => 'PaperIDlength',
4248: FirstName => 'FirstNamelength',
4249: LastName => 'LastNamelength',
4250: );
4251: if (open(my $fh,'<',$fullpath)) {
4252: my $output;
4253: my %lettdig = &letter_to_digits();
4254: my %diglett = reverse(%lettdig);
4255: my $numletts = scalar(keys(%lettdig));
4256: my $num = 0;
4257: while (my $line=<$fh>) {
4258: $num ++;
4259: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4260: $line =~ s{[\r\n]+$}{};
4261: my %found;
4262: my @values = split(/,/,$line);
4263: my ($qstart,$record);
4264: for (my $i=0; $i<@values; $i++) {
4265: if ((($qstart ne '') && ($i > $qstart)) ||
4266: ($csvbynum{$i} eq 'FirstQuestion')) {
4267: if ($values[$i] eq '') {
4268: $values[$i] = $scantronconf{'Qoff'};
4269: } elsif ($scantronconf{'Qon'} eq 'number') {
4270: if ($values[$i] =~ /^[A-Ja-j]$/) {
4271: $values[$i] = $lettdig{uc($values[$i])};
4272: }
4273: } elsif ($scantronconf{'Qon'} eq 'letter') {
4274: if ($values[$i] =~ /^[0-9]$/) {
4275: $values[$i] = $diglett{$values[$i]};
4276: }
4277: } else {
4278: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4279: my $digit;
4280: if ($values[$i] =~ /^[A-Ja-j]$/) {
4281: $digit = $lettdig{uc($values[$i])}-1;
4282: if ($values[$i] eq 'J') {
4283: $digit += $numletts;
4284: }
4285: } elsif ($values[$i] =~ /^[0-9]$/) {
4286: $digit = $values[$i]-1;
4287: if ($values[$i] eq '0') {
4288: $digit += $numletts;
4289: }
4290: }
4291: my $qval='';
4292: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4293: if ($j == $digit) {
4294: $qval .= $scantronconf{'Qon'};
4295: } else {
4296: $qval .= $scantronconf{'Qoff'};
4297: }
4298: }
4299: $values[$i] = $qval;
4300: }
4301: }
4302: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4303: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4304: }
4305: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4306: if ($numblank > 0) {
4307: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4308: }
4309: if ($csvbynum{$i} eq 'FirstQuestion') {
4310: $qstart = $i;
4311: $found{$csvbynum{$i}} = $values[$i];
4312: } else {
4313: $found{'FirstQuestion'} .= $values[$i];
4314: }
4315: } elsif (exists($csvbynum{$i})) {
4316: if ($csvoptions{'rem'}) {
4317: $values[$i] =~ s/^\s+//;
4318: }
4319: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4320: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4321: $values[$i] = '0'.$values[$i];
4322: }
4323: }
4324: $found{$csvbynum{$i}} = $values[$i];
4325: }
4326: }
4327: foreach my $item (@ordered) {
4328: my $currlength = 1+length($record);
4329: my $numspaces = $scantronconf{$item} - $currlength;
4330: if ($numspaces > 0) {
4331: $record .= (' ' x $numspaces);
4332: }
4333: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4334: unless ($item eq 'Qstart') {
4335: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4336: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4337: }
4338: }
4339: $record .= $found{$mapstart{$item}};
4340: }
4341: }
4342: $output .= "$record\n";
4343: }
4344: close($fh);
4345: if ($output) {
4346: if (open(my $fh,'>',$fullpath)) {
4347: print $fh $output;
4348: close($fh);
4349: }
4350: }
4351: }
4352: }
4353: return;
4354: }
4355: }
4356:
4357: sub letter_to_digits {
4358: my %lettdig = (
4359: A => 1,
4360: B => 2,
4361: C => 3,
4362: D => 4,
4363: E => 5,
4364: F => 6,
4365: G => 7,
4366: H => 8,
4367: I => 9,
4368: J => 0,
4369: );
4370: return %lettdig;
4371: }
4372:
4373: sub get_scantron_config {
4374: my ($which,$cdom) = @_;
4375: my @lines = &get_scantronformat_file($cdom);
4376: my %config;
4377: #FIXME probably should move to XML it has already gotten a bit much now
4378: foreach my $line (@lines) {
4379: my ($name,$descrip)=split(/:/,$line);
4380: if ($name ne $which ) { next; }
4381: chomp($line);
4382: my @config=split(/:/,$line);
4383: $config{'name'}=$config[0];
4384: $config{'description'}=$config[1];
4385: $config{'CODElocation'}=$config[2];
4386: $config{'CODEstart'}=$config[3];
4387: $config{'CODElength'}=$config[4];
4388: $config{'IDstart'}=$config[5];
4389: $config{'IDlength'}=$config[6];
4390: $config{'Qstart'}=$config[7];
4391: $config{'Qlength'}=$config[8];
4392: $config{'Qoff'}=$config[9];
4393: $config{'Qon'}=$config[10];
4394: $config{'PaperID'}=$config[11];
4395: $config{'PaperIDlength'}=$config[12];
4396: $config{'FirstName'}=$config[13];
4397: $config{'FirstNamelength'}=$config[14];
4398: $config{'LastName'}=$config[15];
4399: $config{'LastNamelength'}=$config[16];
4400: $config{'BubblesPerRow'}=$config[17];
4401: last;
4402: }
4403: return %config;
4404: }
4405:
4406: sub get_scantronformat_file {
4407: my ($cdom) = @_;
4408: if ($cdom eq '') {
4409: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4410: }
4411: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4412: my $gottab = 0;
4413: my @lines;
4414: if (ref($domconfig{'scantron'}) eq 'HASH') {
4415: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4416: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4417: if ($formatfile ne '-1') {
4418: @lines = split("\n",$formatfile,-1);
4419: $gottab = 1;
4420: }
4421: }
4422: }
4423: if (!$gottab) {
4424: my $confname = $cdom.'-domainconfig';
4425: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4426: my $formatfile = &getfile($default);
4427: if ($formatfile ne '-1') {
4428: @lines = split("\n",$formatfile,-1);
4429: $gottab = 1;
4430: }
4431: }
4432: if (!$gottab) {
4433: my @domains = ¤t_machine_domains();
4434: if (grep(/^\Q$cdom\E$/,@domains)) {
4435: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4436: @lines = <$fh>;
4437: close($fh);
4438: }
4439: } else {
4440: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4441: @lines = <$fh>;
4442: close($fh);
4443: }
4444: }
4445: }
4446: return @lines;
4447: }
4448:
1.493 albertel 4449: sub removeuploadedurl {
1.984 neumanie 4450: my ($url)=@_;
4451: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4452: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4453: }
4454:
4455: sub removeuserfile {
4456: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4457: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4458: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4459: if ($result eq 'ok') {
1.798 raeburn 4460: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4461: my $metafile = $fname.'.meta';
4462: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4463: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4464: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4465: my $sqlresult =
1.823 albertel 4466: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4467: 'portfolio_metadata',$group,
4468: 'delete');
1.798 raeburn 4469: }
4470: }
4471: return $result;
1.257 www 4472: }
1.15 www 4473:
1.530 albertel 4474: sub mkdiruserfile {
4475: my ($docuname,$docudom,$dir)=@_;
4476: my $home=&homeserver($docuname,$docudom);
4477: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4478: }
4479:
1.531 albertel 4480: sub renameuserfile {
4481: my ($docuname,$docudom,$old,$new)=@_;
4482: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4483: my $result = &reply("renameuserfile:$docudom:$docuname:".
4484: &escape("$old").':'.&escape("$new"),$home);
4485: if ($result eq 'ok') {
4486: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4487: my $oldmeta = $old.'.meta';
4488: my $newmeta = $new.'.meta';
4489: my $metaresult =
4490: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4491: my $url = "/uploaded/$docudom/$docuname/$old";
4492: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4493: my $sqlresult =
1.823 albertel 4494: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4495: 'portfolio_metadata',$group,
4496: 'delete');
1.798 raeburn 4497: }
4498: }
4499: return $result;
1.531 albertel 4500: }
4501:
1.14 www 4502: # ------------------------------------------------------------------------- Log
4503:
4504: sub log {
4505: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4506: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4507: }
4508:
4509: # ------------------------------------------------------------------ Course Log
1.352 www 4510: #
4511: # This routine flushes several buffers of non-mission-critical nature
4512: #
1.157 www 4513:
4514: sub flushcourselogs {
1.352 www 4515: &logthis('Flushing log buffers');
4516: #
4517: # course logs
4518: # This is a log of all transactions in a course, which can be used
4519: # for data mining purposes
4520: #
4521: # It also collects the courseid database, which lists last transaction
4522: # times and course titles for all courseids
4523: #
4524: my %courseidbuffer=();
1.921 raeburn 4525: foreach my $crsid (keys(%courselogs)) {
1.352 www 4526: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4527: &escape($courselogs{$crsid}),
4528: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4529: delete $courselogs{$crsid};
4530: } else {
4531: &logthis('Failed to flush log buffer for '.$crsid);
4532: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4533: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4534: " exceeded maximum size, deleting.</font>");
4535: delete $courselogs{$crsid};
4536: }
1.352 www 4537: }
1.920 raeburn 4538: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4539: 'description' => $coursedescrbuf{$crsid},
4540: 'inst_code' => $courseinstcodebuf{$crsid},
4541: 'type' => $coursetypebuf{$crsid},
4542: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4543: };
1.191 harris41 4544: }
1.352 www 4545: #
4546: # Write course id database (reverse lookup) to homeserver of courses
4547: # Is used in pickcourse
4548: #
1.840 albertel 4549: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4550: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4551: $courseidbuffer{$crs_home},
4552: $crs_home,'timeonly');
1.352 www 4553: }
4554: #
4555: # File accesses
4556: # Writes to the dynamic metadata of resources to get hit counts, etc.
4557: #
1.449 matthew 4558: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4559: if ($entry =~ /___count$/) {
4560: my ($dom,$name);
1.807 albertel 4561: ($dom,$name,undef)=
1.811 albertel 4562: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4563: if (! defined($dom) || $dom eq '' ||
4564: ! defined($name) || $name eq '') {
1.620 albertel 4565: my $cid = $env{'request.course.id'};
4566: $dom = $env{'request.'.$cid.'.domain'};
4567: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4568: }
1.450 matthew 4569: my $value = $accesshash{$entry};
4570: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4571: my %temphash=($url => $value);
1.449 matthew 4572: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4573: if ($result eq 'ok') {
4574: delete $accesshash{$entry};
4575: }
4576: } else {
1.811 albertel 4577: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4578: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4579: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4580: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4581: delete $accesshash{$entry};
4582: }
1.185 www 4583: }
1.191 harris41 4584: }
1.352 www 4585: #
4586: # Roles
4587: # Reverse lookup of user roles for course faculty/staff and co-authorship
4588: #
1.800 albertel 4589: foreach my $entry (keys(%userrolehash)) {
1.351 www 4590: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4591: split(/\:/,$entry);
4592: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4593: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4594: $rudom,$runame) eq 'ok') {
4595: delete $userrolehash{$entry};
4596: }
4597: }
1.662 raeburn 4598: #
1.1172.2.90 raeburn 4599: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4600: #
4601: my %domrolebuffer = ();
1.1000 raeburn 4602: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4603: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4604: if ($domrolebuffer{$rudom}) {
4605: $domrolebuffer{$rudom}.='&'.&escape($entry).
4606: '='.&escape($domainrolehash{$entry});
4607: } else {
4608: $domrolebuffer{$rudom}.=&escape($entry).
4609: '='.&escape($domainrolehash{$entry});
4610: }
4611: delete $domainrolehash{$entry};
4612: }
4613: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4614: my %servers;
4615: if (defined(&domain($dom,'primary'))) {
4616: my $primary=&domain($dom,'primary');
4617: my $hostname=&hostname($primary);
4618: $servers{$primary} = $hostname;
4619: } else {
4620: %servers = &get_servers($dom,'library');
4621: }
1.841 albertel 4622: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4623: if (&reply('domroleput:'.$dom.':'.
4624: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4625: last;
4626: } else {
1.841 albertel 4627: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4628: }
1.662 raeburn 4629: }
4630: }
1.186 www 4631: $dumpcount++;
1.157 www 4632: }
4633:
4634: sub courselog {
4635: my $what=shift;
1.158 www 4636: $what=time.':'.$what;
1.620 albertel 4637: unless ($env{'request.course.id'}) { return ''; }
4638: $coursedombuf{$env{'request.course.id'}}=
4639: $env{'course.'.$env{'request.course.id'}.'.domain'};
4640: $coursenumbuf{$env{'request.course.id'}}=
4641: $env{'course.'.$env{'request.course.id'}.'.num'};
4642: $coursehombuf{$env{'request.course.id'}}=
4643: $env{'course.'.$env{'request.course.id'}.'.home'};
4644: $coursedescrbuf{$env{'request.course.id'}}=
4645: $env{'course.'.$env{'request.course.id'}.'.description'};
4646: $courseinstcodebuf{$env{'request.course.id'}}=
4647: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4648: $courseownerbuf{$env{'request.course.id'}}=
4649: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4650: $coursetypebuf{$env{'request.course.id'}}=
4651: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4652: if (defined $courselogs{$env{'request.course.id'}}) {
4653: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4654: } else {
1.620 albertel 4655: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4656: }
1.620 albertel 4657: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4658: &flushcourselogs();
4659: }
1.158 www 4660: }
4661:
4662: sub courseacclog {
4663: my $fnsymb=shift;
1.620 albertel 4664: unless ($env{'request.course.id'}) { return ''; }
4665: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4666: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4667: $what.=':POST';
1.583 matthew 4668: # FIXME: Probably ought to escape things....
1.800 albertel 4669: foreach my $key (keys(%env)) {
4670: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4671: my $formitem = $1;
4672: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4673: $what.=':'.$formitem.'='.$env{$key};
4674: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4675: $what.=':'.$formitem.'='.$env{$key};
4676: }
1.158 www 4677: }
1.191 harris41 4678: }
1.583 matthew 4679: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4680: # FIXME: We should not be depending on a form parameter that someone
4681: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4682: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4683: $what.= ':POST';
4684: # FIXME: Probably ought to escape things....
4685: foreach my $element ('courseexp','crsfulltext','crsrelated',
4686: 'crsdiscuss') {
1.620 albertel 4687: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4688: }
4689: }
1.158 www 4690: }
4691: &courselog($what);
1.149 www 4692: }
4693:
1.185 www 4694: sub countacc {
4695: my $url=&declutter(shift);
1.458 matthew 4696: return if (! defined($url) || $url eq '');
1.620 albertel 4697: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4698: #
4699: # Mark that this url was used in this course
4700: #
1.620 albertel 4701: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4702: #
4703: # Increase the access count for this resource in this child process
4704: #
1.281 www 4705: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4706: $accesshash{$key}++;
1.185 www 4707: }
1.349 www 4708:
1.361 www 4709: sub linklog {
4710: my ($from,$to)=@_;
4711: $from=&declutter($from);
4712: $to=&declutter($to);
4713: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4714: $accesshash{$to.'___'.$from.'___goto'}=1;
4715: }
1.1160 www 4716:
4717: sub statslog {
4718: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4719: if ($users<2) { return; }
4720: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4721: 'course' => $env{'request.course.id'},
4722: 'sections' => '"all"',
4723: 'num_students' => $users,
4724: 'part' => $part,
4725: 'symb' => $symb,
4726: 'mean_tries' => $av_attempts,
4727: 'deg_of_diff' => $degdiff});
4728: foreach my $key (keys(%dynstore)) {
4729: $accesshash{$key}=$dynstore{$key};
4730: }
4731: }
1.361 www 4732:
1.349 www 4733: sub userrolelog {
4734: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4735: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4736: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4737: $userrolehash
4738: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4739: =$tend.':'.$tstart;
1.662 raeburn 4740: }
1.1169 droeschl 4741: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4742: $userrolehash
4743: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4744: =$tend.':'.$tstart;
4745: }
1.1172.2.90 raeburn 4746: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4747: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4748: $domainrolehash
4749: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4750: = $tend.':'.$tstart;
4751: }
1.351 www 4752: }
4753:
1.957 raeburn 4754: sub courserolelog {
4755: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4756: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4757: my $cdom = $1;
4758: my $cnum = $2;
4759: my $sec = $3;
4760: my $namespace = 'rolelog';
4761: my %storehash = (
4762: role => $trole,
4763: start => $tstart,
4764: end => $tend,
4765: selfenroll => $selfenroll,
4766: context => $context,
4767: );
4768: if ($trole eq 'gr') {
4769: $namespace = 'groupslog';
4770: $storehash{'group'} = $sec;
4771: } else {
4772: $storehash{'section'} = $sec;
4773: }
4774: &write_log('course',$namespace,\%storehash,$delflag,$username,
4775: $domain,$cnum,$cdom);
4776: if (($trole ne 'st') || ($sec ne '')) {
4777: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4778: }
4779: }
4780: return;
4781: }
4782:
1.1172.2.9 raeburn 4783: sub domainrolelog {
4784: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4785: if ($area =~ m{^/($match_domain)/$}) {
4786: my $cdom = $1;
4787: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4788: my $namespace = 'rolelog';
4789: my %storehash = (
4790: role => $trole,
4791: start => $tstart,
4792: end => $tend,
4793: context => $context,
4794: );
4795: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4796: $domain,$domconfiguser,$cdom);
4797: }
4798: return;
4799:
4800: }
4801:
4802: sub coauthorrolelog {
4803: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4804: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4805: my $audom = $1;
4806: my $auname = $2;
4807: my $namespace = 'rolelog';
4808: my %storehash = (
4809: role => $trole,
4810: start => $tstart,
4811: end => $tend,
4812: context => $context,
4813: );
4814: &write_log('author',$namespace,\%storehash,$delflag,$username,
4815: $domain,$auname,$audom);
4816: }
4817: return;
4818: }
4819:
1.351 www 4820: sub get_course_adv_roles {
1.948 raeburn 4821: my ($cid,$codes) = @_;
1.620 albertel 4822: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4823: my %coursehash=&coursedescription($cid);
1.988 raeburn 4824: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4825: my %nothide=();
1.800 albertel 4826: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4827: if ($user !~ /:/) {
4828: $nothide{join(':',split(/[\@]/,$user))}=1;
4829: } else {
4830: $nothide{$user}=1;
4831: }
1.470 www 4832: }
1.1172.2.23 raeburn 4833: my @possdoms = ($coursehash{'domain'});
4834: if ($coursehash{'checkforpriv'}) {
4835: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4836: }
1.351 www 4837: my %returnhash=();
4838: my %dumphash=
4839: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4840: my $now=time;
1.997 raeburn 4841: my %privileged;
1.1000 raeburn 4842: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4843: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4844: if (($tstart) && ($tstart<0)) { next; }
4845: if (($tend) && ($tend<$now)) { next; }
4846: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4847: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4848: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4849: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4850: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4851: if ($role eq 'cr') { next; }
1.948 raeburn 4852: if ($codes) {
4853: if ($section) { $role .= ':'.$section; }
4854: if ($returnhash{$role}) {
4855: $returnhash{$role}.=','.$username.':'.$domain;
4856: } else {
4857: $returnhash{$role}=$username.':'.$domain;
4858: }
1.351 www 4859: } else {
1.988 raeburn 4860: my $key=&plaintext($role,$crstype);
1.973 bisitz 4861: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4862: if ($returnhash{$key}) {
4863: $returnhash{$key}.=','.$username.':'.$domain;
4864: } else {
4865: $returnhash{$key}=$username.':'.$domain;
4866: }
1.351 www 4867: }
1.948 raeburn 4868: }
1.400 www 4869: return %returnhash;
4870: }
4871:
4872: sub get_my_roles {
1.937 raeburn 4873: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4874: unless (defined($uname)) { $uname=$env{'user.name'}; }
4875: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4876: my (%dumphash,%nothide);
1.1086 raeburn 4877: if ($context eq 'userroles') {
1.1166 raeburn 4878: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4879: } else {
1.1172.2.23 raeburn 4880: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4881: if ($hidepriv) {
4882: my %coursehash=&coursedescription($udom.'_'.$uname);
4883: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4884: if ($user !~ /:/) {
4885: $nothide{join(':',split(/[\@]/,$user))} = 1;
4886: } else {
4887: $nothide{$user} = 1;
4888: }
4889: }
4890: }
1.858 raeburn 4891: }
1.400 www 4892: my %returnhash=();
4893: my $now=time;
1.999 raeburn 4894: my %privileged;
1.800 albertel 4895: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4896: my ($role,$tend,$tstart);
4897: if ($context eq 'userroles') {
1.1149 raeburn 4898: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4899: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4900: } else {
4901: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4902: }
1.400 www 4903: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4904: my $status = 'active';
1.939 raeburn 4905: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4906: $status = 'previous';
4907: }
4908: if (($tstart) && ($now<$tstart)) {
4909: $status = 'future';
4910: }
4911: if (ref($types) eq 'ARRAY') {
4912: if (!grep(/^\Q$status\E$/,@{$types})) {
4913: next;
4914: }
4915: } else {
4916: if ($status ne 'active') {
4917: next;
4918: }
4919: }
1.867 raeburn 4920: my ($rolecode,$username,$domain,$section,$area);
4921: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4922: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4923: (undef,$domain,$username,$section) = split(/\//,$area);
4924: } else {
4925: ($role,$username,$domain,$section) = split(/\:/,$entry);
4926: }
1.832 raeburn 4927: if (ref($roledoms) eq 'ARRAY') {
4928: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4929: next;
4930: }
4931: }
4932: if (ref($roles) eq 'ARRAY') {
4933: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4934: if ($role =~ /^cr\//) {
4935: if (!grep(/^cr$/,@{$roles})) {
4936: next;
4937: }
1.1104 raeburn 4938: } elsif ($role =~ /^gr\//) {
4939: if (!grep(/^gr$/,@{$roles})) {
4940: next;
4941: }
1.922 raeburn 4942: } else {
4943: next;
4944: }
1.832 raeburn 4945: }
1.867 raeburn 4946: }
1.937 raeburn 4947: if ($hidepriv) {
1.1172.2.23 raeburn 4948: my @privroles = ('dc','su');
1.999 raeburn 4949: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4950: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4951: } else {
1.1172.2.23 raeburn 4952: my $possdoms = [$domain];
4953: if (ref($roledoms) eq 'ARRAY') {
4954: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4955: }
1.1172.2.23 raeburn 4956: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4957: if (!$nothide{$username.':'.$domain}) {
4958: next;
4959: }
4960: }
1.937 raeburn 4961: }
4962: }
1.933 raeburn 4963: if ($withsec) {
4964: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4965: $tstart.':'.$tend;
4966: } else {
4967: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4968: }
1.832 raeburn 4969: }
1.373 www 4970: return %returnhash;
1.399 www 4971: }
4972:
1.1172.2.89 raeburn 4973: sub get_all_adhocroles {
4974: my ($dom) = @_;
4975: my @roles_by_num = ();
4976: my %domdefaults = &get_domain_defaults($dom);
4977: my (%description,%access_in_dom,%access_info);
4978: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4979: my $count = 0;
4980: my %domcurrent = %{$domdefaults{'adhocroles'}};
4981: my %ordered;
4982: foreach my $role (sort(keys(%domcurrent))) {
4983: my ($order,$desc,$access_in_dom);
4984: if (ref($domcurrent{$role}) eq 'HASH') {
4985: $order = $domcurrent{$role}{'order'};
4986: $desc = $domcurrent{$role}{'desc'};
4987: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4988: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4989: }
4990: if ($order eq '') {
4991: $order = $count;
4992: }
4993: $ordered{$order} = $role;
4994: if ($desc ne '') {
4995: $description{$role} = $desc;
4996: } else {
4997: $description{$role}= $role;
4998: }
4999: $count++;
5000: }
5001: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5002: push(@roles_by_num,$ordered{$item});
5003: }
5004: }
5005: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5006: }
5007:
5008: sub get_my_adhocroles {
5009: my ($cid,$checkreg) = @_;
5010: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5011: if ($env{'request.course.id'} eq $cid) {
5012: $cdom = $env{'course.'.$cid.'.domain'};
5013: $cnum = $env{'course.'.$cid.'.num'};
5014: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5015: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5016: $cdom = $1;
5017: $cnum = $2;
5018: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5019: $cdom,$cnum);
5020: }
5021: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5022: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5023: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5024: if ($rosterhash{$user} ne '') {
5025: my $type = (split(/:/,$rosterhash{$user}))[5];
5026: return ([],{}) if ($type eq 'auto');
5027: }
5028: }
5029: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 5030: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 5031: my $then=$env{'user.login.time'};
5032: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 5033: if (!$update) {
5034: $update = $then;
5035: }
5036: my @liveroles;
5037: foreach my $role ('dh','da') {
5038: if ($env{"user.role.$role./$cdom/"}) {
5039: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5040: my $limit = $update;
5041: if ($env{'request.role'} eq "$role./$cdom/") {
5042: $limit = $then;
5043: }
5044: my $activerole = 1;
5045: if ($tstart && $tstart>$limit) { $activerole = 0; }
5046: if ($tend && $tend <$limit) { $activerole = 0; }
5047: if ($activerole) {
5048: push(@liveroles,$role);
5049: }
5050: }
5051: }
5052: if (@liveroles) {
1.1172.2.89 raeburn 5053: if (&homeserver($cnum,$cdom) ne 'no_host') {
5054: my ($accessref,$accessinfo,%access_in_dom);
5055: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5056: if (ref($roles_by_num) eq 'ARRAY') {
5057: if (@{$roles_by_num}) {
5058: my %settings;
5059: if ($env{'request.course.id'} eq $cid) {
5060: foreach my $envkey (keys(%env)) {
5061: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5062: $settings{$1} = $env{$envkey};
5063: }
5064: }
5065: } else {
5066: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5067: }
5068: my %setincrs;
5069: if ($settings{'internal.adhocaccess'}) {
5070: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5071: }
5072: my @statuses;
5073: if ($env{'environment.inststatus'}) {
5074: @statuses = split(/,/,$env{'environment.inststatus'});
5075: }
5076: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5077: if (ref($accessref) eq 'HASH') {
5078: %access_in_dom = %{$accessref};
5079: }
5080: foreach my $role (@{$roles_by_num}) {
5081: my ($curraccess,@okstatus,@personnel);
5082: if ($setincrs{$role}) {
5083: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5084: if ($curraccess eq 'status') {
5085: @okstatus = split(/\&/,$rest);
5086: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5087: @personnel = split(/\&/,$rest);
5088: }
5089: } else {
5090: $curraccess = $access_in_dom{$role};
5091: if (ref($accessinfo) eq 'HASH') {
5092: if ($curraccess eq 'status') {
5093: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5094: @okstatus = @{$accessinfo->{$role}};
5095: }
5096: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5097: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5098: @personnel = @{$accessinfo->{$role}};
5099: }
5100: }
5101: }
5102: }
5103: if ($curraccess eq 'none') {
5104: next;
5105: } elsif ($curraccess eq 'all') {
5106: push(@possroles,$role);
1.1172.2.90 raeburn 5107: } elsif ($curraccess eq 'dh') {
5108: if (grep(/^dh$/,@liveroles)) {
5109: push(@possroles,$role);
5110: } else {
5111: next;
5112: }
5113: } elsif ($curraccess eq 'da') {
5114: if (grep(/^da$/,@liveroles)) {
5115: push(@possroles,$role);
5116: } else {
5117: next;
5118: }
1.1172.2.89 raeburn 5119: } elsif ($curraccess eq 'status') {
5120: if (@okstatus) {
5121: if (!@statuses) {
5122: if (grep(/^default$/,@okstatus)) {
5123: push(@possroles,$role);
5124: }
5125: } else {
5126: foreach my $status (@okstatus) {
5127: if (grep(/^\Q$status\E$/,@statuses)) {
5128: push(@possroles,$role);
5129: last;
5130: }
5131: }
5132: }
5133: }
5134: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5135: if (grep(/^\Q$user\E$/,@personnel)) {
5136: if ($curraccess eq 'exc') {
5137: push(@possroles,$role);
5138: }
5139: } elsif ($curraccess eq 'inc') {
5140: push(@possroles,$role);
5141: }
5142: }
5143: }
5144: }
5145: }
5146: }
5147: }
5148: }
5149: }
5150: unless (ref($description) eq 'HASH') {
5151: if (ref($roles_by_num) eq 'ARRAY') {
5152: my %desc;
5153: map { $desc{$_} = $_; } (@{$roles_by_num});
5154: $description = \%desc;
5155: } else {
5156: $description = {};
5157: }
5158: }
5159: return (\@possroles,$description);
5160: }
5161:
1.399 www 5162: # ----------------------------------------------------- Frontpage Announcements
5163: #
5164: #
5165:
5166: sub postannounce {
5167: my ($server,$text)=@_;
1.844 albertel 5168: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5169: unless ($text=~/\w/) { $text=''; }
5170: return &reply('setannounce:'.&escape($text),$server);
5171: }
5172:
5173: sub getannounce {
1.448 albertel 5174:
1.1172.2.96 raeburn 5175: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5176: my $announcement='';
1.800 albertel 5177: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5178: close($fh);
1.399 www 5179: if ($announcement=~/\w/) {
5180: return
5181: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5182: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5183: } else {
5184: return '';
5185: }
5186: } else {
5187: return '';
5188: }
1.351 www 5189: }
1.353 www 5190:
5191: # ---------------------------------------------------------- Course ID routines
5192: # Deal with domain's nohist_courseid.db files
5193: #
5194:
5195: sub courseidput {
1.921 raeburn 5196: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5197: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5198: my $outcome;
5199: if ($caller eq 'timeonly') {
5200: my $cids = '';
5201: foreach my $item (keys(%$storehash)) {
5202: $cids.=&escape($item).'&';
5203: }
5204: $cids=~s/\&$//;
5205: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5206: $coursehome);
5207: } else {
5208: my $items = '';
5209: foreach my $item (keys(%$storehash)) {
5210: $items.= &escape($item).'='.
5211: &freeze_escape($$storehash{$item}).'&';
5212: }
5213: $items=~s/\&$//;
5214: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5215: $coursehome);
1.918 raeburn 5216: }
5217: if ($outcome eq 'unknown_cmd') {
5218: my $what;
5219: foreach my $cid (keys(%$storehash)) {
5220: $what .= &escape($cid).'=';
1.921 raeburn 5221: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5222: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5223: }
5224: $what =~ s/\:$/&/;
5225: }
5226: $what =~ s/\&$//;
5227: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5228: } else {
5229: return $outcome;
5230: }
1.353 www 5231: }
5232:
5233: sub courseiddump {
1.921 raeburn 5234: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5235: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5236: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 5237: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 5238: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5239: my $as_hash = 1;
5240: my %returnhash;
5241: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5242: my %libserv = &all_library();
5243: foreach my $tryserver (keys(%libserv)) {
5244: if ( ( $hostidflag == 1
5245: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5246: || (!defined($hostidflag)) ) {
5247:
1.918 raeburn 5248: if (($domfilter eq '') ||
5249: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 5250: my $rep;
5251: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5252: $rep = &LONCAPA::Lond::dump_course_id_handler(
5253: join(":", (&host_domain($tryserver), $sincefilter,
5254: &escape($descfilter), &escape($instcodefilter),
5255: &escape($ownerfilter), &escape($coursefilter),
5256: &escape($typefilter), &escape($regexp_ok),
5257: $as_hash, &escape($selfenrollonly),
5258: &escape($catfilter), $showhidden, $caller,
5259: &escape($cloner), &escape($cc_clone), $cloneonly,
5260: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 5261: &escape($creationcontext),$domcloner,$hasuniquecode,
5262: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 5263: } else {
5264: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5265: $sincefilter.':'.&escape($descfilter).':'.
5266: &escape($instcodefilter).':'.&escape($ownerfilter).
5267: ':'.&escape($coursefilter).':'.&escape($typefilter).
5268: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5269: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5270: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5271: &escape($cc_clone).':'.$cloneonly.':'.
5272: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 5273: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5274: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 5275: }
5276:
1.918 raeburn 5277: my @pairs=split(/\&/,$rep);
5278: foreach my $item (@pairs) {
5279: my ($key,$value)=split(/\=/,$item,2);
5280: $key = &unescape($key);
5281: next if ($key =~ /^error: 2 /);
5282: my $result = &thaw_unescape($value);
5283: if (ref($result) eq 'HASH') {
5284: $returnhash{$key}=$result;
5285: } else {
1.921 raeburn 5286: my @responses = split(/:/,$value);
5287: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5288: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5289: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5290: }
1.1008 raeburn 5291: }
1.353 www 5292: }
5293: }
5294: }
5295: }
5296: return %returnhash;
5297: }
5298:
1.1055 raeburn 5299: sub courselastaccess {
5300: my ($cdom,$cnum,$hostidref) = @_;
5301: my %returnhash;
5302: if ($cdom && $cnum) {
5303: my $chome = &homeserver($cnum,$cdom);
5304: if ($chome ne 'no_host') {
5305: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5306: &extract_lastaccess(\%returnhash,$rep);
5307: }
5308: } else {
5309: if (!$cdom) { $cdom=''; }
5310: my %libserv = &all_library();
5311: foreach my $tryserver (keys(%libserv)) {
5312: if (ref($hostidref) eq 'ARRAY') {
5313: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5314: }
5315: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5316: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5317: &extract_lastaccess(\%returnhash,$rep);
5318: }
5319: }
5320: }
5321: return %returnhash;
5322: }
5323:
5324: sub extract_lastaccess {
5325: my ($returnhash,$rep) = @_;
5326: if (ref($returnhash) eq 'HASH') {
5327: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5328: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5329: $rep eq '') {
5330: my @pairs=split(/\&/,$rep);
5331: foreach my $item (@pairs) {
5332: my ($key,$value)=split(/\=/,$item,2);
5333: $key = &unescape($key);
5334: next if ($key =~ /^error: 2 /);
5335: $returnhash->{$key} = &thaw_unescape($value);
5336: }
5337: }
5338: }
5339: return;
5340: }
5341:
1.658 raeburn 5342: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5343:
5344: sub dcmailput {
1.685 raeburn 5345: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5346: my $status = &Apache::lonnet::critical(
1.740 www 5347: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5348: &escape($message),$server);
1.662 raeburn 5349: return $status;
5350: }
5351:
1.658 raeburn 5352: sub dcmaildump {
5353: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5354: my %returnhash=();
1.846 albertel 5355:
5356: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5357: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5358: &escape($enddate).':';
5359: my @esc_senders=map { &escape($_)} @$senders;
5360: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5361: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5362: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5363: if (($key) && ($value)) {
5364: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5365: }
5366: }
5367: }
5368: return %returnhash;
5369: }
1.662 raeburn 5370: # ---------------------------------------------------------- Domain roles
5371:
5372: sub get_domain_roles {
5373: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5374: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5375: $startdate = '.';
5376: }
1.1018 raeburn 5377: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5378: $enddate = '.';
5379: }
1.922 raeburn 5380: my $rolelist;
5381: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5382: $rolelist = join('&',@{$roles});
1.922 raeburn 5383: }
1.662 raeburn 5384: my %personnel = ();
1.841 albertel 5385:
5386: my %servers = &get_servers($dom,'library');
5387: foreach my $tryserver (keys(%servers)) {
5388: %{$personnel{$tryserver}}=();
5389: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5390: &escape($startdate).':'.
5391: &escape($enddate).':'.
5392: &escape($rolelist), $tryserver))) {
5393: my ($key,$value) = split(/\=/,$line,2);
5394: if (($key) && ($value)) {
5395: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5396: }
5397: }
1.662 raeburn 5398: }
5399: return %personnel;
5400: }
1.658 raeburn 5401:
1.1172.2.89 raeburn 5402: sub get_active_domroles {
5403: my ($dom,$roles) = @_;
5404: return () unless (ref($roles) eq 'ARRAY');
5405: my $now = time;
5406: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5407: my %domroles;
5408: foreach my $server (keys(%dompersonnel)) {
5409: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5410: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5411: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5412: }
5413: }
5414: return %domroles;
5415: }
5416:
1.1057 www 5417: # ----------------------------------------------------------- Interval timing
1.149 www 5418:
1.1153 www 5419: {
5420: # Caches needed for speedup of navmaps
5421: # We don't want to cache this for very long at all (5 seconds at most)
5422: #
5423: # The user for whom we cache
5424: my $cachedkey='';
5425: # The cached times for this user
5426: my %cachedtimes=();
5427: # When this was last done
1.1172.2.66 raeburn 5428: my $cachedtime='';
1.1153 www 5429:
5430: sub load_all_first_access {
1.1154 raeburn 5431: my ($uname,$udom)=@_;
1.1156 www 5432: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 5433: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 5434: return;
5435: }
5436: $cachedtime=time;
5437: $cachedkey=$uname.':'.$udom;
5438: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5439: }
5440:
1.504 albertel 5441: sub get_first_access {
1.1162 raeburn 5442: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 5443: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5444: if ($argsymb) { $symb=$argsymb; }
5445: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5446: if ($argmap) { $map = $argmap; }
1.926 albertel 5447: if ($type eq 'course') {
5448: $res='course';
5449: } elsif ($type eq 'map') {
1.588 albertel 5450: $res=&symbread($map);
5451: } else {
5452: $res=$symb;
5453: }
1.1153 www 5454: &load_all_first_access($uname,$udom);
5455: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5456: }
5457:
5458: sub set_first_access {
1.1162 raeburn 5459: my ($type,$interval)=@_;
1.790 albertel 5460: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5461: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5462: if ($type eq 'course') {
5463: $res='course';
5464: } elsif ($type eq 'map') {
1.588 albertel 5465: $res=&symbread($map);
5466: } else {
5467: $res=$symb;
5468: }
1.1153 www 5469: $cachedkey='';
1.1162 raeburn 5470: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 5471: if ($firstaccess) {
5472: &logthis("First access time already set ($firstaccess) when attempting ".
5473: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5474: "in $courseid");
5475: return 'already_set';
5476: } else {
1.1162 raeburn 5477: my $start = time;
5478: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5479: $udom,$uname);
5480: if ($putres eq 'ok') {
5481: &put('timerinterval',{"$courseid\0$res"=>$interval},
5482: $udom,$uname);
5483: &appenv(
5484: {
5485: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5486: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5487: }
5488: );
1.1172.2.97 raeburn 5489: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5490: $cachedtimes{"$courseid\0$res"} = $start;
5491: }
1.1172.2.102 raeburn 5492: } elsif ($putres ne 'refused') {
5493: &logthis("Result: $putres when attempting to set first access time ".
5494: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5495: }
5496: return $putres;
1.505 albertel 5497: }
5498: return 'already_set';
1.504 albertel 5499: }
1.1153 www 5500: }
1.1172.2.32 raeburn 5501:
5502: sub checkout {
5503: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5504: my $now=time;
5505: my $lonhost=$perlvar{'lonHostID'};
5506: my $infostr=&escape(
5507: 'CHECKOUTTOKEN&'.
5508: $tuname.'&'.
5509: $tudom.'&'.
5510: $tcrsid.'&'.
5511: $symb.'&'.
5512: $now.'&'.$ENV{'REMOTE_ADDR'});
5513: my $token=&reply('tmpput:'.$infostr,$lonhost);
5514: if ($token=~/^error\:/) {
5515: &logthis("<font color=\"blue\">WARNING: ".
5516: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5517: "</font>");
5518: return '';
5519: }
5520:
5521: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5522: $token=~tr/a-z/A-Z/;
5523:
5524: my %infohash=('resource.0.outtoken' => $token,
5525: 'resource.0.checkouttime' => $now,
5526: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
5527:
5528: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5529: return '';
5530: } else {
5531: &logthis("<font color=\"blue\">WARNING: ".
5532: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5533: "</font>");
5534: }
5535:
5536: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5537: &escape('Checkout '.$infostr.' - '.
5538: $token)) ne 'ok') {
5539: return '';
5540: } else {
5541: &logthis("<font color=\"blue\">WARNING: ".
5542: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5543: "</font>");
5544: }
5545: return $token;
5546: }
5547:
5548: # ------------------------------------------------------------ Check in an item
5549:
5550: sub checkin {
5551: my $token=shift;
5552: my $now=time;
5553: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5554: $lonhost=~tr/A-Z/a-z/;
5555: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5556: $dtoken=~s/\W/\_/g;
5557: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5558: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5559:
5560: unless (($tuname) && ($tudom)) {
5561: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5562: return '';
5563: }
5564:
5565: unless (&allowed('mgr',$tcrsid)) {
5566: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5567: $env{'user.name'}.' - '.$env{'user.domain'});
5568: return '';
5569: }
5570:
5571: my %infohash=('resource.0.intoken' => $token,
5572: 'resource.0.checkintime' => $now,
5573: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
5574:
5575: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5576: return '';
5577: }
5578:
5579: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5580: &escape('Checkin - '.$token)) ne 'ok') {
5581: return '';
5582: }
5583:
5584: return ($symb,$tuname,$tudom,$tcrsid);
5585: }
5586:
1.110 www 5587: # --------------------------------------------- Set Expire Date for Spreadsheet
5588:
5589: sub expirespread {
5590: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5591: my $cid=$env{'request.course.id'};
1.110 www 5592: if ($cid) {
5593: my $now=time;
5594: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5595: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5596: $env{'course.'.$cid.'.num'}.
1.110 www 5597: ':nohist_expirationdates:'.
5598: &escape($key).'='.$now,
1.620 albertel 5599: $env{'course.'.$cid.'.home'})
1.110 www 5600: }
5601: return 'ok';
1.14 www 5602: }
5603:
1.109 www 5604: # ----------------------------------------------------- Devalidate Spreadsheets
5605:
5606: sub devalidate {
1.325 www 5607: my ($symb,$uname,$udom)=@_;
1.620 albertel 5608: my $cid=$env{'request.course.id'};
1.109 www 5609: if ($cid) {
1.391 matthew 5610: # delete the stored spreadsheets for
5611: # - the student level sheet of this user in course's homespace
5612: # - the assessment level sheet for this resource
5613: # for this user in user's homespace
1.553 albertel 5614: # - current conditional state info
1.325 www 5615: my $key=$uname.':'.$udom.':';
1.109 www 5616: my $status=
1.299 matthew 5617: &del('nohist_calculatedsheets',
1.391 matthew 5618: [$key.'studentcalc:'],
1.620 albertel 5619: $env{'course.'.$cid.'.domain'},
5620: $env{'course.'.$cid.'.num'})
1.133 albertel 5621: .' '.
5622: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5623: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5624: unless ($status eq 'ok ok') {
5625: &logthis('Could not devalidate spreadsheet '.
1.325 www 5626: $uname.' at '.$udom.' for '.
1.109 www 5627: $symb.': '.$status);
1.133 albertel 5628: }
1.553 albertel 5629: &delenv('user.state.'.$cid);
1.109 www 5630: }
5631: }
5632:
1.265 albertel 5633: sub get_scalar {
5634: my ($string,$end) = @_;
5635: my $value;
5636: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5637: $value = $1;
5638: } elsif ($$string =~ s/^([^&]*?)&//) {
5639: $value = $1;
5640: }
5641: return &unescape($value);
5642: }
5643:
5644: sub array2str {
5645: my (@array) = @_;
5646: my $result=&arrayref2str(\@array);
5647: $result=~s/^__ARRAY_REF__//;
5648: $result=~s/__END_ARRAY_REF__$//;
5649: return $result;
5650: }
5651:
1.204 albertel 5652: sub arrayref2str {
5653: my ($arrayref) = @_;
1.265 albertel 5654: my $result='__ARRAY_REF__';
1.204 albertel 5655: foreach my $elem (@$arrayref) {
1.265 albertel 5656: if(ref($elem) eq 'ARRAY') {
5657: $result.=&arrayref2str($elem).'&';
5658: } elsif(ref($elem) eq 'HASH') {
5659: $result.=&hashref2str($elem).'&';
5660: } elsif(ref($elem)) {
5661: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5662: } else {
5663: $result.=&escape($elem).'&';
5664: }
5665: }
5666: $result=~s/\&$//;
1.265 albertel 5667: $result .= '__END_ARRAY_REF__';
1.204 albertel 5668: return $result;
5669: }
5670:
1.168 albertel 5671: sub hash2str {
1.204 albertel 5672: my (%hash) = @_;
5673: my $result=&hashref2str(\%hash);
1.265 albertel 5674: $result=~s/^__HASH_REF__//;
5675: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5676: return $result;
5677: }
5678:
5679: sub hashref2str {
5680: my ($hashref)=@_;
1.265 albertel 5681: my $result='__HASH_REF__';
1.800 albertel 5682: foreach my $key (sort(keys(%$hashref))) {
5683: if (ref($key) eq 'ARRAY') {
5684: $result.=&arrayref2str($key).'=';
5685: } elsif (ref($key) eq 'HASH') {
5686: $result.=&hashref2str($key).'=';
5687: } elsif (ref($key)) {
1.265 albertel 5688: $result.='=';
1.800 albertel 5689: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5690: } else {
1.1132 raeburn 5691: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5692: }
5693:
1.800 albertel 5694: if(ref($hashref->{$key}) eq 'ARRAY') {
5695: $result.=&arrayref2str($hashref->{$key}).'&';
5696: } elsif(ref($hashref->{$key}) eq 'HASH') {
5697: $result.=&hashref2str($hashref->{$key}).'&';
5698: } elsif(ref($hashref->{$key})) {
1.265 albertel 5699: $result.='&';
1.800 albertel 5700: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5701: } else {
1.800 albertel 5702: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5703: }
5704: }
1.168 albertel 5705: $result=~s/\&$//;
1.265 albertel 5706: $result .= '__END_HASH_REF__';
1.168 albertel 5707: return $result;
5708: }
5709:
5710: sub str2hash {
1.265 albertel 5711: my ($string)=@_;
5712: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5713: return %$hash;
5714: }
5715:
5716: sub str2hashref {
1.168 albertel 5717: my ($string) = @_;
1.265 albertel 5718:
5719: my %hash;
5720:
5721: if($string !~ /^__HASH_REF__/) {
5722: if (! ($string eq '' || !defined($string))) {
5723: $hash{'error'}='Not hash reference';
5724: }
5725: return (\%hash, $string);
5726: }
5727:
5728: $string =~ s/^__HASH_REF__//;
5729:
5730: while($string !~ /^__END_HASH_REF__/) {
5731: #key
5732: my $key='';
5733: if($string =~ /^__HASH_REF__/) {
5734: ($key, $string)=&str2hashref($string);
5735: if(defined($key->{'error'})) {
5736: $hash{'error'}='Bad data';
5737: return (\%hash, $string);
5738: }
5739: } elsif($string =~ /^__ARRAY_REF__/) {
5740: ($key, $string)=&str2arrayref($string);
5741: if($key->[0] eq 'Array reference error') {
5742: $hash{'error'}='Bad data';
5743: return (\%hash, $string);
5744: }
5745: } else {
5746: $string =~ s/^(.*?)=//;
1.267 albertel 5747: $key=&unescape($1);
1.265 albertel 5748: }
5749: $string =~ s/^=//;
5750:
5751: #value
5752: my $value='';
5753: if($string =~ /^__HASH_REF__/) {
5754: ($value, $string)=&str2hashref($string);
5755: if(defined($value->{'error'})) {
5756: $hash{'error'}='Bad data';
5757: return (\%hash, $string);
5758: }
5759: } elsif($string =~ /^__ARRAY_REF__/) {
5760: ($value, $string)=&str2arrayref($string);
5761: if($value->[0] eq 'Array reference error') {
5762: $hash{'error'}='Bad data';
5763: return (\%hash, $string);
5764: }
5765: } else {
5766: $value=&get_scalar(\$string,'__END_HASH_REF__');
5767: }
5768: $string =~ s/^&//;
5769:
5770: $hash{$key}=$value;
1.204 albertel 5771: }
1.265 albertel 5772:
5773: $string =~ s/^__END_HASH_REF__//;
5774:
5775: return (\%hash, $string);
1.204 albertel 5776: }
5777:
5778: sub str2array {
1.265 albertel 5779: my ($string)=@_;
5780: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5781: return @$array;
5782: }
5783:
5784: sub str2arrayref {
1.204 albertel 5785: my ($string) = @_;
1.265 albertel 5786: my @array;
5787:
5788: if($string !~ /^__ARRAY_REF__/) {
5789: if (! ($string eq '' || !defined($string))) {
5790: $array[0]='Array reference error';
5791: }
5792: return (\@array, $string);
5793: }
5794:
5795: $string =~ s/^__ARRAY_REF__//;
5796:
5797: while($string !~ /^__END_ARRAY_REF__/) {
5798: my $value='';
5799: if($string =~ /^__HASH_REF__/) {
5800: ($value, $string)=&str2hashref($string);
5801: if(defined($value->{'error'})) {
5802: $array[0] ='Array reference error';
5803: return (\@array, $string);
5804: }
5805: } elsif($string =~ /^__ARRAY_REF__/) {
5806: ($value, $string)=&str2arrayref($string);
5807: if($value->[0] eq 'Array reference error') {
5808: $array[0] ='Array reference error';
5809: return (\@array, $string);
5810: }
5811: } else {
5812: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5813: }
5814: $string =~ s/^&//;
5815:
5816: push(@array, $value);
1.191 harris41 5817: }
1.265 albertel 5818:
5819: $string =~ s/^__END_ARRAY_REF__//;
5820:
5821: return (\@array, $string);
1.168 albertel 5822: }
5823:
1.167 albertel 5824: # -------------------------------------------------------------------Temp Store
5825:
1.168 albertel 5826: sub tmpreset {
5827: my ($symb,$namespace,$domain,$stuname) = @_;
5828: if (!$symb) {
5829: $symb=&symbread();
1.620 albertel 5830: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5831: }
5832: $symb=escape($symb);
5833:
1.620 albertel 5834: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5835: $namespace=~s/\//\_/g;
5836: $namespace=~s/\W//g;
5837:
1.620 albertel 5838: if (!$domain) { $domain=$env{'user.domain'}; }
5839: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5840: if ($domain eq 'public' && $stuname eq 'public') {
5841: $stuname=$ENV{'REMOTE_ADDR'};
5842: }
1.1117 foxr 5843: my $path=LONCAPA::tempdir();
1.168 albertel 5844: my %hash;
5845: if (tie(%hash,'GDBM_File',
5846: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5847: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5848: foreach my $key (keys(%hash)) {
1.180 albertel 5849: if ($key=~ /:$symb/) {
1.168 albertel 5850: delete($hash{$key});
5851: }
5852: }
5853: }
5854: }
5855:
1.167 albertel 5856: sub tmpstore {
1.168 albertel 5857: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5858:
5859: if (!$symb) {
5860: $symb=&symbread();
1.620 albertel 5861: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5862: }
5863: $symb=escape($symb);
5864:
5865: if (!$namespace) {
5866: # I don't think we would ever want to store this for a course.
5867: # it seems this will only be used if we don't have a course.
1.620 albertel 5868: #$namespace=$env{'request.course.id'};
1.168 albertel 5869: #if (!$namespace) {
1.620 albertel 5870: $namespace=$env{'request.state'};
1.168 albertel 5871: #}
5872: }
5873: $namespace=~s/\//\_/g;
5874: $namespace=~s/\W//g;
1.620 albertel 5875: if (!$domain) { $domain=$env{'user.domain'}; }
5876: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5877: if ($domain eq 'public' && $stuname eq 'public') {
5878: $stuname=$ENV{'REMOTE_ADDR'};
5879: }
1.168 albertel 5880: my $now=time;
5881: my %hash;
1.1117 foxr 5882: my $path=LONCAPA::tempdir();
1.168 albertel 5883: if (tie(%hash,'GDBM_File',
5884: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5885: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5886: $hash{"version:$symb"}++;
5887: my $version=$hash{"version:$symb"};
5888: my $allkeys='';
5889: foreach my $key (keys(%$storehash)) {
5890: $allkeys.=$key.':';
1.591 albertel 5891: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5892: }
5893: $hash{"$version:$symb:timestamp"}=$now;
5894: $allkeys.='timestamp';
5895: $hash{"$version:keys:$symb"}=$allkeys;
5896: if (untie(%hash)) {
5897: return 'ok';
5898: } else {
5899: return "error:$!";
5900: }
5901: } else {
5902: return "error:$!";
5903: }
5904: }
1.167 albertel 5905:
1.168 albertel 5906: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5907:
1.168 albertel 5908: sub tmprestore {
5909: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5910:
1.168 albertel 5911: if (!$symb) {
5912: $symb=&symbread();
1.620 albertel 5913: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5914: }
5915: $symb=escape($symb);
5916:
1.620 albertel 5917: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5918:
1.620 albertel 5919: if (!$domain) { $domain=$env{'user.domain'}; }
5920: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5921: if ($domain eq 'public' && $stuname eq 'public') {
5922: $stuname=$ENV{'REMOTE_ADDR'};
5923: }
1.168 albertel 5924: my %returnhash;
5925: $namespace=~s/\//\_/g;
5926: $namespace=~s/\W//g;
5927: my %hash;
1.1117 foxr 5928: my $path=LONCAPA::tempdir();
1.168 albertel 5929: if (tie(%hash,'GDBM_File',
5930: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5931: &GDBM_READER(),0640)) {
1.168 albertel 5932: my $version=$hash{"version:$symb"};
5933: $returnhash{'version'}=$version;
5934: my $scope;
5935: for ($scope=1;$scope<=$version;$scope++) {
5936: my $vkeys=$hash{"$scope:keys:$symb"};
5937: my @keys=split(/:/,$vkeys);
5938: my $key;
5939: $returnhash{"$scope:keys"}=$vkeys;
5940: foreach $key (@keys) {
1.591 albertel 5941: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5942: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5943: }
5944: }
1.168 albertel 5945: if (!(untie(%hash))) {
5946: return "error:$!";
5947: }
5948: } else {
5949: return "error:$!";
5950: }
5951: return %returnhash;
1.167 albertel 5952: }
5953:
1.9 www 5954: # ----------------------------------------------------------------------- Store
5955:
5956: sub store {
1.1172.2.64 raeburn 5957: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5958: my $home='';
5959:
1.168 albertel 5960: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5961:
1.213 www 5962: $symb=&symbclean($symb);
1.122 albertel 5963: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5964:
1.620 albertel 5965: if (!$domain) { $domain=$env{'user.domain'}; }
5966: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5967:
5968: &devalidate($symb,$stuname,$domain);
1.109 www 5969:
5970: $symb=escape($symb);
1.187 www 5971: if (!$namespace) {
1.620 albertel 5972: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5973: return '';
5974: }
5975: }
1.620 albertel 5976: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5977:
5978: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5979: $$storehash{'host'}=$perlvar{'lonHostID'};
5980:
1.12 www 5981: my $namevalue='';
1.800 albertel 5982: foreach my $key (keys(%$storehash)) {
5983: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5984: }
1.12 www 5985: $namevalue=~s/\&$//;
1.187 www 5986: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5987: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5988: }
5989:
1.47 www 5990: # -------------------------------------------------------------- Critical Store
5991:
5992: sub cstore {
1.1172.2.64 raeburn 5993: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5994: my $home='';
5995:
1.168 albertel 5996: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5997:
1.213 www 5998: $symb=&symbclean($symb);
1.122 albertel 5999: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6000:
1.620 albertel 6001: if (!$domain) { $domain=$env{'user.domain'}; }
6002: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6003:
6004: &devalidate($symb,$stuname,$domain);
1.109 www 6005:
6006: $symb=escape($symb);
1.187 www 6007: if (!$namespace) {
1.620 albertel 6008: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6009: return '';
6010: }
6011: }
1.620 albertel 6012: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6013:
6014: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6015: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6016:
1.47 www 6017: my $namevalue='';
1.800 albertel 6018: foreach my $key (keys(%$storehash)) {
6019: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6020: }
1.47 www 6021: $namevalue=~s/\&$//;
1.187 www 6022: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6023: return critical
1.1172.2.64 raeburn 6024: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6025: }
6026:
1.9 www 6027: # --------------------------------------------------------------------- Restore
6028:
6029: sub restore {
1.124 www 6030: my ($symb,$namespace,$domain,$stuname) = @_;
6031: my $home='';
6032:
1.168 albertel 6033: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6034:
1.122 albertel 6035: if (!$symb) {
1.1172.2.26 raeburn 6036: return if ($namespace eq 'courserequests');
6037: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6038: } else {
1.1172.2.26 raeburn 6039: unless ($namespace eq 'courserequests') {
6040: $symb=&escape(&symbclean($symb));
6041: }
1.122 albertel 6042: }
1.188 www 6043: if (!$namespace) {
1.620 albertel 6044: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6045: return '';
6046: }
6047: }
1.620 albertel 6048: if (!$domain) { $domain=$env{'user.domain'}; }
6049: if (!$stuname) { $stuname=$env{'user.name'}; }
6050: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6051: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6052:
1.12 www 6053: my %returnhash=();
1.800 albertel 6054: foreach my $line (split(/\&/,$answer)) {
6055: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6056: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6057: }
1.75 www 6058: my $version;
6059: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6060: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6061: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6062: }
1.75 www 6063: }
1.13 www 6064: return %returnhash;
1.34 www 6065: }
6066:
6067: # ---------------------------------------------------------- Course Description
1.1118 foxr 6068: #
6069: #
1.34 www 6070:
6071: sub coursedescription {
1.731 albertel 6072: my ($courseid,$args)=@_;
1.34 www 6073: $courseid=~s/^\///;
1.49 www 6074: $courseid=~s/\_/\//g;
1.34 www 6075: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6076: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6077: my $normalid=$cdomain.'_'.$cnum;
6078: # need to always cache even if we get errors otherwise we keep
6079: # trying and trying and trying to get the course description.
6080: my %envhash=();
6081: my %returnhash=();
1.731 albertel 6082:
6083: my $expiretime=600;
6084: if ($env{'request.course.id'} eq $normalid) {
6085: $expiretime=120;
6086: }
6087:
6088: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6089: if (!$args->{'freshen_cache'}
6090: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6091: foreach my $key (keys(%env)) {
6092: next if ($key !~ /^\Q$prefix\E(.*)/);
6093: my ($setting) = $1;
6094: $returnhash{$setting} = $env{$key};
6095: }
6096: return %returnhash;
6097: }
6098:
1.1118 foxr 6099: # get the data again
6100:
1.731 albertel 6101: if (!$args->{'one_time'}) {
6102: $envhash{'course.'.$normalid.'.last_cache'}=time;
6103: }
1.811 albertel 6104:
1.34 www 6105: if ($chome ne 'no_host') {
1.302 albertel 6106: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6107: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6108: my $username = $env{'user.name'}; # Defult username
6109: if(defined $args->{'user'}) {
6110: $username = $args->{'user'};
6111: }
1.129 albertel 6112: $returnhash{'home'}= $chome;
6113: $returnhash{'domain'} = $cdomain;
6114: $returnhash{'num'} = $cnum;
1.741 raeburn 6115: if (!defined($returnhash{'type'})) {
6116: $returnhash{'type'} = 'Course';
6117: }
1.130 albertel 6118: while (my ($name,$value) = each %returnhash) {
1.53 www 6119: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6120: }
1.270 www 6121: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6122: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6123: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6124: $envhash{'course.'.$normalid.'.home'}=$chome;
6125: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6126: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6127: }
6128: }
1.731 albertel 6129: if (!$args->{'one_time'}) {
1.949 raeburn 6130: &appenv(\%envhash);
1.731 albertel 6131: }
1.302 albertel 6132: return %returnhash;
1.461 www 6133: }
6134:
1.1080 raeburn 6135: sub update_released_required {
6136: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6137: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6138: $cid = $env{'request.course.id'};
6139: $cdom = $env{'course.'.$cid.'.domain'};
6140: $cnum = $env{'course.'.$cid.'.num'};
6141: $chome = $env{'course.'.$cid.'.home'};
6142: }
6143: if ($needsrelease) {
6144: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6145: my $needsupdate;
6146: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6147: $needsupdate = 1;
6148: } else {
6149: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6150: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6151: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6152: $needsupdate = 1;
6153: }
6154: }
6155: if ($needsupdate) {
6156: my %needshash = (
6157: 'internal.releaserequired' => $needsrelease,
6158: );
6159: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6160: if ($putresult eq 'ok') {
6161: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6162: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6163: if (ref($crsinfo{$cid}) eq 'HASH') {
6164: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6165: &courseidput($cdom,\%crsinfo,$chome,'notime');
6166: }
6167: }
6168: }
6169: }
6170: return;
6171: }
6172:
1.461 www 6173: # -------------------------------------------------See if a user is privileged
6174:
6175: sub privileged {
1.1172.2.23 raeburn 6176: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6177: my $now = time;
1.1172.2.23 raeburn 6178: my $roles;
6179: if (ref($possroles) eq 'ARRAY') {
6180: $roles = $possroles;
6181: } else {
6182: $roles = ['dc','su'];
6183: }
6184: if (ref($possdomains) eq 'ARRAY') {
6185: my %privileged = &privileged_by_domain($possdomains,$roles);
6186: foreach my $dom (@{$possdomains}) {
6187: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6188: (ref($privileged{$dom}) eq 'HASH')) {
6189: foreach my $role (@{$roles}) {
6190: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6191: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6192: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6193: return 1 unless (($end && $end < $now) ||
6194: ($start && $start > $now));
6195: }
6196: }
6197: }
6198: }
6199: }
6200: } else {
6201: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6202: my $now = time;
1.1170 droeschl 6203:
1.1172.2.58 raeburn 6204: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6205: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 6206: if (grep(/^\Q$trole\E$/,@{$roles})) {
6207: return 1 unless ($tend && $tend < $now)
6208: or ($tstart && $tstart > $now);
1.1170 droeschl 6209: }
1.1172.2.23 raeburn 6210: }
6211: }
1.461 www 6212: return 0;
1.9 www 6213: }
1.1 albertel 6214:
1.1172.2.23 raeburn 6215: sub privileged_by_domain {
6216: my ($domains,$roles) = @_;
6217: my %privileged = ();
6218: my $cachetime = 60*60*24;
6219: my $now = time;
6220: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6221: return %privileged;
6222: }
6223: foreach my $dom (@{$domains}) {
6224: next if (ref($privileged{$dom}) eq 'HASH');
6225: my $needroles;
6226: foreach my $role (@{$roles}) {
6227: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6228: if (defined($cached)) {
6229: if (ref($result) eq 'HASH') {
6230: $privileged{$dom}{$role} = $result;
6231: }
6232: } else {
6233: $needroles = 1;
6234: }
6235: }
6236: if ($needroles) {
6237: my %dompersonnel = &get_domain_roles($dom,$roles);
6238: $privileged{$dom} = {};
6239: foreach my $server (keys(%dompersonnel)) {
6240: if (ref($dompersonnel{$server}) eq 'HASH') {
6241: foreach my $item (keys(%{$dompersonnel{$server}})) {
6242: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6243: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6244: next if ($end && $end < $now);
6245: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6246: $dompersonnel{$server}{$item};
6247: }
6248: }
6249: }
6250: if (ref($privileged{$dom}) eq 'HASH') {
6251: foreach my $role (@{$roles}) {
6252: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6253: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6254: } else {
6255: my %hash = ();
6256: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6257: }
6258: }
6259: }
6260: }
6261: }
6262: return %privileged;
6263: }
6264:
1.103 harris41 6265: # -------------------------------------------------------- Get user privileges
1.11 www 6266:
6267: sub rolesinit {
1.1169 droeschl 6268: my ($domain, $username) = @_;
6269: my %userroles = ('user.login.time' => time);
6270: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6271:
6272: # firstaccess and timerinterval are related to timed maps/resources.
6273: # also, blocking can be triggered by an activating timer
6274: # it's saved in the user's %env.
6275: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6276: my %timerinterval = &dump('timerinterval', $domain, $username);
6277: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6278: %timerintchk, %timerintenv);
6279:
1.1162 raeburn 6280: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6281: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6282: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6283: }
1.1169 droeschl 6284:
1.1162 raeburn 6285: foreach my $key (keys(%timerinterval)) {
6286: my ($cid,$rest) = split(/\0/,$key);
6287: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6288: }
1.1169 droeschl 6289:
1.11 www 6290: my %allroles=();
1.1162 raeburn 6291: my %allgroups=();
1.11 www 6292:
1.1172.2.58 raeburn 6293: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6294: my $role = $rolesdump{$area};
6295: $area =~ s/\_\w\w$//;
6296:
6297: my ($trole, $tend, $tstart, $group_privs);
6298:
6299: if ($role =~ /^cr/) {
6300: # Custom role, defined by a user
6301: # e.g., user.role.cr/msu/smith/mynewrole
6302: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6303: $trole = $1;
6304: ($tend, $tstart) = split('_', $2);
6305: } else {
6306: $trole = $role;
6307: }
6308: } elsif ($role =~ m|^gr/|) {
6309: # Role of member in a group, defined within a course/community
6310: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6311: ($trole, $tend, $tstart) = split(/_/, $role);
6312: next if $tstart eq '-1';
6313: ($trole, $group_privs) = split(/\//, $trole);
6314: $group_privs = &unescape($group_privs);
6315: } else {
6316: # Just a normal role, defined in roles.tab
6317: ($trole, $tend, $tstart) = split(/_/,$role);
6318: }
6319:
6320: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6321: $username);
6322: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6323:
6324: # role expired or not available yet?
6325: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6326: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6327:
6328: next if $area eq '' or $trole eq '';
6329:
6330: my $spec = "$trole.$area";
6331: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6332:
6333: if ($trole =~ /^cr\//) {
6334: # Custom role, defined by a user
6335: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6336: } elsif ($trole eq 'gr') {
6337: # Role of a member in a group, defined within a course/community
6338: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6339: next;
6340: } else {
6341: # Normal role, defined in roles.tab
6342: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6343: }
6344:
6345: my $cid = $tdomain.'_'.$trest;
6346: unless ($firstaccchk{$cid}) {
6347: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6348: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6349: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6350: $coursetimerstarts{$cid}{$item};
6351: }
6352: }
6353: $firstaccchk{$cid} = 1;
6354: }
6355: unless ($timerintchk{$cid}) {
6356: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6357: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6358: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6359: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6360: }
1.12 www 6361: }
1.1169 droeschl 6362: $timerintchk{$cid} = 1;
1.191 harris41 6363: }
1.11 www 6364: }
1.1169 droeschl 6365:
1.1172.2.91 raeburn 6366: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6367: \%allroles, \%allgroups);
1.1169 droeschl 6368: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6369: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6370:
1.1162 raeburn 6371: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6372: }
6373:
1.567 raeburn 6374: sub set_arearole {
1.1172.2.19 raeburn 6375: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6376: unless ($nolog) {
1.567 raeburn 6377: # log the associated role with the area
1.1172.2.19 raeburn 6378: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6379: }
1.743 albertel 6380: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6381: }
6382:
6383: sub custom_roleprivs {
6384: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6385: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6386: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6387: if (&hostname($homsvr) ne '') {
1.567 raeburn 6388: my ($rdummy,$roledef)=
6389: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6390: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6391: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6392: if (defined($syspriv)) {
1.1043 raeburn 6393: if ($trest =~ /^$match_community$/) {
6394: $syspriv =~ s/bre\&S//;
6395: }
1.567 raeburn 6396: $$allroles{'cm./'}.=':'.$syspriv;
6397: $$allroles{$spec.'./'}.=':'.$syspriv;
6398: }
6399: if ($tdomain ne '') {
6400: if (defined($dompriv)) {
6401: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6402: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6403: }
6404: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6405: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6406: my $rolename = $1;
6407: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6408: }
1.567 raeburn 6409: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6410: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6411: }
6412: }
6413: }
6414: }
6415: }
6416:
1.1172.2.89 raeburn 6417: sub course_adhocrole_privs {
6418: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6419: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6420: if ($overrides{"internal.adhocpriv.$rolename"}) {
6421: my (%currprivs,%storeprivs);
6422: foreach my $item (split(/:/,$coursepriv)) {
6423: my ($priv,$restrict) = split(/\&/,$item);
6424: $currprivs{$priv} = $restrict;
6425: }
6426: my (%possadd,%possremove,%full);
6427: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6428: my ($priv,$restrict)=split(/\&/,$item);
6429: $full{$priv} = $restrict;
6430: }
6431: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6432: next if ($item eq '');
6433: my ($rule,$rest) = split(/=/,$item);
6434: next unless (($rule eq 'off') || ($rule eq 'on'));
6435: foreach my $priv (split(/:/,$rest)) {
6436: if ($priv ne '') {
6437: if ($rule eq 'off') {
6438: $possremove{$priv} = 1;
6439: } else {
6440: $possadd{$priv} = 1;
6441: }
6442: }
6443: }
6444: }
6445: foreach my $priv (sort(keys(%full))) {
6446: if (exists($currprivs{$priv})) {
6447: unless (exists($possremove{$priv})) {
6448: $storeprivs{$priv} = $currprivs{$priv};
6449: }
6450: } elsif (exists($possadd{$priv})) {
6451: $storeprivs{$priv} = $full{$priv};
6452: }
6453: }
6454: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6455: }
6456: return $coursepriv;
6457: }
6458:
1.678 raeburn 6459: sub group_roleprivs {
6460: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6461: my $access = 1;
6462: my $now = time;
6463: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6464: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6465: if ($access) {
1.811 albertel 6466: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6467: $$allgroups{$course}{$group} .=':'.$group_privs;
6468: }
6469: }
1.567 raeburn 6470:
6471: sub standard_roleprivs {
6472: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6473: if (defined($pr{$trole.':s'})) {
6474: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6475: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6476: }
6477: if ($tdomain ne '') {
6478: if (defined($pr{$trole.':d'})) {
6479: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6480: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6481: }
6482: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6483: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6484: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6485: }
6486: }
6487: }
6488:
6489: sub set_userprivs {
1.1064 raeburn 6490: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6491: my $author=0;
6492: my $adv=0;
1.1172.2.91 raeburn 6493: my $rar=0;
1.678 raeburn 6494: my %grouproles = ();
6495: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6496: my @groupkeys;
1.1000 raeburn 6497: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6498: push(@groupkeys,$role);
6499: }
6500: if (ref($groups_roles) eq 'HASH') {
6501: foreach my $key (keys(%{$groups_roles})) {
6502: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6503: push(@groupkeys,$key);
6504: }
6505: }
6506: }
6507: if (@groupkeys > 0) {
6508: foreach my $role (@groupkeys) {
6509: my ($trole,$area,$sec,$extendedarea);
6510: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6511: $trole = $1;
6512: $area = $2;
6513: $sec = $3;
6514: $extendedarea = $area.$sec;
6515: if (exists($$allgroups{$area})) {
6516: foreach my $group (keys(%{$$allgroups{$area}})) {
6517: my $spec = $trole.'.'.$extendedarea;
6518: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6519: $$allgroups{$area}{$group};
1.1064 raeburn 6520: }
1.678 raeburn 6521: }
6522: }
6523: }
6524: }
6525: }
1.800 albertel 6526: foreach my $group (keys(%grouproles)) {
6527: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6528: }
1.800 albertel 6529: foreach my $role (keys(%{$allroles})) {
6530: my %thesepriv;
1.941 raeburn 6531: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6532: foreach my $item (split(/:/,$$allroles{$role})) {
6533: if ($item ne '') {
6534: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6535: if ($restrictions eq '') {
6536: $thesepriv{$privilege}='F';
6537: } elsif ($thesepriv{$privilege} ne 'F') {
6538: $thesepriv{$privilege}.=$restrictions;
6539: }
6540: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 6541: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6542: }
6543: }
6544: my $thesestr='';
1.1104 raeburn 6545: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6546: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6547: }
6548: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6549: }
1.1172.2.91 raeburn 6550: return ($author,$adv,$rar);
1.567 raeburn 6551: }
6552:
1.994 raeburn 6553: sub role_status {
1.1104 raeburn 6554: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6555: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 6556: my ($one,$two) = split(m{\./},$rolekey,2);
6557: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6558: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 6559: $$where = '/'.$two;
1.994 raeburn 6560: $$trolecode=$$role.'.'.$$where;
6561: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6562: $$tstatus='is';
1.1104 raeburn 6563: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6564: $$tstatus='future';
1.1034 raeburn 6565: if ($$tstart<$now) {
6566: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6567: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6568: my (%allroles,%allgroups,$group_privs,
6569: %groups_roles,@rolecodes);
1.1002 raeburn 6570: my %userroles = (
6571: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6572: );
1.1064 raeburn 6573: @rolecodes = ('cm');
1.1002 raeburn 6574: my $spec=$$role.'.'.$$where;
6575: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6576: if ($$role =~ /^cr\//) {
6577: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6578: push(@rolecodes,'cr');
1.1002 raeburn 6579: } elsif ($$role eq 'gr') {
1.1064 raeburn 6580: push(@rolecodes,$$role);
1.1002 raeburn 6581: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6582: $env{'user.name'});
1.1064 raeburn 6583: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6584: (undef,my $group_privs) = split(/\//,$trole);
6585: $group_privs = &unescape($group_privs);
6586: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6587: 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 6588: &get_groups_roles($tdomain,$trest,
6589: \%course_roles,\@rolecodes,
6590: \%groups_roles);
1.1002 raeburn 6591: } else {
1.1064 raeburn 6592: push(@rolecodes,$$role);
1.1002 raeburn 6593: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6594: }
1.1172.2.91 raeburn 6595: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6596: \%groups_roles);
1.1064 raeburn 6597: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 6598: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6599: }
6600: }
1.1034 raeburn 6601: $$tstatus = 'is';
1.1002 raeburn 6602: }
1.994 raeburn 6603: }
6604: if ($$tend) {
1.1104 raeburn 6605: if ($$tend<$update) {
1.994 raeburn 6606: $$tstatus='expired';
6607: } elsif ($$tend<$now) {
6608: $$tstatus='will_not';
6609: }
6610: }
6611: }
6612: }
6613: }
6614:
1.1104 raeburn 6615: sub get_groups_roles {
6616: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6617: return unless((ref($cdom_courseroles) eq 'HASH') &&
6618: (ref($rolecodes) eq 'ARRAY') &&
6619: (ref($groups_roles) eq 'HASH'));
6620: if (keys(%{$cdom_courseroles}) > 0) {
6621: my ($cnum) = ($rest =~ /^($match_courseid)/);
6622: if ($cdom ne '' && $cnum ne '') {
6623: foreach my $key (keys(%{$cdom_courseroles})) {
6624: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6625: my $crsrole = $1;
6626: my $crssec = $2;
6627: if ($crsrole =~ /^cr/) {
6628: unless (grep(/^cr$/,@{$rolecodes})) {
6629: push(@{$rolecodes},'cr');
6630: }
6631: } else {
6632: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6633: push(@{$rolecodes},$crsrole);
6634: }
6635: }
6636: my $rolekey = "$crsrole./$cdom/$cnum";
6637: if ($crssec ne '') {
6638: $rolekey .= "/$crssec";
6639: }
6640: $rolekey .= './';
6641: $groups_roles->{$rolekey} = $rolecodes;
6642: }
6643: }
6644: }
6645: }
6646: return;
6647: }
6648:
6649: sub delete_env_groupprivs {
6650: my ($where,$courseroles,$possroles) = @_;
6651: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6652: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6653: unless (ref($courseroles->{$udom}) eq 'HASH') {
6654: %{$courseroles->{$udom}} =
6655: &get_my_roles('','','userroles',['active'],
6656: $possroles,[$udom],1);
6657: }
6658: if (ref($courseroles->{$udom}) eq 'HASH') {
6659: foreach my $item (keys(%{$courseroles->{$udom}})) {
6660: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6661: my $area = '/'.$cdom.'/'.$cnum;
6662: my $privkey = "user.priv.$crsrole.$area";
6663: if ($crssec ne '') {
6664: $privkey .= '/'.$crssec;
6665: }
6666: $privkey .= ".$area/$group";
6667: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6668: }
6669: }
6670: return;
6671: }
6672:
1.994 raeburn 6673: sub check_adhoc_privs {
1.1172.2.86 raeburn 6674: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6675: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6676: if ($sec) {
6677: $cckey .= '/'.$sec;
6678: }
1.1172.2.9 raeburn 6679: my $setprivs;
1.994 raeburn 6680: if ($env{$cckey}) {
6681: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6682: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6683: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6684: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6685: $setprivs = 1;
1.994 raeburn 6686: }
6687: } else {
1.1172.2.87 raeburn 6688: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6689: $setprivs = 1;
1.994 raeburn 6690: }
1.1172.2.9 raeburn 6691: return $setprivs;
1.994 raeburn 6692: }
6693:
6694: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6695: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6696: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6697: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6698: if ($sec ne '') {
6699: $area .= '/'.$sec;
6700: }
1.994 raeburn 6701: my $spec = $role.'.'.$area;
6702: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6703: $env{'user.name'},1);
1.1172.2.84 raeburn 6704: my %rolehash = ();
1.1172.2.89 raeburn 6705: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6706: my $rolename = $1;
1.1172.2.84 raeburn 6707: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6708: my %domdef = &get_domain_defaults($dcdom);
6709: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6710: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6711: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6712: }
6713: }
1.1172.2.84 raeburn 6714: } else {
6715: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6716: }
1.1172.2.91 raeburn 6717: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6718: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6719: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6720: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6721: &appenv( {'request.role' => $spec,
6722: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6723: 'request.course.sec' => $sec,
1.1088 raeburn 6724: }
6725: );
6726: my $tadv=0;
6727: if (&allowed('adv') eq 'F') { $tadv=1; }
6728: &appenv({'request.role.adv' => $tadv});
6729: }
1.994 raeburn 6730: }
6731:
1.12 www 6732: # --------------------------------------------------------------- get interface
6733:
6734: sub get {
1.131 albertel 6735: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6736: my $items='';
1.800 albertel 6737: foreach my $item (@$storearr) {
6738: $items.=&escape($item).'&';
1.191 harris41 6739: }
1.12 www 6740: $items=~s/\&$//;
1.620 albertel 6741: if (!$udomain) { $udomain=$env{'user.domain'}; }
6742: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6743: my $uhome=&homeserver($uname,$udomain);
6744:
1.133 albertel 6745: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6746: my @pairs=split(/\&/,$rep);
1.273 albertel 6747: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6748: return @pairs;
6749: }
1.15 www 6750: my %returnhash=();
1.42 www 6751: my $i=0;
1.800 albertel 6752: foreach my $item (@$storearr) {
6753: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6754: $i++;
1.191 harris41 6755: }
1.15 www 6756: return %returnhash;
1.27 www 6757: }
6758:
6759: # --------------------------------------------------------------- del interface
6760:
6761: sub del {
1.133 albertel 6762: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6763: my $items='';
1.800 albertel 6764: foreach my $item (@$storearr) {
6765: $items.=&escape($item).'&';
1.191 harris41 6766: }
1.984 neumanie 6767:
1.27 www 6768: $items=~s/\&$//;
1.620 albertel 6769: if (!$udomain) { $udomain=$env{'user.domain'}; }
6770: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6771: my $uhome=&homeserver($uname,$udomain);
6772: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6773: }
6774:
6775: # -------------------------------------------------------------- dump interface
6776:
1.1172.2.22 raeburn 6777: sub unserialize {
6778: my ($rep, $escapedkeys) = @_;
6779:
6780: return {} if $rep =~ /^error/;
6781:
6782: my %returnhash=();
6783: foreach my $item (split(/\&/,$rep)) {
6784: my ($key, $value) = split(/=/, $item, 2);
6785: $key = unescape($key) unless $escapedkeys;
6786: next if $key =~ /^error: 2 /;
6787: $returnhash{$key} = &thaw_unescape($value);
6788: }
6789: return \%returnhash;
6790: }
6791:
6792: # see Lond::dump_with_regexp
6793: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6794: sub dump {
1.1172.2.22 raeburn 6795: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6796: if (!$udomain) { $udomain=$env{'user.domain'}; }
6797: if (!$uname) { $uname=$env{'user.name'}; }
6798: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6799:
1.1172.2.55 raeburn 6800: if ($regexp) {
6801: $regexp=&escape($regexp);
6802: } else {
6803: $regexp='.';
6804: }
1.1172.2.22 raeburn 6805: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6806: # user is hosted on this machine
1.1172.2.55 raeburn 6807: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6808: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6809: return %{&unserialize($reply, $escapedkeys)};
6810: }
1.1166 raeburn 6811: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6812: my @pairs=split(/\&/,$rep);
6813: my %returnhash=();
1.1098 foxr 6814: if (!($rep =~ /^error/ )) {
6815: foreach my $item (@pairs) {
6816: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6817: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6818: next if ($key =~ /^error: 2 /);
6819: $returnhash{$key}=&thaw_unescape($value);
6820: }
1.755 albertel 6821: }
6822: return %returnhash;
1.407 www 6823: }
6824:
1.1098 foxr 6825:
1.717 albertel 6826: # --------------------------------------------------------- dumpstore interface
6827:
6828: sub dumpstore {
6829: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6830: # same as dump but keys must be escaped. They may contain colon separated
6831: # lists of values that may themself contain colons (e.g. symbs).
6832: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6833: }
6834:
1.407 www 6835: # -------------------------------------------------------------- keys interface
6836:
6837: sub getkeys {
6838: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6839: if (!$udomain) { $udomain=$env{'user.domain'}; }
6840: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6841: my $uhome=&homeserver($uname,$udomain);
6842: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6843: my @keyarray=();
1.800 albertel 6844: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6845: next if ($key =~ /^error: 2 /);
1.800 albertel 6846: push(@keyarray,&unescape($key));
1.407 www 6847: }
6848: return @keyarray;
1.318 matthew 6849: }
6850:
1.319 matthew 6851: # --------------------------------------------------------------- currentdump
6852: sub currentdump {
1.328 matthew 6853: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6854: $courseid = $env{'request.course.id'} if (! defined($courseid));
6855: $sdom = $env{'user.domain'} if (! defined($sdom));
6856: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6857: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6858: my $rep;
6859:
6860: if (grep { $_ eq $uhome } current_machine_ids()) {
6861: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6862: $courseid)));
6863: } else {
6864: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6865: }
6866:
1.318 matthew 6867: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6868: #
1.318 matthew 6869: my %returnhash=();
1.319 matthew 6870: #
6871: if ($rep eq "unknown_cmd") {
6872: # an old lond will not know currentdump
6873: # Do a dump and make it look like a currentdump
1.822 albertel 6874: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6875: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6876: my %hash = @tmp;
6877: @tmp=();
1.424 matthew 6878: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6879: } else {
6880: my @pairs=split(/\&/,$rep);
1.800 albertel 6881: foreach my $pair (@pairs) {
6882: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6883: my ($symb,$param) = split(/:/,$key);
6884: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6885: &thaw_unescape($value);
1.319 matthew 6886: }
1.191 harris41 6887: }
1.12 www 6888: return %returnhash;
1.424 matthew 6889: }
6890:
6891: sub convert_dump_to_currentdump{
6892: my %hash = %{shift()};
6893: my %returnhash;
6894: # Code ripped from lond, essentially. The only difference
6895: # here is the unescaping done by lonnet::dump(). Conceivably
6896: # we might run in to problems with parameter names =~ /^v\./
6897: while (my ($key,$value) = each(%hash)) {
6898: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6899: $symb = &unescape($symb);
6900: $param = &unescape($param);
1.424 matthew 6901: next if ($v eq 'version' || $symb eq 'keys');
6902: next if (exists($returnhash{$symb}) &&
6903: exists($returnhash{$symb}->{$param}) &&
6904: $returnhash{$symb}->{'v.'.$param} > $v);
6905: $returnhash{$symb}->{$param}=$value;
6906: $returnhash{$symb}->{'v.'.$param}=$v;
6907: }
6908: #
6909: # Remove all of the keys in the hashes which keep track of
6910: # the version of the parameter.
6911: while (my ($symb,$param_hash) = each(%returnhash)) {
6912: # use a foreach because we are going to delete from the hash.
6913: foreach my $key (keys(%$param_hash)) {
6914: delete($param_hash->{$key}) if ($key =~ /^v\./);
6915: }
6916: }
6917: return \%returnhash;
1.12 www 6918: }
6919:
1.627 albertel 6920: # ------------------------------------------------------ critical inc interface
6921:
6922: sub cinc {
6923: return &inc(@_,'critical');
6924: }
6925:
1.449 matthew 6926: # --------------------------------------------------------------- inc interface
6927:
6928: sub inc {
1.627 albertel 6929: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6930: if (!$udomain) { $udomain=$env{'user.domain'}; }
6931: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6932: my $uhome=&homeserver($uname,$udomain);
6933: my $items='';
6934: if (! ref($store)) {
6935: # got a single value, so use that instead
6936: $items = &escape($store).'=&';
6937: } elsif (ref($store) eq 'SCALAR') {
6938: $items = &escape($$store).'=&';
6939: } elsif (ref($store) eq 'ARRAY') {
6940: $items = join('=&',map {&escape($_);} @{$store});
6941: } elsif (ref($store) eq 'HASH') {
6942: while (my($key,$value) = each(%{$store})) {
6943: $items.= &escape($key).'='.&escape($value).'&';
6944: }
6945: }
6946: $items=~s/\&$//;
1.627 albertel 6947: if ($critical) {
6948: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6949: } else {
6950: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6951: }
1.449 matthew 6952: }
6953:
1.12 www 6954: # --------------------------------------------------------------- put interface
6955:
6956: sub put {
1.134 albertel 6957: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6958: if (!$udomain) { $udomain=$env{'user.domain'}; }
6959: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6960: my $uhome=&homeserver($uname,$udomain);
1.12 www 6961: my $items='';
1.800 albertel 6962: foreach my $item (keys(%$storehash)) {
6963: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6964: }
1.12 www 6965: $items=~s/\&$//;
1.134 albertel 6966: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6967: }
6968:
1.631 albertel 6969: # ------------------------------------------------------------ newput interface
6970:
6971: sub newput {
6972: my ($namespace,$storehash,$udomain,$uname)=@_;
6973: if (!$udomain) { $udomain=$env{'user.domain'}; }
6974: if (!$uname) { $uname=$env{'user.name'}; }
6975: my $uhome=&homeserver($uname,$udomain);
6976: my $items='';
6977: foreach my $key (keys(%$storehash)) {
6978: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6979: }
6980: $items=~s/\&$//;
6981: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6982: }
6983:
6984: # --------------------------------------------------------- putstore interface
6985:
1.524 raeburn 6986: sub putstore {
1.1172.2.59 raeburn 6987: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6988: if (!$udomain) { $udomain=$env{'user.domain'}; }
6989: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6990: my $uhome=&homeserver($uname,$udomain);
6991: my $items='';
1.715 albertel 6992: foreach my $key (keys(%$storehash)) {
6993: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6994: }
1.715 albertel 6995: $items=~s/\&$//;
1.716 albertel 6996: my $esc_symb=&escape($symb);
6997: my $esc_v=&escape($version);
1.715 albertel 6998: my $reply =
1.716 albertel 6999: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7000: $uhome);
1.1172.2.59 raeburn 7001: if (($tolog) && ($reply eq 'ok')) {
7002: my $namevalue='';
7003: foreach my $key (keys(%{$storehash})) {
7004: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7005: }
7006: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
7007: '&host='.&escape($perlvar{'lonHostID'}).
7008: '&version='.$esc_v.
7009: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7010: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7011: }
1.715 albertel 7012: if ($reply eq 'unknown_cmd') {
1.716 albertel 7013: # gfall back to way things use to be done
1.715 albertel 7014: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7015: $uname);
1.524 raeburn 7016: }
1.715 albertel 7017: return $reply;
7018: }
7019:
7020: sub old_putstore {
1.716 albertel 7021: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7022: if (!$udomain) { $udomain=$env{'user.domain'}; }
7023: if (!$uname) { $uname=$env{'user.name'}; }
7024: my $uhome=&homeserver($uname,$udomain);
7025: my %newstorehash;
1.800 albertel 7026: foreach my $item (keys(%$storehash)) {
7027: my $key = $version.':'.&escape($symb).':'.$item;
7028: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7029: }
7030: my $items='';
7031: my %allitems = ();
1.800 albertel 7032: foreach my $item (keys(%newstorehash)) {
7033: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7034: my $key = $1.':keys:'.$2;
7035: $allitems{$key} .= $3.':';
7036: }
1.800 albertel 7037: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7038: }
1.800 albertel 7039: foreach my $item (keys(%allitems)) {
7040: $allitems{$item} =~ s/\:$//;
7041: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7042: }
7043: $items=~s/\&$//;
7044: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7045: }
7046:
1.47 www 7047: # ------------------------------------------------------ critical put interface
7048:
7049: sub cput {
1.134 albertel 7050: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7051: if (!$udomain) { $udomain=$env{'user.domain'}; }
7052: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7053: my $uhome=&homeserver($uname,$udomain);
1.47 www 7054: my $items='';
1.800 albertel 7055: foreach my $item (keys(%$storehash)) {
7056: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7057: }
1.47 www 7058: $items=~s/\&$//;
1.134 albertel 7059: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7060: }
7061:
7062: # -------------------------------------------------------------- eget interface
7063:
7064: sub eget {
1.133 albertel 7065: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7066: my $items='';
1.800 albertel 7067: foreach my $item (@$storearr) {
7068: $items.=&escape($item).'&';
1.191 harris41 7069: }
1.12 www 7070: $items=~s/\&$//;
1.620 albertel 7071: if (!$udomain) { $udomain=$env{'user.domain'}; }
7072: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7073: my $uhome=&homeserver($uname,$udomain);
7074: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7075: my @pairs=split(/\&/,$rep);
7076: my %returnhash=();
1.42 www 7077: my $i=0;
1.800 albertel 7078: foreach my $item (@$storearr) {
7079: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7080: $i++;
1.191 harris41 7081: }
1.12 www 7082: return %returnhash;
7083: }
7084:
1.667 albertel 7085: # ------------------------------------------------------------ tmpput interface
7086: sub tmpput {
1.802 raeburn 7087: my ($storehash,$server,$context)=@_;
1.667 albertel 7088: my $items='';
1.800 albertel 7089: foreach my $item (keys(%$storehash)) {
7090: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7091: }
7092: $items=~s/\&$//;
1.802 raeburn 7093: if (defined($context)) {
7094: $items .= ':'.&escape($context);
7095: }
1.667 albertel 7096: return &reply("tmpput:$items",$server);
7097: }
7098:
7099: # ------------------------------------------------------------ tmpget interface
7100: sub tmpget {
1.688 albertel 7101: my ($token,$server)=@_;
7102: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7103: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7104: my %returnhash;
1.1172.2.85 raeburn 7105: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7106: return %returnhash;
7107: }
1.667 albertel 7108: foreach my $item (split(/\&/,$rep)) {
7109: my ($key,$value)=split(/=/,$item);
7110: $returnhash{&unescape($key)}=&thaw_unescape($value);
7111: }
7112: return %returnhash;
7113: }
7114:
1.1113 raeburn 7115: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7116: sub tmpdel {
7117: my ($token,$server)=@_;
7118: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7119: return &reply("tmpdel:$token",$server);
7120: }
7121:
1.1172.2.13 raeburn 7122: # ------------------------------------------------------------ get_timebased_id
7123:
7124: sub get_timebased_id {
7125: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7126: $maxtries) = @_;
7127: my ($newid,$error,$dellock);
7128: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7129: return ('','ok','invalid call to get suffix');
7130: }
7131:
7132: # set defaults for any optional args for which values were not supplied
7133: if ($who eq '') {
7134: $who = $env{'user.name'}.':'.$env{'user.domain'};
7135: }
7136: if (!$locktries) {
7137: $locktries = 3;
7138: }
7139: if (!$maxtries) {
7140: $maxtries = 10;
7141: }
7142:
7143: if (($cdom eq '') || ($cnum eq '')) {
7144: if ($env{'request.course.id'}) {
7145: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7146: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7147: }
7148: if (($cdom eq '') || ($cnum eq '')) {
7149: return ('','ok','call to get suffix not in course context');
7150: }
7151: }
7152:
7153: # construct locking item
7154: my $lockhash = {
7155: $prefix."\0".'locked_'.$keyid => $who,
7156: };
7157: my $tries = 0;
7158:
7159: # attempt to get lock on nohist_$namespace file
7160: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7161: while (($gotlock ne 'ok') && $tries <$locktries) {
7162: $tries ++;
7163: sleep 1;
7164: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7165: }
7166:
7167: # attempt to get unique identifier, based on current timestamp
7168: if ($gotlock eq 'ok') {
7169: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7170: my $id = time;
7171: $newid = $id;
1.1172.2.56 raeburn 7172: if ($idtype eq 'addcode') {
7173: $newid .= &sixnum_code();
7174: }
1.1172.2.13 raeburn 7175: my $idtries = 0;
7176: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7177: if ($idtype eq 'concat') {
7178: $newid = $id.$idtries;
1.1172.2.56 raeburn 7179: } elsif ($idtype eq 'addcode') {
7180: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 7181: } else {
7182: $newid ++;
7183: }
7184: $idtries ++;
7185: }
7186: if (!exists($inuse{$prefix."\0".$newid})) {
7187: my %new_item = (
7188: $prefix."\0".$newid => $who,
7189: );
7190: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7191: $cdom,$cnum);
7192: if ($putresult ne 'ok') {
7193: undef($newid);
7194: $error = 'error saving new item: '.$putresult;
7195: }
7196: } else {
1.1172.2.56 raeburn 7197: undef($newid);
1.1172.2.13 raeburn 7198: $error = ('error: no unique suffix available for the new item ');
7199: }
7200: # remove lock
7201: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7202: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7203: } else {
7204: $error = "error: could not obtain lockfile\n";
7205: $dellock = 'ok';
1.1172.2.58 raeburn 7206: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7207: $dellock = 'nolock';
7208: }
1.1172.2.13 raeburn 7209: }
7210: return ($newid,$dellock,$error);
7211: }
7212:
1.1172.2.56 raeburn 7213: sub sixnum_code {
7214: my $code;
7215: for (0..6) {
7216: $code .= int( rand(9) );
7217: }
7218: return $code;
7219: }
7220:
1.765 albertel 7221: # -------------------------------------------------- portfolio access checking
7222:
7223: sub portfolio_access {
1.1172.2.77 raeburn 7224: my ($requrl,$clientip) = @_;
1.765 albertel 7225: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 7226: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7227: if ($result) {
7228: my %setters;
7229: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7230: my ($startblock,$endblock) =
7231: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7232: if ($startblock && $endblock) {
7233: return 'B';
7234: }
7235: } else {
7236: my ($startblock,$endblock) =
7237: &Apache::loncommon::blockcheck(\%setters,'port');
7238: if ($startblock && $endblock) {
7239: return 'B';
7240: }
7241: }
7242: }
1.765 albertel 7243: if ($result eq 'ok') {
1.766 albertel 7244: return 'F';
1.765 albertel 7245: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7246: return 'A';
1.765 albertel 7247: }
1.766 albertel 7248: return '';
1.765 albertel 7249: }
7250:
7251: sub get_portfolio_access {
1.1172.2.77 raeburn 7252: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7253:
7254: if (!ref($access_hash)) {
7255: my $current_perms = &get_portfile_permissions($udom,$unum);
7256: my %access_controls = &get_access_controls($current_perms,$group,
7257: $file_name);
7258: $access_hash = $access_controls{$file_name};
7259: }
7260:
1.1172.2.77 raeburn 7261: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7262: my $now = time;
7263: if (ref($access_hash) eq 'HASH') {
7264: foreach my $key (keys(%{$access_hash})) {
7265: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7266: if ($start > $now) {
7267: next;
7268: }
7269: if ($end && $end<$now) {
7270: next;
7271: }
7272: if ($scope eq 'public') {
7273: $public = $key;
7274: last;
7275: } elsif ($scope eq 'guest') {
7276: $guest = $key;
7277: } elsif ($scope eq 'domains') {
7278: push(@domains,$key);
7279: } elsif ($scope eq 'users') {
7280: push(@users,$key);
7281: } elsif ($scope eq 'course') {
7282: push(@courses,$key);
7283: } elsif ($scope eq 'group') {
7284: push(@groups,$key);
1.1172.2.77 raeburn 7285: } elsif ($scope eq 'ip') {
7286: push(@ips,$key);
1.765 albertel 7287: }
7288: }
7289: if ($public) {
7290: return 'ok';
1.1172.2.77 raeburn 7291: } elsif (@ips > 0) {
7292: my $allowed;
7293: foreach my $ipkey (@ips) {
7294: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7295: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7296: $allowed = 1;
7297: last;
7298: }
7299: }
7300: }
7301: if ($allowed) {
7302: return 'ok';
7303: }
1.765 albertel 7304: }
7305: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7306: if ($guest) {
7307: return $guest;
7308: }
7309: } else {
7310: if (@domains > 0) {
7311: foreach my $domkey (@domains) {
7312: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7313: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7314: return 'ok';
7315: }
7316: }
7317: }
7318: }
7319: if (@users > 0) {
7320: foreach my $userkey (@users) {
1.865 raeburn 7321: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7322: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7323: if (ref($item) eq 'HASH') {
7324: if (($item->{'uname'} eq $env{'user.name'}) &&
7325: ($item->{'udom'} eq $env{'user.domain'})) {
7326: return 'ok';
7327: }
7328: }
7329: }
7330: }
1.765 albertel 7331: }
7332: }
7333: my %roleshash;
7334: my @courses_and_groups = @courses;
7335: push(@courses_and_groups,@groups);
7336: if (@courses_and_groups > 0) {
7337: my (%allgroups,%allroles);
7338: my ($start,$end,$role,$sec,$group);
7339: foreach my $envkey (%env) {
1.1060 raeburn 7340: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7341: my $cid = $2.'_'.$3;
7342: if ($1 eq 'gr') {
7343: $group = $4;
7344: $allgroups{$cid}{$group} = $env{$envkey};
7345: } else {
7346: if ($4 eq '') {
7347: $sec = 'none';
7348: } else {
7349: $sec = $4;
7350: }
7351: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7352: }
1.811 albertel 7353: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7354: my $cid = $2.'_'.$3;
7355: if ($4 eq '') {
7356: $sec = 'none';
7357: } else {
7358: $sec = $4;
7359: }
7360: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7361: }
7362: }
7363: if (keys(%allroles) == 0) {
7364: return;
7365: }
7366: foreach my $key (@courses_and_groups) {
7367: my %content = %{$$access_hash{$key}};
7368: my $cnum = $content{'number'};
7369: my $cdom = $content{'domain'};
7370: my $cid = $cdom.'_'.$cnum;
7371: if (!exists($allroles{$cid})) {
7372: next;
7373: }
7374: foreach my $role_id (keys(%{$content{'roles'}})) {
7375: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7376: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7377: my @status = @{$content{'roles'}{$role_id}{'access'}};
7378: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7379: foreach my $role (keys(%{$allroles{$cid}})) {
7380: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7381: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7382: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7383: if (grep/^all$/,@sections) {
7384: return 'ok';
7385: } else {
7386: if (grep/^$sec$/,@sections) {
7387: return 'ok';
7388: }
7389: }
7390: }
7391: }
7392: if (keys(%{$allgroups{$cid}}) == 0) {
7393: if (grep/^none$/,@groups) {
7394: return 'ok';
7395: }
7396: } else {
7397: if (grep/^all$/,@groups) {
7398: return 'ok';
7399: }
7400: foreach my $group (keys(%{$allgroups{$cid}})) {
7401: if (grep/^$group$/,@groups) {
7402: return 'ok';
7403: }
7404: }
7405: }
7406: }
7407: }
7408: }
7409: }
7410: }
7411: if ($guest) {
7412: return $guest;
7413: }
7414: }
7415: }
7416: return;
7417: }
7418:
7419: sub course_group_datechecker {
7420: my ($dates,$now,$status) = @_;
7421: my ($start,$end) = split(/\./,$dates);
7422: if (!$start && !$end) {
7423: return 'ok';
7424: }
7425: if (grep/^active$/,@{$status}) {
7426: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7427: return 'ok';
7428: }
7429: }
7430: if (grep/^previous$/,@{$status}) {
7431: if ($end > $now ) {
7432: return 'ok';
7433: }
7434: }
7435: if (grep/^future$/,@{$status}) {
7436: if ($start > $now) {
7437: return 'ok';
7438: }
7439: }
7440: return;
7441: }
7442:
7443: sub parse_portfolio_url {
7444: my ($url) = @_;
7445:
7446: my ($type,$udom,$unum,$group,$file_name);
7447:
1.823 albertel 7448: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7449: $type = 1;
7450: $udom = $1;
7451: $unum = $2;
7452: $file_name = $3;
1.823 albertel 7453: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7454: $type = 2;
7455: $udom = $1;
7456: $unum = $2;
7457: $group = $3;
7458: $file_name = $3.'/'.$4;
7459: }
7460: if (wantarray) {
7461: return ($type,$udom,$unum,$file_name,$group);
7462: }
7463: return $type;
7464: }
7465:
7466: sub is_portfolio_url {
7467: my ($url) = @_;
7468: return scalar(&parse_portfolio_url($url));
7469: }
7470:
1.798 raeburn 7471: sub is_portfolio_file {
7472: my ($file) = @_;
1.820 raeburn 7473: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7474: return 1;
7475: }
7476: return;
7477: }
7478:
1.976 raeburn 7479: sub usertools_access {
1.1084 raeburn 7480: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7481: my ($access,%tools);
7482: if ($context eq '') {
7483: $context = 'tools';
7484: }
7485: if ($context eq 'requestcourses') {
7486: %tools = (
7487: official => 1,
7488: unofficial => 1,
1.1006 raeburn 7489: community => 1,
1.1172.2.37 raeburn 7490: textbook => 1,
1.985 raeburn 7491: );
1.1172.2.9 raeburn 7492: } elsif ($context eq 'requestauthor') {
7493: %tools = (
7494: requestauthor => 1,
7495: );
1.985 raeburn 7496: } else {
7497: %tools = (
7498: aboutme => 1,
7499: blog => 1,
1.1172.2.6 raeburn 7500: webdav => 1,
1.985 raeburn 7501: portfolio => 1,
7502: );
7503: }
1.976 raeburn 7504: return if (!defined($tools{$tool}));
7505:
1.1172.2.35 raeburn 7506: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7507: $udom = $env{'user.domain'};
7508: $uname = $env{'user.name'};
7509: }
7510:
1.978 raeburn 7511: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7512: if ($action ne 'reload') {
1.985 raeburn 7513: if ($context eq 'requestcourses') {
7514: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 7515: } elsif ($context eq 'requestauthor') {
7516: return $env{'environment.canrequest.author'};
1.985 raeburn 7517: } else {
7518: return $env{'environment.availabletools.'.$tool};
7519: }
7520: }
1.976 raeburn 7521: }
7522:
1.1172.2.9 raeburn 7523: my ($toolstatus,$inststatus,$envkey);
7524: if ($context eq 'requestauthor') {
7525: $envkey = $context;
7526: } else {
7527: $envkey = $context.'.'.$tool;
7528: }
1.976 raeburn 7529:
1.985 raeburn 7530: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7531: ($action ne 'reload')) {
1.1172.2.9 raeburn 7532: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7533: $inststatus = $env{'environment.inststatus'};
7534: } else {
1.1084 raeburn 7535: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 7536: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7537: $inststatus = $userenvref->{'inststatus'};
7538: } else {
1.1172.2.9 raeburn 7539: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7540: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7541: $inststatus = $userenv{'inststatus'};
7542: }
1.976 raeburn 7543: }
7544:
7545: if ($toolstatus ne '') {
7546: if ($toolstatus) {
7547: $access = 1;
7548: } else {
7549: $access = 0;
7550: }
7551: return $access;
7552: }
7553:
1.1084 raeburn 7554: my ($is_adv,%domdef);
7555: if (ref($is_advref) eq 'HASH') {
7556: $is_adv = $is_advref->{'is_adv'};
7557: } else {
7558: $is_adv = &is_advanced_user($udom,$uname);
7559: }
7560: if (ref($domdefref) eq 'HASH') {
7561: %domdef = %{$domdefref};
7562: } else {
7563: %domdef = &get_domain_defaults($udom);
7564: }
1.976 raeburn 7565: if (ref($domdef{$tool}) eq 'HASH') {
7566: if ($is_adv) {
7567: if ($domdef{$tool}{'_LC_adv'} ne '') {
7568: if ($domdef{$tool}{'_LC_adv'}) {
7569: $access = 1;
7570: } else {
7571: $access = 0;
7572: }
7573: return $access;
7574: }
7575: }
7576: if ($inststatus ne '') {
7577: my ($hasaccess,$hasnoaccess);
7578: foreach my $affiliation (split(/:/,$inststatus)) {
7579: if ($domdef{$tool}{$affiliation} ne '') {
7580: if ($domdef{$tool}{$affiliation}) {
7581: $hasaccess = 1;
7582: } else {
7583: $hasnoaccess = 1;
7584: }
7585: }
7586: }
7587: if ($hasaccess || $hasnoaccess) {
7588: if ($hasaccess) {
7589: $access = 1;
7590: } elsif ($hasnoaccess) {
7591: $access = 0;
7592: }
7593: return $access;
7594: }
7595: } else {
7596: if ($domdef{$tool}{'default'} ne '') {
7597: if ($domdef{$tool}{'default'}) {
7598: $access = 1;
7599: } elsif ($domdef{$tool}{'default'} == 0) {
7600: $access = 0;
7601: }
7602: return $access;
7603: }
7604: }
7605: } else {
1.1172.2.6 raeburn 7606: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7607: $access = 1;
7608: } else {
7609: $access = 0;
7610: }
1.976 raeburn 7611: return $access;
7612: }
7613: }
7614:
1.1050 raeburn 7615: sub is_course_owner {
7616: my ($cdom,$cnum,$udom,$uname) = @_;
7617: if (($udom eq '') || ($uname eq '')) {
7618: $udom = $env{'user.domain'};
7619: $uname = $env{'user.name'};
7620: }
7621: unless (($udom eq '') || ($uname eq '')) {
7622: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7623: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7624: return 1;
7625: } else {
7626: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7627: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7628: return 1;
7629: }
7630: }
7631: }
7632: }
7633: return;
7634: }
7635:
1.976 raeburn 7636: sub is_advanced_user {
7637: my ($udom,$uname) = @_;
1.1085 raeburn 7638: if ($udom ne '' && $uname ne '') {
7639: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7640: if (wantarray) {
7641: return ($env{'user.adv'},$env{'user.author'});
7642: } else {
7643: return $env{'user.adv'};
7644: }
1.1085 raeburn 7645: }
7646: }
1.976 raeburn 7647: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7648: my %allroles;
1.1128 raeburn 7649: my ($is_adv,$is_author);
1.976 raeburn 7650: foreach my $role (keys(%roleshash)) {
7651: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7652: my $area = '/'.$tdomain.'/'.$trest;
7653: if ($sec ne '') {
7654: $area .= '/'.$sec;
7655: }
7656: if (($area ne '') && ($trole ne '')) {
7657: my $spec=$trole.'.'.$area;
7658: if ($trole =~ /^cr\//) {
7659: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7660: } elsif ($trole ne 'gr') {
7661: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7662: }
1.1128 raeburn 7663: if ($trole eq 'au') {
7664: $is_author = 1;
7665: }
1.976 raeburn 7666: }
7667: }
7668: foreach my $role (keys(%allroles)) {
7669: last if ($is_adv);
7670: foreach my $item (split(/:/,$allroles{$role})) {
7671: if ($item ne '') {
7672: my ($privilege,$restrictions)=split(/&/,$item);
7673: if ($privilege eq 'adv') {
7674: $is_adv = 1;
7675: last;
7676: }
7677: }
7678: }
7679: }
1.1128 raeburn 7680: if (wantarray) {
7681: return ($is_adv,$is_author);
7682: }
1.976 raeburn 7683: return $is_adv;
7684: }
1.798 raeburn 7685:
1.1035 raeburn 7686: sub check_can_request {
1.1036 raeburn 7687: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7688: my $canreq = 0;
7689: my ($types,$typename) = &Apache::loncommon::course_types();
7690: my @options = ('approval','validate','autolimit');
7691: my $optregex = join('|',@options);
7692: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7693: foreach my $type (@{$types}) {
7694: if (&usertools_access($env{'user.name'},
7695: $env{'user.domain'},
7696: $type,undef,'requestcourses')) {
7697: $canreq ++;
1.1036 raeburn 7698: if (ref($request_domains) eq 'HASH') {
7699: push(@{$request_domains->{$type}},$env{'user.domain'});
7700: }
1.1035 raeburn 7701: if ($dom eq $env{'user.domain'}) {
7702: $can_request->{$type} = 1;
7703: }
7704: }
7705: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7706: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7707: if (@curr > 0) {
1.1036 raeburn 7708: foreach my $item (@curr) {
7709: if (ref($request_domains) eq 'HASH') {
7710: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7711: if ($otherdom ne '') {
7712: if (ref($request_domains->{$type}) eq 'ARRAY') {
7713: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7714: push(@{$request_domains->{$type}},$otherdom);
7715: }
7716: } else {
7717: push(@{$request_domains->{$type}},$otherdom);
7718: }
7719: }
7720: }
7721: }
7722: unless($dom eq $env{'user.domain'}) {
7723: $canreq ++;
1.1035 raeburn 7724: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7725: $can_request->{$type} = 1;
7726: }
7727: }
7728: }
7729: }
7730: }
7731: }
7732: return $canreq;
7733: }
7734:
1.341 www 7735: # ---------------------------------------------- Custom access rule evaluation
7736:
7737: sub customaccess {
7738: my ($priv,$uri)=@_;
1.807 albertel 7739: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7740: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7741: $udom = &LONCAPA::clean_domain($udom);
7742: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7743: my $access=0;
1.800 albertel 7744: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7745: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7746: if ($type eq 'user') {
7747: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7748: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7749: if ($tdom) {
7750: if ($tdom ne $env{'user.domain'}) { next; }
7751: }
1.896 albertel 7752: if ($tuname) {
7753: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7754: }
7755: $access=($effect eq 'allow');
7756: last;
7757: }
7758: } else {
7759: if ($role) {
7760: if ($role ne $urole) { next; }
7761: }
7762: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7763: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7764: if ($tdom) {
7765: if ($tdom ne $udom) { next; }
7766: }
7767: if ($tcrs) {
7768: if ($tcrs ne $ucrs) { next; }
7769: }
7770: if ($tsec) {
7771: if ($tsec ne $usec) { next; }
7772: }
7773: $access=($effect eq 'allow');
7774: last;
7775: }
7776: if ($realm eq '' && $role eq '') {
7777: $access=($effect eq 'allow');
7778: }
1.402 bowersj2 7779: }
1.341 www 7780: }
7781: return $access;
7782: }
7783:
1.103 harris41 7784: # ------------------------------------------------- Check for a user privilege
1.12 www 7785:
7786: sub allowed {
1.1172.2.126 raeburn 7787: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705 albertel 7788: my $ver_orguri=$uri;
1.439 www 7789: $uri=&deversion($uri);
1.152 www 7790: my $orguri=$uri;
1.52 www 7791: $uri=&declutter($uri);
1.809 raeburn 7792:
1.810 raeburn 7793: if ($priv eq 'evb') {
7794: # Evade communication block restrictions for specified role in a course
7795: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7796: return $1;
7797: } else {
7798: return;
7799: }
7800: }
7801:
1.620 albertel 7802: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7803: # Free bre access to adm and meta resources
1.775 albertel 7804: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 7805: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7806: && ($priv eq 'bre')) {
1.14 www 7807: return 'F';
1.159 www 7808: }
7809:
1.545 banghart 7810: # Free bre access to user's own portfolio contents
1.714 raeburn 7811: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7812: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7813: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7814: my %setters;
7815: my ($startblock,$endblock) =
7816: &Apache::loncommon::blockcheck(\%setters,'port');
7817: if ($startblock && $endblock) {
7818: return 'B';
7819: } else {
7820: return 'F';
7821: }
1.545 banghart 7822: }
7823:
1.762 raeburn 7824: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7825: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7826: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7827: if (exists($env{'request.course.id'})) {
7828: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7829: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7830: if (($domain eq $cdom) && ($name eq $cnum)) {
7831: my $courseprivid=$env{'request.course.id'};
7832: $courseprivid=~s/\_/\//;
7833: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7834: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7835: return $1;
1.762 raeburn 7836: } else {
7837: if ($env{'request.course.sec'}) {
7838: $courseprivid.='/'.$env{'request.course.sec'};
7839: }
7840: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7841: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7842: return $2;
7843: }
1.714 raeburn 7844: }
7845: }
7846: }
7847: }
7848:
1.159 www 7849: # Free bre to public access
7850:
7851: if ($priv eq 'bre') {
1.238 www 7852: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7853: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7854: return 'F';
7855: }
1.238 www 7856: if ($copyright eq 'priv') {
7857: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7858: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7859: return '';
7860: }
7861: }
7862: if ($copyright eq 'domain') {
7863: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7864: unless (($env{'user.domain'} eq $1) ||
7865: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7866: return '';
7867: }
1.262 matthew 7868: }
1.620 albertel 7869: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7870: # Library role, so allow browsing of resources in this domain.
7871: return 'F';
1.238 www 7872: }
1.341 www 7873: if ($copyright eq 'custom') {
7874: unless (&customaccess($priv,$uri)) { return ''; }
7875: }
1.14 www 7876: }
1.264 matthew 7877: # Domain coordinator is trying to create a course
1.620 albertel 7878: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7879: # uri is the requested domain in this case.
7880: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7881: # a role of dc for the domain in question.
1.620 albertel 7882: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7883: }
1.29 www 7884:
1.52 www 7885: my $thisallowed='';
7886: my $statecond=0;
7887: my $courseprivid='';
7888:
1.1039 raeburn 7889: my $ownaccess;
1.1043 raeburn 7890: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7891: if (($priv eq 'bro') && ($env{'user.author'})) {
7892: if ($uri eq '') {
7893: $ownaccess = 1;
7894: } else {
7895: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7896: my $udom = $env{'user.domain'};
7897: my $uname = $env{'user.name'};
7898: if ($uri =~ m{^\Q$udom\E/?$}) {
7899: $ownaccess = 1;
1.1040 raeburn 7900: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7901: unless ($uri =~ m{\.\./}) {
7902: $ownaccess = 1;
7903: }
7904: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7905: my $now = time;
7906: if ($uri =~ m{^([^/]+)/?$}) {
7907: my $adom = $1;
7908: foreach my $key (keys(%env)) {
1.1042 raeburn 7909: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7910: my ($start,$end) = split('.',$env{$key});
7911: if (($now >= $start) && (!$end || $end < $now)) {
7912: $ownaccess = 1;
7913: last;
7914: }
7915: }
7916: }
7917: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7918: my $adom = $1;
7919: my $aname = $2;
1.1042 raeburn 7920: foreach my $role ('ca','aa') {
7921: if ($env{"user.role.$role./$adom/$aname"}) {
7922: my ($start,$end) =
7923: split('.',$env{"user.role.$role./$adom/$aname"});
7924: if (($now >= $start) && (!$end || $end < $now)) {
7925: $ownaccess = 1;
7926: last;
7927: }
1.1039 raeburn 7928: }
7929: }
7930: }
7931: }
7932: }
7933: }
7934: }
7935:
1.52 www 7936: # Course
7937:
1.620 albertel 7938: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7939: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7940: $thisallowed.=$1;
7941: }
1.52 www 7942: }
1.29 www 7943:
1.52 www 7944: # Domain
7945:
1.620 albertel 7946: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7947: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7948: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7949: $thisallowed.=$1;
7950: }
1.12 www 7951: }
1.52 www 7952:
1.1141 raeburn 7953: # User who is not author or co-author might still be able to edit
7954: # resource of an author in the domain (e.g., if Domain Coordinator).
7955: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7956: (&allowed('mdc',$env{'request.course.id'}))) {
7957: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7958: $thisallowed.=$1;
7959: }
7960: }
7961:
1.52 www 7962: # Course: uri itself is a course
1.66 www 7963: my $courseuri=$uri;
7964: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7965: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7966:
1.620 albertel 7967: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7968: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115 raeburn 7969: if ($priv eq 'mip') {
7970: my $rem = $1;
7971: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
7972: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
7973: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7974: if ($cdom ne '') {
7975: my %passwdconf = &get_passwdconf($cdom);
7976: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
7977: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
7978: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
7979: my @inststatuses = split(':',$env{'environment.inststatus'});
7980: unless (@inststatuses) {
7981: @inststatuses = ('default');
7982: }
7983: foreach my $status (@inststatuses) {
7984: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
7985: $thisallowed.=$rem;
7986: }
7987: }
7988: }
7989: }
7990: }
7991: }
7992: }
7993: } else {
7994: unless (($priv eq 'bro') && (!$ownaccess)) {
7995: $thisallowed.=$1;
7996: }
1.1039 raeburn 7997: }
1.12 www 7998: }
1.29 www 7999:
1.665 albertel 8000: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8001: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8002: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8003: $thisallowed='';
1.671 raeburn 8004: my ($match)=&is_on_map($uri);
8005: if ($match) {
8006: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8007: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 8008: my $value = $1;
8009: if ($noblockcheck) {
8010: $thisallowed.=$value;
1.1162 raeburn 8011: } else {
1.1172.2.126 raeburn 8012: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8013: if (@blockers > 0) {
8014: $thisallowed = 'B';
8015: } else {
8016: $thisallowed.=$value;
8017: }
1.1162 raeburn 8018: }
1.671 raeburn 8019: }
8020: } else {
1.705 albertel 8021: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8022: if ($refuri) {
8023: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8024: $thisallowed='F';
1.671 raeburn 8025: } else {
8026: $refuri=&declutter($refuri);
8027: my ($match) = &is_on_map($refuri);
8028: if ($match) {
1.1172.2.65 raeburn 8029: if ($noblockcheck) {
1.1162 raeburn 8030: $thisallowed='F';
1.1172.2.65 raeburn 8031: } else {
1.1172.2.127! raeburn 8032: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8033: if (@blockers > 0) {
8034: $thisallowed = 'B';
8035: } else {
8036: $thisallowed='F';
8037: }
1.1162 raeburn 8038: }
1.671 raeburn 8039: }
1.669 raeburn 8040: }
1.671 raeburn 8041: }
8042: }
1.314 www 8043: }
1.492 albertel 8044:
1.766 albertel 8045: if ($priv eq 'bre'
8046: && $thisallowed ne 'F'
8047: && $thisallowed ne '2'
8048: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 8049: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8050: }
8051:
1.52 www 8052: # Full access at system, domain or course-wide level? Exit.
1.29 www 8053: if ($thisallowed=~/F/) {
8054: return 'F';
8055: }
8056:
1.52 www 8057: # If this is generating or modifying users, exit with special codes
1.29 www 8058:
1.643 www 8059: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8060: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8061: my ($audom,$auname)=split('/',$uri);
1.643 www 8062: # no author name given, so this just checks on the general right to make a co-author in this domain
8063: unless ($auname) { return $thisallowed; }
8064: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8065: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8066: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8067: ($audom ne $env{'request.role.domain'}))) { return ''; }
8068: }
1.52 www 8069: return $thisallowed;
8070: }
8071: #
1.103 harris41 8072: # Gathered so far: system, domain and course wide privileges
1.52 www 8073: #
8074: # Course: See if uri or referer is an individual resource that is part of
8075: # the course
8076:
1.620 albertel 8077: if ($env{'request.course.id'}) {
1.232 www 8078:
1.1172.2.115 raeburn 8079: # If this is modifying password (internal auth) domains must match for user and user's role.
8080:
8081: if ($priv eq 'mip') {
8082: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8083: return $thisallowed;
8084: } else {
8085: return '';
8086: }
8087: }
8088:
1.620 albertel 8089: $courseprivid=$env{'request.course.id'};
8090: if ($env{'request.course.sec'}) {
8091: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8092: }
8093: $courseprivid=~s/\_/\//;
8094: my $checkreferer=1;
1.232 www 8095: my ($match,$cond)=&is_on_map($uri);
8096: if ($match) {
8097: $statecond=$cond;
1.620 albertel 8098: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8099: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8100: my $value = $1;
8101: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8102: if ($noblockcheck) {
1.1162 raeburn 8103: $thisallowed.=$value;
1.1172.2.65 raeburn 8104: } else {
1.1172.2.126 raeburn 8105: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8106: if (@blockers > 0) {
8107: $thisallowed = 'B';
8108: } else {
8109: $thisallowed.=$value;
8110: }
1.1162 raeburn 8111: }
8112: } else {
8113: $thisallowed.=$value;
8114: }
1.52 www 8115: $checkreferer=0;
8116: }
1.29 www 8117: }
1.1172.2.126 raeburn 8118:
1.148 www 8119: if ($checkreferer) {
1.620 albertel 8120: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8121: unless ($refuri) {
1.800 albertel 8122: foreach my $key (keys(%env)) {
8123: if ($key=~/^httpref\..*\*/) {
8124: my $pattern=$key;
1.156 www 8125: $pattern=~s/^httpref\.\/res\///;
1.148 www 8126: $pattern=~s/\*/\[\^\/\]\+/g;
8127: $pattern=~s/\//\\\//g;
1.152 www 8128: if ($orguri=~/$pattern/) {
1.800 albertel 8129: $refuri=$env{$key};
1.148 www 8130: }
8131: }
1.191 harris41 8132: }
1.148 www 8133: }
1.232 www 8134:
1.148 www 8135: if ($refuri) {
1.152 www 8136: $refuri=&declutter($refuri);
1.232 www 8137: my ($match,$cond)=&is_on_map($refuri);
8138: if ($match) {
8139: my $refstatecond=$cond;
1.620 albertel 8140: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8141: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8142: my $value = $1;
8143: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8144: if ($noblockcheck) {
1.1162 raeburn 8145: $thisallowed.=$value;
1.1172.2.65 raeburn 8146: } else {
1.1172.2.127! raeburn 8147: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8148: if (@blockers > 0) {
8149: $thisallowed = 'B';
8150: } else {
8151: $thisallowed.=$value;
8152: }
1.1162 raeburn 8153: }
8154: } else {
8155: $thisallowed.=$value;
8156: }
1.53 www 8157: $uri=$refuri;
8158: $statecond=$refstatecond;
1.52 www 8159: }
8160: }
1.148 www 8161: }
1.29 www 8162: }
1.52 www 8163: }
1.29 www 8164:
1.52 www 8165: #
1.103 harris41 8166: # Gathered now: all privileges that could apply, and condition number
1.52 www 8167: #
8168: #
8169: # Full or no access?
8170: #
1.29 www 8171:
1.52 www 8172: if ($thisallowed=~/F/) {
8173: return 'F';
8174: }
1.29 www 8175:
1.52 www 8176: unless ($thisallowed) {
8177: return '';
8178: }
1.29 www 8179:
1.52 www 8180: # Restrictions exist, deal with them
8181: #
8182: # C:according to course preferences
8183: # R:according to resource settings
8184: # L:unless locked
8185: # X:according to user session state
8186: #
8187:
8188: # Possibly locked functionality, check all courses
1.54 www 8189: # Locks might take effect only after 10 minutes cache expiration for other
8190: # courses, and 2 minutes for current course
1.52 www 8191:
8192: my $envkey;
8193: if ($thisallowed=~/L/) {
1.1000 raeburn 8194: foreach $envkey (keys(%env)) {
1.54 www 8195: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8196: my $courseid=$2;
8197: my $roleid=$1.'.'.$2;
1.92 www 8198: $courseid=~s/^\///;
1.54 www 8199: my $expiretime=600;
1.620 albertel 8200: if ($env{'request.role'} eq $roleid) {
1.54 www 8201: $expiretime=120;
8202: }
8203: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8204: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8205: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8206: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8207: }
1.620 albertel 8208: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8209: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8210: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8211: &log($env{'user.domain'},$env{'user.name'},
8212: $env{'user.home'},
1.57 www 8213: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8214: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8215: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8216: return '';
8217: }
8218: }
1.620 albertel 8219: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8220: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8221: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8222: &log($env{'user.domain'},$env{'user.name'},
8223: $env{'user.home'},
1.57 www 8224: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8225: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8226: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8227: return '';
8228: }
8229: }
8230: }
1.29 www 8231: }
1.52 www 8232: }
1.1172.2.126 raeburn 8233:
1.52 www 8234: #
8235: # Rest of the restrictions depend on selected course
8236: #
8237:
1.620 albertel 8238: unless ($env{'request.course.id'}) {
1.766 albertel 8239: if ($thisallowed eq 'A') {
8240: return 'A';
1.814 raeburn 8241: } elsif ($thisallowed eq 'B') {
8242: return 'B';
1.766 albertel 8243: } else {
8244: return '1';
8245: }
1.52 www 8246: }
1.29 www 8247:
1.52 www 8248: #
8249: # Now user is definitely in a course
8250: #
1.53 www 8251:
8252:
8253: # Course preferences
8254:
8255: if ($thisallowed=~/C/) {
1.620 albertel 8256: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8257: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8258: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8259: =~/\Q$rolecode\E/) {
1.1103 raeburn 8260: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8261: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8262: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8263: $env{'request.course.id'});
8264: }
1.237 www 8265: return '';
8266: }
8267:
1.620 albertel 8268: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8269: =~/\Q$unamedom\E/) {
1.1103 raeburn 8270: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8271: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8272: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8273: $env{'request.course.id'});
8274: }
1.54 www 8275: return '';
8276: }
1.53 www 8277: }
8278:
8279: # Resource preferences
8280:
8281: if ($thisallowed=~/R/) {
1.620 albertel 8282: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8283: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8284: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8285: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8286: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8287: }
8288: return '';
1.54 www 8289: }
1.53 www 8290: }
1.30 www 8291:
1.246 www 8292: # Restricted by state or randomout?
1.30 www 8293:
1.52 www 8294: if ($thisallowed=~/X/) {
1.620 albertel 8295: if ($env{'acc.randomout'}) {
1.579 albertel 8296: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8297: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8298: return '';
8299: }
1.247 www 8300: }
8301: if (&condval($statecond)) {
1.52 www 8302: return '2';
8303: } else {
8304: return '';
8305: }
8306: }
1.30 www 8307:
1.766 albertel 8308: if ($thisallowed eq 'A') {
8309: return 'A';
1.814 raeburn 8310: } elsif ($thisallowed eq 'B') {
8311: return 'B';
1.766 albertel 8312: }
1.52 www 8313: return 'F';
1.232 www 8314: }
1.1162 raeburn 8315:
1.1172.2.13 raeburn 8316: # ------------------------------------------- Check construction space access
8317:
8318: sub constructaccess {
8319: my ($url,$setpriv)=@_;
8320:
8321: # We do not allow editing of previous versions of files
8322: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8323:
8324: # Get username and domain from URL
8325: my ($ownername,$ownerdomain,$ownerhome);
8326:
8327: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 8328: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 8329:
8330: # The URL does not really point to any authorspace, forget it
8331: unless (($ownername) && ($ownerdomain)) { return ''; }
8332:
8333: # Now we need to see if the user has access to the authorspace of
8334: # $ownername at $ownerdomain
8335:
8336: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8337: # Real author for this?
8338: $ownerhome = $env{'user.home'};
8339: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8340: return ($ownername,$ownerdomain,$ownerhome);
8341: }
8342: } else {
8343: # Co-author for this?
8344: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8345: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8346: $ownerhome = &homeserver($ownername,$ownerdomain);
8347: return ($ownername,$ownerdomain,$ownerhome);
8348: }
8349: }
8350:
8351: # We don't have any access right now. If we are not possibly going to do anything about this,
8352: # we might as well leave
8353: unless ($setpriv) { return ''; }
8354:
8355: # Backdoor access?
8356: my $allowed=&allowed('eco',$ownerdomain);
8357: # Nope
8358: unless ($allowed) { return ''; }
8359: # Looks like we may have access, but could be locked by the owner of the construction space
8360: if ($allowed eq 'U') {
8361: my %blocked=&get('environment',['domcoord.author'],
8362: $ownerdomain,$ownername);
8363: # Is blocked by owner
8364: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8365: }
8366: if (($allowed eq 'F') || ($allowed eq 'U')) {
8367: # Grant temporary access
8368: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 8369: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 8370: if (!$update) { $update = $then; }
8371: my $refresh=$env{'user.refresh.time'};
8372: if (!$refresh) { $refresh = $update; }
8373: my $now = time;
8374: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8375: $now,'ca','constructaccess');
8376: $ownerhome = &homeserver($ownername,$ownerdomain);
8377: return($ownername,$ownerdomain,$ownerhome);
8378: }
8379: # No business here
8380: return '';
8381: }
8382:
1.1172.2.66 raeburn 8383: # ----------------------------------------------------------- Content Blocking
8384:
8385: {
8386: # Caches for faster Course Contents display where content blocking
8387: # is in operation (i.e., interval param set) for timed quiz.
8388: #
8389: # User for whom data are being temporarily cached.
8390: my $cacheduser='';
1.1172.2.126 raeburn 8391: # Course for which data are being temporarily cached.
8392: my $cachedcid='';
8393: # List of blocks passed to &get_commblock_resources();
8394: my $cachedblocks='';
1.1172.2.66 raeburn 8395: # Cached blockers for this user (a hash of blocking items).
8396: my %cachedblockers=();
8397: # When the data were last cached.
8398: my $cachedlast='';
8399:
8400: sub load_all_blockers {
8401: my ($uname,$udom,$blocks)=@_;
8402: if (($uname ne '') && ($udom ne '')) {
8403: if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126 raeburn 8404: ($cachedcid eq $env{'request.course.id'}) &&
8405: (abs($cachedlast-time)<5) &&
8406: (((ref($blocks) eq 'HASH') &&
8407: ($cachedblocks eq join(',',sort(keys(%{$blocks}))))) ||
8408: (!ref($blocks) && $cachedblocks eq ''))) {
1.1172.2.66 raeburn 8409: return;
8410: }
8411: }
8412: $cachedlast=time;
8413: $cacheduser=$uname.':'.$udom;
1.1172.2.126 raeburn 8414: $cachedcid=$env{'request.course.id'};
1.1172.2.66 raeburn 8415: %cachedblockers = &get_commblock_resources($blocks);
1.1172.2.126 raeburn 8416: if ((ref($blocks) eq 'HASH') && (keys(%{$blocks}) > 0)) {
8417: $cachedblocks = join(',',sort(keys(%{$blocks})));
8418: }
8419: return;
1.1172.2.66 raeburn 8420: }
8421:
1.1162 raeburn 8422: sub get_comm_blocks {
8423: my ($cdom,$cnum) = @_;
8424: if ($cdom eq '' || $cnum eq '') {
8425: return unless ($env{'request.course.id'});
8426: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8427: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8428: }
8429: my %commblocks;
8430: my $hashid=$cdom.'_'.$cnum;
8431: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8432: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8433: %commblocks = %{$blocksref};
8434: } else {
8435: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8436: my $cachetime = 600;
8437: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8438: }
8439: return %commblocks;
8440: }
8441:
1.1172.2.66 raeburn 8442: sub get_commblock_resources {
8443: my ($blocks) = @_;
8444: my %blockers = ();
8445: return %blockers unless ($env{'request.course.id'});
8446: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8447: my %commblocks;
8448: if (ref($blocks) eq 'HASH') {
8449: %commblocks = %{$blocks};
8450: } else {
8451: %commblocks = &get_comm_blocks();
8452: }
1.1172.2.66 raeburn 8453: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 8454: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 8455: return %blockers unless (ref($navmap));
8456: my $now = time;
1.1162 raeburn 8457: foreach my $block (keys(%commblocks)) {
8458: if ($block =~ /^(\d+)____(\d+)$/) {
8459: my ($start,$end) = ($1,$2);
8460: if ($start <= $now && $end >= $now) {
8461: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8462: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8463: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 8464: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8465: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8466: }
8467: }
8468: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 8469: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8470: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8471: }
8472: }
8473: }
8474: }
8475: }
8476: } elsif ($block =~ /^firstaccess____(.+)$/) {
8477: my $item = $1;
1.1163 raeburn 8478: my @to_test;
1.1162 raeburn 8479: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8480: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 8481: my @interval;
8482: my $type = 'map';
8483: if ($item eq 'course') {
8484: $type = 'course';
8485: @interval=&EXT("resource.0.interval");
8486: } else {
8487: if ($item =~ /___\d+___/) {
8488: $type = 'resource';
8489: @interval=&EXT("resource.0.interval",$item);
8490: if (ref($navmap)) {
8491: my $res = $navmap->getBySymb($item);
8492: push(@to_test,$res);
8493: }
1.1162 raeburn 8494: } else {
1.1172.2.66 raeburn 8495: my $mapsymb = &symbread($item,1);
8496: if ($mapsymb) {
8497: if (ref($navmap)) {
8498: my $mapres = $navmap->getBySymb($mapsymb);
8499: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8500: foreach my $res (@to_test) {
8501: my $symb = $res->symb();
8502: next if ($symb eq $mapsymb);
8503: if ($symb ne '') {
8504: @interval=&EXT("resource.0.interval",$symb);
8505: if ($interval[1] eq 'map') {
8506: last;
1.1162 raeburn 8507: }
8508: }
8509: }
8510: }
8511: }
8512: }
1.1172.2.66 raeburn 8513: }
8514: if ($interval[0] =~ /^\d+$/) {
8515: my $first_access;
8516: if ($type eq 'resource') {
8517: $first_access=&get_first_access($interval[1],$item);
8518: } elsif ($type eq 'map') {
8519: $first_access=&get_first_access($interval[1],undef,$item);
8520: } else {
8521: $first_access=&get_first_access($interval[1]);
8522: }
8523: if ($first_access) {
8524: my $timesup = $first_access+$interval[0];
8525: if ($timesup > $now) {
8526: my $activeblock;
8527: foreach my $res (@to_test) {
8528: if ($res->answerable()) {
8529: $activeblock = 1;
8530: last;
8531: }
8532: }
8533: if ($activeblock) {
8534: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8535: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8536: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8537: }
8538: }
8539: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8540: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8541: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8542: }
1.1162 raeburn 8543: }
8544: }
8545: }
8546: }
8547: }
8548: }
8549: }
8550: }
8551: }
1.1172.2.66 raeburn 8552: return %blockers;
1.1162 raeburn 8553: }
8554:
1.1172.2.66 raeburn 8555: sub has_comm_blocking {
1.1172.2.127! raeburn 8556: my ($priv,$symb,$uri,$nosymbcache,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66 raeburn 8557: my @blockers;
8558: return unless ($env{'request.course.id'});
8559: return unless ($priv eq 'bre');
8560: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8561: return if ($env{'request.state'} eq 'construct');
8562: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
8563: return unless (keys(%cachedblockers) > 0);
8564: my (%possibles,@symbs);
8565: if (!$symb) {
1.1172.2.127! raeburn 8566: $symb = &symbread($uri,1,1,1,\%possibles,$nosymbcache,$noenccheck);
1.1162 raeburn 8567: }
1.1172.2.66 raeburn 8568: if ($symb) {
8569: @symbs = ($symb);
8570: } elsif (keys(%possibles)) {
8571: @symbs = keys(%possibles);
8572: }
8573: my $noblock;
8574: foreach my $symb (@symbs) {
8575: last if ($noblock);
8576: my ($map,$resid,$resurl)=&decode_symb($symb);
8577: foreach my $block (keys(%cachedblockers)) {
8578: if ($block =~ /^firstaccess____(.+)$/) {
8579: my $item = $1;
1.1172.2.126 raeburn 8580: unless ($blocked) {
8581: if (($item eq $map) || ($item eq $symb)) {
8582: $noblock = 1;
8583: last;
8584: }
1.1172.2.66 raeburn 8585: }
1.1162 raeburn 8586: }
1.1172.2.66 raeburn 8587: if (ref($cachedblockers{$block}) eq 'HASH') {
8588: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8589: if ($cachedblockers{$block}{'resources'}{$symb}) {
8590: unless (grep(/^\Q$block\E$/,@blockers)) {
8591: push(@blockers,$block);
8592: }
8593: }
8594: }
1.1172.2.126 raeburn 8595: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8596: if ($cachedblockers{$block}{'maps'}{$map}) {
8597: unless (grep(/^\Q$block\E$/,@blockers)) {
8598: push(@blockers,$block);
8599: }
1.1172.2.66 raeburn 8600: }
8601: }
1.1162 raeburn 8602: }
8603: }
8604: }
1.1172.2.126 raeburn 8605: unless ($noblock) {
8606: return @blockers;
8607: }
8608: return;
1.1172.2.66 raeburn 8609: }
1.1162 raeburn 8610: }
8611:
1.1172.2.66 raeburn 8612: # -------------------------------- Deversion and split uri into path an filename
8613:
1.1133 foxr 8614: #
1.1172.2.66 raeburn 8615: # Removes the version from a URI and
1.1133 foxr 8616: # splits it in to its filename and path to the filename.
8617: # Seems like File::Basename could have done this more clearly.
8618: # Parameters:
8619: # $uri - input URI
8620: # Returns:
8621: # Two element list consisting of
8622: # $pathname - the URI up to and excluding the trailing /
8623: # $filename - The part of the URI following the last /
8624: # NOTE:
8625: # Another realization of this is simply:
8626: # use File::Basename;
8627: # ...
8628: # $uri = shift;
8629: # $filename = basename($uri);
8630: # $path = dirname($uri);
8631: # return ($filename, $path);
8632: #
8633: # The implementation below is probably faster however.
8634: #
1.710 albertel 8635: sub split_uri_for_cond {
8636: my $uri=&deversion(&declutter(shift));
8637: my @uriparts=split(/\//,$uri);
8638: my $filename=pop(@uriparts);
8639: my $pathname=join('/',@uriparts);
8640: return ($pathname,$filename);
8641: }
1.232 www 8642: # --------------------------------------------------- Is a resource on the map?
8643:
8644: sub is_on_map {
1.710 albertel 8645: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8646: #Trying to find the conditional for the file
1.620 albertel 8647: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8648: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8649: if ($match) {
1.289 bowersj2 8650: return (1,$1);
8651: } else {
1.434 www 8652: return (0,0);
1.289 bowersj2 8653: }
1.12 www 8654: }
8655:
1.427 www 8656: # --------------------------------------------------------- Get symb from alias
8657:
8658: sub get_symb_from_alias {
8659: my $symb=shift;
8660: my ($map,$resid,$url)=&decode_symb($symb);
8661: # Already is a symb
8662: if ($url) { return $symb; }
8663: # Must be an alias
8664: my $aliassymb='';
8665: my %bighash;
1.620 albertel 8666: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8667: &GDBM_READER(),0640)) {
8668: my $rid=$bighash{'mapalias_'.$symb};
8669: if ($rid) {
8670: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8671: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8672: $resid,$bighash{'src_'.$rid});
1.427 www 8673: }
8674: untie %bighash;
8675: }
8676: return $aliassymb;
8677: }
8678:
1.12 www 8679: # ----------------------------------------------------------------- Define Role
8680:
8681: sub definerole {
8682: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8683: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8684: foreach my $role (split(':',$sysrole)) {
8685: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8686: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8687: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8688: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8689: return "refused:s:$crole&$cqual";
8690: }
8691: }
1.191 harris41 8692: }
1.800 albertel 8693: foreach my $role (split(':',$domrole)) {
8694: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8695: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8696: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8697: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8698: return "refused:d:$crole&$cqual";
8699: }
8700: }
1.191 harris41 8701: }
1.800 albertel 8702: foreach my $role (split(':',$courole)) {
8703: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8704: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8705: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8706: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8707: return "refused:c:$crole&$cqual";
8708: }
8709: }
1.191 harris41 8710: }
1.1172.2.84 raeburn 8711: my $uhome;
8712: if (($uname ne '') && ($udom ne '')) {
8713: $uhome = &homeserver($uname,$udom);
8714: return $uhome if ($uhome eq 'no_host');
8715: } else {
8716: $uname = $env{'user.name'};
8717: $udom = $env{'user.domain'};
8718: $uhome = $env{'user.home'};
8719: }
1.620 albertel 8720: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8721: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8722: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8723: return reply($command,$uhome);
1.12 www 8724: } else {
8725: return 'refused';
8726: }
1.105 harris41 8727: }
8728:
8729: # ---------------- Make a metadata query against the network of library servers
8730:
8731: sub metadata_query {
1.1172.2.33 raeburn 8732: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8733: my %rhash;
1.845 albertel 8734: my %libserv = &all_library();
1.244 matthew 8735: my @server_list = (defined($server_array) ? @$server_array
8736: : keys(%libserv) );
8737: for my $server (@server_list) {
1.1172.2.33 raeburn 8738: my $domains = '';
8739: if (ref($domains_hash) eq 'HASH') {
8740: $domains = $domains_hash->{$server};
8741: }
1.118 harris41 8742: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8743: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8744: $rhash{$server}=$reply;
8745: }
8746: else {
8747: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8748: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8749: $server);
8750: $rhash{$server}=$reply;
8751: }
1.112 harris41 8752: }
1.118 harris41 8753: return \%rhash;
1.240 www 8754: }
8755:
8756: # ----------------------------------------- Send log queries and wait for reply
8757:
8758: sub log_query {
8759: my ($uname,$udom,$query,%filters)=@_;
8760: my $uhome=&homeserver($uname,$udom);
8761: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8762: my $uhost=&hostname($uhome);
1.800 albertel 8763: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8764: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8765: $uhome);
1.479 albertel 8766: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8767: return get_query_reply($queryid);
8768: }
8769:
1.818 raeburn 8770: # -------------------------- Update MySQL table for portfolio file
8771:
8772: sub update_portfolio_table {
1.821 raeburn 8773: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8774: if ($group ne '') {
8775: $file_name =~s /^\Q$group\E//;
8776: }
1.818 raeburn 8777: my $homeserver = &homeserver($uname,$udom);
8778: my $queryid=
1.821 raeburn 8779: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8780: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8781: my $reply = &get_query_reply($queryid);
8782: return $reply;
8783: }
8784:
1.899 raeburn 8785: # -------------------------- Update MySQL allusers table
8786:
8787: sub update_allusers_table {
8788: my ($uname,$udom,$names) = @_;
8789: my $homeserver = &homeserver($uname,$udom);
8790: my $queryid=
8791: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8792: 'lastname='.&escape($names->{'lastname'}).'%%'.
8793: 'firstname='.&escape($names->{'firstname'}).'%%'.
8794: 'middlename='.&escape($names->{'middlename'}).'%%'.
8795: 'generation='.&escape($names->{'generation'}).'%%'.
8796: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8797: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8798: return;
1.899 raeburn 8799: }
8800:
1.508 raeburn 8801: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8802:
8803: sub fetch_enrollment_query {
1.511 raeburn 8804: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8805: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8806: my $maxtries = 1;
1.508 raeburn 8807: if ($context eq 'automated') {
8808: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8809: $sleep = 2;
8810: $loopmax = 100;
1.547 raeburn 8811: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8812: } else {
8813: $homeserver = &homeserver($cnum,$dom);
8814: }
1.838 albertel 8815: my $host=&hostname($homeserver);
1.506 raeburn 8816: my $cmd = '';
1.1000 raeburn 8817: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8818: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8819: }
8820: $cmd =~ s/%%$//;
8821: $cmd = &escape($cmd);
8822: my $query = 'fetchenrollment';
1.620 albertel 8823: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8824: unless ($queryid=~/^\Q$host\E\_/) {
8825: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8826: return 'error: '.$queryid;
8827: }
1.1172.2.93 raeburn 8828: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8829: my $tries = 1;
8830: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8831: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8832: $tries ++;
8833: }
1.526 raeburn 8834: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8835: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8836: } else {
1.901 albertel 8837: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8838: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8839: foreach my $line (@responses) {
8840: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8841: $$replyref{$key} = $value;
8842: }
8843: } else {
1.1117 foxr 8844: my $pathname = LONCAPA::tempdir();
1.800 albertel 8845: foreach my $line (@responses) {
8846: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8847: $$replyref{$key} = $value;
8848: if ($value > 0) {
1.800 albertel 8849: foreach my $item (@{$$affiliatesref{$key}}) {
8850: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8851: my $destname = $pathname.'/'.$filename;
8852: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8853: if ($xml_classlist =~ /^error/) {
8854: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8855: } else {
1.1172.2.96 raeburn 8856: if ( open(FILE,">",$destname) ) {
1.506 raeburn 8857: print FILE &unescape($xml_classlist);
8858: close(FILE);
1.526 raeburn 8859: } else {
8860: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8861: }
8862: }
8863: }
8864: }
8865: }
8866: }
8867: return 'ok';
8868: }
8869: return 'error';
8870: }
8871:
1.242 www 8872: sub get_query_reply {
1.1172.2.79 raeburn 8873: my ($queryid,$sleep,$loopmax) = @_;
8874: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8875: $sleep = 0.2;
8876: }
8877: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8878: $loopmax = 100;
8879: }
1.1117 foxr 8880: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8881: my $reply='';
1.1172.2.79 raeburn 8882: for (1..$loopmax) {
8883: sleep($sleep);
1.240 www 8884: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 8885: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 8886: $reply = join('',<$fh>);
8887: close($fh);
1.240 www 8888: } else { return 'error: reply_file_error'; }
1.242 www 8889: return &unescape($reply);
8890: }
1.240 www 8891: }
1.242 www 8892: return 'timeout:'.$queryid;
1.240 www 8893: }
8894:
8895: sub courselog_query {
1.241 www 8896: #
8897: # possible filters:
8898: # url: url or symb
8899: # username
8900: # domain
8901: # action: view, submit, grade
8902: # start: timestamp
8903: # end: timestamp
8904: #
1.240 www 8905: my (%filters)=@_;
1.620 albertel 8906: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8907: if ($filters{'url'}) {
8908: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8909: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8910: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8911: }
1.620 albertel 8912: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8913: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8914: return &log_query($cname,$cdom,'courselog',%filters);
8915: }
8916:
8917: sub userlog_query {
1.858 raeburn 8918: #
8919: # possible filters:
8920: # action: log check role
8921: # start: timestamp
8922: # end: timestamp
8923: #
1.240 www 8924: my ($uname,$udom,%filters)=@_;
8925: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8926: }
8927:
1.506 raeburn 8928: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8929:
8930: sub auto_run {
1.508 raeburn 8931: my ($cnum,$cdom) = @_;
1.876 raeburn 8932: my $response = 0;
8933: my $settings;
8934: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8935: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8936: $settings = $domconfig{'autoenroll'};
8937: if ($settings->{'run'} eq '1') {
8938: $response = 1;
8939: }
8940: } else {
1.934 raeburn 8941: my $homeserver;
8942: if (&is_course($cdom,$cnum)) {
8943: $homeserver = &homeserver($cnum,$cdom);
8944: } else {
8945: $homeserver = &domain($cdom,'primary');
8946: }
8947: if ($homeserver ne 'no_host') {
8948: $response = &reply('autorun:'.$cdom,$homeserver);
8949: }
1.876 raeburn 8950: }
1.506 raeburn 8951: return $response;
8952: }
1.776 albertel 8953:
1.506 raeburn 8954: sub auto_get_sections {
1.508 raeburn 8955: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8956: my $homeserver;
8957: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8958: $homeserver = &homeserver($cnum,$cdom);
8959: }
8960: if (!defined($homeserver)) {
8961: if ($cdom =~ /^$match_domain$/) {
8962: $homeserver = &domain($cdom,'primary');
8963: }
8964: }
8965: my @secs;
8966: if (defined($homeserver)) {
8967: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8968: unless ($response eq 'refused') {
8969: @secs = split(/:/,$response);
8970: }
1.506 raeburn 8971: }
8972: return @secs;
8973: }
1.776 albertel 8974:
1.506 raeburn 8975: sub auto_new_course {
1.1099 raeburn 8976: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8977: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8978: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8979: return $response;
8980: }
1.776 albertel 8981:
1.506 raeburn 8982: sub auto_validate_courseID {
1.508 raeburn 8983: my ($cnum,$cdom,$inst_course_id) = @_;
8984: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8985: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8986: return $response;
8987: }
1.776 albertel 8988:
1.1007 raeburn 8989: sub auto_validate_instcode {
1.1020 raeburn 8990: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8991: my ($homeserver,$response);
8992: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8993: $homeserver = &homeserver($cnum,$cdom);
8994: }
8995: if (!defined($homeserver)) {
8996: if ($cdom =~ /^$match_domain$/) {
8997: $homeserver = &domain($cdom,'primary');
8998: }
8999: }
1.1065 raeburn 9000: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9001: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 9002: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9003: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9004: }
9005:
1.506 raeburn 9006: sub auto_create_password {
1.873 raeburn 9007: my ($cnum,$cdom,$authparam,$udom) = @_;
9008: my ($homeserver,$response);
1.506 raeburn 9009: my $create_passwd = 0;
9010: my $authchk = '';
1.873 raeburn 9011: if ($udom =~ /^$match_domain$/) {
9012: $homeserver = &domain($udom,'primary');
9013: }
9014: if ($homeserver eq '') {
9015: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9016: $homeserver = &homeserver($cnum,$cdom);
9017: }
9018: }
9019: if ($homeserver eq '') {
9020: $authchk = 'nodomain';
1.506 raeburn 9021: } else {
1.873 raeburn 9022: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9023: if ($response eq 'refused') {
9024: $authchk = 'refused';
9025: } else {
1.901 albertel 9026: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9027: }
1.506 raeburn 9028: }
9029: return ($authparam,$create_passwd,$authchk);
9030: }
9031:
1.706 raeburn 9032: sub auto_photo_permission {
9033: my ($cnum,$cdom,$students) = @_;
9034: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9035: my ($outcome,$perm_reqd,$conditions) =
9036: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9037: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9038: return (undef,undef);
9039: }
1.706 raeburn 9040: return ($outcome,$perm_reqd,$conditions);
9041: }
9042:
9043: sub auto_checkphotos {
9044: my ($uname,$udom,$pid) = @_;
9045: my $homeserver = &homeserver($uname,$udom);
9046: my ($result,$resulttype);
9047: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9048: &escape($uname).':'.&escape($pid),
9049: $homeserver));
1.709 albertel 9050: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9051: return (undef,undef);
9052: }
1.706 raeburn 9053: if ($outcome) {
9054: ($result,$resulttype) = split(/:/,$outcome);
9055: }
9056: return ($result,$resulttype);
9057: }
9058:
9059: sub auto_photochoice {
9060: my ($cnum,$cdom) = @_;
9061: my $homeserver = &homeserver($cnum,$cdom);
9062: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9063: &escape($cdom),
9064: $homeserver)));
1.709 albertel 9065: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9066: return (undef,undef);
9067: }
1.706 raeburn 9068: return ($update,$comment);
9069: }
9070:
9071: sub auto_photoupdate {
9072: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9073: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9074: my $host=&hostname($homeserver);
1.706 raeburn 9075: my $cmd = '';
9076: my $maxtries = 1;
1.800 albertel 9077: foreach my $affiliate (keys(%{$affiliatesref})) {
9078: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9079: }
9080: $cmd =~ s/%%$//;
9081: $cmd = &escape($cmd);
9082: my $query = 'institutionalphotos';
9083: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9084: unless ($queryid=~/^\Q$host\E\_/) {
9085: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9086: return 'error: '.$queryid;
9087: }
9088: my $reply = &get_query_reply($queryid);
9089: my $tries = 1;
9090: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9091: $reply = &get_query_reply($queryid);
9092: $tries ++;
9093: }
9094: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9095: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9096: } else {
9097: my @responses = split(/:/,$reply);
9098: my $outcome = shift(@responses);
9099: foreach my $item (@responses) {
9100: my ($key,$value) = split(/=/,$item);
9101: $$photo{$key} = $value;
9102: }
9103: return $outcome;
9104: }
9105: return 'error';
9106: }
9107:
1.521 raeburn 9108: sub auto_instcode_format {
1.793 albertel 9109: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9110: $cat_order) = @_;
1.521 raeburn 9111: my $courses = '';
1.772 raeburn 9112: my @homeservers;
1.521 raeburn 9113: if ($caller eq 'global') {
1.841 albertel 9114: my %servers = &get_servers($codedom,'library');
9115: foreach my $tryserver (keys(%servers)) {
9116: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9117: push(@homeservers,$tryserver);
9118: }
1.584 raeburn 9119: }
1.1022 raeburn 9120: } elsif ($caller eq 'requests') {
9121: if ($codedom =~ /^$match_domain$/) {
9122: my $chome = &domain($codedom,'primary');
9123: unless ($chome eq 'no_host') {
9124: push(@homeservers,$chome);
9125: }
9126: }
1.521 raeburn 9127: } else {
1.772 raeburn 9128: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9129: }
1.793 albertel 9130: foreach my $code (keys(%{$instcodes})) {
9131: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9132: }
9133: chop($courses);
1.772 raeburn 9134: my $ok_response = 0;
9135: my $response;
9136: while (@homeservers > 0 && $ok_response == 0) {
9137: my $server = shift(@homeservers);
9138: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9139: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9140: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9141: split(/:/,$response);
1.772 raeburn 9142: %{$codes} = (%{$codes},&str2hash($codes_str));
9143: push(@{$codetitles},&str2array($codetitles_str));
9144: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9145: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9146: $ok_response = 1;
9147: }
9148: }
9149: if ($ok_response) {
1.521 raeburn 9150: return 'ok';
1.772 raeburn 9151: } else {
9152: return $response;
1.521 raeburn 9153: }
9154: }
9155:
1.792 raeburn 9156: sub auto_instcode_defaults {
9157: my ($domain,$returnhash,$code_order) = @_;
9158: my @homeservers;
1.841 albertel 9159:
9160: my %servers = &get_servers($domain,'library');
9161: foreach my $tryserver (keys(%servers)) {
9162: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9163: push(@homeservers,$tryserver);
9164: }
1.792 raeburn 9165: }
1.841 albertel 9166:
1.792 raeburn 9167: my $response;
1.841 albertel 9168: foreach my $server (@homeservers) {
1.792 raeburn 9169: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9170: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9171:
9172: foreach my $pair (split(/\&/,$response)) {
9173: my ($name,$value)=split(/\=/,$pair);
9174: if ($name eq 'code_order') {
9175: @{$code_order} = split(/\&/,&unescape($value));
9176: } else {
9177: $returnhash->{&unescape($name)}=&unescape($value);
9178: }
9179: }
9180: return 'ok';
1.792 raeburn 9181: }
1.841 albertel 9182:
9183: return $response;
1.1003 raeburn 9184: }
9185:
9186: sub auto_possible_instcodes {
1.1007 raeburn 9187: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9188: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9189: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9190: return;
9191: }
1.1003 raeburn 9192: my (@homeservers,$uhome);
9193: if (defined(&domain($domain,'primary'))) {
9194: $uhome=&domain($domain,'primary');
9195: push(@homeservers,&domain($domain,'primary'));
9196: } else {
9197: my %servers = &get_servers($domain,'library');
9198: foreach my $tryserver (keys(%servers)) {
9199: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9200: push(@homeservers,$tryserver);
9201: }
9202: }
9203: }
9204: my $response;
9205: foreach my $server (@homeservers) {
9206: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9207: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9208: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9209: split(':',$response);
9210: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9211: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9212: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9213: my ($name,$value)=split('=',$item);
9214: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9215: }
9216: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9217: my ($name,$value)=split('=',$item);
9218: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9219: }
9220: return 'ok';
9221: }
9222: return $response;
9223: }
1.792 raeburn 9224:
1.1010 raeburn 9225: sub auto_courserequest_checks {
9226: my ($dom) = @_;
1.1020 raeburn 9227: my ($homeserver,%validations);
9228: if ($dom =~ /^$match_domain$/) {
9229: $homeserver = &domain($dom,'primary');
9230: }
9231: unless ($homeserver eq 'no_host') {
9232: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9233: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9234: my @items = split(/&/,$response);
9235: foreach my $item (@items) {
9236: my ($key,$value) = split('=',$item);
9237: $validations{&unescape($key)} = &thaw_unescape($value);
9238: }
9239: }
9240: }
1.1010 raeburn 9241: return %validations;
9242: }
9243:
1.1020 raeburn 9244: sub auto_courserequest_validation {
1.1172.2.43 raeburn 9245: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9246: my ($homeserver,$response);
9247: if ($dom =~ /^$match_domain$/) {
9248: $homeserver = &domain($dom,'primary');
9249: }
1.1172.2.43 raeburn 9250: unless ($homeserver eq 'no_host') {
9251: my $customdata;
9252: if (ref($custominfo) eq 'HASH') {
9253: $customdata = &freeze_escape($custominfo);
9254: }
1.1020 raeburn 9255: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9256: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 9257: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9258: $customdata,$homeserver));
1.1020 raeburn 9259: }
9260: return $response;
9261: }
9262:
1.777 albertel 9263: sub auto_validate_class_sec {
1.918 raeburn 9264: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9265: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9266: my $ownerlist;
9267: if (ref($owners) eq 'ARRAY') {
9268: $ownerlist = join(',',@{$owners});
9269: } else {
9270: $ownerlist = $owners;
9271: }
1.773 raeburn 9272: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9273: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9274: return $response;
9275: }
9276:
1.1172.2.94 raeburn 9277: sub auto_validate_instclasses {
9278: my ($cdom,$cnum,$owners,$classesref) = @_;
9279: my ($homeserver,%validations);
9280: $homeserver = &homeserver($cnum,$cdom);
9281: unless ($homeserver eq 'no_host') {
9282: my $ownerlist;
9283: if (ref($owners) eq 'ARRAY') {
9284: $ownerlist = join(',',@{$owners});
9285: } else {
9286: $ownerlist = $owners;
9287: }
9288: if (ref($classesref) eq 'HASH') {
9289: my $classes = &freeze_escape($classesref);
9290: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9291: ':'.$cdom.':'.$classes,$homeserver);
9292: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9293: my @items = split(/&/,$response);
9294: foreach my $item (@items) {
9295: my ($key,$value) = split('=',$item);
9296: $validations{&unescape($key)} = &thaw_unescape($value);
9297: }
9298: }
9299: }
9300: }
9301: return %validations;
9302: }
9303:
1.1172.2.38 raeburn 9304: sub auto_crsreq_update {
9305: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 9306: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 9307: my ($homeserver,%crsreqresponse);
9308: if ($cdom =~ /^$match_domain$/) {
9309: $homeserver = &domain($cdom,'primary');
9310: }
9311: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9312: my $info;
9313: if (ref($inbound) eq 'HASH') {
9314: $info = &freeze_escape($inbound);
9315: }
9316: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9317: ':'.&escape($action).':'.&escape($ownername).':'.
9318: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 9319: &escape($title).':'.&escape($code).':'.
9320: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 9321: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9322: my @items = split(/&/,$response);
9323: foreach my $item (@items) {
9324: my ($key,$value) = split('=',$item);
9325: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9326: }
9327: }
9328: }
9329: return \%crsreqresponse;
9330: }
9331:
1.1172.2.78 raeburn 9332: sub auto_export_grades {
9333: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9334: my ($homeserver,%exportresponse);
9335: if ($cdom =~ /^$match_domain$/) {
9336: $homeserver = &domain($cdom,'primary');
9337: }
9338: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9339: my $info;
9340: if (ref($inforef) eq 'HASH') {
9341: $info = &freeze_escape($inforef);
9342: }
9343: if (ref($gradesref) eq 'HASH') {
9344: my $grades = &freeze_escape($gradesref);
9345: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9346: $info.':'.$grades,$homeserver);
9347: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9348: my @items = split(/&/,$response);
9349: foreach my $item (@items) {
9350: my ($key,$value) = split('=',$item);
9351: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9352: }
9353: }
9354: }
9355: }
9356: return \%exportresponse;
9357: }
9358:
1.1172.2.68 raeburn 9359: sub check_instcode_cloning {
9360: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9361: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9362: return;
9363: }
9364: my $canclone;
9365: if (@{$code_order} > 0) {
9366: my $instcoderegexp ='^';
9367: my @clonecodes = split(/\&/,$cloner);
9368: foreach my $item (@{$code_order}) {
9369: if (grep(/^\Q$item\E=/,@clonecodes)) {
9370: foreach my $pair (@clonecodes) {
9371: my ($key,$val) = split(/\=/,$pair,2);
9372: $val = &unescape($val);
9373: if ($key eq $item) {
9374: $instcoderegexp .= '('.$val.')';
9375: last;
9376: }
9377: }
9378: } else {
9379: $instcoderegexp .= $codedefaults->{$item};
9380: }
9381: }
9382: $instcoderegexp .= '$';
9383: my (@from,@to);
9384: eval {
9385: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9386: (@to) = ($clonetocode =~ /$instcoderegexp/);
9387: };
9388: if ((@from > 0) && (@to > 0)) {
9389: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9390: if (!@diffs) {
9391: $canclone = 1;
9392: }
9393: }
9394: }
9395: return $canclone;
9396: }
9397:
9398: sub default_instcode_cloning {
9399: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9400: my (%codedefaults,@code_order,$canclone);
9401: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9402: %codedefaults = %{$codedefaultsref};
9403: @code_order = @{$codeorderref};
9404: } elsif ($clonedom) {
9405: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9406: }
9407: if (($domdefclone) && (@code_order)) {
9408: my @clonecodes = split(/\+/,$domdefclone);
9409: my $instcoderegexp ='^';
9410: foreach my $item (@code_order) {
9411: if (grep(/^\Q$item\E$/,@clonecodes)) {
9412: $instcoderegexp .= '('.$codedefaults{$item}.')';
9413: } else {
9414: $instcoderegexp .= $codedefaults{$item};
9415: }
9416: }
9417: $instcoderegexp .= '$';
9418: my (@from,@to);
9419: eval {
9420: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9421: (@to) = ($clonetocode =~ /$instcoderegexp/);
9422: };
9423: if ((@from > 0) && (@to > 0)) {
9424: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9425: if (!@diffs) {
9426: $canclone = 1;
9427: }
9428: }
9429: }
9430: return $canclone;
9431: }
9432:
1.679 raeburn 9433: # ------------------------------------------------------- Course Group routines
9434:
9435: sub get_coursegroups {
1.809 raeburn 9436: my ($cdom,$cnum,$group,$namespace) = @_;
9437: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9438: }
9439:
1.679 raeburn 9440: sub modify_coursegroup {
9441: my ($cdom,$cnum,$groupsettings) = @_;
9442: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9443: }
9444:
1.809 raeburn 9445: sub toggle_coursegroup_status {
9446: my ($cdom,$cnum,$group,$action) = @_;
9447: my ($from_namespace,$to_namespace);
9448: if ($action eq 'delete') {
9449: $from_namespace = 'coursegroups';
9450: $to_namespace = 'deleted_groups';
9451: } else {
9452: $from_namespace = 'deleted_groups';
9453: $to_namespace = 'coursegroups';
9454: }
9455: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9456: if (my $tmp = &error(%curr_group)) {
9457: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9458: return ('read error',$tmp);
9459: } else {
9460: my %savedsettings = %curr_group;
1.809 raeburn 9461: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9462: my $deloutcome;
9463: if ($result eq 'ok') {
1.809 raeburn 9464: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9465: } else {
9466: return ('write error',$result);
9467: }
9468: if ($deloutcome eq 'ok') {
9469: return 'ok';
9470: } else {
9471: return ('delete error',$deloutcome);
9472: }
9473: }
9474: }
9475:
1.679 raeburn 9476: sub modify_group_roles {
1.957 raeburn 9477: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9478: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9479: my $role = 'gr/'.&escape($userprivs);
9480: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9481: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9482: if ($result eq 'ok') {
9483: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9484: }
1.679 raeburn 9485: return $result;
9486: }
9487:
9488: sub modify_coursegroup_membership {
9489: my ($cdom,$cnum,$membership) = @_;
9490: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9491: return $result;
9492: }
9493:
1.682 raeburn 9494: sub get_active_groups {
9495: my ($udom,$uname,$cdom,$cnum) = @_;
9496: my $now = time;
9497: my %groups = ();
9498: foreach my $key (keys(%env)) {
1.811 albertel 9499: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9500: my ($start,$end) = split(/\./,$env{$key});
9501: if (($end!=0) && ($end<$now)) { next; }
9502: if (($start!=0) && ($start>$now)) { next; }
9503: if ($1 eq $cdom && $2 eq $cnum) {
9504: $groups{$3} = $env{$key} ;
9505: }
9506: }
9507: }
9508: return %groups;
9509: }
9510:
1.683 raeburn 9511: sub get_group_membership {
9512: my ($cdom,$cnum,$group) = @_;
9513: return(&dump('groupmembership',$cdom,$cnum,$group));
9514: }
9515:
9516: sub get_users_groups {
9517: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9518: my @usersgroups;
1.683 raeburn 9519: my $cachetime=1800;
9520:
9521: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9522: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9523: if (defined($cached)) {
1.734 albertel 9524: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9525: } else {
9526: $grouplist = '';
1.816 raeburn 9527: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9528: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9529: my $access_end = $env{'course.'.$courseid.
9530: '.default_enrollment_end_date'};
9531: my $now = time;
9532: foreach my $key (keys(%roleshash)) {
9533: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9534: my $group = $1;
9535: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9536: my $start = $2;
9537: my $end = $1;
9538: if ($start == -1) { next; } # deleted from group
9539: if (($start!=0) && ($start>$now)) { next; }
9540: if (($end!=0) && ($end<$now)) {
9541: if ($access_end && $access_end < $now) {
9542: if ($access_end - $end < 86400) {
9543: push(@usersgroups,$group);
1.733 raeburn 9544: }
9545: }
1.817 raeburn 9546: next;
1.733 raeburn 9547: }
1.817 raeburn 9548: push(@usersgroups,$group);
1.683 raeburn 9549: }
9550: }
9551: }
1.817 raeburn 9552: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9553: $grouplist = join(':',@usersgroups);
9554: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9555: }
1.733 raeburn 9556: return @usersgroups;
1.683 raeburn 9557: }
9558:
9559: sub devalidate_getgroups_cache {
9560: my ($udom,$uname,$cdom,$cnum)=@_;
9561: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9562:
1.683 raeburn 9563: my $hashid="$udom:$uname:$courseid";
9564: &devalidate_cache_new('getgroups',$hashid);
9565: }
9566:
1.12 www 9567: # ------------------------------------------------------------------ Plain Text
9568:
9569: sub plaintext {
1.988 raeburn 9570: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9571: if ($short =~ m{^cr/}) {
1.758 albertel 9572: return (split('/',$short))[-1];
9573: }
1.742 raeburn 9574: if (!defined($cid)) {
9575: $cid = $env{'request.course.id'};
9576: }
9577: my %rolenames = (
1.1008 raeburn 9578: Course => 'std',
9579: Community => 'alt1',
1.742 raeburn 9580: );
1.1037 raeburn 9581: if ($cid ne '') {
9582: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9583: unless ($forcedefault) {
9584: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9585: &Apache::lonlocal::mt_escape(\$roletext);
9586: return &Apache::lonlocal::mt($roletext);
9587: }
9588: }
9589: }
9590: if ((defined($type)) && (defined($rolenames{$type})) &&
9591: (defined($rolenames{$type})) &&
9592: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9593: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9594: } elsif ($cid ne '') {
9595: my $crstype = $env{'course.'.$cid.'.type'};
9596: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9597: (defined($prp{$short}{$rolenames{$crstype}}))) {
9598: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9599: }
1.742 raeburn 9600: }
1.1037 raeburn 9601: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9602: }
9603:
9604: # ----------------------------------------------------------------- Assign Role
9605:
9606: sub assignrole {
1.957 raeburn 9607: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9608: $context)=@_;
1.21 www 9609: my $mrole;
9610: if ($role =~ /^cr\//) {
1.393 www 9611: my $cwosec=$url;
1.811 albertel 9612: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9613: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9614: my $refused = 1;
9615: if ($context eq 'requestcourses') {
9616: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9617: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9618: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9619: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9620: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9621: if ($crsenv{'internal.courseowner'} eq
9622: $env{'user.name'}.':'.$env{'user.domain'}) {
9623: $refused = '';
9624: }
9625: }
9626: }
9627: }
9628: }
9629: if ($refused) {
9630: &logthis('Refused custom assignrole: '.
9631: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9632: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9633: return 'refused';
9634: }
1.104 www 9635: }
1.21 www 9636: $mrole='cr';
1.678 raeburn 9637: } elsif ($role =~ /^gr\//) {
9638: my $cwogrp=$url;
1.811 albertel 9639: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9640: unless (&allowed('mdg',$cwogrp)) {
9641: &logthis('Refused group assignrole: '.
9642: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9643: $env{'user.name'}.' at '.$env{'user.domain'});
9644: return 'refused';
9645: }
9646: $mrole='gr';
1.21 www 9647: } else {
1.82 www 9648: my $cwosec=$url;
1.811 albertel 9649: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9650: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9651: my $refused;
9652: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9653: if (!(&allowed('c'.$role,$url))) {
9654: $refused = 1;
9655: }
9656: } else {
9657: $refused = 1;
9658: }
1.947 raeburn 9659: if ($refused) {
1.1045 raeburn 9660: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9661: if (!$selfenroll && $context eq 'course') {
9662: my %crsenv;
9663: if ($role eq 'cc' || $role eq 'co') {
9664: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9665: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9666: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9667: if ($crsenv{'internal.courseowner'} eq
9668: $env{'user.name'}.':'.$env{'user.domain'}) {
9669: $refused = '';
9670: }
9671: }
9672: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9673: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9674: if ($crsenv{'internal.courseowner'} eq
9675: $env{'user.name'}.':'.$env{'user.domain'}) {
9676: $refused = '';
9677: }
9678: }
9679: }
9680: }
9681: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9682: $refused = '';
1.1017 raeburn 9683: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9684: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9685: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9686: my $wrongcc;
9687: if ($cnum =~ /^$match_community$/) {
9688: $wrongcc = 1 if ($role eq 'cc');
9689: } else {
9690: $wrongcc = 1 if ($role eq 'co');
9691: }
9692: unless ($wrongcc) {
9693: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9694: if ($crsenv{'internal.courseowner'} eq
9695: $env{'user.name'}.':'.$env{'user.domain'}) {
9696: $refused = '';
9697: }
1.1017 raeburn 9698: }
9699: }
1.1172.2.9 raeburn 9700: } elsif ($context eq 'requestauthor') {
9701: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9702: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9703: if ($env{'environment.requestauthor'} eq 'automatic') {
9704: $refused = '';
9705: } else {
9706: my %domdefaults = &get_domain_defaults($udom);
9707: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9708: my $checkbystatus;
9709: if ($env{'user.adv'}) {
9710: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9711: if ($disposition eq 'automatic') {
9712: $refused = '';
9713: } elsif ($disposition eq '') {
9714: $checkbystatus = 1;
9715: }
9716: } else {
9717: $checkbystatus = 1;
9718: }
9719: if ($checkbystatus) {
9720: if ($env{'environment.inststatus'}) {
9721: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9722: foreach my $type (@inststatuses) {
9723: if (($type ne '') &&
9724: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9725: $refused = '';
9726: }
9727: }
9728: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9729: $refused = '';
9730: }
9731: }
9732: }
9733: }
9734: }
1.1017 raeburn 9735: }
9736: if ($refused) {
1.947 raeburn 9737: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9738: ' '.$role.' '.$end.' '.$start.' by '.
9739: $env{'user.name'}.' at '.$env{'user.domain'});
9740: return 'refused';
9741: }
1.932 raeburn 9742: }
1.1131 raeburn 9743: } elsif ($role eq 'au') {
9744: if ($url ne '/'.$udom.'/') {
9745: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9746: ' to assign author role for '.$uname.':'.$udom.
9747: ' in domain: '.$url.' refused (wrong domain).');
9748: return 'refused';
9749: }
1.104 www 9750: }
1.21 www 9751: $mrole=$role;
9752: }
1.620 albertel 9753: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9754: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9755: if ($end) { $command.='_'.$end; }
1.21 www 9756: if ($start) {
9757: if ($end) {
1.81 www 9758: $command.='_'.$start;
1.21 www 9759: } else {
1.81 www 9760: $command.='_0_'.$start;
1.21 www 9761: }
9762: }
1.739 raeburn 9763: my $origstart = $start;
9764: my $origend = $end;
1.957 raeburn 9765: my $delflag;
1.357 www 9766: # actually delete
9767: if ($deleteflag) {
1.373 www 9768: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9769: # modify command to delete the role
1.620 albertel 9770: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9771: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9772: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9773: # set start and finish to negative values for userrolelog
9774: $start=-1;
9775: $end=-1;
1.957 raeburn 9776: $delflag = 1;
1.357 www 9777: }
9778: }
9779: # send command
1.349 www 9780: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9781: # log new user role if status is ok
1.349 www 9782: if ($answer eq 'ok') {
1.663 raeburn 9783: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9784: if (($role eq 'cc') || ($role eq 'in') ||
9785: ($role eq 'ep') || ($role eq 'ad') ||
9786: ($role eq 'ta') || ($role eq 'st') ||
9787: ($role=~/^cr/) || ($role eq 'gr') ||
9788: ($role eq 'co')) {
1.1172.2.13 raeburn 9789: # for course roles, perform group memberships changes triggered by role change.
9790: unless ($role =~ /^gr/) {
9791: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9792: $origstart,$selfenroll,$context);
9793: }
1.1172.2.9 raeburn 9794: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9795: $selfenroll,$context);
9796: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9797: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9798: ($role eq 'da')) {
1.1172.2.9 raeburn 9799: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9800: $context);
9801: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9802: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9803: $context);
9804: }
1.1053 raeburn 9805: if ($role eq 'cc') {
9806: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9807: }
1.349 www 9808: }
9809: return $answer;
1.169 harris41 9810: }
9811:
1.1053 raeburn 9812: sub autoupdate_coowners {
9813: my ($url,$end,$start,$uname,$udom) = @_;
9814: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9815: if (($cdom ne '') && ($cnum ne '')) {
9816: my $now = time;
9817: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9818: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9819: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9820: my $instcode = $coursehash{'internal.coursecode'};
9821: if ($instcode ne '') {
1.1056 raeburn 9822: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9823: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9824: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9825: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9826: if ($result eq 'valid') {
9827: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9828: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9829: push(@newcoowners,$coowner);
9830: }
9831: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9832: push(@newcoowners,$uname.':'.$udom);
9833: }
9834: @newcoowners = sort(@newcoowners);
9835: } else {
9836: push(@newcoowners,$uname.':'.$udom);
9837: }
9838: } else {
9839: if ($coursehash{'internal.co-owners'}) {
9840: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9841: unless ($coowner eq $uname.':'.$udom) {
9842: push(@newcoowners,$coowner);
9843: }
9844: }
9845: unless (@newcoowners > 0) {
9846: $delcoowners = 1;
9847: $coowners = '';
9848: }
9849: }
9850: }
9851: if (@newcoowners || $delcoowners) {
9852: &store_coowners($cdom,$cnum,$coursehash{'home'},
9853: $delcoowners,@newcoowners);
9854: }
9855: }
9856: }
9857: }
9858: }
9859: }
9860: }
9861:
9862: sub store_coowners {
9863: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9864: my $cid = $cdom.'_'.$cnum;
9865: my ($coowners,$delresult,$putresult);
9866: if (@newcoowners) {
9867: $coowners = join(',',@newcoowners);
9868: my %coownershash = (
9869: 'internal.co-owners' => $coowners,
9870: );
9871: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9872: if ($putresult eq 'ok') {
9873: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9874: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9875: }
9876: }
9877: }
9878: if ($delcoowners) {
9879: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9880: if ($delresult eq 'ok') {
9881: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9882: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9883: }
9884: }
9885: }
9886: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9887: my %crsinfo =
9888: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9889: if (ref($crsinfo{$cid}) eq 'HASH') {
9890: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9891: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9892: }
9893: }
9894: }
9895:
1.169 harris41 9896: # -------------------------------------------------- Modify user authentication
1.197 www 9897: # Overrides without validation
9898:
1.169 harris41 9899: sub modifyuserauth {
9900: my ($udom,$uname,$umode,$upass)=@_;
9901: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 9902: my $allowed;
9903: if (&allowed('mau',$udom)) {
9904: $allowed = 1;
9905: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
9906: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
9907: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
9908: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9909: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9910: if (($cdom ne '') && ($cnum ne '')) {
9911: my $is_owner = &is_course_owner($cdom,$cnum);
9912: if ($is_owner) {
9913: $allowed = 1;
9914: }
9915: }
9916: }
9917: unless ($allowed) { return 'refused'; }
1.197 www 9918: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9919: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9920: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9921: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9922: &escape($upass),$uhome);
1.620 albertel 9923: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9924: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9925: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9926: &log($udom,,$uname,$uhome,
1.620 albertel 9927: 'Authentication changed by '.$env{'user.domain'}.', '.
9928: $env{'user.name'}.', '.$umode.
1.197 www 9929: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9930: unless ($reply eq 'ok') {
1.197 www 9931: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9932: return 'error: '.$reply;
9933: }
1.170 harris41 9934: return 'ok';
1.80 www 9935: }
9936:
1.81 www 9937: # --------------------------------------------------------------- Modify a user
1.80 www 9938:
1.81 www 9939: sub modifyuser {
1.206 matthew 9940: my ($udom, $uname, $uid,
9941: $umode, $upass, $first,
9942: $middle, $last, $gene,
1.1058 raeburn 9943: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9944: $udom= &LONCAPA::clean_domain($udom);
9945: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9946: my $showcandelete = 'none';
9947: if (ref($candelete) eq 'ARRAY') {
9948: if (@{$candelete} > 0) {
9949: $showcandelete = join(', ',@{$candelete});
9950: }
9951: }
1.81 www 9952: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9953: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9954: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9955: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9956: ' desiredhome not specified').
1.620 albertel 9957: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9958: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9959: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9960: my $newuser;
9961: if ($uhome eq 'no_host') {
9962: $newuser = 1;
9963: }
1.80 www 9964: # ----------------------------------------------------------------- Create User
1.406 albertel 9965: if (($uhome eq 'no_host') &&
9966: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9967: my $unhome='';
1.844 albertel 9968: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9969: $unhome = $desiredhome;
1.620 albertel 9970: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9971: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9972: } else { # load balancing routine for determining $unhome
1.81 www 9973: my $loadm=10000000;
1.841 albertel 9974: my %servers = &get_servers($udom,'library');
9975: foreach my $tryserver (keys(%servers)) {
9976: my $answer=reply('load',$tryserver);
9977: if (($answer=~/\d+/) && ($answer<$loadm)) {
9978: $loadm=$answer;
9979: $unhome=$tryserver;
9980: }
1.80 www 9981: }
9982: }
9983: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9984: return 'error: unable to find a home server for '.$uname.
9985: ' in domain '.$udom;
1.80 www 9986: }
9987: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9988: &escape($upass),$unhome);
9989: unless ($reply eq 'ok') {
9990: return 'error: '.$reply;
9991: }
1.230 stredwic 9992: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9993: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9994: return 'error: unable verify users home machine.';
1.80 www 9995: }
1.209 matthew 9996: } # End of creation of new user
1.80 www 9997: # ---------------------------------------------------------------------- Add ID
9998: if ($uid) {
9999: $uid=~tr/A-Z/a-z/;
10000: my %uidhash=&idrget($udom,$uname);
1.196 www 10001: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10002: && (!$forceid)) {
1.80 www 10003: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10004: return 'error: user id "'.$uid.'" does not match '.
10005: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10006: }
10007: } else {
10008: &idput($udom,($uname => $uid));
10009: }
10010: }
10011: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10012: my @tmp=&get('environment',
1.899 raeburn 10013: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10014: 'permanentemail','inststatus'],
1.134 albertel 10015: $udom,$uname);
1.1075 raeburn 10016: my (%names,%oldnames);
1.313 matthew 10017: if ($tmp[0] =~ m/^error:.*/) {
10018: %names=();
10019: } else {
10020: %names = @tmp;
1.1075 raeburn 10021: %oldnames = %names;
1.313 matthew 10022: }
1.388 www 10023: #
1.1058 raeburn 10024: # If name, email and/or uid are blank (e.g., because an uploaded file
10025: # of users did not contain them), do not overwrite existing values
10026: # unless field is in $candelete array ref.
10027: #
10028:
10029: my @fields = ('firstname','middlename','lastname','generation',
10030: 'permanentemail','id');
10031: my %newvalues;
10032: if (ref($candelete) eq 'ARRAY') {
10033: foreach my $field (@fields) {
10034: if (grep(/^\Q$field\E$/,@{$candelete})) {
10035: if ($field eq 'firstname') {
10036: $names{$field} = $first;
10037: } elsif ($field eq 'middlename') {
10038: $names{$field} = $middle;
10039: } elsif ($field eq 'lastname') {
10040: $names{$field} = $last;
10041: } elsif ($field eq 'generation') {
10042: $names{$field} = $gene;
10043: } elsif ($field eq 'permanentemail') {
10044: $names{$field} = $email;
10045: } elsif ($field eq 'id') {
10046: $names{$field} = $uid;
10047: }
10048: }
10049: }
10050: }
1.388 www 10051: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10052: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10053: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10054: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10055: if ($email) {
10056: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10057: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10058: }
1.899 raeburn 10059: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10060: if (defined($inststatus)) {
10061: $names{'inststatus'} = '';
10062: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10063: if (ref($usertypes) eq 'HASH') {
10064: my @okstatuses;
10065: foreach my $item (split(/:/,$inststatus)) {
10066: if (defined($usertypes->{$item})) {
10067: push(@okstatuses,$item);
10068: }
10069: }
10070: if (@okstatuses) {
10071: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10072: }
10073: }
10074: }
1.1075 raeburn 10075: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10076: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10077: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10078: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10079: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10080: } else {
10081: $logmsg .= ' during self creation';
10082: }
1.1075 raeburn 10083: my $changed;
10084: if ($newuser) {
10085: $changed = 1;
10086: } else {
10087: foreach my $field (@fields) {
10088: if ($names{$field} ne $oldnames{$field}) {
10089: $changed = 1;
10090: last;
10091: }
10092: }
10093: }
10094: unless ($changed) {
10095: $logmsg = 'No changes in user information needed for: '.$logmsg;
10096: &logthis($logmsg);
10097: return 'ok';
10098: }
10099: my $reply = &put('environment', \%names, $udom,$uname);
10100: if ($reply ne 'ok') {
10101: return 'error: '.$reply;
10102: }
1.1087 raeburn 10103: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10104: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10105: }
1.1075 raeburn 10106: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10107: &devalidate_cache_new('namescache',$uname.':'.$udom);
10108: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10109: &logthis($logmsg);
1.134 albertel 10110: return 'ok';
1.80 www 10111: }
10112:
1.81 www 10113: # -------------------------------------------------------------- Modify student
1.80 www 10114:
1.81 www 10115: sub modifystudent {
10116: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10117: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10118: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10119: if (!$cid) {
1.620 albertel 10120: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10121: return 'not_in_class';
10122: }
1.80 www 10123: }
10124: # --------------------------------------------------------------- Make the user
1.81 www 10125: my $reply=&modifyuser
1.209 matthew 10126: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10127: $desiredhome,$email,$inststatus);
1.80 www 10128: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10129: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10130: # student's environment
1.297 matthew 10131: $uid = undef if (!$forceid);
1.455 albertel 10132: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10133: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10134: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10135: return $reply;
10136: }
10137:
10138: sub modify_student_enrollment {
1.1172.2.23 raeburn 10139: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10140: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10141: my ($cdom,$cnum,$chome);
10142: if (!$cid) {
1.620 albertel 10143: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10144: return 'not_in_class';
10145: }
1.620 albertel 10146: $cdom=$env{'course.'.$cid.'.domain'};
10147: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10148: } else {
10149: ($cdom,$cnum)=split(/_/,$cid);
10150: }
1.620 albertel 10151: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10152: if (!$chome) {
1.457 raeburn 10153: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10154: }
1.455 albertel 10155: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10156: # Make sure the user exists
1.81 www 10157: my $uhome=&homeserver($uname,$udom);
10158: if (($uhome eq '') || ($uhome eq 'no_host')) {
10159: return 'error: no such user';
10160: }
1.297 matthew 10161: # Get student data if we were not given enough information
10162: if (!defined($first) || $first eq '' ||
10163: !defined($last) || $last eq '' ||
10164: !defined($uid) || $uid eq '' ||
10165: !defined($middle) || $middle eq '' ||
10166: !defined($gene) || $gene eq '') {
1.294 matthew 10167: # They did not supply us with enough data to enroll the student, so
10168: # we need to pick up more information.
1.297 matthew 10169: my %tmp = &get('environment',
1.294 matthew 10170: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10171: ,$udom,$uname);
10172:
1.800 albertel 10173: #foreach my $key (keys(%tmp)) {
10174: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10175: #}
1.294 matthew 10176: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10177: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10178: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10179: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10180: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10181: }
1.556 albertel 10182: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10183: my $user = "$uname:$udom";
10184: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10185: my $reply=cput('classlist',
1.1148 raeburn 10186: {$user =>
1.1172.2.76 raeburn 10187: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10188: $cdom,$cnum);
1.1148 raeburn 10189: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10190: &devalidate_getsection_cache($udom,$uname,$cid);
10191: } else {
1.81 www 10192: return 'error: '.$reply;
10193: }
1.297 matthew 10194: # Add student role to user
1.83 www 10195: my $uurl='/'.$cid;
1.81 www 10196: $uurl=~s/\_/\//g;
10197: if ($usec) {
10198: $uurl.='/'.$usec;
10199: }
1.1148 raeburn 10200: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10201: $selfenroll,$context);
10202: if ($result ne 'ok') {
10203: if ($old_entry{$user} ne '') {
10204: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10205: } else {
10206: $reply = &del('classlist',[$user],$cdom,$cnum);
10207: }
10208: }
10209: return $result;
1.21 www 10210: }
10211:
1.556 albertel 10212: sub format_name {
10213: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10214: my $name;
10215: if ($first ne 'lastname') {
10216: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10217: } else {
10218: if ($lastname=~/\S/) {
10219: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10220: $name=~s/\s+,/,/;
10221: } else {
10222: $name.= $firstname.' '.$middlename.' '.$generation;
10223: }
10224: }
10225: $name=~s/^\s+//;
10226: $name=~s/\s+$//;
10227: $name=~s/\s+/ /g;
10228: return $name;
10229: }
10230:
1.84 www 10231: # ------------------------------------------------- Write to course preferences
10232:
10233: sub writecoursepref {
10234: my ($courseid,%prefs)=@_;
10235: $courseid=~s/^\///;
10236: $courseid=~s/\_/\//g;
10237: my ($cdomain,$cnum)=split(/\//,$courseid);
10238: my $chome=homeserver($cnum,$cdomain);
10239: if (($chome eq '') || ($chome eq 'no_host')) {
10240: return 'error: no such course';
10241: }
10242: my $cstring='';
1.800 albertel 10243: foreach my $pref (keys(%prefs)) {
10244: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10245: }
1.84 www 10246: $cstring=~s/\&$//;
10247: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10248: }
10249:
10250: # ---------------------------------------------------------- Make/modify course
10251:
10252: sub createcourse {
1.741 raeburn 10253: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10254: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10255: $url=&declutter($url);
10256: my $cid='';
1.1028 raeburn 10257: if ($context eq 'requestcourses') {
10258: my $can_create = 0;
10259: my ($ownername,$ownerdom) = split(':',$course_owner);
10260: if ($udom eq $ownerdom) {
10261: if (&usertools_access($ownername,$ownerdom,$category,undef,
10262: $context)) {
10263: $can_create = 1;
10264: }
10265: } else {
10266: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10267: $category);
10268: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10269: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10270: if (@curr > 0) {
10271: my @options = qw(approval validate autolimit);
10272: my $optregex = join('|',@options);
10273: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10274: $can_create = 1;
10275: }
10276: }
10277: }
10278: }
10279: if ($can_create) {
10280: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10281: unless (&allowed('ccc',$udom)) {
10282: return 'refused';
10283: }
1.1017 raeburn 10284: }
10285: } else {
10286: return 'refused';
10287: }
1.1028 raeburn 10288: } elsif (!&allowed('ccc',$udom)) {
10289: return 'refused';
1.84 www 10290: }
1.1011 raeburn 10291: # --------------------------------------------------------------- Get Unique ID
10292: my $uname;
10293: if ($cnum =~ /^$match_courseid$/) {
10294: my $chome=&homeserver($cnum,$udom,'true');
10295: if (($chome eq '') || ($chome eq 'no_host')) {
10296: $uname = $cnum;
10297: } else {
1.1038 raeburn 10298: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10299: }
10300: } else {
1.1038 raeburn 10301: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10302: }
10303: return $uname if ($uname =~ /^error/);
10304: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10305: if (!defined($course_server)) {
10306: if (defined(&domain($udom,'primary'))) {
10307: $course_server = &domain($udom,'primary');
10308: } else {
10309: $course_server = $env{'user.home'};
10310: }
10311: }
10312: my %host_servers =
10313: &Apache::lonnet::get_servers($udom,'library');
10314: unless ($host_servers{$course_server}) {
10315: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10316: }
1.84 www 10317: # ------------------------------------------------------------- Make the course
10318: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10319: $course_server);
1.84 www 10320: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10321: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10322: if (($uhome eq '') || ($uhome eq 'no_host')) {
10323: return 'error: no such course';
10324: }
1.271 www 10325: # ----------------------------------------------------------------- Course made
1.516 raeburn 10326: # log existence
1.1029 raeburn 10327: my $now = time;
1.918 raeburn 10328: my $newcourse = {
10329: $udom.'_'.$uname => {
1.921 raeburn 10330: description => $description,
10331: inst_code => $inst_code,
10332: owner => $course_owner,
10333: type => $crstype,
1.1029 raeburn 10334: creator => $env{'user.name'}.':'.
10335: $env{'user.domain'},
10336: created => $now,
10337: context => $context,
1.918 raeburn 10338: },
10339: };
1.921 raeburn 10340: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10341: # set toplevel url
1.271 www 10342: my $topurl=$url;
10343: unless ($nonstandard) {
10344: # ------------------------------------------ For standard courses, make top url
10345: my $mapurl=&clutter($url);
1.278 www 10346: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10347: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10348: <map>
10349: <resource id="1" type="start"></resource>
10350: <resource id="2" src="$mapurl"></resource>
10351: <resource id="3" type="finish"></resource>
10352: <link index="1" from="1" to="2"></link>
10353: <link index="2" from="2" to="3"></link>
10354: </map>
10355: ENDINITMAP
10356: $topurl=&declutter(
1.638 albertel 10357: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10358: );
10359: }
10360: # ----------------------------------------------------------- Write preferences
1.84 www 10361: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10362: ('description' => $description,
10363: 'url' => $topurl,
10364: 'internal.creator' => $env{'user.name'}.':'.
10365: $env{'user.domain'},
10366: 'internal.created' => $now,
10367: 'internal.creationcontext' => $context)
10368: );
1.84 www 10369: return '/'.$udom.'/'.$uname;
10370: }
10371:
1.1011 raeburn 10372: # ------------------------------------------------------------------- Create ID
10373: sub generate_coursenum {
1.1038 raeburn 10374: my ($udom,$crstype) = @_;
1.1011 raeburn 10375: my $domdesc = &domain($udom);
10376: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10377: my $first;
10378: if ($crstype eq 'Community') {
10379: $first = '0';
10380: } else {
10381: $first = int(1+rand(9));
10382: }
10383: my $uname=$first.
1.1011 raeburn 10384: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10385: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10386: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10387: # ----------------------------------------------- Make sure that does not exist
10388: my $uhome=&homeserver($uname,$udom,'true');
10389: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10390: if ($crstype eq 'Community') {
10391: $first = '0';
10392: } else {
10393: $first = int(1+rand(9));
10394: }
10395: $uname=$first.
1.1011 raeburn 10396: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10397: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10398: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10399: $uhome=&homeserver($uname,$udom,'true');
10400: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10401: return 'error: unable to generate unique course-ID';
10402: }
10403: }
10404: return $uname;
10405: }
10406:
1.813 albertel 10407: sub is_course {
1.1167 droeschl 10408: my ($cdom, $cnum) = scalar(@_) == 1 ?
10409: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 10410: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10411: my $uhome=&homeserver($cnum,$cdom);
10412: my $iscourse;
10413: if (grep { $_ eq $uhome } current_machine_ids()) {
10414: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10415: } else {
10416: my $hashid = $cdom.':'.$cnum;
10417: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10418: unless (defined($cached)) {
10419: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10420: $cnum,undef,undef,'.');
10421: $iscourse = 0;
10422: if (exists($courses{$cdom.'_'.$cnum})) {
10423: $iscourse = 1;
10424: }
10425: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10426: }
10427: }
10428: return unless($iscourse);
1.1167 droeschl 10429: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10430: }
10431:
1.1015 raeburn 10432: sub store_userdata {
10433: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10434: my $result;
1.1016 raeburn 10435: if ($datakey ne '') {
1.1013 raeburn 10436: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10437: if ($udom eq '' || $uname eq '') {
10438: $udom = $env{'user.domain'};
10439: $uname = $env{'user.name'};
10440: }
10441: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10442: if (($uhome eq '') || ($uhome eq 'no_host')) {
10443: $result = 'error: no_host';
10444: } else {
10445: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10446: $storehash->{'host'} = $perlvar{'lonHostID'};
10447:
10448: my $namevalue='';
10449: foreach my $key (keys(%{$storehash})) {
10450: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10451: }
10452: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 10453: unless ($namespace eq 'courserequests') {
10454: $datakey = &escape($datakey);
10455: }
1.1105 raeburn 10456: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10457: $namevalue,$uhome);
1.1013 raeburn 10458: }
10459: } else {
10460: $result = 'error: data to store was not a hash reference';
10461: }
10462: } else {
10463: $result= 'error: invalid requestkey';
10464: }
10465: return $result;
10466: }
10467:
1.21 www 10468: # ---------------------------------------------------------- Assign Custom Role
10469:
10470: sub assigncustomrole {
1.957 raeburn 10471: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10472: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10473: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10474: }
10475:
10476: # ----------------------------------------------------------------- Revoke Role
10477:
10478: sub revokerole {
1.957 raeburn 10479: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10480: my $now=time;
1.965 raeburn 10481: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10482: }
10483:
10484: # ---------------------------------------------------------- Revoke Custom Role
10485:
10486: sub revokecustomrole {
1.957 raeburn 10487: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10488: my $now=time;
1.357 www 10489: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10490: $deleteflag,$selfenroll,$context);
1.17 www 10491: }
10492:
1.533 banghart 10493: # ------------------------------------------------------------ Disk usage
1.535 albertel 10494: sub diskusage {
1.955 raeburn 10495: my ($udom,$uname,$directorypath,$getpropath)=@_;
10496: $directorypath =~ s/\/$//;
10497: my $listing=&reply('du2:'.&escape($directorypath).':'
10498: .&escape($getpropath).':'.&escape($uname).':'
10499: .&escape($udom),homeserver($uname,$udom));
10500: if ($listing eq 'unknown_cmd') {
10501: if ($getpropath) {
10502: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10503: }
10504: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10505: }
1.514 albertel 10506: return $listing;
1.512 banghart 10507: }
10508:
1.566 banghart 10509: sub is_locked {
1.1096 raeburn 10510: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10511: my @check;
10512: my $is_locked;
1.1093 raeburn 10513: push (@check,$file_name);
1.613 albertel 10514: my %locked = &get('file_permissions',\@check,
1.620 albertel 10515: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10516: my ($tmp)=keys(%locked);
10517: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10518:
1.566 banghart 10519: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10520: $is_locked = 'false';
10521: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10522: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10523: $is_locked = 'true';
1.1096 raeburn 10524: if (ref($which) eq 'ARRAY') {
10525: push(@{$which},$entry);
10526: } else {
10527: last;
10528: }
1.745 raeburn 10529: }
10530: }
1.566 banghart 10531: } else {
10532: $is_locked = 'false';
10533: }
1.1093 raeburn 10534: return $is_locked;
1.566 banghart 10535: }
10536:
1.759 albertel 10537: sub declutter_portfile {
10538: my ($file) = @_;
1.833 albertel 10539: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10540: return $file;
10541: }
10542:
1.559 banghart 10543: # ------------------------------------------------------------- Mark as Read Only
10544:
10545: sub mark_as_readonly {
10546: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10547: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10548: my ($tmp)=keys(%current_permissions);
10549: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10550: foreach my $file (@{$files}) {
1.759 albertel 10551: $file = &declutter_portfile($file);
1.561 banghart 10552: push(@{$current_permissions{$file}},$what);
1.559 banghart 10553: }
1.613 albertel 10554: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10555: return;
10556: }
10557:
1.572 banghart 10558: # ------------------------------------------------------------Save Selected Files
10559:
10560: sub save_selected_files {
10561: my ($user, $path, @files) = @_;
10562: my $filename = $user."savedfiles";
1.573 banghart 10563: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 10564: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10565: foreach my $file (@files) {
1.620 albertel 10566: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10567: }
10568: foreach my $file (@other_files) {
1.574 banghart 10569: print (OUT $file."\n");
1.572 banghart 10570: }
1.574 banghart 10571: close (OUT);
1.572 banghart 10572: return 'ok';
10573: }
10574:
1.574 banghart 10575: sub clear_selected_files {
10576: my ($user) = @_;
10577: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 10578: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10579: print (OUT undef);
10580: close (OUT);
10581: return ("ok");
10582: }
10583:
1.572 banghart 10584: sub files_in_path {
10585: my ($user, $path) = @_;
10586: my $filename = $user."savedfiles";
10587: my %return_files;
1.1172.2.96 raeburn 10588: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10589: while (my $line_in = <IN>) {
1.574 banghart 10590: chomp ($line_in);
10591: my @paths_and_file = split (m!/!, $line_in);
10592: my $file_part = pop (@paths_and_file);
10593: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10594: $path_part.='/';
10595: my $path_and_file = $path_part.$file_part;
10596: if ($path_part eq $path) {
10597: $return_files{$file_part}= 'selected';
10598: }
10599: }
1.574 banghart 10600: close (IN);
10601: return (\%return_files);
1.572 banghart 10602: }
10603:
10604: # called in portfolio select mode, to show files selected NOT in current directory
10605: sub files_not_in_path {
10606: my ($user, $path) = @_;
10607: my $filename = $user."savedfiles";
10608: my @return_files;
10609: my $path_part;
1.1172.2.96 raeburn 10610: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10611: while (my $line = <IN>) {
1.572 banghart 10612: #ok, I know it's clunky, but I want it to work
1.800 albertel 10613: my @paths_and_file = split(m|/|, $line);
10614: my $file_part = pop(@paths_and_file);
10615: chomp($file_part);
10616: my $path_part = join('/', @paths_and_file);
1.572 banghart 10617: $path_part .= '/';
10618: my $path_and_file = $path_part.$file_part;
10619: if ($path_part ne $path) {
1.800 albertel 10620: push(@return_files, ($path_and_file));
1.572 banghart 10621: }
10622: }
1.800 albertel 10623: close(OUT);
1.574 banghart 10624: return (@return_files);
1.572 banghart 10625: }
10626:
1.745 raeburn 10627: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10628:
1.745 raeburn 10629: sub get_portfile_permissions {
10630: my ($domain,$user) = @_;
1.613 albertel 10631: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10632: my ($tmp)=keys(%current_permissions);
10633: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10634: return \%current_permissions;
10635: }
10636:
10637: #---------------------------------------------Get portfolio file access controls
10638:
1.749 raeburn 10639: sub get_access_controls {
1.745 raeburn 10640: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10641: my %access;
10642: my $real_file = $file;
10643: $file =~ s/\.meta$//;
1.745 raeburn 10644: if (defined($file)) {
1.749 raeburn 10645: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10646: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10647: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10648: }
10649: }
1.745 raeburn 10650: } else {
1.749 raeburn 10651: foreach my $key (keys(%{$current_permissions})) {
10652: if ($key =~ /\0accesscontrol$/) {
10653: if (defined($group)) {
10654: if ($key !~ m-^\Q$group\E/-) {
10655: next;
10656: }
10657: }
10658: my ($fullpath) = split(/\0/,$key);
10659: if (ref($$current_permissions{$key}) eq 'HASH') {
10660: foreach my $control (keys(%{$$current_permissions{$key}})) {
10661: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10662: }
10663: }
10664: }
10665: }
10666: }
10667: return %access;
10668: }
10669:
10670: sub modify_access_controls {
10671: my ($file_name,$changes,$domain,$user)=@_;
10672: my ($outcome,$deloutcome);
10673: my %store_permissions;
10674: my %new_values;
10675: my %new_control;
10676: my %translation;
10677: my @deletions = ();
10678: my $now = time;
10679: if (exists($$changes{'activate'})) {
10680: if (ref($$changes{'activate'}) eq 'HASH') {
10681: my @newitems = sort(keys(%{$$changes{'activate'}}));
10682: my $numnew = scalar(@newitems);
10683: for (my $i=0; $i<$numnew; $i++) {
10684: my $newkey = $newitems[$i];
10685: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10686: if ($newkey =~ /^\d+:/) {
10687: $newkey =~ s/^(\d+)/$newid/;
10688: $translation{$1} = $newid;
10689: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10690: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10691: $translation{$1} = $newid;
10692: }
1.749 raeburn 10693: $new_values{$file_name."\0".$newkey} =
10694: $$changes{'activate'}{$newitems[$i]};
10695: $new_control{$newkey} = $now;
10696: }
10697: }
10698: }
10699: my %todelete;
10700: my %changed_items;
10701: foreach my $action ('delete','update') {
10702: if (exists($$changes{$action})) {
10703: if (ref($$changes{$action}) eq 'HASH') {
10704: foreach my $key (keys(%{$$changes{$action}})) {
10705: my ($itemnum) = ($key =~ /^([^:]+):/);
10706: if ($action eq 'delete') {
10707: $todelete{$itemnum} = 1;
10708: } else {
10709: $changed_items{$itemnum} = $key;
10710: }
10711: }
1.745 raeburn 10712: }
10713: }
1.749 raeburn 10714: }
10715: # get lock on access controls for file.
10716: my $lockhash = {
10717: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10718: ':'.$env{'user.domain'},
10719: };
10720: my $tries = 0;
10721: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10722:
1.1172.2.79 raeburn 10723: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10724: $tries ++;
1.1172.2.79 raeburn 10725: sleep(0.1);
1.749 raeburn 10726: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10727: }
10728: if ($gotlock eq 'ok') {
10729: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10730: my ($tmp)=keys(%curr_permissions);
10731: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10732: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10733: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10734: if (ref($curr_controls) eq 'HASH') {
10735: foreach my $control_item (keys(%{$curr_controls})) {
10736: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10737: if (defined($todelete{$itemnum})) {
10738: push(@deletions,$file_name."\0".$control_item);
10739: } else {
10740: if (defined($changed_items{$itemnum})) {
10741: $new_control{$changed_items{$itemnum}} = $now;
10742: push(@deletions,$file_name."\0".$control_item);
10743: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10744: } else {
10745: $new_control{$control_item} = $$curr_controls{$control_item};
10746: }
10747: }
1.745 raeburn 10748: }
10749: }
10750: }
1.970 raeburn 10751: my ($group);
10752: if (&is_course($domain,$user)) {
10753: ($group,my $file) = split(/\//,$file_name,2);
10754: }
1.749 raeburn 10755: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10756: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10757: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10758: # remove lock
10759: my @del_lock = ($file_name."\0".'locked_access_records');
10760: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10761: my $sqlresult =
1.970 raeburn 10762: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10763: $group);
1.749 raeburn 10764: } else {
10765: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10766: }
1.749 raeburn 10767: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10768: }
10769:
1.827 raeburn 10770: sub make_public_indefinitely {
10771: my ($requrl) = @_;
10772: my $now = time;
10773: my $action = 'activate';
10774: my $aclnum = 0;
10775: if (&is_portfolio_url($requrl)) {
10776: my (undef,$udom,$unum,$file_name,$group) =
10777: &parse_portfolio_url($requrl);
10778: my $current_perms = &get_portfile_permissions($udom,$unum);
10779: my %access_controls = &get_access_controls($current_perms,
10780: $group,$file_name);
10781: foreach my $key (keys(%{$access_controls{$file_name}})) {
10782: my ($num,$scope,$end,$start) =
10783: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10784: if ($scope eq 'public') {
10785: if ($start <= $now && $end == 0) {
10786: $action = 'none';
10787: } else {
10788: $action = 'update';
10789: $aclnum = $num;
10790: }
10791: last;
10792: }
10793: }
10794: if ($action eq 'none') {
10795: return 'ok';
10796: } else {
10797: my %changes;
10798: my $newend = 0;
10799: my $newstart = $now;
10800: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10801: $changes{$action}{$newkey} = {
10802: type => 'public',
10803: time => {
10804: start => $newstart,
10805: end => $newend,
10806: },
10807: };
10808: my ($outcome,$deloutcome,$new_values,$translation) =
10809: &modify_access_controls($file_name,\%changes,$udom,$unum);
10810: return $outcome;
10811: }
10812: } else {
10813: return 'invalid';
10814: }
10815: }
10816:
1.745 raeburn 10817: #------------------------------------------------------Get Marked as Read Only
10818:
10819: sub get_marked_as_readonly {
10820: my ($domain,$user,$what,$group) = @_;
10821: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10822: my @readonly_files;
1.629 banghart 10823: my $cmp1=$what;
10824: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10825: while (my ($file_name,$value) = each(%{$current_permissions})) {
10826: if (defined($group)) {
10827: if ($file_name !~ m-^\Q$group\E/-) {
10828: next;
10829: }
10830: }
1.561 banghart 10831: if (ref($value) eq "ARRAY"){
10832: foreach my $stored_what (@{$value}) {
1.629 banghart 10833: my $cmp2=$stored_what;
1.759 albertel 10834: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10835: $cmp2=join('',@{$stored_what});
1.745 raeburn 10836: }
1.629 banghart 10837: if ($cmp1 eq $cmp2) {
1.561 banghart 10838: push(@readonly_files, $file_name);
1.745 raeburn 10839: last;
1.563 banghart 10840: } elsif (!defined($what)) {
10841: push(@readonly_files, $file_name);
1.745 raeburn 10842: last;
1.561 banghart 10843: }
10844: }
1.745 raeburn 10845: }
1.561 banghart 10846: }
10847: return @readonly_files;
10848: }
1.577 banghart 10849: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10850:
1.577 banghart 10851: sub get_marked_as_readonly_hash {
1.745 raeburn 10852: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10853: my %readonly_files;
1.745 raeburn 10854: while (my ($file_name,$value) = each(%{$current_permissions})) {
10855: if (defined($group)) {
10856: if ($file_name !~ m-^\Q$group\E/-) {
10857: next;
10858: }
10859: }
1.577 banghart 10860: if (ref($value) eq "ARRAY"){
10861: foreach my $stored_what (@{$value}) {
1.745 raeburn 10862: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10863: foreach my $lock_descriptor(@{$stored_what}) {
10864: if ($lock_descriptor eq 'graded') {
10865: $readonly_files{$file_name} = 'graded';
10866: } elsif ($lock_descriptor eq 'handback') {
10867: $readonly_files{$file_name} = 'handback';
10868: } else {
10869: if (!exists($readonly_files{$file_name})) {
10870: $readonly_files{$file_name} = 'locked';
10871: }
10872: }
1.745 raeburn 10873: }
1.750 banghart 10874: }
1.577 banghart 10875: }
10876: }
10877: }
10878: return %readonly_files;
10879: }
1.559 banghart 10880: # ------------------------------------------------------------ Unmark as Read Only
10881:
10882: sub unmark_as_readonly {
1.629 banghart 10883: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10884: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10885: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10886: $file_name = &declutter_portfile($file_name);
1.634 albertel 10887: my $symb_crs = $what;
10888: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10889: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10890: my ($tmp)=keys(%current_permissions);
10891: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10892: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10893: foreach my $file (@readonly_files) {
1.759 albertel 10894: my $clean_file = &declutter_portfile($file);
10895: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10896: my $current_locks = $current_permissions{$file};
1.563 banghart 10897: my @new_locks;
10898: my @del_keys;
10899: if (ref($current_locks) eq "ARRAY"){
10900: foreach my $locker (@{$current_locks}) {
1.632 albertel 10901: my $compare=$locker;
1.749 raeburn 10902: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10903: $compare=join('',@{$locker});
1.746 raeburn 10904: if ($compare ne $symb_crs) {
10905: push(@new_locks, $locker);
10906: }
1.563 banghart 10907: }
10908: }
1.650 albertel 10909: if (scalar(@new_locks) > 0) {
1.563 banghart 10910: $current_permissions{$file} = \@new_locks;
10911: } else {
10912: push(@del_keys, $file);
1.613 albertel 10913: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10914: delete($current_permissions{$file});
1.563 banghart 10915: }
10916: }
1.561 banghart 10917: }
1.613 albertel 10918: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10919: return;
10920: }
1.512 banghart 10921:
1.17 www 10922: # ------------------------------------------------------------ Directory lister
10923:
10924: sub dirlist {
1.955 raeburn 10925: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10926: $uri=~s/^\///;
10927: $uri=~s/\/$//;
1.253 stredwic 10928: my ($udom, $uname);
1.955 raeburn 10929: if ($getuserdir) {
1.253 stredwic 10930: $udom = $userdomain;
10931: $uname = $username;
1.955 raeburn 10932: } else {
10933: (undef,$udom,$uname)=split(/\//,$uri);
10934: if(defined($userdomain)) {
10935: $udom = $userdomain;
10936: }
10937: if(defined($username)) {
10938: $uname = $username;
10939: }
1.253 stredwic 10940: }
1.955 raeburn 10941: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10942:
1.955 raeburn 10943: $dirRoot = $perlvar{'lonDocRoot'};
10944: if (defined($getpropath)) {
10945: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10946: $dirRoot =~ s/\/$//;
1.955 raeburn 10947: } elsif (defined($getuserdir)) {
10948: my $subdir=$uname.'__';
10949: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10950: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10951: ."/$udom/$subdir/$uname";
10952: } elsif (defined($alternateRoot)) {
10953: $dirRoot = $alternateRoot;
1.751 banghart 10954: }
1.253 stredwic 10955:
10956: if($udom) {
10957: if($uname) {
1.1135 raeburn 10958: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10959: if ($uhome eq 'no_host') {
10960: return ([],'no_host');
10961: }
1.955 raeburn 10962: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10963: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10964: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10965: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10966: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10967: } else {
10968: @listing_results = map { &unescape($_); } split(/:/,$listing);
10969: }
1.605 matthew 10970: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10971: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10972: @listing_results = split(/:/,$listing);
10973: } else {
10974: @listing_results = map { &unescape($_); } split(/:/,$listing);
10975: }
1.1135 raeburn 10976: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10977: ($listing eq 'rejected') || ($listing eq 'refused') ||
10978: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10979: return ([],$listing);
10980: } else {
10981: return (\@listing_results);
1.1135 raeburn 10982: }
1.955 raeburn 10983: } elsif(!$alternateRoot) {
1.1136 raeburn 10984: my (%allusers,%listerror);
1.841 albertel 10985: my %servers = &get_servers($udom,'library');
1.955 raeburn 10986: foreach my $tryserver (keys(%servers)) {
10987: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10988: &escape($udom),$tryserver);
10989: if ($listing eq 'unknown_cmd') {
10990: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10991: $udom, $tryserver);
10992: } else {
10993: @listing_results = map { &unescape($_); } split(/:/,$listing);
10994: }
1.841 albertel 10995: if ($listing eq 'unknown_cmd') {
10996: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10997: $udom, $tryserver);
10998: @listing_results = split(/:/,$listing);
10999: } else {
11000: @listing_results =
11001: map { &unescape($_); } split(/:/,$listing);
11002: }
1.1136 raeburn 11003: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11004: ($listing eq 'rejected') || ($listing eq 'refused') ||
11005: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11006: $listerror{$tryserver} = $listing;
11007: } else {
1.841 albertel 11008: foreach my $line (@listing_results) {
11009: my ($entry) = split(/&/,$line,2);
11010: $allusers{$entry} = 1;
11011: }
11012: }
1.253 stredwic 11013: }
1.1136 raeburn 11014: my @alluserslist=();
1.800 albertel 11015: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11016: push(@alluserslist,$user.'&user');
1.253 stredwic 11017: }
1.1172.2.80 raeburn 11018: if (!%listerror) {
11019: # no errors
11020: return (\@alluserslist);
11021: } elsif (scalar(keys(%servers)) == 1) {
11022: # one library server, one error
11023: my ($key) = keys(%listerror);
11024: return (\@alluserslist, $listerror{$key});
11025: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11026: # con_lost indicates that we might miss data from at least one
11027: # library server
11028: return (\@alluserslist, 'con_lost');
11029: } else {
11030: # multiple library servers and no con_lost -> data should be
11031: # complete.
11032: return (\@alluserslist);
11033: }
11034:
1.253 stredwic 11035: } else {
1.1136 raeburn 11036: return ([],'missing username');
1.253 stredwic 11037: }
1.955 raeburn 11038: } elsif(!defined($getpropath)) {
1.1136 raeburn 11039: my $path = $perlvar{'lonDocRoot'}.'/res/';
11040: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11041: return (\@all_domains);
1.955 raeburn 11042: } else {
1.1136 raeburn 11043: return ([],'missing domain');
1.275 stredwic 11044: }
11045: }
11046:
11047: # --------------------------------------------- GetFileTimestamp
11048: # This function utilizes dirlist and returns the date stamp for
11049: # when it was last modified. It will also return an error of -1
11050: # if an error occurs
11051:
11052: sub GetFileTimestamp {
1.955 raeburn 11053: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11054: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11055: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11056: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11057: undef,$getuserdir);
11058: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11059: return -1;
11060: }
11061: if (ref($fileref) eq 'ARRAY') {
11062: my @stats = split('&',$fileref->[0]);
1.375 matthew 11063: # @stats contains first the filename, then the stat output
11064: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11065: } else {
11066: return -1;
1.253 stredwic 11067: }
1.26 www 11068: }
11069:
1.712 albertel 11070: sub stat_file {
11071: my ($uri) = @_;
1.787 albertel 11072: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11073:
1.955 raeburn 11074: my ($udom,$uname,$file);
1.712 albertel 11075: if ($uri =~ m-^/(uploaded|editupload)/-) {
11076: ($udom,$uname,$file) =
1.811 albertel 11077: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11078: $file = 'userfiles/'.$file;
11079: }
11080: if ($uri =~ m-^/res/-) {
11081: ($udom,$uname) =
1.807 albertel 11082: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11083: $file = $uri;
11084: }
11085:
11086: if (!$udom || !$uname || !$file) {
11087: # unable to handle the uri
11088: return ();
11089: }
1.956 raeburn 11090: my $getpropath;
11091: if ($file =~ /^userfiles\//) {
11092: $getpropath = 1;
11093: }
1.1136 raeburn 11094: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11095: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11096: return ();
11097: } else {
11098: if (ref($listref) eq 'ARRAY') {
11099: my @stats = split('&',$listref->[0]);
11100: shift(@stats); #filename is first
11101: return @stats;
11102: }
1.712 albertel 11103: }
11104: return ();
11105: }
11106:
1.26 www 11107: # -------------------------------------------------------- Value of a Condition
11108:
1.713 albertel 11109: # gets the value of a specific preevaluated condition
11110: # stored in the string $env{user.state.<cid>}
11111: # or looks up a condition reference in the bighash and if if hasn't
11112: # already been evaluated recurses into docondval to get the value of
11113: # the condition, then memoizing it to
11114: # $env{user.state.<cid>.<condition>}
1.40 www 11115: sub directcondval {
11116: my $number=shift;
1.620 albertel 11117: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11118: &Apache::lonuserstate::evalstate();
11119: }
1.713 albertel 11120: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11121: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11122: } elsif ($number =~ /^_/) {
11123: my $sub_condition;
11124: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11125: &GDBM_READER(),0640)) {
11126: $sub_condition=$bighash{'conditions'.$number};
11127: untie(%bighash);
11128: }
11129: my $value = &docondval($sub_condition);
1.949 raeburn 11130: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11131: return $value;
11132: }
1.620 albertel 11133: if ($env{'user.state.'.$env{'request.course.id'}}) {
11134: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11135: } else {
11136: return 2;
11137: }
11138: }
11139:
1.713 albertel 11140: # get the collection of conditions for this resource
1.26 www 11141: sub condval {
11142: my $condidx=shift;
1.54 www 11143: my $allpathcond='';
1.713 albertel 11144: foreach my $cond (split(/\|/,$condidx)) {
11145: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11146: $allpathcond.=
11147: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11148: }
1.191 harris41 11149: }
1.54 www 11150: $allpathcond=~s/\|$//;
1.713 albertel 11151: return &docondval($allpathcond);
11152: }
11153:
11154: #evaluates an expression of conditions
11155: sub docondval {
11156: my ($allpathcond) = @_;
11157: my $result=0;
11158: if ($env{'request.course.id'}
11159: && defined($allpathcond)) {
11160: my $operand='|';
11161: my @stack;
11162: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11163: if ($chunk eq '(') {
11164: push @stack,($operand,$result);
11165: } elsif ($chunk eq ')') {
11166: my $before=pop @stack;
11167: if (pop @stack eq '&') {
11168: $result=$result>$before?$before:$result;
11169: } else {
11170: $result=$result>$before?$result:$before;
11171: }
11172: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11173: $operand=$chunk;
11174: } else {
11175: my $new=directcondval($chunk);
11176: if ($operand eq '&') {
11177: $result=$result>$new?$new:$result;
11178: } else {
11179: $result=$result>$new?$result:$new;
11180: }
11181: }
11182: }
1.26 www 11183: }
11184: return $result;
1.421 albertel 11185: }
11186:
11187: # ---------------------------------------------------- Devalidate courseresdata
11188:
11189: sub devalidatecourseresdata {
11190: my ($coursenum,$coursedomain)=@_;
11191: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11192: &devalidate_cache_new('courseres',$hashid);
1.28 www 11193: }
11194:
1.763 www 11195:
1.200 www 11196: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11197: #
11198: # Parameters:
11199: # $coursenum - Number of the course.
11200: # $coursedomain - Domain at which the course was created.
11201: # Returns:
11202: # A hash of the course parameters along (I think) with timestamps
11203: # and version info.
1.877 foxr 11204:
1.624 albertel 11205: sub get_courseresdata {
11206: my ($coursenum,$coursedomain)=@_;
1.200 www 11207: my $coursehom=&homeserver($coursenum,$coursedomain);
11208: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11209: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11210: my %dumpreply;
1.417 albertel 11211: unless (defined($cached)) {
1.624 albertel 11212: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11213: $result=\%dumpreply;
1.251 albertel 11214: my ($tmp) = keys(%dumpreply);
11215: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11216: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11217: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11218: return $tmp;
1.416 albertel 11219: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11220: $result=undef;
1.599 albertel 11221: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11222: }
11223: }
1.624 albertel 11224: return $result;
11225: }
11226:
1.633 albertel 11227: sub devalidateuserresdata {
11228: my ($uname,$udom)=@_;
11229: my $hashid="$udom:$uname";
11230: &devalidate_cache_new('userres',$hashid);
11231: }
11232:
1.624 albertel 11233: sub get_userresdata {
11234: my ($uname,$udom)=@_;
11235: #most student don\'t have any data set, check if there is some data
11236: if (&EXT_cache_status($udom,$uname)) { return undef; }
11237:
11238: my $hashid="$udom:$uname";
11239: my ($result,$cached)=&is_cached_new('userres',$hashid);
11240: if (!defined($cached)) {
11241: my %resourcedata=&dump('resourcedata',$udom,$uname);
11242: $result=\%resourcedata;
11243: &do_cache_new('userres',$hashid,$result,600);
11244: }
11245: my ($tmp)=keys(%$result);
11246: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11247: return $result;
11248: }
11249: #error 2 occurs when the .db doesn't exist
11250: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 11251: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11252: &logthis("<font color=\"blue\">WARNING:".
11253: " Trying to get resource data for ".
11254: $uname." at ".$udom.": ".
11255: $tmp."</font>");
11256: }
1.624 albertel 11257: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11258: #&EXT_cache_set($udom,$uname);
11259: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11260: undef($tmp); # not really an error so don't send it back
1.624 albertel 11261: }
11262: return $tmp;
11263: }
1.879 foxr 11264: #----------------------------------------------- resdata - return resource data
11265: # Purpose:
11266: # Return resource data for either users or for a course.
11267: # Parameters:
11268: # $name - Course/user name.
11269: # $domain - Name of the domain the user/course is registered on.
11270: # $type - Type of thing $name is (must be 'course' or 'user'
11271: # @which - Array of names of resources desired.
11272: # Returns:
11273: # The value of the first reasource in @which that is found in the
11274: # resource hash.
11275: # Exceptional Conditions:
11276: # If the $type passed in is not valid (not the string 'course' or
11277: # 'user', an undefined reference is returned.
11278: # If none of the resources are found, an undef is returned
1.624 albertel 11279: sub resdata {
11280: my ($name,$domain,$type,@which)=@_;
11281: my $result;
11282: if ($type eq 'course') {
11283: $result=&get_courseresdata($name,$domain);
11284: } elsif ($type eq 'user') {
11285: $result=&get_userresdata($name,$domain);
11286: }
11287: if (!ref($result)) { return $result; }
1.251 albertel 11288: foreach my $item (@which) {
1.927 albertel 11289: if (defined($result->{$item->[0]})) {
11290: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11291: }
1.250 albertel 11292: }
1.291 albertel 11293: return undef;
1.200 www 11294: }
11295:
1.1172.2.31 raeburn 11296: sub get_numsuppfiles {
11297: my ($cnum,$cdom,$ignorecache)=@_;
11298: my $hashid=$cnum.':'.$cdom;
11299: my ($suppcount,$cached);
11300: unless ($ignorecache) {
11301: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11302: }
11303: unless (defined($cached)) {
11304: my $chome=&homeserver($cnum,$cdom);
11305: unless ($chome eq 'no_host') {
11306: ($suppcount,my $errors) = (0,0);
11307: my $suppmap = 'supplemental.sequence';
11308: ($suppcount,$errors) =
11309: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11310: }
11311: &do_cache_new('suppcount',$hashid,$suppcount,600);
11312: }
11313: return $suppcount;
11314: }
11315:
1.379 matthew 11316: #
11317: # EXT resource caching routines
11318: #
11319:
11320: sub clear_EXT_cache_status {
1.383 albertel 11321: &delenv('cache.EXT.');
1.379 matthew 11322: }
11323:
11324: sub EXT_cache_status {
11325: my ($target_domain,$target_user) = @_;
1.383 albertel 11326: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11327: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11328: # We know already the user has no data
11329: return 1;
11330: } else {
11331: return 0;
11332: }
11333: }
11334:
11335: sub EXT_cache_set {
11336: my ($target_domain,$target_user) = @_;
1.383 albertel 11337: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11338: #&appenv({$cachename => time});
1.379 matthew 11339: }
11340:
1.28 www 11341: # --------------------------------------------------------- Value of a Variable
1.58 www 11342: sub EXT {
1.715 albertel 11343:
1.1172.2.28 raeburn 11344: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11345: unless ($varname) { return ''; }
1.218 albertel 11346: #get real user name/domain, courseid and symb
11347: my $courseid;
1.359 albertel 11348: my $publicuser;
1.427 www 11349: if ($symbparm) {
11350: $symbparm=&get_symb_from_alias($symbparm);
11351: }
1.218 albertel 11352: if (!($uname && $udom)) {
1.790 albertel 11353: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11354: if (!$symbparm) { $symbparm=$cursymb; }
11355: } else {
1.620 albertel 11356: $courseid=$env{'request.course.id'};
1.218 albertel 11357: }
1.48 www 11358: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11359: my $rest;
1.320 albertel 11360: if (defined($therest[0])) {
1.48 www 11361: $rest=join('.',@therest);
11362: } else {
11363: $rest='';
11364: }
1.320 albertel 11365:
1.57 www 11366: my $qualifierrest=$qualifier;
11367: if ($rest) { $qualifierrest.='.'.$rest; }
11368: my $spacequalifierrest=$space;
11369: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11370: if ($realm eq 'user') {
1.48 www 11371: # --------------------------------------------------------------- user.resource
11372: if ($space eq 'resource') {
1.651 albertel 11373: if ( (defined($Apache::lonhomework::parsing_a_problem)
11374: || defined($Apache::lonhomework::parsing_a_task))
11375: &&
1.744 albertel 11376: ($symbparm eq &symbread()) ) {
11377: # if we are in the middle of processing the resource the
11378: # get the value we are planning on committing
11379: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11380: return $Apache::lonhomework::results{$qualifierrest};
11381: } else {
11382: return $Apache::lonhomework::history{$qualifierrest};
11383: }
1.335 albertel 11384: } else {
1.359 albertel 11385: my %restored;
1.620 albertel 11386: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11387: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11388: } else {
11389: %restored=&restore($symbparm,$courseid,$udom,$uname);
11390: }
1.335 albertel 11391: return $restored{$qualifierrest};
11392: }
1.48 www 11393: # ----------------------------------------------------------------- user.access
11394: } elsif ($space eq 'access') {
1.218 albertel 11395: # FIXME - not supporting calls for a specific user
1.48 www 11396: return &allowed($qualifier,$rest);
11397: # ------------------------------------------ user.preferences, user.environment
11398: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11399: if (($uname eq $env{'user.name'}) &&
11400: ($udom eq $env{'user.domain'})) {
11401: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11402: } else {
1.359 albertel 11403: my %returnhash;
11404: if (!$publicuser) {
11405: %returnhash=&userenvironment($udom,$uname,
11406: $qualifierrest);
11407: }
1.218 albertel 11408: return $returnhash{$qualifierrest};
11409: }
1.48 www 11410: # ----------------------------------------------------------------- user.course
11411: } elsif ($space eq 'course') {
1.218 albertel 11412: # FIXME - not supporting calls for a specific user
1.620 albertel 11413: return $env{join('.',('request.course',$qualifier))};
1.48 www 11414: # ------------------------------------------------------------------- user.role
11415: } elsif ($space eq 'role') {
1.218 albertel 11416: # FIXME - not supporting calls for a specific user
1.620 albertel 11417: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11418: if ($qualifier eq 'value') {
11419: return $role;
11420: } elsif ($qualifier eq 'extent') {
11421: return $where;
11422: }
11423: # ----------------------------------------------------------------- user.domain
11424: } elsif ($space eq 'domain') {
1.218 albertel 11425: return $udom;
1.48 www 11426: # ------------------------------------------------------------------- user.name
11427: } elsif ($space eq 'name') {
1.218 albertel 11428: return $uname;
1.48 www 11429: # ---------------------------------------------------- Any other user namespace
1.29 www 11430: } else {
1.359 albertel 11431: my %reply;
11432: if (!$publicuser) {
11433: %reply=&get($space,[$qualifierrest],$udom,$uname);
11434: }
11435: return $reply{$qualifierrest};
1.48 www 11436: }
1.236 www 11437: } elsif ($realm eq 'query') {
11438: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11439: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11440: [$spacequalifierrest]);
1.620 albertel 11441: return $env{'form.'.$spacequalifierrest};
1.236 www 11442: } elsif ($realm eq 'request') {
1.48 www 11443: # ------------------------------------------------------------- request.browser
11444: if ($space eq 'browser') {
1.1145 bisitz 11445: return $env{'browser.'.$qualifier};
1.57 www 11446: # ------------------------------------------------------------ request.filename
11447: } else {
1.620 albertel 11448: return $env{'request.'.$spacequalifierrest};
1.29 www 11449: }
1.28 www 11450: } elsif ($realm eq 'course') {
1.48 www 11451: # ---------------------------------------------------------- course.description
1.620 albertel 11452: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11453: } elsif ($realm eq 'resource') {
1.165 www 11454:
1.620 albertel 11455: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11456: if (!$symbparm) { $symbparm=&symbread(); }
11457: }
1.693 albertel 11458:
1.1172.2.30 raeburn 11459: if ($qualifier eq '') {
11460: if ($space eq 'title') {
11461: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11462: return &gettitle($symbparm);
11463: }
1.693 albertel 11464:
1.1172.2.30 raeburn 11465: if ($space eq 'map') {
11466: my ($map) = &decode_symb($symbparm);
11467: return &symbread($map);
11468: }
11469: if ($space eq 'maptitle') {
11470: my ($map) = &decode_symb($symbparm);
11471: return &gettitle($map);
11472: }
11473: if ($space eq 'filename') {
11474: if ($symbparm) {
11475: return &clutter((&decode_symb($symbparm))[2]);
11476: }
11477: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11478: }
1.1172.2.30 raeburn 11479:
11480: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11481: if ($space eq 'visibleparts') {
11482: my $navmap = Apache::lonnavmaps::navmap->new();
11483: my $item;
11484: if (ref($navmap)) {
11485: my $res = $navmap->getBySymb($symbparm);
11486: my $parts = $res->parts();
11487: if (ref($parts) eq 'ARRAY') {
11488: $item = join(',',@{$parts});
11489: }
11490: undef($navmap);
11491: }
11492: return $item;
11493: }
11494: }
11495: }
1.693 albertel 11496:
11497: my ($section, $group, @groups);
1.593 albertel 11498: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 11499: if (($courseid eq '') && ($cid)) {
11500: $courseid = $cid;
11501: }
11502: if (($symbparm && $courseid) &&
11503: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11504:
1.218 albertel 11505: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11506:
1.60 www 11507: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11508: my $symbp=$symbparm;
1.735 albertel 11509: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11510:
11511: my $symbparm=$symbp.'.'.$spacequalifierrest;
11512: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11513:
1.620 albertel 11514: if (($env{'user.name'} eq $uname) &&
11515: ($env{'user.domain'} eq $udom)) {
11516: $section=$env{'request.course.sec'};
1.733 raeburn 11517: @groups = split(/:/,$env{'request.course.groups'});
11518: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11519: } else {
1.539 albertel 11520: if (! defined($usection)) {
1.551 albertel 11521: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11522: } else {
11523: $section = $usection;
11524: }
1.733 raeburn 11525: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11526: }
11527:
11528: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11529: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11530: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11531:
1.593 albertel 11532: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11533: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 11534: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11535:
1.60 www 11536: # ----------------------------------------------------------- first, check user
1.624 albertel 11537:
11538: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 11539: ([$courselevelr,'resource'],
11540: [$courselevelm,'map' ],
11541: [$courselevel, 'course' ]));
1.931 albertel 11542: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11543:
1.594 albertel 11544: # ------------------------------------------------ second, check some of course
1.684 raeburn 11545: my $coursereply;
1.691 raeburn 11546: if (@groups > 0) {
11547: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11548: $mapparm,$spacequalifierrest);
1.927 albertel 11549: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11550: }
1.96 www 11551:
1.684 raeburn 11552: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11553: $env{'course.'.$courseid.'.domain'},
11554: 'course',
11555: ([$seclevelr, 'resource'],
11556: [$seclevelm, 'map' ],
11557: [$seclevel, 'course' ],
11558: [$courselevelr,'resource']));
11559: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11560:
1.60 www 11561: # ------------------------------------------------------ third, check map parms
1.218 albertel 11562: my %parmhash=();
11563: my $thisparm='';
11564: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11565: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11566: &GDBM_READER(),0640)) {
1.218 albertel 11567: $thisparm=$parmhash{$symbparm};
11568: untie(%parmhash);
11569: }
1.927 albertel 11570: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11571: }
1.594 albertel 11572: # ------------------------------------------ fourth, look in resource metadata
1.71 www 11573:
1.218 albertel 11574: $spacequalifierrest=~s/\./\_/;
1.282 albertel 11575: my $filename;
11576: if (!$symbparm) { $symbparm=&symbread(); }
11577: if ($symbparm) {
1.409 www 11578: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11579: } else {
1.620 albertel 11580: $filename=$env{'request.filename'};
1.282 albertel 11581: }
11582: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 11583: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 11584: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 11585: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11586:
1.927 albertel 11587: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 11588: if ($symbparm && defined($courseid) &&
1.620 albertel 11589: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11590: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11591: $env{'course.'.$courseid.'.domain'},
11592: 'course',
1.927 albertel 11593: ([$courselevelm,'map' ],
11594: [$courselevel, 'course']));
11595: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11596: }
1.145 www 11597: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11598: unless ($space eq '0') {
1.336 albertel 11599: my @parts=split(/_/,$space);
11600: my $id=pop(@parts);
11601: my $part=join('_',@parts);
11602: if ($part eq '') { $part='0'; }
1.927 albertel 11603: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11604: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11605: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11606: }
1.395 albertel 11607: if ($recurse) { return undef; }
11608: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11609: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11610: # ---------------------------------------------------- Any other user namespace
11611: } elsif ($realm eq 'environment') {
11612: # ----------------------------------------------------------------- environment
1.620 albertel 11613: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11614: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11615: } else {
1.770 albertel 11616: if ($uname eq 'anonymous' && $udom eq '') {
11617: return '';
11618: }
1.219 albertel 11619: my %returnhash=&userenvironment($udom,$uname,
11620: $spacequalifierrest);
11621: return $returnhash{$spacequalifierrest};
11622: }
1.28 www 11623: } elsif ($realm eq 'system') {
1.48 www 11624: # ----------------------------------------------------------------- system.time
11625: if ($space eq 'time') {
11626: return time;
11627: }
1.696 albertel 11628: } elsif ($realm eq 'server') {
11629: # ----------------------------------------------------------------- system.time
11630: if ($space eq 'name') {
11631: return $ENV{'SERVER_NAME'};
11632: }
1.28 www 11633: }
1.48 www 11634: return '';
1.61 www 11635: }
11636:
1.927 albertel 11637: sub get_reply {
11638: my ($reply_value) = @_;
1.940 raeburn 11639: if (ref($reply_value) eq 'ARRAY') {
11640: if (wantarray) {
11641: return @$reply_value;
11642: }
11643: return $reply_value->[0];
11644: } else {
11645: return $reply_value;
1.927 albertel 11646: }
11647: }
11648:
1.691 raeburn 11649: sub check_group_parms {
11650: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11651: my @groupitems = ();
11652: my $resultitem;
1.927 albertel 11653: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11654: foreach my $group (@{$groups}) {
11655: foreach my $level (@levels) {
1.927 albertel 11656: my $item = $courseid.'.['.$group.'].'.$level->[0];
11657: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11658: }
11659: }
11660: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11661: $env{'course.'.$courseid.'.domain'},
11662: 'course',@groupitems);
11663: return $coursereply;
11664: }
11665:
11666: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11667: my ($courseid,@groups) = @_;
11668: @groups = sort(@groups);
1.691 raeburn 11669: return @groups;
11670: }
11671:
1.395 albertel 11672: sub packages_tab_default {
11673: my ($uri,$varname)=@_;
11674: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11675:
11676: my (@extension,@specifics,$do_default);
11677: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11678: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11679: if ($pack_type eq 'default') {
11680: $do_default=1;
11681: } elsif ($pack_type eq 'extension') {
11682: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11683: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11684: # only look at packages defaults for packages that this id is
1.738 albertel 11685: push(@specifics,[$package,$pack_type,$pack_part]);
11686: }
11687: }
11688: # first look for a package that matches the requested part id
11689: foreach my $package (@specifics) {
11690: my (undef,$pack_type,$pack_part)=@{$package};
11691: next if ($pack_part ne $part);
11692: if (defined($packagetab{"$pack_type&$name&default"})) {
11693: return $packagetab{"$pack_type&$name&default"};
11694: }
11695: }
11696: # look for any possible matching non extension_ package
11697: foreach my $package (@specifics) {
11698: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11699: if (defined($packagetab{"$pack_type&$name&default"})) {
11700: return $packagetab{"$pack_type&$name&default"};
11701: }
1.585 albertel 11702: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11703: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11704: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11705: }
11706: }
1.738 albertel 11707: # look for any posible extension_ match
11708: foreach my $package (@extension) {
11709: my ($package,$pack_type)=@{$package};
11710: if (defined($packagetab{"$pack_type&$name&default"})) {
11711: return $packagetab{"$pack_type&$name&default"};
11712: }
11713: if (defined($packagetab{$package."&$name&default"})) {
11714: return $packagetab{$package."&$name&default"};
11715: }
11716: }
11717: # look for a global default setting
11718: if ($do_default && defined($packagetab{"default&$name&default"})) {
11719: return $packagetab{"default&$name&default"};
11720: }
1.395 albertel 11721: return undef;
11722: }
11723:
1.334 albertel 11724: sub add_prefix_and_part {
11725: my ($prefix,$part)=@_;
11726: my $keyroot;
11727: if (defined($prefix) && $prefix !~ /^__/) {
11728: # prefix that has a part already
11729: $keyroot=$prefix;
11730: } elsif (defined($prefix)) {
11731: # prefix that is missing a part
11732: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11733: } else {
11734: # no prefix at all
11735: if (defined($part)) { $keyroot='_'.$part; }
11736: }
11737: return $keyroot;
11738: }
11739:
1.71 www 11740: # ---------------------------------------------------------------- Get metadata
11741:
1.599 albertel 11742: my %metaentry;
1.1070 www 11743: my %importedpartids;
1.1172.2.99 raeburn 11744: my %importedrespids;
1.71 www 11745: sub metadata {
1.176 www 11746: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11747: $uri=&declutter($uri);
1.288 albertel 11748: # if it is a non metadata possible uri return quickly
1.529 albertel 11749: if (($uri eq '') ||
11750: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 11751: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 11752: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11753: return undef;
11754: }
1.1172.2.49 raeburn 11755: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11756: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11757: return undef;
1.288 albertel 11758: }
1.73 www 11759: my $filename=$uri;
11760: $uri=~s/\.meta$//;
1.172 www 11761: #
11762: # Is the metadata already cached?
1.177 www 11763: # Look at timestamp of caching
1.172 www 11764: # Everything is cached by the main uri, libraries are never directly cached
11765: #
1.428 albertel 11766: if (!defined($liburi)) {
1.599 albertel 11767: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11768: if (defined($cached)) { return $result->{':'.$what}; }
11769: }
11770: {
1.1069 www 11771: # Imported parts would go here
1.1172.2.99 raeburn 11772: my @origfiletagids=();
1.1069 www 11773: my $importedparts=0;
1.1172.2.99 raeburn 11774:
11775: # Imported responseids would go here
11776: my $importedresponses=0;
1.172 www 11777: #
11778: # Is this a recursive call for a library?
11779: #
1.599 albertel 11780: # if (! exists($metacache{$uri})) {
11781: # $metacache{$uri}={};
11782: # }
1.924 albertel 11783: my $cachetime = 60*60;
1.171 www 11784: if ($liburi) {
11785: $liburi=&declutter($liburi);
11786: $filename=$liburi;
1.401 bowersj2 11787: } else {
1.599 albertel 11788: &devalidate_cache_new('meta',$uri);
11789: undef(%metaentry);
1.401 bowersj2 11790: }
1.140 www 11791: my %metathesekeys=();
1.73 www 11792: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11793: my $metastring;
1.1140 www 11794: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11795: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11796: $metastring =
1.929 albertel 11797: &Apache::lonnet::ssi_body($which,
1.924 albertel 11798: ('grade_target' => 'meta'));
11799: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11800: } elsif (($uri !~ m -^(editupload)/-) &&
11801: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11802: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11803: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11804: $metastring=&getfile($file);
1.489 albertel 11805: }
1.208 albertel 11806: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11807: my $token;
1.140 www 11808: undef %metathesekeys;
1.71 www 11809: while ($token=$parser->get_token) {
1.339 albertel 11810: if ($token->[0] eq 'S') {
11811: if (defined($token->[2]->{'package'})) {
1.172 www 11812: #
11813: # This is a package - get package info
11814: #
1.339 albertel 11815: my $package=$token->[2]->{'package'};
11816: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11817: if (defined($token->[2]->{'id'})) {
11818: $keyroot.='_'.$token->[2]->{'id'};
11819: }
1.599 albertel 11820: if ($metaentry{':packages'}) {
11821: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11822: } else {
1.599 albertel 11823: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11824: }
1.736 albertel 11825: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11826: my $part=$keyroot;
11827: $part=~s/^\_//;
1.736 albertel 11828: if ($pack_entry=~/^\Q$package\E\&/ ||
11829: $pack_entry=~/^\Q$package\E_0\&/) {
11830: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11831: # ignore package.tab specified default values
11832: # here &package_tab_default() will fetch those
11833: if ($subp eq 'default') { next; }
1.736 albertel 11834: my $value=$packagetab{$pack_entry};
1.432 albertel 11835: my $unikey;
11836: if ($pack =~ /_0$/) {
11837: $unikey='parameter_0_'.$name;
11838: $part=0;
11839: } else {
11840: $unikey='parameter'.$keyroot.'_'.$name;
11841: }
1.339 albertel 11842: if ($subp eq 'display') {
11843: $value.=' [Part: '.$part.']';
11844: }
1.599 albertel 11845: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11846: $metathesekeys{$unikey}=1;
1.599 albertel 11847: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11848: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11849: }
1.599 albertel 11850: if (defined($metaentry{':'.$unikey.'.default'})) {
11851: $metaentry{':'.$unikey}=
11852: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11853: }
1.339 albertel 11854: }
11855: }
11856: } else {
1.172 www 11857: #
11858: # This is not a package - some other kind of start tag
1.339 albertel 11859: #
11860: my $entry=$token->[1];
1.1068 www 11861: my $unikey='';
1.175 www 11862:
1.339 albertel 11863: if ($entry eq 'import') {
1.175 www 11864: #
11865: # Importing a library here
1.339 albertel 11866: #
1.1067 www 11867: my $location=$parser->get_text('/import');
11868: my $dir=$filename;
11869: $dir=~s|[^/]*$||;
11870: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 11871:
11872: my $importid=$token->[2]->{'id'};
1.1068 www 11873: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 11874: #
11875: # Check metadata for imported file to
11876: # see if it contained response items
11877: #
11878: my %currmetaentry = %metaentry;
11879: my $libresponseorder = &metadata($location,'responseorder');
11880: my $origfile;
11881: if ($libresponseorder ne '') {
11882: if ($#origfiletagids<0) {
11883: undef(%importedrespids);
11884: undef(%importedpartids);
11885: }
11886: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11887: if (@{$importedrespids{$importid}} > 0) {
11888: $importedresponses = 1;
11889: # We need to get the original file and the imported file to get the response order correct
11890: # Load and inspect original file
11891: if ($#origfiletagids<0) {
11892: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11893: $origfile=&getfile($origfilelocation);
11894: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11895: }
11896: }
11897: }
11898: # Do not overwrite contents of %metaentry hash for resource itself with
11899: # hash populated for imported library file
11900: %metaentry = %currmetaentry;
11901: undef(%currmetaentry);
1.1068 www 11902: if ($importmode eq 'problem') {
1.1069 www 11903: # Import as problem/response
1.1068 www 11904: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11905: } elsif ($importmode eq 'part') {
11906: # Import as part(s)
1.1069 www 11907: $importedparts=1;
11908: # We need to get the original file and the imported file to get the part order correct
11909: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 11910: # Load and inspect original file if we didn't do that already
11911: if ($#origfiletagids<0) {
11912: undef(%importedrespids);
11913: undef(%importedpartids);
11914: if ($origfile eq '') {
11915: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11916: $origfile=&getfile($origfilelocation);
11917: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11918: }
1.1070 www 11919: }
11920:
1.1069 www 11921: # Load and inspect imported file
11922: my $impfile=&getfile($location);
11923: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11924: if ($#impfilepartids>=0) {
11925: # This problem had parts
1.1070 www 11926: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11927: } else {
11928: # Importing by turning a single problem into a problem part
11929: # It gets the import-tags ID as part-ID
11930: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11931: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11932: }
1.1068 www 11933: } else {
11934: # Normal import
11935: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11936: if (defined($token->[2]->{'id'})) {
11937: $unikey.='_'.$token->[2]->{'id'};
11938: }
1.1067 www 11939: }
11940:
1.339 albertel 11941: if ($depthcount<20) {
1.736 albertel 11942: my $metadata =
11943: &metadata($uri,'keys', $location,$unikey,
11944: $depthcount+1);
11945: foreach my $meta (split(',',$metadata)) {
11946: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11947: $metathesekeys{$meta}=1;
1.339 albertel 11948: }
1.1068 www 11949:
11950: }
1.1067 www 11951: } else {
11952: #
11953: # Not importing, some other kind of non-package, non-library start tag
11954: #
11955: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11956: if (defined($token->[2]->{'id'})) {
11957: $unikey.='_'.$token->[2]->{'id'};
11958: }
1.339 albertel 11959: if (defined($token->[2]->{'name'})) {
11960: $unikey.='_'.$token->[2]->{'name'};
11961: }
11962: $metathesekeys{$unikey}=1;
1.736 albertel 11963: foreach my $param (@{$token->[3]}) {
11964: $metaentry{':'.$unikey.'.'.$param} =
11965: $token->[2]->{$param};
1.339 albertel 11966: }
11967: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11968: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11969: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11970: # only ws inside the tag, and not in default, so use default
11971: # as value
1.599 albertel 11972: $metaentry{':'.$unikey}=$default;
1.908 albertel 11973: } elsif ( $internaltext =~ /\S/ ) {
11974: # something interesting inside the tag
11975: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11976: } else {
1.908 albertel 11977: # no interesting values, don't set a default
1.339 albertel 11978: }
1.172 www 11979: # end of not-a-package not-a-library import
1.339 albertel 11980: }
1.172 www 11981: # end of not-a-package start tag
1.339 albertel 11982: }
1.172 www 11983: # the next is the end of "start tag"
1.339 albertel 11984: }
11985: }
1.483 albertel 11986: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11987: $extension = lc($extension);
11988: if ($extension eq 'htm') { $extension='html'; }
11989:
1.737 albertel 11990: foreach my $key (keys(%packagetab)) {
1.483 albertel 11991: #no specific packages #how's our extension
11992: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11993: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11994: \%metathesekeys);
11995: }
1.883 albertel 11996:
11997: if (!exists($metaentry{':packages'})
11998: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11999: foreach my $key (keys(%packagetab)) {
1.483 albertel 12000: #no specific packages well let's get default then
12001: if ($key!~/^default&/) { next; }
1.488 albertel 12002: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12003: \%metathesekeys);
12004: }
12005: }
1.338 www 12006: # are there custom rights to evaluate
1.599 albertel 12007: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12008:
1.338 www 12009: #
12010: # Importing a rights file here
1.339 albertel 12011: #
12012: unless ($depthcount) {
1.599 albertel 12013: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12014: my $dir=$filename;
12015: $dir=~s|[^/]*$||;
12016: $location=&filelocation($dir,$location);
1.736 albertel 12017: my $rights_metadata =
12018: &metadata($uri,'keys',$location,'_rights',
12019: $depthcount+1);
12020: foreach my $rights (split(',',$rights_metadata)) {
12021: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12022: $metathesekeys{$rights}=1;
1.339 albertel 12023: }
12024: }
12025: }
1.737 albertel 12026: # uniqifiy package listing
12027: my %seen;
12028: my @uniq_packages =
12029: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12030: $metaentry{':packages'} = join(',',@uniq_packages);
12031:
1.1172.2.99 raeburn 12032: if (($importedresponses) || ($importedparts)) {
12033: if ($importedparts) {
1.1070 www 12034: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 12035: $metaentry{':partorder'}='';
12036: $metathesekeys{'partorder'}=1;
12037: }
12038: if ($importedresponses) {
12039: # We had imported responses and need to rebuild responseorder
12040: $metaentry{':responseorder'}='';
12041: $metathesekeys{'responseorder'}=1;
12042: }
12043: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12044: my $origid = $origfiletagids[$index+1];
12045: if ($origfiletagids[$index] eq 'part') {
12046: # Original part, part of the problem
12047: if ($importedparts) {
12048: $metaentry{':partorder'}.=','.$origid;
12049: }
12050: } elsif ($origfiletagids[$index] eq 'import') {
12051: if ($importedparts) {
12052: # We have imported parts at this position
12053: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12054: }
12055: if ($importedresponses) {
12056: # We have imported responses at this position
12057: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12058: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12059: }
12060: }
12061: } else {
12062: # Original response item, part of the problem
12063: if ($importedresponses) {
12064: $metaentry{':responseorder'}.=','.$origid;
12065: }
12066: }
12067: }
12068: if ($importedparts) {
12069: $metaentry{':partorder'}=~s/^\,//;
12070: }
12071: if ($importedresponses) {
12072: $metaentry{':responseorder'}=~s/^\,//;
12073: }
1.1070 www 12074: }
12075:
1.737 albertel 12076: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12077: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 12078: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 12079: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 12080: # this is the end of "was not already recently cached
1.71 www 12081: }
1.599 albertel 12082: return $metaentry{':'.$what};
1.261 albertel 12083: }
12084:
1.488 albertel 12085: sub metadata_create_package_def {
1.483 albertel 12086: my ($uri,$key,$package,$metathesekeys)=@_;
12087: my ($pack,$name,$subp)=split(/\&/,$key);
12088: if ($subp eq 'default') { next; }
12089:
1.599 albertel 12090: if (defined($metaentry{':packages'})) {
12091: $metaentry{':packages'}.=','.$package;
1.483 albertel 12092: } else {
1.599 albertel 12093: $metaentry{':packages'}=$package;
1.483 albertel 12094: }
12095: my $value=$packagetab{$key};
12096: my $unikey;
12097: $unikey='parameter_0_'.$name;
1.599 albertel 12098: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12099: $$metathesekeys{$unikey}=1;
1.599 albertel 12100: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12101: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12102: }
1.599 albertel 12103: if (defined($metaentry{':'.$unikey.'.default'})) {
12104: $metaentry{':'.$unikey}=
12105: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12106: }
12107: }
12108:
1.261 albertel 12109: sub metadata_generate_part0 {
12110: my ($metadata,$metacache,$uri) = @_;
12111: my %allnames;
1.737 albertel 12112: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12113: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12114: my $part=$$metacache{':'.$metakey.'.part'};
12115: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12116: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12117: $allnames{$name}=$part;
12118: }
12119: }
12120: }
12121: foreach my $name (keys(%allnames)) {
12122: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12123: my $key=":parameter_0_$name";
1.261 albertel 12124: $$metacache{"$key.part"}='0';
12125: $$metacache{"$key.name"}=$name;
1.428 albertel 12126: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12127: $allnames{$name}.'_'.$name.
12128: '.type'};
1.428 albertel 12129: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12130: '.display'};
1.644 www 12131: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12132: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12133: $$metacache{"$key.display"}=$olddis;
12134: }
1.71 www 12135: }
12136:
1.764 albertel 12137: # ------------------------------------------------------ Devalidate title cache
12138:
12139: sub devalidate_title_cache {
12140: my ($url)=@_;
12141: if (!$env{'request.course.id'}) { return; }
12142: my $symb=&symbread($url);
12143: if (!$symb) { return; }
12144: my $key=$env{'request.course.id'}."\0".$symb;
12145: &devalidate_cache_new('title',$key);
12146: }
12147:
1.1014 droeschl 12148: # ------------------------------------------------- Get the title of a course
12149:
12150: sub current_course_title {
12151: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12152: }
1.301 www 12153: # ------------------------------------------------- Get the title of a resource
12154:
12155: sub gettitle {
12156: my $urlsymb=shift;
12157: my $symb=&symbread($urlsymb);
1.534 albertel 12158: if ($symb) {
1.620 albertel 12159: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12160: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12161: if (defined($cached)) {
12162: return $result;
12163: }
1.534 albertel 12164: my ($map,$resid,$url)=&decode_symb($symb);
12165: my $title='';
1.907 albertel 12166: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12167: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12168: } else {
12169: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12170: &GDBM_READER(),0640)) {
12171: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12172: $title=$bighash{'title_'.$mapid.'.'.$resid};
12173: untie(%bighash);
12174: }
1.534 albertel 12175: }
12176: $title=~s/\&colon\;/\:/gs;
12177: if ($title) {
1.1159 www 12178: # Remember both $symb and $title for dynamic metadata
12179: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12180: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12181: # Cache this title and then return it
1.599 albertel 12182: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12183: }
12184: $urlsymb=$url;
12185: }
12186: my $title=&metadata($urlsymb,'title');
12187: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12188: return $title;
1.301 www 12189: }
1.613 albertel 12190:
1.614 albertel 12191: sub get_slot {
12192: my ($which,$cnum,$cdom)=@_;
12193: if (!$cnum || !$cdom) {
1.790 albertel 12194: (undef,my $courseid)=&whichuser();
1.620 albertel 12195: $cdom=$env{'course.'.$courseid.'.domain'};
12196: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12197: }
1.703 albertel 12198: my $key=join("\0",'slots',$cdom,$cnum,$which);
12199: my %slotinfo;
12200: if (exists($remembered{$key})) {
12201: $slotinfo{$which} = $remembered{$key};
12202: } else {
12203: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12204: &Apache::lonhomework::showhash(%slotinfo);
12205: my ($tmp)=keys(%slotinfo);
12206: if ($tmp=~/^error:/) { return (); }
12207: $remembered{$key} = $slotinfo{$which};
12208: }
1.616 albertel 12209: if (ref($slotinfo{$which}) eq 'HASH') {
12210: return %{$slotinfo{$which}};
12211: }
12212: return $slotinfo{$which};
1.614 albertel 12213: }
1.1150 raeburn 12214:
12215: sub get_reservable_slots {
12216: my ($cnum,$cdom,$uname,$udom) = @_;
12217: my $now = time;
12218: my $reservable_info;
12219: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12220: if (exists($remembered{$key})) {
12221: $reservable_info = $remembered{$key};
12222: } else {
12223: my %resv;
12224: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12225: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12226: $reservable_info = \%resv;
12227: $remembered{$key} = $reservable_info;
12228: }
12229: return $reservable_info;
12230: }
12231:
12232: sub get_course_slots {
12233: my ($cnum,$cdom) = @_;
12234: my $hashid=$cnum.':'.$cdom;
12235: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12236: if (defined($cached)) {
12237: if (ref($result) eq 'HASH') {
12238: return %{$result};
12239: }
12240: } else {
12241: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12242: my ($tmp) = keys(%slots);
12243: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 12244: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12245: return %slots;
12246: }
12247: }
12248: return;
12249: }
12250:
12251: sub devalidate_slots_cache {
12252: my ($cnum,$cdom)=@_;
12253: my $hashid=$cnum.':'.$cdom;
12254: &devalidate_cache_new('allslots',$hashid);
12255: }
12256:
1.1172.2.8 raeburn 12257: sub get_coursechange {
12258: my ($cdom,$cnum) = @_;
12259: if ($cdom eq '' || $cnum eq '') {
12260: return unless ($env{'request.course.id'});
12261: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12262: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12263: }
12264: my $hashid=$cdom.'_'.$cnum;
12265: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12266: if ((defined($cached)) && ($change ne '')) {
12267: return $change;
12268: } else {
12269: my %crshash;
12270: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12271: if ($crshash{'internal.contentchange'} eq '') {
12272: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12273: if ($change eq '') {
12274: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12275: $change = $crshash{'internal.created'};
12276: }
12277: } else {
12278: $change = $crshash{'internal.contentchange'};
12279: }
12280: my $cachetime = 600;
12281: &do_cache_new('crschange',$hashid,$change,$cachetime);
12282: }
12283: return $change;
12284: }
12285:
12286: sub devalidate_coursechange_cache {
12287: my ($cnum,$cdom)=@_;
12288: my $hashid=$cnum.':'.$cdom;
12289: &devalidate_cache_new('crschange',$hashid);
12290: }
12291:
1.31 www 12292: # ------------------------------------------------- Update symbolic store links
12293:
12294: sub symblist {
12295: my ($mapname,%newhash)=@_;
1.438 www 12296: $mapname=&deversion(&declutter($mapname));
1.31 www 12297: my %hash;
1.620 albertel 12298: if (($env{'request.course.fn'}) && (%newhash)) {
12299: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12300: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12301: foreach my $url (keys(%newhash)) {
1.711 albertel 12302: next if ($url eq 'last_known'
12303: && $env{'form.no_update_last_known'});
12304: $hash{declutter($url)}=&encode_symb($mapname,
12305: $newhash{$url}->[1],
12306: $newhash{$url}->[0]);
1.191 harris41 12307: }
1.31 www 12308: if (untie(%hash)) {
12309: return 'ok';
12310: }
12311: }
12312: }
12313: return 'error';
1.212 www 12314: }
12315:
12316: # --------------------------------------------------------------- Verify a symb
12317:
12318: sub symbverify {
1.1172.2.11 raeburn 12319: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12320: my $thisfn=$thisurl;
1.439 www 12321: $thisfn=&declutter($thisfn);
1.215 www 12322: # direct jump to resource in page or to a sequence - will construct own symbs
12323: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12324: # check URL part
1.409 www 12325: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12326:
1.431 www 12327: unless ($url eq $thisfn) { return 0; }
1.213 www 12328:
1.216 www 12329: $symb=&symbclean($symb);
1.510 www 12330: $thisurl=&deversion($thisurl);
1.439 www 12331: $thisfn=&deversion($thisfn);
1.213 www 12332:
12333: my %bighash;
12334: my $okay=0;
1.431 www 12335:
1.620 albertel 12336: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12337: &GDBM_READER(),0640)) {
1.1032 raeburn 12338: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12339: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 12340: if ($map =~ m{^uploaded/.+\.page$}) {
12341: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12342: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12343: }
12344: }
12345: my $ids;
1.1172.2.122 raeburn 12346: if ($map =~ m{^uploaded/.+\.page$}) {
12347: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 12348: } else {
12349: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12350: }
1.1102 raeburn 12351: unless ($ids) {
1.1172.2.13 raeburn 12352: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 12353: $ids=$bighash{$idkey};
1.216 www 12354: }
12355: if ($ids) {
12356: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 12357: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12358: $symb =~ s/\?.+$//;
12359: }
1.800 albertel 12360: foreach my $id (split(/\,/,$ids)) {
12361: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12362: if (
12363: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 12364: eq $symb) {
1.1172.2.11 raeburn 12365: if (ref($encstate)) {
12366: $$encstate = $bighash{'encrypted_'.$id};
12367: }
1.1172.2.13 raeburn 12368: if (($env{'request.role.adv'}) ||
12369: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 12370: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 12371: $okay=1;
12372: last;
12373: }
12374: }
12375: }
1.216 www 12376: }
1.213 www 12377: untie(%bighash);
12378: }
12379: return $okay;
1.31 www 12380: }
12381:
1.210 www 12382: # --------------------------------------------------------------- Clean-up symb
12383:
12384: sub symbclean {
12385: my $symb=shift;
1.568 albertel 12386: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12387: # remove version from map
12388: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12389:
1.210 www 12390: # remove version from URL
12391: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12392:
1.507 www 12393: # remove wrapper
12394:
1.510 www 12395: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12396: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12397: return $symb;
1.409 www 12398: }
12399:
12400: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12401:
12402: sub encode_symb {
12403: my ($map,$resid,$url)=@_;
12404: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12405: }
1.409 www 12406:
12407: sub decode_symb {
1.568 albertel 12408: my $symb=shift;
12409: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12410: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12411: return (&fixversion($map),$resid,&fixversion($url));
12412: }
12413:
12414: sub fixversion {
12415: my $fn=shift;
1.609 banghart 12416: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12417: my %bighash;
12418: my $uri=&clutter($fn);
1.620 albertel 12419: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12420: # is this cached?
1.599 albertel 12421: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12422: if (defined($cached)) { return $result; }
12423: # unfortunately not cached, or expired
1.620 albertel 12424: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12425: &GDBM_READER(),0640)) {
12426: if ($bighash{'version_'.$uri}) {
12427: my $version=$bighash{'version_'.$uri};
1.444 www 12428: unless (($version eq 'mostrecent') ||
12429: ($version==&getversion($uri))) {
1.440 www 12430: $uri=~s/\.(\w+)$/\.$version\.$1/;
12431: }
12432: }
12433: untie %bighash;
1.413 www 12434: }
1.599 albertel 12435: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12436: }
12437:
12438: sub deversion {
12439: my $url=shift;
12440: $url=~s/\.\d+\.(\w+)$/\.$1/;
12441: return $url;
1.210 www 12442: }
12443:
1.31 www 12444: # ------------------------------------------------------ Return symb list entry
12445:
12446: sub symbread {
1.1172.2.126 raeburn 12447: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.127! raeburn 12448: $nocache,$noenccheck)=@_;
1.1172.2.54 raeburn 12449: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.126 raeburn 12450: if (defined($env{$cache_str}) && !$nocache) {
12451: unless (ref($possibles) eq 'HASH') {
12452: if ($ignorecachednull) {
12453: return $env{$cache_str} unless ($env{$cache_str} eq '');
12454: } else {
12455: return $env{$cache_str};
12456: }
1.1172.2.66 raeburn 12457: }
12458: }
1.242 www 12459: # no filename provided? try from environment
1.1172.2.54 raeburn 12460: unless ($thisfn) {
1.620 albertel 12461: if ($env{'request.symb'}) {
1.1172.2.126 raeburn 12462: if ($nocache) {
12463: return &symbclean($env{'request.symb'});
12464: } else {
12465: return $env{$cache_str}=&symbclean($env{'request.symb'});
12466: }
1.1172.2.13 raeburn 12467: }
12468: $thisfn=$env{'request.filename'};
1.44 www 12469: }
1.569 albertel 12470: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12471: # is that filename actually a symb? Verify, clean, and return
12472: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12473: if (&symbverify($thisfn,$1)) {
1.1172.2.126 raeburn 12474: if ($nocache) {
12475: return &symbclean($thisfn);
12476: } else {
12477: return $env{$cache_str}=&symbclean($thisfn);
12478: }
1.539 albertel 12479: }
1.242 www 12480: }
1.44 www 12481: $thisfn=declutter($thisfn);
1.31 www 12482: my %hash;
1.37 www 12483: my %bighash;
12484: my $syval='';
1.620 albertel 12485: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12486: my $targetfn = $thisfn;
1.609 banghart 12487: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12488: $targetfn = 'adm/wrapper/'.$thisfn;
12489: }
1.687 albertel 12490: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12491: $targetfn=$1;
12492: }
1.1172.2.126 raeburn 12493: unless ($nocache) {
12494: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12495: &GDBM_READER(),0640)) {
12496: $syval=$hash{$targetfn};
12497: untie(%hash);
12498: }
12499: if ($syval) {
1.1172.2.127! raeburn 12500: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$nocache,$noenccheck);
1.1172.2.126 raeburn 12501: if (@blockers) {
12502: $syval='';
12503: }
12504: }
1.37 www 12505: }
12506: # ---------------------------------------------------------- There was an entry
12507: if ($syval) {
1.601 albertel 12508: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12509: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12510: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12511: #return $env{$cache_str}='';
1.601 albertel 12512: #}
12513: #$syval.=$1;
12514: #}
1.37 www 12515: } else {
12516: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12517: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12518: &GDBM_READER(),0640)) {
1.37 www 12519: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12520: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12521: unless ($ids) {
12522: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12523: }
12524: unless ($ids) {
12525: # alias?
12526: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12527: }
1.37 www 12528: if ($ids) {
12529: # ------------------------------------------------------------------- Has ID(s)
12530: my @possibilities=split(/\,/,$ids);
1.39 www 12531: if ($#possibilities==0) {
12532: # ----------------------------------------------- There is only one possibility
1.37 www 12533: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12534: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12535: $resid,$thisfn);
1.1172.2.66 raeburn 12536: if (ref($possibles) eq 'HASH') {
1.1172.2.126 raeburn 12537: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12538: $possibles->{$syval} = 1;
12539: }
1.1172.2.66 raeburn 12540: }
12541: if ($checkforblock) {
1.1172.2.126 raeburn 12542: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127! raeburn 12543: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126 raeburn 12544: if (@blockers) {
12545: $syval = '';
12546: untie(%bighash);
12547: return '' if ($nocache);
12548: return $env{$cache_str}='';
12549: }
1.1172.2.66 raeburn 12550: }
12551: }
12552: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12553: # ------------------------------------------ There is more than one possibility
12554: my $realpossible=0;
1.800 albertel 12555: foreach my $id (@possibilities) {
12556: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 12557: my $canaccess;
12558: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12559: $canaccess = 1;
12560: } else {
12561: $canaccess = &allowed('bre',$file);
12562: }
12563: if ($canaccess) {
12564: my ($mapid,$resid)=split(/\./,$id);
12565: if ($bighash{'map_type_'.$mapid} ne 'page') {
12566: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12567: $resid,$thisfn);
1.1172.2.126 raeburn 12568: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127! raeburn 12569: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66 raeburn 12570: if ($checkforblock) {
1.1172.2.127! raeburn 12571: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126 raeburn 12572: if (@blockers > 0) {
12573: $syval = '';
12574: } else {
1.1172.2.66 raeburn 12575: $syval = $poss_syval;
12576: $realpossible++;
12577: }
12578: } else {
12579: $syval = $poss_syval;
12580: $realpossible++;
12581: }
1.1172.2.126 raeburn 12582: if ($syval) {
12583: if (ref($possibles) eq 'HASH') {
12584: $possibles->{$syval} = 1;
12585: }
12586: }
1.1172.2.66 raeburn 12587: }
1.39 www 12588: }
1.191 harris41 12589: }
1.39 www 12590: if ($realpossible!=1) { $syval=''; }
1.249 www 12591: } else {
12592: $syval='';
1.37 www 12593: }
12594: }
1.1172.2.66 raeburn 12595: untie(%bighash);
1.481 raeburn 12596: }
1.31 www 12597: }
1.62 www 12598: if ($syval) {
1.1172.2.126 raeburn 12599: if ($nocache) {
12600: return $syval;
12601: } else {
12602: return $env{$cache_str}=$syval;
12603: }
1.62 www 12604: }
1.31 www 12605: }
1.949 raeburn 12606: &appenv({'request.ambiguous' => $thisfn});
1.1172.2.126 raeburn 12607: return '' if ($nocache);
1.620 albertel 12608: return $env{$cache_str}='';
1.31 www 12609: }
12610:
12611: # ---------------------------------------------------------- Return random seed
12612:
1.32 www 12613: sub numval {
12614: my $txt=shift;
12615: $txt=~tr/A-J/0-9/;
12616: $txt=~tr/a-j/0-9/;
12617: $txt=~tr/K-T/0-9/;
12618: $txt=~tr/k-t/0-9/;
12619: $txt=~tr/U-Z/0-5/;
12620: $txt=~tr/u-z/0-5/;
12621: $txt=~s/\D//g;
1.564 albertel 12622: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12623: return int($txt);
1.368 albertel 12624: }
12625:
1.484 albertel 12626: sub numval2 {
12627: my $txt=shift;
12628: $txt=~tr/A-J/0-9/;
12629: $txt=~tr/a-j/0-9/;
12630: $txt=~tr/K-T/0-9/;
12631: $txt=~tr/k-t/0-9/;
12632: $txt=~tr/U-Z/0-5/;
12633: $txt=~tr/u-z/0-5/;
12634: $txt=~s/\D//g;
12635: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12636: my $total;
12637: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12638: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12639: return int($total);
12640: }
12641:
1.575 albertel 12642: sub numval3 {
12643: use integer;
12644: my $txt=shift;
12645: $txt=~tr/A-J/0-9/;
12646: $txt=~tr/a-j/0-9/;
12647: $txt=~tr/K-T/0-9/;
12648: $txt=~tr/k-t/0-9/;
12649: $txt=~tr/U-Z/0-5/;
12650: $txt=~tr/u-z/0-5/;
12651: $txt=~s/\D//g;
12652: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12653: my $total;
12654: foreach my $val (@txts) { $total+=$val; }
12655: if ($_64bit) { $total=(($total<<32)>>32); }
12656: return $total;
12657: }
12658:
1.675 albertel 12659: sub digest {
12660: my ($data)=@_;
12661: my $digest=&Digest::MD5::md5($data);
12662: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12663: my ($e,$f);
12664: {
12665: use integer;
12666: $e=($a+$b);
12667: $f=($c+$d);
12668: if ($_64bit) {
12669: $e=(($e<<32)>>32);
12670: $f=(($f<<32)>>32);
12671: }
12672: }
12673: if (wantarray) {
12674: return ($e,$f);
12675: } else {
12676: my $g;
12677: {
12678: use integer;
12679: $g=($e+$f);
12680: if ($_64bit) {
12681: $g=(($g<<32)>>32);
12682: }
12683: }
12684: return $g;
12685: }
12686: }
12687:
1.368 albertel 12688: sub latest_rnd_algorithm_id {
1.675 albertel 12689: return '64bit5';
1.366 albertel 12690: }
1.32 www 12691:
1.503 albertel 12692: sub get_rand_alg {
12693: my ($courseid)=@_;
1.790 albertel 12694: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12695: if ($courseid) {
1.620 albertel 12696: return $env{"course.$courseid.rndseed"};
1.503 albertel 12697: }
12698: return &latest_rnd_algorithm_id();
12699: }
12700:
1.562 albertel 12701: sub validCODE {
12702: my ($CODE)=@_;
12703: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12704: return 0;
12705: }
12706:
1.491 albertel 12707: sub getCODE {
1.620 albertel 12708: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12709: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12710: defined($Apache::lonhomework::parsing_a_task) ) &&
12711: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12712: return $Apache::lonhomework::history{'resource.CODE'};
12713: }
12714: return undef;
12715: }
1.1133 foxr 12716: #
12717: # Determines the random seed for a specific context:
12718: #
12719: # parameters:
12720: # symb - in course context the symb for the seed.
12721: # course_id - The course id of the form domain_coursenum.
12722: # domain - Domain for the user.
12723: # course - Course for the user.
12724: # cenv - environment of the course.
12725: #
12726: # NOTE:
12727: # All parameters are picked out of the environment if missing
12728: # or not defined.
12729: # If a symb cannot be determined the current time is used instead.
12730: #
12731: # For a given well defined symb, courside, domain, username,
12732: # and course environment, the seed is reproducible.
12733: #
1.31 www 12734: sub rndseed {
1.1133 foxr 12735: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12736: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12737: if (!defined($symb)) {
1.366 albertel 12738: unless ($symb=$wsymb) { return time; }
12739: }
1.1146 foxr 12740: if (!defined $courseid) {
12741: $courseid=$wcourseid;
12742: }
12743: if (!defined $domain) { $domain=$wdomain; }
12744: if (!defined $username) { $username=$wusername }
1.1133 foxr 12745:
12746: my $which;
12747: if (defined($cenv->{'rndseed'})) {
12748: $which = $cenv->{'rndseed'};
12749: } else {
12750: $which =&get_rand_alg($courseid);
12751: }
1.491 albertel 12752: if (defined(&getCODE())) {
1.675 albertel 12753: if ($which eq '64bit5') {
12754: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12755: } elsif ($which eq '64bit4') {
1.575 albertel 12756: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12757: } else {
12758: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12759: }
1.675 albertel 12760: } elsif ($which eq '64bit5') {
12761: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12762: } elsif ($which eq '64bit4') {
12763: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12764: } elsif ($which eq '64bit3') {
12765: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12766: } elsif ($which eq '64bit2') {
12767: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12768: } elsif ($which eq '64bit') {
12769: return &rndseed_64bit($symb,$courseid,$domain,$username);
12770: }
12771: return &rndseed_32bit($symb,$courseid,$domain,$username);
12772: }
12773:
12774: sub rndseed_32bit {
12775: my ($symb,$courseid,$domain,$username)=@_;
12776: {
12777: use integer;
12778: my $symbchck=unpack("%32C*",$symb) << 27;
12779: my $symbseed=numval($symb) << 22;
12780: my $namechck=unpack("%32C*",$username) << 17;
12781: my $nameseed=numval($username) << 12;
12782: my $domainseed=unpack("%32C*",$domain) << 7;
12783: my $courseseed=unpack("%32C*",$courseid);
12784: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12785: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12786: #&logthis("rndseed :$num:$symb");
1.564 albertel 12787: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12788: return $num;
12789: }
12790: }
12791:
12792: sub rndseed_64bit {
12793: my ($symb,$courseid,$domain,$username)=@_;
12794: {
12795: use integer;
12796: my $symbchck=unpack("%32S*",$symb) << 21;
12797: my $symbseed=numval($symb) << 10;
12798: my $namechck=unpack("%32S*",$username);
12799:
12800: my $nameseed=numval($username) << 21;
12801: my $domainseed=unpack("%32S*",$domain) << 10;
12802: my $courseseed=unpack("%32S*",$courseid);
12803:
12804: my $num1=$symbchck+$symbseed+$namechck;
12805: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12806: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12807: #&logthis("rndseed :$num:$symb");
1.564 albertel 12808: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12809: return "$num1,$num2";
1.155 albertel 12810: }
1.366 albertel 12811: }
12812:
1.443 albertel 12813: sub rndseed_64bit2 {
12814: my ($symb,$courseid,$domain,$username)=@_;
12815: {
12816: use integer;
12817: # strings need to be an even # of cahracters long, it it is odd the
12818: # last characters gets thrown away
12819: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12820: my $symbseed=numval($symb) << 10;
12821: my $namechck=unpack("%32S*",$username.' ');
12822:
12823: my $nameseed=numval($username) << 21;
1.501 albertel 12824: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12825: my $courseseed=unpack("%32S*",$courseid.' ');
12826:
12827: my $num1=$symbchck+$symbseed+$namechck;
12828: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12829: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12830: #&logthis("rndseed :$num:$symb");
1.803 albertel 12831: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12832: return "$num1,$num2";
12833: }
12834: }
12835:
12836: sub rndseed_64bit3 {
12837: my ($symb,$courseid,$domain,$username)=@_;
12838: {
12839: use integer;
12840: # strings need to be an even # of cahracters long, it it is odd the
12841: # last characters gets thrown away
12842: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12843: my $symbseed=numval2($symb) << 10;
12844: my $namechck=unpack("%32S*",$username.' ');
12845:
12846: my $nameseed=numval2($username) << 21;
1.443 albertel 12847: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12848: my $courseseed=unpack("%32S*",$courseid.' ');
12849:
12850: my $num1=$symbchck+$symbseed+$namechck;
12851: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12852: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12853: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12854: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12855:
1.503 albertel 12856: return "$num1:$num2";
1.443 albertel 12857: }
12858: }
12859:
1.575 albertel 12860: sub rndseed_64bit4 {
12861: my ($symb,$courseid,$domain,$username)=@_;
12862: {
12863: use integer;
12864: # strings need to be an even # of cahracters long, it it is odd the
12865: # last characters gets thrown away
12866: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12867: my $symbseed=numval3($symb) << 10;
12868: my $namechck=unpack("%32S*",$username.' ');
12869:
12870: my $nameseed=numval3($username) << 21;
12871: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12872: my $courseseed=unpack("%32S*",$courseid.' ');
12873:
12874: my $num1=$symbchck+$symbseed+$namechck;
12875: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12876: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12877: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12878: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12879:
1.575 albertel 12880: return "$num1:$num2";
12881: }
12882: }
12883:
1.675 albertel 12884: sub rndseed_64bit5 {
12885: my ($symb,$courseid,$domain,$username)=@_;
12886: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12887: return "$num1:$num2";
12888: }
12889:
1.366 albertel 12890: sub rndseed_CODE_64bit {
12891: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12892: {
1.366 albertel 12893: use integer;
1.443 albertel 12894: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12895: my $symbseed=numval2($symb);
1.491 albertel 12896: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12897: my $CODEseed=numval(&getCODE());
1.443 albertel 12898: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12899: my $num1=$symbseed+$CODEchck;
12900: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12901: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12902: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12903: if ($_64bit) { $num1=(($num1<<32)>>32); }
12904: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12905: return "$num1:$num2";
1.366 albertel 12906: }
12907: }
12908:
1.575 albertel 12909: sub rndseed_CODE_64bit4 {
12910: my ($symb,$courseid,$domain,$username)=@_;
12911: {
12912: use integer;
12913: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12914: my $symbseed=numval3($symb);
12915: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12916: my $CODEseed=numval3(&getCODE());
12917: my $courseseed=unpack("%32S*",$courseid.' ');
12918: my $num1=$symbseed+$CODEchck;
12919: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12920: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12921: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12922: if ($_64bit) { $num1=(($num1<<32)>>32); }
12923: if ($_64bit) { $num2=(($num2<<32)>>32); }
12924: return "$num1:$num2";
12925: }
12926: }
12927:
1.675 albertel 12928: sub rndseed_CODE_64bit5 {
12929: my ($symb,$courseid,$domain,$username)=@_;
12930: my $code = &getCODE();
12931: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12932: return "$num1:$num2";
12933: }
12934:
1.366 albertel 12935: sub setup_random_from_rndseed {
12936: my ($rndseed)=@_;
1.503 albertel 12937: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 12938: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12939: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12940: &Math::Random::random_set_seed_from_phrase($rndseed);
12941: } else {
12942: &Math::Random::random_set_seed($num1,$num2);
12943: }
1.366 albertel 12944: } else {
12945: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12946: }
1.36 albertel 12947: }
12948:
1.474 albertel 12949: sub latest_receipt_algorithm_id {
1.835 albertel 12950: return 'receipt3';
1.474 albertel 12951: }
12952:
1.480 www 12953: sub recunique {
12954: my $fucourseid=shift;
12955: my $unique;
1.835 albertel 12956: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12957: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12958: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12959: } else {
12960: $unique=$perlvar{'lonReceipt'};
12961: }
12962: return unpack("%32C*",$unique);
12963: }
12964:
12965: sub recprefix {
12966: my $fucourseid=shift;
12967: my $prefix;
1.835 albertel 12968: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12969: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12970: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12971: } else {
12972: $prefix=$perlvar{'lonHostID'};
12973: }
12974: return unpack("%32C*",$prefix);
12975: }
12976:
1.76 www 12977: sub ireceipt {
1.474 albertel 12978: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12979:
12980: my $return =&recprefix($fucourseid).'-';
12981:
12982: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12983: $env{'request.state'} eq 'construct') {
12984: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12985: return $return;
12986: }
12987:
1.76 www 12988: my $cuname=unpack("%32C*",$funame);
12989: my $cudom=unpack("%32C*",$fudom);
12990: my $cucourseid=unpack("%32C*",$fucourseid);
12991: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12992: my $cunique=&recunique($fucourseid);
1.474 albertel 12993: my $cpart=unpack("%32S*",$part);
1.835 albertel 12994: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12995:
1.790 albertel 12996: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12997:
12998: $return.= ($cunique%$cuname+
12999: $cunique%$cudom+
13000: $cusymb%$cuname+
13001: $cusymb%$cudom+
13002: $cucourseid%$cuname+
13003: $cucourseid%$cudom+
13004: $cpart%$cuname+
13005: $cpart%$cudom);
13006: } else {
13007: $return.= ($cunique%$cuname+
13008: $cunique%$cudom+
13009: $cusymb%$cuname+
13010: $cusymb%$cudom+
13011: $cucourseid%$cuname+
13012: $cucourseid%$cudom);
13013: }
13014: return $return;
1.76 www 13015: }
13016:
13017: sub receipt {
1.474 albertel 13018: my ($part)=@_;
1.790 albertel 13019: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13020: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13021: }
1.260 ng 13022:
1.790 albertel 13023: sub whichuser {
13024: my ($passedsymb)=@_;
13025: my ($symb,$courseid,$domain,$name,$publicuser);
13026: if (defined($env{'form.grade_symb'})) {
13027: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13028: my $allowed=&allowed('vgr',$tmp_courseid);
13029: if (!$allowed &&
13030: exists($env{'request.course.sec'}) &&
13031: $env{'request.course.sec'} !~ /^\s*$/) {
13032: $allowed=&allowed('vgr',$tmp_courseid.
13033: '/'.$env{'request.course.sec'});
13034: }
13035: if ($allowed) {
13036: ($symb)=&get_env_multiple('form.grade_symb');
13037: $courseid=$tmp_courseid;
13038: ($domain)=&get_env_multiple('form.grade_domain');
13039: ($name)=&get_env_multiple('form.grade_username');
13040: return ($symb,$courseid,$domain,$name,$publicuser);
13041: }
13042: }
13043: if (!$passedsymb) {
13044: $symb=&symbread();
13045: } else {
13046: $symb=$passedsymb;
13047: }
13048: $courseid=$env{'request.course.id'};
13049: $domain=$env{'user.domain'};
13050: $name=$env{'user.name'};
13051: if ($name eq 'public' && $domain eq 'public') {
13052: if (!defined($env{'form.username'})) {
13053: $env{'form.username'}.=time.rand(10000000);
13054: }
13055: $name.=$env{'form.username'};
13056: }
13057: return ($symb,$courseid,$domain,$name,$publicuser);
13058:
13059: }
13060:
1.36 albertel 13061: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13062: # returns either the contents of the file or
13063: # -1 if the file doesn't exist
1.481 raeburn 13064: #
13065: # if the target is a file that was uploaded via DOCS,
13066: # a check will be made to see if a current copy exists on the local server,
13067: # if it does this will be served, otherwise a copy will be retrieved from
13068: # the home server for the course and stored in /home/httpd/html/userfiles on
13069: # the local server.
1.472 albertel 13070:
1.36 albertel 13071: sub getfile {
1.538 albertel 13072: my ($file) = @_;
1.609 banghart 13073: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13074: &repcopy($file);
13075: return &readfile($file);
13076: }
13077:
13078: sub repcopy_userfile {
13079: my ($file)=@_;
1.1142 raeburn 13080: my $londocroot = $perlvar{'lonDocRoot'};
13081: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13082: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13083: my ($cdom,$cnum,$filename) =
1.811 albertel 13084: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13085: my $uri="/uploaded/$cdom/$cnum/$filename";
13086: if (-e "$file") {
1.828 www 13087: # we already have a local copy, check it out
1.538 albertel 13088: my @fileinfo = stat($file);
1.828 www 13089: my $rtncode;
13090: my $info;
1.538 albertel 13091: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13092: if ($lwpresp ne 'ok') {
1.828 www 13093: # there is no such file anymore, even though we had a local copy
1.482 albertel 13094: if ($rtncode eq '404') {
1.538 albertel 13095: unlink($file);
1.482 albertel 13096: }
13097: return -1;
13098: }
13099: if ($info < $fileinfo[9]) {
1.828 www 13100: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13101: return 'ok';
1.828 www 13102: } else {
13103: # the file is outdated, get rid of it
13104: unlink($file);
1.482 albertel 13105: }
1.828 www 13106: }
13107: # one way or the other, at this point, we don't have the file
13108: # construct the correct path for the file
13109: my @parts = ($cdom,$cnum);
13110: if ($filename =~ m|^(.+)/[^/]+$|) {
13111: push @parts, split(/\//,$1);
13112: }
13113: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13114: foreach my $part (@parts) {
13115: $path .= '/'.$part;
13116: if (!-e $path) {
13117: mkdir($path,0770);
1.482 albertel 13118: }
13119: }
1.828 www 13120: # now the path exists for sure
13121: # get a user agent
13122: my $ua=new LWP::UserAgent;
13123: my $transferfile=$file.'.in.transfer';
13124: # FIXME: this should flock
13125: if (-e $transferfile) { return 'ok'; }
13126: my $request;
13127: $uri=~s/^\///;
1.980 raeburn 13128: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13129: my $hostname = &hostname($homeserver);
1.980 raeburn 13130: my $protocol = $protocol{$homeserver};
13131: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13132: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 13133: my $response=$ua->request($request,$transferfile);
13134: # did it work?
13135: if ($response->is_error()) {
13136: unlink($transferfile);
13137: &logthis("Userfile repcopy failed for $uri");
13138: return -1;
13139: }
13140: # worked, rename the transfer file
13141: rename($transferfile,$file);
1.607 raeburn 13142: return 'ok';
1.481 raeburn 13143: }
13144:
1.517 albertel 13145: sub tokenwrapper {
13146: my $uri=shift;
1.980 raeburn 13147: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13148: $uri=~s|^/||;
1.620 albertel 13149: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13150: my $token=$1;
1.552 albertel 13151: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13152: if ($udom && $uname && $file) {
13153: $file=~s|(\?\.*)*$||;
1.949 raeburn 13154: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13155: my $homeserver = &homeserver($uname,$udom);
1.1172.2.120 raeburn 13156: my $hostname = &hostname($homeserver);
1.980 raeburn 13157: my $protocol = $protocol{$homeserver};
13158: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13159: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13160: (($uri=~/\?/)?'&':'?').'token='.$token.
13161: '&tokenissued='.$perlvar{'lonHostID'};
13162: } else {
13163: return '/adm/notfound.html';
13164: }
13165: }
13166:
1.828 www 13167: # call with reqtype HEAD: get last modification time
13168: # call with reqtype GET: get the file contents
13169: # Do not call this with reqtype GET for large files! It loads everything into memory
13170: #
1.481 raeburn 13171: sub getuploaded {
13172: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13173: $uri=~s/^\///;
1.980 raeburn 13174: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13175: my $hostname = &hostname($homeserver);
1.980 raeburn 13176: my $protocol = $protocol{$homeserver};
13177: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13178: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13179: my $ua=new LWP::UserAgent;
13180: my $request=new HTTP::Request($reqtype,$uri);
13181: my $response=$ua->request($request);
13182: $$rtncode = $response->code;
1.482 albertel 13183: if (! $response->is_success()) {
13184: return 'failed';
13185: }
13186: if ($reqtype eq 'HEAD') {
1.486 www 13187: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13188: } elsif ($reqtype eq 'GET') {
13189: $$info = $response->content;
1.472 albertel 13190: }
1.482 albertel 13191: return 'ok';
1.36 albertel 13192: }
13193:
1.481 raeburn 13194: sub readfile {
13195: my $file = shift;
13196: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13197: my $fh;
1.1172.2.96 raeburn 13198: open($fh,"<",$file);
1.481 raeburn 13199: my $a='';
1.800 albertel 13200: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13201: return $a;
13202: }
13203:
1.36 albertel 13204: sub filelocation {
1.590 banghart 13205: my ($dir,$file) = @_;
13206: my $location;
13207: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13208:
13209: if ($file =~ m-^/adm/-) {
13210: $file=~s-^/adm/wrapper/-/-;
13211: $file=~s-^/adm/coursedocs/showdoc/-/-;
13212: }
1.882 albertel 13213:
1.1139 www 13214: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13215: $location = $file;
1.609 banghart 13216: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13217: my ($udom,$uname,$filename)=
1.811 albertel 13218: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13219: my $home=&homeserver($uname,$udom);
13220: my $is_me=0;
13221: my @ids=¤t_machine_ids();
13222: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13223: if ($is_me) {
1.1117 foxr 13224: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13225: } else {
13226: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13227: $udom.'/'.$uname.'/'.$filename;
13228: }
1.882 albertel 13229: } elsif ($file =~ m-^/adm/-) {
13230: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13231: } else {
13232: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13233: $file=~s:^/(res|priv)/:/:;
13234: my $space=$1;
1.590 banghart 13235: if ( !( $file =~ m:^/:) ) {
13236: $location = $dir. '/'.$file;
13237: } else {
1.1142 raeburn 13238: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13239: }
1.59 albertel 13240: }
1.590 banghart 13241: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13242: while ($location=~m{/\.\./}) {
13243: if ($location =~ m{/[^/]+/\.\./}) {
13244: $location=~ s{/[^/]+/\.\./}{/}g;
13245: } else {
13246: $location=~ s{/\.\./}{/}g;
13247: }
13248: } #remove dir/..
1.590 banghart 13249: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13250: return $location;
1.46 www 13251: }
1.36 albertel 13252:
1.46 www 13253: sub hreflocation {
13254: my ($dir,$file)=@_;
1.980 raeburn 13255: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13256: $file=filelocation($dir,$file);
1.700 albertel 13257: } elsif ($file=~m-^/adm/-) {
13258: $file=~s-^/adm/wrapper/-/-;
13259: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13260: }
13261: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13262: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13263: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13264: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13265: {/uploaded/$1/$2/}x;
1.46 www 13266: }
1.913 albertel 13267: if ($file=~ m{^/userfiles/}) {
13268: $file =~ s{^/userfiles/}{/uploaded/};
13269: }
1.462 albertel 13270: return $file;
1.465 albertel 13271: }
13272:
1.1139 www 13273:
13274:
13275:
13276:
1.465 albertel 13277: sub current_machine_domains {
1.853 albertel 13278: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13279: }
13280:
13281: sub machine_domains {
13282: my ($hostname) = @_;
1.465 albertel 13283: my @domains;
1.838 albertel 13284: my %hostname = &all_hostnames();
1.465 albertel 13285: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13286: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13287: if ($hostname eq $name) {
1.844 albertel 13288: push(@domains,&host_domain($id));
1.465 albertel 13289: }
13290: }
13291: return @domains;
13292: }
13293:
13294: sub current_machine_ids {
1.853 albertel 13295: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13296: }
13297:
13298: sub machine_ids {
13299: my ($hostname) = @_;
13300: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13301: my @ids;
1.888 albertel 13302: my %name_to_host = &all_names();
1.889 albertel 13303: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13304: return @{ $name_to_host{$hostname} };
13305: }
13306: return;
1.31 www 13307: }
13308:
1.824 raeburn 13309: sub additional_machine_domains {
13310: my @domains;
1.1172.2.96 raeburn 13311: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 13312: while( my $line = <$fh>) {
13313: $line =~ s/\s//g;
13314: push(@domains,$line);
13315: }
13316: return @domains;
13317: }
13318:
13319: sub default_login_domain {
13320: my $domain = $perlvar{'lonDefDomain'};
13321: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13322: foreach my $posdom (¤t_machine_domains(),
13323: &additional_machine_domains()) {
13324: if (lc($posdom) eq lc($testdomain)) {
13325: $domain=$posdom;
13326: last;
13327: }
13328: }
13329: return $domain;
13330: }
13331:
1.1172.2.106 raeburn 13332: sub shared_institution {
13333: my ($dom) = @_;
13334: my $same_intdom;
13335: my $hostintdom = &internet_dom($perlvar{'lonHostID'});
13336: if ($hostintdom ne '') {
13337: my %iphost = &get_iphost();
13338: my $primary_id = &domain($dom,'primary');
13339: my $primary_ip = &get_host_ip($primary_id);
13340: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13341: foreach my $id (@{$iphost{$primary_ip}}) {
13342: my $intdom = &internet_dom($id);
13343: if ($intdom eq $hostintdom) {
13344: $same_intdom = 1;
13345: last;
13346: }
13347: }
13348: }
13349: }
13350: return $same_intdom;
13351: }
13352:
1.1172.2.120 raeburn 13353: sub uses_sts {
13354: my ($ignore_cache) = @_;
13355: my $lonhost = $perlvar{'lonHostID'};
13356: my $hostname = &hostname($lonhost);
13357: my $sts_on;
13358: if ($protocol{$lonhost} eq 'https') {
13359: my $cachetime = 12*3600;
13360: if (!$ignore_cache) {
13361: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13362: if (defined($cached)) {
13363: return $sts_on;
13364: }
13365: }
1.1172.2.121 raeburn 13366: my $ua=new LWP::UserAgent;
1.1172.2.120 raeburn 13367: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13368: my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121 raeburn 13369: my $response=$ua->request($request);
1.1172.2.120 raeburn 13370: if ($response->is_success) {
13371: my $has_sts = $response->header('Strict-Transport-Security');
13372: if ($has_sts eq '') {
13373: $sts_on = 0;
13374: } else {
13375: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13376: my $maxage = $1;
13377: if ($maxage) {
13378: $sts_on = 1;
13379: } else {
13380: $sts_on = 0;
13381: }
13382: } else {
13383: $sts_on = 0;
13384: }
13385: }
13386: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13387: }
13388: }
13389: return;
13390: }
13391:
1.31 www 13392: # ------------------------------------------------------------- Declutters URLs
13393:
13394: sub declutter {
13395: my $thisfn=shift;
1.569 albertel 13396: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 13397: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13398: $thisfn=~s{^/home/httpd/html}{};
13399: }
1.31 www 13400: $thisfn=~s/^\///;
1.697 albertel 13401: $thisfn=~s|^adm/wrapper/||;
13402: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13403: $thisfn=~s/^res\///;
1.1172 bisitz 13404: $thisfn=~s/^priv\///;
1.1032 raeburn 13405: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13406: $thisfn=~s/\?.+$//;
13407: }
1.268 www 13408: return $thisfn;
13409: }
13410:
13411: # ------------------------------------------------------------- Clutter up URLs
13412:
13413: sub clutter {
13414: my $thisfn='/'.&declutter(shift);
1.887 albertel 13415: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13416: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13417: $thisfn='/res'.$thisfn;
13418: }
1.1031 raeburn 13419: if ($thisfn !~m|^/adm|) {
13420: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13421: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13422: } else {
13423: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13424: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13425: if ($embstyle eq 'ssi'
13426: || ($embstyle eq 'hdn')
13427: || ($embstyle eq 'rat')
13428: || ($embstyle eq 'prv')
13429: || ($embstyle eq 'ign')) {
13430: #do nothing with these
13431: } elsif (($embstyle eq 'img')
1.695 albertel 13432: || ($embstyle eq 'emb')
13433: || ($embstyle eq 'wrp')) {
13434: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13435: } elsif ($embstyle eq 'unk'
13436: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13437: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13438: } else {
1.718 www 13439: # &logthis("Got a blank emb style");
1.695 albertel 13440: }
1.694 albertel 13441: }
13442: }
1.31 www 13443: return $thisfn;
1.12 www 13444: }
13445:
1.787 albertel 13446: sub clutter_with_no_wrapper {
13447: my $uri = &clutter(shift);
13448: if ($uri =~ m-^/adm/-) {
13449: $uri =~ s-^/adm/wrapper/-/-;
13450: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13451: }
13452: return $uri;
13453: }
13454:
1.557 albertel 13455: sub freeze_escape {
13456: my ($value)=@_;
13457: if (ref($value)) {
13458: $value=&nfreeze($value);
13459: return '__FROZEN__'.&escape($value);
13460: }
13461: return &escape($value);
13462: }
13463:
1.11 www 13464:
1.557 albertel 13465: sub thaw_unescape {
13466: my ($value)=@_;
13467: if ($value =~ /^__FROZEN__/) {
13468: substr($value,0,10,undef);
13469: $value=&unescape($value);
13470: return &thaw($value);
13471: }
13472: return &unescape($value);
13473: }
13474:
1.436 albertel 13475: sub correct_line_ends {
13476: my ($result)=@_;
13477: $$result =~s/\r\n/\n/mg;
13478: $$result =~s/\r/\n/mg;
1.415 albertel 13479: }
1.1 albertel 13480: # ================================================================ Main Program
13481:
1.184 www 13482: sub goodbye {
1.204 albertel 13483: &logthis("Starting Shut down");
1.443 albertel 13484: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13485: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13486: #converted
1.599 albertel 13487: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13488: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13489: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13490: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13491: #1.1 only
1.870 albertel 13492: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13493: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13494: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13495: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13496: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13497: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13498: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13499: &flushcourselogs();
13500: &logthis("Shutting down");
13501: }
13502:
1.852 albertel 13503: sub get_dns {
1.1172.2.17 raeburn 13504: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13505: if (!$ignore_cache) {
13506: my ($content,$cached)=
13507: &Apache::lonnet::is_cached_new('dns',$url);
13508: if ($cached) {
1.1172.2.17 raeburn 13509: &$func($content,$hashref);
1.869 albertel 13510: return;
13511: }
13512: }
13513:
13514: my %alldns;
1.1172.2.96 raeburn 13515: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13516: foreach my $dns (<$config>) {
13517: next if ($dns !~ /^\^(\S*)/x);
13518: my $line = $1;
13519: my ($host,$protocol) = split(/:/,$line);
13520: if ($protocol ne 'https') {
13521: $protocol = 'http';
13522: }
13523: $alldns{$host} = $protocol;
1.979 raeburn 13524: }
1.1172.2.96 raeburn 13525: close($config);
1.869 albertel 13526: }
13527: while (%alldns) {
1.1172.2.52 raeburn 13528: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 13529: my $ua=new LWP::UserAgent;
1.1134 raeburn 13530: $ua->timeout(30);
1.979 raeburn 13531: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 13532: my $response=$ua->request($request);
1.979 raeburn 13533: delete($alldns{$dns});
1.852 albertel 13534: next if ($response->is_error());
13535: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 13536: unless ($nocache) {
1.1172.2.23 raeburn 13537: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 13538: }
13539: &$func(\@content,$hashref);
1.869 albertel 13540: return;
1.852 albertel 13541: }
1.871 albertel 13542: my $which = (split('/',$url))[3];
13543: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 13544: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13545: my @content = <$config>;
13546: &$func(\@content,$hashref);
13547: }
1.1172.2.17 raeburn 13548: return;
13549: }
13550:
13551: # ------------------------------------------------------Get DNS checksums file
13552: sub parse_dns_checksums_tab {
13553: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 13554: my $lonhost = $perlvar{'lonHostID'};
13555: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 13556: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 13557: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13558: my $webconfdir = '/etc/httpd/conf';
13559: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13560: $webconfdir = '/etc/apache2';
13561: } elsif ($distro =~ /^sles(\d+)$/) {
13562: if ($1 >= 10) {
13563: $webconfdir = '/etc/apache2';
13564: }
13565: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13566: if ($1 >= 10.0) {
13567: $webconfdir = '/etc/apache2';
13568: }
13569: }
1.1172.2.17 raeburn 13570: my ($release,$timestamp) = split(/\-/,$loncaparev);
13571: my (%chksum,%revnum);
13572: if (ref($lines) eq 'ARRAY') {
13573: chomp(@{$lines});
1.1172.2.34 raeburn 13574: my $version = shift(@{$lines});
13575: if ($version eq $release) {
1.1172.2.17 raeburn 13576: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 13577: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 13578: if ($file =~ m{^/etc/httpd/conf}) {
13579: if ($webconfdir eq '/etc/apache2') {
13580: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13581: }
13582: }
1.1172.2.34 raeburn 13583: $chksum{$file} = $shasum;
13584: $revnum{$file} = $version;
1.1172.2.17 raeburn 13585: }
13586: if (ref($hashref) eq 'HASH') {
13587: %{$hashref} = (
13588: sums => \%chksum,
13589: versions => \%revnum,
13590: );
13591: }
13592: }
13593: }
1.869 albertel 13594: return;
1.852 albertel 13595: }
1.1172.2.17 raeburn 13596:
13597: sub fetch_dns_checksums {
13598: my %checksums;
1.1172.2.34 raeburn 13599: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 13600: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 13601: my ($release,$timestamp) = split(/\-/,$loncaparev);
13602: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 13603: \%checksums);
13604: return \%checksums;
13605: }
13606:
1.327 albertel 13607: # ------------------------------------------------------------ Read domain file
13608: {
1.852 albertel 13609: my $loaded;
1.846 albertel 13610: my %domain;
13611:
1.852 albertel 13612: sub parse_domain_tab {
13613: my ($lines) = @_;
13614: foreach my $line (@$lines) {
13615: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 13616:
1.846 albertel 13617: chomp($line);
1.852 albertel 13618: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 13619: my %this_domain;
13620: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13621: 'lang_def', 'city', 'longi', 'lati',
13622: 'primary') {
13623: $this_domain{$field} = shift(@elements);
13624: }
13625: $domain{$name} = \%this_domain;
1.852 albertel 13626: }
13627: }
1.864 albertel 13628:
13629: sub reset_domain_info {
13630: undef($loaded);
13631: undef(%domain);
13632: }
13633:
1.852 albertel 13634: sub load_domain_tab {
1.1172.2.70 raeburn 13635: my ($ignore_cache,$nocache) = @_;
13636: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 13637: my $fh;
1.1172.2.96 raeburn 13638: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 13639: my @lines = <$fh>;
13640: &parse_domain_tab(\@lines);
1.448 albertel 13641: }
1.852 albertel 13642: close($fh);
13643: $loaded = 1;
1.327 albertel 13644: }
1.846 albertel 13645:
13646: sub domain {
1.852 albertel 13647: &load_domain_tab() if (!$loaded);
13648:
1.846 albertel 13649: my ($name,$what) = @_;
13650: return if ( !exists($domain{$name}) );
13651:
13652: if (!$what) {
13653: return $domain{$name}{'description'};
13654: }
13655: return $domain{$name}{$what};
13656: }
1.974 raeburn 13657:
13658: sub domain_info {
13659: &load_domain_tab() if (!$loaded);
13660: return %domain;
13661: }
13662:
1.327 albertel 13663: }
13664:
13665:
1.1 albertel 13666: # ------------------------------------------------------------- Read hosts file
13667: {
1.838 albertel 13668: my %hostname;
1.844 albertel 13669: my %hostdom;
1.845 albertel 13670: my %libserv;
1.852 albertel 13671: my $loaded;
1.888 albertel 13672: my %name_to_host;
1.1074 raeburn 13673: my %internetdom;
1.1107 raeburn 13674: my %LC_dns_serv;
1.852 albertel 13675:
13676: sub parse_hosts_tab {
13677: my ($file) = @_;
13678: foreach my $configline (@$file) {
13679: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 13680: chomp($configline);
13681: if ($configline =~ /^\^/) {
13682: if ($configline =~ /^\^([\w.\-]+)/) {
13683: $LC_dns_serv{$1} = 1;
13684: }
13685: next;
13686: }
1.1074 raeburn 13687: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 13688: $name=~s/\s//g;
13689: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 13690: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13691: my $curr = $hostname{$id};
13692: my $skip;
13693: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13694: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13695: $skip = 1;
13696: } else {
13697: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13698: }
13699: }
13700: unless ($skip) {
13701: push(@{$name_to_host{$name}},$id);
13702: }
13703: } else {
13704: push(@{$name_to_host{$name}},$id);
13705: }
1.852 albertel 13706: $hostname{$id}=$name;
13707: $hostdom{$id}=$domain;
13708: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 13709: if (defined($protocol)) {
13710: if ($protocol eq 'https') {
13711: $protocol{$id} = $protocol;
13712: } else {
13713: $protocol{$id} = 'http';
13714: }
1.968 raeburn 13715: } else {
1.969 raeburn 13716: $protocol{$id} = 'http';
1.968 raeburn 13717: }
1.1074 raeburn 13718: if (defined($intdom)) {
13719: $internetdom{$id} = $intdom;
13720: }
1.852 albertel 13721: }
13722: }
13723: }
1.864 albertel 13724:
13725: sub reset_hosts_info {
1.897 albertel 13726: &purge_remembered();
1.864 albertel 13727: &reset_domain_info();
13728: &reset_hosts_ip_info();
1.892 albertel 13729: undef(%name_to_host);
1.864 albertel 13730: undef(%hostname);
13731: undef(%hostdom);
13732: undef(%libserv);
13733: undef($loaded);
13734: }
1.1 albertel 13735:
1.852 albertel 13736: sub load_hosts_tab {
1.1172.2.70 raeburn 13737: my ($ignore_cache,$nocache) = @_;
13738: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 13739: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 13740: my @config = <$config>;
13741: &parse_hosts_tab(\@config);
13742: close($config);
13743: $loaded=1;
1.1 albertel 13744: }
1.852 albertel 13745:
1.838 albertel 13746: sub hostname {
1.852 albertel 13747: &load_hosts_tab() if (!$loaded);
13748:
1.838 albertel 13749: my ($lonid) = @_;
13750: return $hostname{$lonid};
13751: }
1.845 albertel 13752:
1.838 albertel 13753: sub all_hostnames {
1.852 albertel 13754: &load_hosts_tab() if (!$loaded);
13755:
1.838 albertel 13756: return %hostname;
13757: }
1.845 albertel 13758:
1.888 albertel 13759: sub all_names {
1.1172.2.70 raeburn 13760: my ($ignore_cache,$nocache) = @_;
13761: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13762:
13763: return %name_to_host;
13764: }
13765:
1.974 raeburn 13766: sub all_host_domain {
13767: &load_hosts_tab() if (!$loaded);
13768: return %hostdom;
13769: }
13770:
1.845 albertel 13771: sub is_library {
1.852 albertel 13772: &load_hosts_tab() if (!$loaded);
13773:
1.845 albertel 13774: return exists($libserv{$_[0]});
13775: }
13776:
13777: sub all_library {
1.852 albertel 13778: &load_hosts_tab() if (!$loaded);
13779:
1.845 albertel 13780: return %libserv;
13781: }
13782:
1.1062 droeschl 13783: sub unique_library {
13784: #2x reverse removes all hostnames that appear more than once
13785: my %unique = reverse &all_library();
13786: return reverse %unique;
13787: }
13788:
1.841 albertel 13789: sub get_servers {
1.852 albertel 13790: &load_hosts_tab() if (!$loaded);
13791:
1.841 albertel 13792: my ($domain,$type) = @_;
13793: my %possible_hosts = ($type eq 'library') ? %libserv
13794: : %hostname;
13795: my %result;
1.842 albertel 13796: if (ref($domain) eq 'ARRAY') {
13797: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13798: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13799: $result{$host} = $hostname;
13800: }
13801: }
13802: } else {
13803: while ( my ($host,$hostname) = each(%possible_hosts)) {
13804: if ($hostdom{$host} eq $domain) {
13805: $result{$host} = $hostname;
13806: }
1.841 albertel 13807: }
13808: }
13809: return %result;
13810: }
1.845 albertel 13811:
1.1062 droeschl 13812: sub get_unique_servers {
13813: my %unique = reverse &get_servers(@_);
13814: return reverse %unique;
13815: }
13816:
1.844 albertel 13817: sub host_domain {
1.852 albertel 13818: &load_hosts_tab() if (!$loaded);
13819:
1.844 albertel 13820: my ($lonid) = @_;
13821: return $hostdom{$lonid};
13822: }
13823:
1.841 albertel 13824: sub all_domains {
1.852 albertel 13825: &load_hosts_tab() if (!$loaded);
13826:
1.841 albertel 13827: my %seen;
13828: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13829: return @uniq;
13830: }
1.1074 raeburn 13831:
13832: sub internet_dom {
13833: &load_hosts_tab() if (!$loaded);
13834:
13835: my ($lonid) = @_;
13836: return $internetdom{$lonid};
13837: }
1.1107 raeburn 13838:
13839: sub is_LC_dns {
13840: &load_hosts_tab() if (!$loaded);
13841:
13842: my ($hostname) = @_;
13843: return exists($LC_dns_serv{$hostname});
13844: }
13845:
1.1 albertel 13846: }
13847:
1.847 albertel 13848: {
13849: my %iphost;
1.856 albertel 13850: my %name_to_ip;
13851: my %lonid_to_ip;
1.869 albertel 13852:
1.847 albertel 13853: sub get_hosts_from_ip {
13854: my ($ip) = @_;
13855: my %iphosts = &get_iphost();
13856: if (ref($iphosts{$ip})) {
13857: return @{$iphosts{$ip}};
13858: }
13859: return;
1.839 albertel 13860: }
1.864 albertel 13861:
13862: sub reset_hosts_ip_info {
13863: undef(%iphost);
13864: undef(%name_to_ip);
13865: undef(%lonid_to_ip);
13866: }
1.856 albertel 13867:
13868: sub get_host_ip {
13869: my ($lonid) = @_;
13870: if (exists($lonid_to_ip{$lonid})) {
13871: return $lonid_to_ip{$lonid};
13872: }
13873: my $name=&hostname($lonid);
13874: my $ip = gethostbyname($name);
13875: return if (!$ip || length($ip) ne 4);
13876: $ip=inet_ntoa($ip);
13877: $name_to_ip{$name} = $ip;
13878: $lonid_to_ip{$lonid} = $ip;
13879: return $ip;
13880: }
1.847 albertel 13881:
13882: sub get_iphost {
1.1172.2.70 raeburn 13883: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13884:
1.869 albertel 13885: if (!$ignore_cache) {
13886: if (%iphost) {
13887: return %iphost;
13888: }
13889: my ($ip_info,$cached)=
13890: &Apache::lonnet::is_cached_new('iphost','iphost');
13891: if ($cached) {
13892: %iphost = %{$ip_info->[0]};
13893: %name_to_ip = %{$ip_info->[1]};
13894: %lonid_to_ip = %{$ip_info->[2]};
13895: return %iphost;
13896: }
13897: }
1.894 albertel 13898:
13899: # get yesterday's info for fallback
13900: my %old_name_to_ip;
13901: my ($ip_info,$cached)=
13902: &Apache::lonnet::is_cached_new('iphost','iphost');
13903: if ($cached) {
13904: %old_name_to_ip = %{$ip_info->[1]};
13905: }
13906:
1.1172.2.70 raeburn 13907: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13908: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13909: my $ip;
13910: if (!exists($name_to_ip{$name})) {
13911: $ip = gethostbyname($name);
13912: if (!$ip || length($ip) ne 4) {
1.894 albertel 13913: if (defined($old_name_to_ip{$name})) {
13914: $ip = $old_name_to_ip{$name};
13915: &logthis("Can't find $name defaulting to old $ip");
13916: } else {
13917: &logthis("Name $name no IP found");
13918: next;
13919: }
13920: } else {
13921: $ip=inet_ntoa($ip);
1.847 albertel 13922: }
13923: $name_to_ip{$name} = $ip;
13924: } else {
13925: $ip = $name_to_ip{$name};
1.653 albertel 13926: }
1.888 albertel 13927: foreach my $id (@{ $name_to_host{$name} }) {
13928: $lonid_to_ip{$id} = $ip;
13929: }
13930: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13931: }
1.1172.2.70 raeburn 13932: unless ($nocache) {
13933: &do_cache_new('iphost','iphost',
13934: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13935: 48*60*60);
13936: }
1.869 albertel 13937:
1.847 albertel 13938: return %iphost;
1.598 albertel 13939: }
13940:
1.992 raeburn 13941: #
13942: # Given a DNS returns the loncapa host name for that DNS
13943: #
13944: sub host_from_dns {
13945: my ($dns) = @_;
13946: my @hosts;
13947: my $ip;
13948:
1.993 raeburn 13949: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13950: $ip = $name_to_ip{$dns};
13951: }
13952: if (!$ip) {
13953: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13954: if (length($ip) == 4) {
13955: $ip = &IO::Socket::inet_ntoa($ip);
13956: }
13957: }
13958: if ($ip) {
13959: @hosts = get_hosts_from_ip($ip);
13960: return $hosts[0];
13961: }
13962: return undef;
1.986 foxr 13963: }
1.992 raeburn 13964:
1.1074 raeburn 13965: sub get_internet_names {
13966: my ($lonid) = @_;
13967: return if ($lonid eq '');
13968: my ($idnref,$cached)=
13969: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13970: if ($cached) {
13971: return $idnref;
13972: }
13973: my $ip = &get_host_ip($lonid);
13974: my @hosts = &get_hosts_from_ip($ip);
13975: my %iphost = &get_iphost();
13976: my (@idns,%seen);
13977: foreach my $id (@hosts) {
13978: my $dom = &host_domain($id);
13979: my $prim_id = &domain($dom,'primary');
13980: my $prim_ip = &get_host_ip($prim_id);
13981: next if ($seen{$prim_ip});
13982: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13983: foreach my $id (@{$iphost{$prim_ip}}) {
13984: my $intdom = &internet_dom($id);
13985: unless (grep(/^\Q$intdom\E$/,@idns)) {
13986: push(@idns,$intdom);
13987: }
13988: }
13989: }
13990: $seen{$prim_ip} = 1;
13991: }
1.1172.2.23 raeburn 13992: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13993: }
13994:
1.986 foxr 13995: }
13996:
1.1079 raeburn 13997: sub all_loncaparevs {
1.1172.2.39 raeburn 13998: 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 13999: }
14000:
1.1172.2.27 raeburn 14001: # ------------------------------------------------------- Read loncaparev table
14002: {
14003: sub load_loncaparevs {
14004: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 14005: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 14006: while (my $configline=<$config>) {
14007: chomp($configline);
14008: my ($hostid,$loncaparev)=split(/:/,$configline);
14009: $loncaparevs{$hostid}=$loncaparev;
14010: }
14011: close($config);
14012: }
14013: }
14014: }
14015: }
14016:
14017: # ----------------------------------------------------- Read serverhostID table
14018: {
14019: sub load_serverhomeIDs {
14020: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 14021: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 14022: while (my $configline=<$config>) {
14023: chomp($configline);
14024: my ($name,$id)=split(/:/,$configline);
14025: $serverhomeIDs{$name}=$id;
14026: }
14027: close($config);
14028: }
14029: }
14030: }
14031: }
14032:
14033:
1.862 albertel 14034: BEGIN {
14035:
14036: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14037: unless ($readit) {
14038: {
14039: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14040: %perlvar = (%perlvar,%{$configvars});
14041: }
14042:
14043:
1.1 albertel 14044: # ------------------------------------------------------ Read spare server file
14045: {
1.1172.2.96 raeburn 14046: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14047:
14048: while (my $configline=<$config>) {
14049: chomp($configline);
1.284 matthew 14050: if ($configline) {
1.784 albertel 14051: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14052: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14053: push(@{ $spareid{$type} }, $host);
1.1 albertel 14054: }
14055: }
1.448 albertel 14056: close($config);
1.1 albertel 14057: }
1.11 www 14058: # ------------------------------------------------------------ Read permissions
14059: {
1.1172.2.96 raeburn 14060: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14061:
14062: while (my $configline=<$config>) {
1.448 albertel 14063: chomp($configline);
14064: if ($configline) {
14065: my ($role,$perm)=split(/ /,$configline);
14066: if ($perm ne '') { $pr{$role}=$perm; }
14067: }
1.11 www 14068: }
1.448 albertel 14069: close($config);
1.11 www 14070: }
14071:
14072: # -------------------------------------------- Read plain texts for permissions
14073: {
1.1172.2.96 raeburn 14074: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14075:
14076: while (my $configline=<$config>) {
1.448 albertel 14077: chomp($configline);
14078: if ($configline) {
1.742 raeburn 14079: my ($short,@plain)=split(/:/,$configline);
14080: %{$prp{$short}} = ();
14081: if (@plain > 0) {
14082: $prp{$short}{'std'} = $plain[0];
14083: for (my $i=1; $i<@plain; $i++) {
14084: $prp{$short}{'alt'.$i} = $plain[$i];
14085: }
14086: }
1.448 albertel 14087: }
1.135 www 14088: }
1.448 albertel 14089: close($config);
1.135 www 14090: }
14091:
14092: # ---------------------------------------------------------- Read package table
14093: {
1.1172.2.96 raeburn 14094: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14095:
14096: while (my $configline=<$config>) {
1.483 albertel 14097: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14098: chomp($configline);
14099: my ($short,$plain)=split(/:/,$configline);
14100: my ($pack,$name)=split(/\&/,$short);
14101: if ($plain ne '') {
14102: $packagetab{$pack.'&'.$name.'&name'}=$name;
14103: $packagetab{$short}=$plain;
14104: }
1.11 www 14105: }
1.448 albertel 14106: close($config);
1.329 matthew 14107: }
14108:
1.1172.2.27 raeburn 14109: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 14110:
1.1172.2.27 raeburn 14111: &load_loncaparevs();
14112:
14113: # ------------------------------------------------------- Read serverhostID table
14114:
14115: &load_serverhomeIDs();
1.1074 raeburn 14116:
1.1172.2.27 raeburn 14117: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14118: {
14119: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14120: if (-e $file) {
14121: my $parser = HTML::LCParser->new($file);
14122: while (my $token = $parser->get_token()) {
14123: if ($token->[0] eq 'S') {
14124: my $item = $token->[1];
14125: my $name = $token->[2]{'name'};
14126: my $value = $token->[2]{'value'};
14127: if ($item ne '' && $name ne '' && $value ne '') {
14128: my $release = $parser->get_text();
14129: $release =~ s/(^\s*|\s*$ )//gx;
14130: $needsrelease{$item.':'.$name.':'.$value} = $release;
14131: }
14132: }
14133: }
14134: }
1.1073 raeburn 14135: }
14136:
1.1138 raeburn 14137: # ---------------------------------------------------------- Read managers table
14138: {
14139: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 14140: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14141: while (my $configline=<$config>) {
14142: chomp($configline);
14143: next if ($configline =~ /^\#/);
14144: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14145: $managerstab{$configline} = 1;
14146: }
14147: }
14148: close($config);
14149: }
14150: }
14151: }
14152:
1.329 matthew 14153: # ------------- set up temporary directory
14154: {
1.1117 foxr 14155: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14156:
1.11 www 14157: }
14158:
1.1172.2.104 raeburn 14159: # ------------- set default texengine (domain default overrides this)
14160: {
14161: $deftex = LONCAPA::texengine();
14162: }
14163:
1.1172.2.114 raeburn 14164: # ------------- set default minimum length for passwords for internal auth users
14165: {
14166: $passwdmin = LONCAPA::passwd_min();
14167: }
14168:
1.794 albertel 14169: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14170: 'compress_threshold'=> 20_000,
14171: });
1.185 www 14172:
1.281 www 14173: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14174: $dumpcount=0;
1.958 www 14175: $locknum=0;
1.22 www 14176:
1.163 harris41 14177: &logtouch();
1.672 albertel 14178: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14179: $readit=1;
1.564 albertel 14180: {
14181: use integer;
14182: my $test=(2**32)+1;
1.568 albertel 14183: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14184: &logthis(" Detected 64bit platform ($_64bit)");
14185: }
1.195 www 14186: }
1.1 albertel 14187: }
1.179 www 14188:
1.1 albertel 14189: 1;
1.191 harris41 14190: __END__
14191:
1.243 albertel 14192: =pod
14193:
1.191 harris41 14194: =head1 NAME
14195:
1.243 albertel 14196: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14197:
14198: =head1 SYNOPSIS
14199:
1.243 albertel 14200: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14201:
14202: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14203:
1.243 albertel 14204: Common parameters:
14205:
14206: =over 4
14207:
14208: =item *
14209:
14210: $uname : an internal username (if $cname expecting a course Id specifically)
14211:
14212: =item *
14213:
14214: $udom : a domain (if $cdom expecting a course's domain specifically)
14215:
14216: =item *
14217:
14218: $symb : a resource instance identifier
14219:
14220: =item *
14221:
14222: $namespace : the name of a .db file that contains the data needed or
14223: being set.
14224:
14225: =back
14226:
1.394 bowersj2 14227: =head1 OVERVIEW
1.191 harris41 14228:
1.394 bowersj2 14229: lonnet provides subroutines which interact with the
14230: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14231: about classes, users, and resources.
1.243 albertel 14232:
14233: For many of these objects you can also use this to store data about
14234: them or modify them in various ways.
1.191 harris41 14235:
1.394 bowersj2 14236: =head2 Symbs
1.191 harris41 14237:
1.394 bowersj2 14238: To identify a specific instance of a resource, LON-CAPA uses symbols
14239: or "symbs"X<symb>. These identifiers are built from the URL of the
14240: map, the resource number of the resource in the map, and the URL of
14241: the resource itself. The latter is somewhat redundant, but might help
14242: if maps change.
14243:
14244: An example is
14245:
14246: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14247:
14248: The respective map entry is
14249:
14250: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14251: title="Problem 2">
14252: </resource>
14253:
14254: Symbs are used by the random number generator, as well as to store and
14255: restore data specific to a certain instance of for example a problem.
14256:
14257: =head2 Storing And Retrieving Data
14258:
14259: X<store()>X<cstore()>X<restore()>Three of the most important functions
14260: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14261: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14262: is is the non-critical message twin of cstore. These functions are for
14263: handlers to store a perl hash to a user's permanent data space in an
14264: easy manner, and to retrieve it again on another call. It is expected
14265: that a handler would use this once at the beginning to retrieve data,
14266: and then again once at the end to send only the new data back.
14267:
14268: The data is stored in the user's data directory on the user's
14269: homeserver under the ID of the course.
14270:
14271: The hash that is returned by restore will have all of the previous
14272: value for all of the elements of the hash.
14273:
14274: Example:
14275:
14276: #creating a hash
14277: my %hash;
14278: $hash{'foo'}='bar';
14279:
14280: #storing it
14281: &Apache::lonnet::cstore(\%hash);
14282:
14283: #changing a value
14284: $hash{'foo'}='notbar';
14285:
14286: #adding a new value
14287: $hash{'bar'}='foo';
14288: &Apache::lonnet::cstore(\%hash);
14289:
14290: #retrieving the hash
14291: my %history=&Apache::lonnet::restore();
14292:
14293: #print the hash
14294: foreach my $key (sort(keys(%history))) {
14295: print("\%history{$key} = $history{$key}");
14296: }
14297:
14298: Will print out:
1.191 harris41 14299:
1.394 bowersj2 14300: %history{1:foo} = bar
14301: %history{1:keys} = foo:timestamp
14302: %history{1:timestamp} = 990455579
14303: %history{2:bar} = foo
14304: %history{2:foo} = notbar
14305: %history{2:keys} = foo:bar:timestamp
14306: %history{2:timestamp} = 990455580
14307: %history{bar} = foo
14308: %history{foo} = notbar
14309: %history{timestamp} = 990455580
14310: %history{version} = 2
14311:
14312: Note that the special hash entries C<keys>, C<version> and
14313: C<timestamp> were added to the hash. C<version> will be equal to the
14314: total number of versions of the data that have been stored. The
14315: C<timestamp> attribute will be the UNIX time the hash was
14316: stored. C<keys> is available in every historical section to list which
14317: keys were added or changed at a specific historical revision of a
14318: hash.
14319:
14320: B<Warning>: do not store the hash that restore returns directly. This
14321: will cause a mess since it will restore the historical keys as if the
14322: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14323:
1.394 bowersj2 14324: Calling convention:
1.191 harris41 14325:
1.1172.2.27 raeburn 14326: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 14327: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14328:
1.394 bowersj2 14329: For more detailed information, see lonnet specific documentation.
1.191 harris41 14330:
1.394 bowersj2 14331: =head1 RETURN MESSAGES
1.191 harris41 14332:
1.394 bowersj2 14333: =over 4
1.191 harris41 14334:
1.394 bowersj2 14335: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14336:
1.394 bowersj2 14337: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14338: when the connection is brought back up
1.191 harris41 14339:
1.394 bowersj2 14340: =item * B<con_failed>: unable to contact remote host and unable to save message
14341: for later delivery
1.191 harris41 14342:
1.967 bisitz 14343: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14344:
1.394 bowersj2 14345: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14346: that was requested
1.191 harris41 14347:
1.243 albertel 14348: =back
1.191 harris41 14349:
1.243 albertel 14350: =head1 PUBLIC SUBROUTINES
1.191 harris41 14351:
1.243 albertel 14352: =head2 Session Environment Functions
1.191 harris41 14353:
1.243 albertel 14354: =over 4
1.191 harris41 14355:
1.394 bowersj2 14356: =item *
14357: X<appenv()>
1.949 raeburn 14358: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14359: the user envirnoment file, and will be restored for each access this
1.620 albertel 14360: user makes during this session, also modifies the %env for the current
1.949 raeburn 14361: process. Optional rolesarrayref - if defined contains a reference to an array
14362: of roles which are exempt from the restriction on modifying user.role entries
14363: in the user's environment.db and in %env.
1.191 harris41 14364:
14365: =item *
1.394 bowersj2 14366: X<delenv()>
1.987 raeburn 14367: B<delenv($delthis,$regexp)>: removes all items from the session
14368: environment file that begin with $delthis. If the
14369: optional second arg - $regexp - is true, $delthis is treated as a
14370: regular expression, otherwise \Q$delthis\E is used.
14371: The values are also deleted from the current processes %env.
1.191 harris41 14372:
1.795 albertel 14373: =item * get_env_multiple($name)
14374:
14375: gets $name from the %env hash, it seemlessly handles the cases where multiple
14376: values may be defined and end up as an array ref.
14377:
14378: returns an array of values
14379:
1.243 albertel 14380: =back
14381:
14382: =head2 User Information
1.191 harris41 14383:
1.243 albertel 14384: =over 4
1.191 harris41 14385:
14386: =item *
1.394 bowersj2 14387: X<queryauthenticate()>
14388: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14389: authentication scheme
14390:
14391: =item *
1.394 bowersj2 14392: X<authenticate()>
1.1073 raeburn 14393: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14394: authenticate user from domain's lib servers (first use the current
14395: one). C<$upass> should be the users password.
1.1073 raeburn 14396: $checkdefauth is optional (value is 1 if a check should be made to
14397: authenticate user using default authentication method, and allow
14398: account creation if username does not have account in the domain).
14399: $clientcancheckhost is optional (value is 1 if checking whether the
14400: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14401:
14402: =item *
1.394 bowersj2 14403: X<homeserver()>
14404: B<homeserver($uname,$udom)>: find the server which has
14405: the user's directory and files (there must be only one), this caches
14406: the answer, and also caches if there is a borken connection.
1.191 harris41 14407:
14408: =item *
1.394 bowersj2 14409: X<idget()>
14410: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14411: (IDs are a unique resource in a domain, there must be only 1 ID per
14412: username, and only 1 username per ID in a specific domain) (returns
14413: hash: id=>name,id=>name)
1.191 harris41 14414:
14415: =item *
1.394 bowersj2 14416: X<idrget()>
14417: B<idrget($udom,@unames)>: find the IDs behind a list of
14418: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14419:
14420: =item *
1.394 bowersj2 14421: X<idput()>
14422: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 14423:
14424: =item *
1.394 bowersj2 14425: X<rolesinit()>
1.1169 droeschl 14426: B<rolesinit($udom,$username)>: get user privileges.
14427: returns user role, first access and timer interval hashes
1.243 albertel 14428:
14429: =item *
1.1171 droeschl 14430: X<privileged()>
14431: B<privileged($username,$domain)>: returns a true if user has a
14432: privileged and active role (i.e. su or dc), false otherwise.
14433:
14434: =item *
1.551 albertel 14435: X<getsection()>
14436: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14437: course $cname, return section name/number or '' for "not in course"
14438: and '-1' for "no section"
14439:
14440: =item *
1.394 bowersj2 14441: X<userenvironment()>
14442: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14443: passed in @what from the requested user's environment, returns a hash
14444:
1.858 raeburn 14445: =item *
14446: X<userlog_query()>
1.859 albertel 14447: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14448: activity.log file. %filters defines filters applied when parsing the
14449: log file. These can be start or end timestamps, or the type of action
14450: - log to look for Login or Logout events, check for Checkin or
14451: Checkout, role for role selection. The response is in the form
14452: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14453: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14454:
1.243 albertel 14455: =back
14456:
14457: =head2 User Roles
14458:
14459: =over 4
14460:
14461: =item *
14462:
1.1172.2.65 raeburn 14463: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14464: returns codes for allowed actions.
14465:
14466: The first argument is required, all others are optional.
14467:
14468: $priv is the privilege being checked.
14469: $uri contains additional information about what is being checked for access (e.g.,
14470: URL, course ID etc.).
14471: $symb is the unique resource instance identifier in a course; if needed,
14472: but not provided, it will be retrieved via a call to &symbread().
14473: $role is the role for which a priv is being checked (only used if priv is evb).
14474: $clientip is the user's IP address (only used when checking for access to portfolio
14475: files).
14476: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14477: prevents recursive calls to &allowed.
14478:
1.243 albertel 14479: F: full access
14480: U,I,K: authentication modes (cxx only)
14481: '': forbidden
14482: 1: user needs to choose course
14483: 2: browse allowed
1.766 albertel 14484: A: passphrase authentication needed
1.1172.2.65 raeburn 14485: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14486:
14487: =item *
14488:
1.1172.2.13 raeburn 14489: constructaccess($url,$setpriv) : check for access to construction space URL
14490:
14491: See if the owner domain and name in the URL match those in the
14492: expected environment. If so, return three element list
14493: ($ownername,$ownerdomain,$ownerhome).
14494:
14495: Otherwise return the null string.
14496:
14497: If second argument 'setpriv' is true, it assigns the privileges,
14498: and returns the same three element list, unless the owner has
14499: blocked "ad hoc" Domain Coordinator access to the Author Space,
14500: in which case the null string is returned.
14501:
14502: =item *
14503:
1.1172.2.84 raeburn 14504: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14505: define a custom role rolename set privileges in format of lonTabs/roles.tab
14506: for system, domain, and course level. $uname and $udom are optional (current
14507: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14508:
14509: =item *
14510:
1.988 raeburn 14511: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14512: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14513: $type is Course (default) or Community.
1.988 raeburn 14514: If $forcedefault evaluates to true, text returned will be default
14515: text for $type. Otherwise, if this is a course, the text returned
14516: will be a custom name for the role (if defined in the course's
14517: environment). If no custom name is defined the default is returned.
14518:
1.832 raeburn 14519: =item *
14520:
1.1172.2.23 raeburn 14521: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14522: All arguments are optional. Returns a hash of a roles, either for
14523: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14524: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14525: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14526: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14527: For each key, value is set to colon-separated start and end times for
14528: the role. If no username and domain are specified, will default to
1.934 raeburn 14529: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14530: of role statuses (active, future or previous), roles
14531: (e.g., cc,in, st etc.) and domains of the roles which can be used
14532: to restrict the list of roles reported. If no array ref is
14533: provided for types, will default to return only active roles.
1.834 albertel 14534:
1.1172.2.13 raeburn 14535: =item *
14536:
14537: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14538: user: $uname:$udom has a role in the course: $cdom_$cnum.
14539:
14540: Additional optional arguments are: $type (if role checking is to be restricted
14541: to certain user status types -- previous (expired roles), active (currently
14542: available roles) or future (roles available in the future), and
14543: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 14544: have active Domain Coordinator role in course's domain or in additional
14545: domains (specified in 'Domains to check for privileged users' in course
14546: environment -- set via: Course Settings -> Classlists and staff listing).
14547:
14548: =item *
14549:
14550: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14551: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14552: $possdomains and $possroles are optional array refs -- to domains to check and
14553: roles to check. If $possdomains is not specified, a dump will be done of the
14554: users' roles.db to check for a dc or su role in any domain. This can be
14555: time consuming if &privileged is called repeatedly (e.g., when displaying a
14556: classlist), so in such cases, supplying a $possdomains array is preferred, as
14557: this then allows &privileged_by_domain() to be used, which caches the identity
14558: of privileged users, eliminating the need for repeated calls to &dump().
14559:
14560: =item *
14561:
14562: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14563: where the outer hash keys are domains specified in the $possdomains array ref,
14564: next inner hash keys are privileged roles specified in the $roles array ref,
14565: and the innermost hash contains key = value pairs for username:domain = end:start
14566: for active or future "privileged" users with that role in that domain. To avoid
14567: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14568: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 14569:
1.243 albertel 14570: =back
14571:
14572: =head2 User Modification
14573:
14574: =over 4
14575:
14576: =item *
14577:
1.957 raeburn 14578: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 14579: user for the level given by URL. Optional start and end dates (leave empty
14580: string or zero for "no date")
1.191 harris41 14581:
14582: =item *
14583:
1.243 albertel 14584: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14585: change a users, password, possible return values are: ok,
14586: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14587: refused
1.191 harris41 14588:
14589: =item *
14590:
1.243 albertel 14591: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 14592:
14593: =item *
14594:
1.1058 raeburn 14595: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14596: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14597:
14598: will update user information (firstname,middlename,lastname,generation,
14599: permanentemail), and if forceid is true, student/employee ID also.
14600: A user's institutional affiliation(s) can also be updated.
14601: User information fields will not be overwritten with empty entries
14602: unless the field is included in the $candelete array reference.
14603: This array is included when a single user is modified via "Manage Users",
14604: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 14605:
14606: =item *
14607:
1.286 matthew 14608: modifystudent
14609:
1.957 raeburn 14610: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 14611: The course id is resolved based on the current user's environment.
14612: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 14613: associated with a course.
14614:
1.297 matthew 14615: This call is essentially a wrapper for lonnet::modifyuser and
14616: lonnet::modify_student_enrollment
1.286 matthew 14617:
14618: Inputs:
14619:
14620: =over 4
14621:
1.957 raeburn 14622: =item B<$udom> Student's loncapa domain
1.286 matthew 14623:
1.957 raeburn 14624: =item B<$uname> Student's loncapa login name
1.286 matthew 14625:
1.964 bisitz 14626: =item B<$uid> Student/Employee ID
1.286 matthew 14627:
1.957 raeburn 14628: =item B<$umode> Student's authentication mode
1.286 matthew 14629:
1.957 raeburn 14630: =item B<$upass> Student's password
1.286 matthew 14631:
1.957 raeburn 14632: =item B<$first> Student's first name
1.286 matthew 14633:
1.957 raeburn 14634: =item B<$middle> Student's middle name
1.286 matthew 14635:
1.957 raeburn 14636: =item B<$last> Student's last name
1.286 matthew 14637:
1.957 raeburn 14638: =item B<$gene> Student's generation
1.286 matthew 14639:
1.957 raeburn 14640: =item B<$usec> Student's section in course
1.286 matthew 14641:
14642: =item B<$end> Unix time of the roles expiration
14643:
14644: =item B<$start> Unix time of the roles start date
14645:
14646: =item B<$forceid> If defined, allow $uid to be changed
14647:
14648: =item B<$desiredhome> server to use as home server for student
14649:
1.957 raeburn 14650: =item B<$email> Student's permanent e-mail address
14651:
14652: =item B<$type> Type of enrollment (auto or manual)
14653:
1.963 raeburn 14654: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14655:
14656: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 14657:
1.963 raeburn 14658: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 14659:
1.963 raeburn 14660: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 14661:
1.1172.2.19 raeburn 14662: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14663:
14664: =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 14665:
1.286 matthew 14666: =back
1.297 matthew 14667:
14668: =item *
14669:
14670: modify_student_enrollment
14671:
1.1172.2.31 raeburn 14672: Change a student's enrollment status in a class. The environment variable
1.297 matthew 14673: 'role.request.course' must be defined for this function to proceed.
14674:
14675: Inputs:
14676:
14677: =over 4
14678:
1.1172.2.31 raeburn 14679: =item $udom, student's domain
1.297 matthew 14680:
1.1172.2.31 raeburn 14681: =item $uname, student's name
1.297 matthew 14682:
1.1172.2.31 raeburn 14683: =item $uid, student's user id
1.297 matthew 14684:
1.1172.2.31 raeburn 14685: =item $first, student's first name
1.297 matthew 14686:
14687: =item $middle
14688:
14689: =item $last
14690:
14691: =item $gene
14692:
14693: =item $usec
14694:
14695: =item $end
14696:
14697: =item $start
14698:
1.957 raeburn 14699: =item $type
14700:
14701: =item $locktype
14702:
14703: =item $cid
14704:
14705: =item $selfenroll
14706:
14707: =item $context
14708:
1.1172.2.19 raeburn 14709: =item $credits, number of credits student will earn from this class
14710:
1.1172.2.76 raeburn 14711: =item $instsec, institutional course section code for student
14712:
1.297 matthew 14713: =back
14714:
1.191 harris41 14715:
14716: =item *
14717:
1.243 albertel 14718: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14719: custom role; give a custom role to a user for the level given by URL. Specify
14720: name and domain of role author, and role name
1.191 harris41 14721:
14722: =item *
14723:
1.243 albertel 14724: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14725:
14726: =item *
14727:
1.243 albertel 14728: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14729:
14730: =back
14731:
14732: =head2 Course Infomation
14733:
14734: =over 4
1.191 harris41 14735:
14736: =item *
14737:
1.1118 foxr 14738: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14739: specified course id, including all environment settings for the
14740: course, the description of the course will be in the hash under the
14741: key 'description'
1.191 harris41 14742:
1.1118 foxr 14743: $options is an optional parameter that if supplied is a hash reference that controls
14744: what how this function works. It has the following key/values:
14745:
14746: =over 4
14747:
14748: =item freshen_cache
14749:
14750: If defined, and the environment cache for the course is valid, it is
14751: returned in the returned hash.
14752:
14753: =item one_time
14754:
14755: If defined, the last cache time is set to _now_
14756:
14757: =item user
14758:
14759: If defined, the supplied username is used instead of the current user.
14760:
14761:
14762: =back
14763:
1.191 harris41 14764: =item *
14765:
1.624 albertel 14766: resdata($name,$domain,$type,@which) : request for current parameter
14767: setting for a specific $type, where $type is either 'course' or 'user',
14768: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 14769: answers for 10 minutes.
1.243 albertel 14770:
1.877 foxr 14771: =item *
14772:
14773: get_courseresdata($courseid, $domain) : dump the entire course resource
14774: data base, returning a hash that is keyed by the resource name and has
14775: values that are the resource value. I believe that the timestamps and
14776: versions are also returned.
14777:
1.1172.2.31 raeburn 14778: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14779: supplemental content area. This routine caches the number of files for
14780: 10 minutes.
14781:
1.243 albertel 14782: =back
14783:
14784: =head2 Course Modification
14785:
14786: =over 4
1.191 harris41 14787:
14788: =item *
14789:
1.243 albertel 14790: writecoursepref($courseid,%prefs) : write preferences (environment
14791: database) for a course
1.191 harris41 14792:
14793: =item *
14794:
1.1011 raeburn 14795: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14796:
14797: =item *
14798:
1.1038 raeburn 14799: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14800:
1.1167 droeschl 14801: =item *
14802:
14803: is_course($courseid), is_course($cdom, $cnum)
14804:
14805: Accepts either a combined $courseid (in the form of domain_courseid) or the
14806: two component version $cdom, $cnum. It checks if the specified course exists.
14807:
14808: Returns:
14809: undef if the course doesn't exist, otherwise
14810: in scalar context the combined courseid.
14811: in list context the two components of the course identifier, domain and
14812: courseid.
14813:
1.243 albertel 14814: =back
14815:
1.1172.2.109 raeburn 14816: =head2 Bubblesheet Configuration
14817:
14818: =over 4
14819:
14820: =item *
14821:
14822: get_scantron_config($which)
14823:
14824: $which - the name of the configuration to parse from the file.
14825:
14826: Parses and returns the bubblesheet configuration line selected as a
14827: hash of configuration file fields.
14828:
14829:
14830: Returns:
14831: If the named configuration is not in the file, an empty
14832: hash is returned.
14833:
14834: a hash with the fields
14835: name - internal name for the this configuration setup
14836: description - text to display to operator that describes this config
14837: CODElocation - if 0 or the string 'none'
14838: - no CODE exists for this config
14839: if -1 || the string 'letter'
14840: - a CODE exists for this config and is
14841: a string of letters
14842: Unsupported value (but planned for future support)
14843: if a positive integer
14844: - The CODE exists as the first n items from
14845: the question section of the form
14846: if the string 'number'
14847: - The CODE exists for this config and is
14848: a string of numbers
14849: CODEstart - (only matter if a CODE exists) column in the line where
14850: the CODE starts
14851: CODElength - length of the CODE
14852: IDstart - column where the student/employee ID starts
14853: IDlength - length of the student/employee ID info
14854: Qstart - column where the information from the bubbled
14855: 'questions' start
14856: Qlength - number of columns comprising a single bubble line from
14857: the sheet. (usually either 1 or 10)
14858: Qon - either a single character representing the character used
14859: to signal a bubble was chosen in the positional setup, or
14860: the string 'letter' if the letter of the chosen bubble is
14861: in the final, or 'number' if a number representing the
14862: chosen bubble is in the file (1->A 0->J)
14863: Qoff - the character used to represent that a bubble was
14864: left blank
14865: PaperID - if the scanning process generates a unique number for each
14866: sheet scanned the column that this ID number starts in
14867: PaperIDlength - number of columns that comprise the unique ID number
14868: for the sheet of paper
14869: FirstName - column that the first name starts in
14870: FirstNameLength - number of columns that the first name spans
14871: LastName - column that the last name starts in
14872: LastNameLength - number of columns that the last name spans
14873: BubblesPerRow - number of bubbles available in each row used to
14874: bubble an answer. (If not specified, 10 assumed).
14875:
14876:
14877: =item *
14878:
14879: get_scantronformat_file($cdom)
14880:
14881: $cdom - the course's domain (optional); if not supplied, uses
14882: domain for current $env{'request.course.id'}.
14883:
14884: Returns an array containing lines from the scantron format file for
14885: the domain of the course.
14886:
14887: If a url for a custom.tab file is listed in domain's configuration.db,
14888: lines are from this file.
14889:
14890: Otherwise, if a default.tab has been published in RES space by the
14891: domainconfig user, lines are from this file.
14892:
14893: Otherwise, fall back to getting lines from the legacy file on the
14894: local server: /home/httpd/lonTabs/default_scantronformat.tab
14895:
14896: =back
14897:
1.243 albertel 14898: =head2 Resource Subroutines
14899:
14900: =over 4
1.191 harris41 14901:
14902: =item *
14903:
1.243 albertel 14904: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14905:
14906: =item *
14907:
1.243 albertel 14908: repcopy($filename) : subscribes to the requested file, and attempts to
14909: replicate from the owning library server, Might return
1.607 raeburn 14910: 'unavailable', 'not_found', 'forbidden', 'ok', or
14911: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14912: resource. Expects the local filesystem pathname
14913: (/home/httpd/html/res/....)
14914:
14915: =back
14916:
14917: =head2 Resource Information
14918:
14919: =over 4
1.191 harris41 14920:
14921: =item *
14922:
1.1172.2.28 raeburn 14923: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14924: and returns the value of a variety of different possible values,
14925: $varname should be a request string, and the other parameters can be
14926: used to specify who and what one is asking about. Ordinarily, $cid
14927: does not need to be specified, as it is retrived from
14928: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14929: within lonuserstate::loadmap() when initializing a course, before
14930: $env{'request.course.id'} has been set, so it needs to be provided
14931: in that one case.
1.243 albertel 14932:
14933: Possible values for $varname are environment.lastname (or other item
14934: from the envirnment hash), user.name (or someother aspect about the
14935: user), resource.0.maxtries (or some other part and parameter of a
14936: resource)
1.204 albertel 14937:
14938: =item *
14939:
1.243 albertel 14940: directcondval($number) : get current value of a condition; reads from a state
14941: string
1.204 albertel 14942:
14943: =item *
14944:
1.243 albertel 14945: condval($condidx) : value of condition index based on state
1.204 albertel 14946:
14947: =item *
14948:
1.243 albertel 14949: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14950: resource's metadata, $what should be either a specific key, or either
14951: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14952: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14953:
14954: this function automatically caches all requests
1.191 harris41 14955:
14956: =item *
14957:
1.243 albertel 14958: metadata_query($query,$custom,$customshow) : make a metadata query against the
14959: network of library servers; returns file handle of where SQL and regex results
14960: will be stored for query
1.191 harris41 14961:
14962: =item *
14963:
1.1172.2.66 raeburn 14964: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14965: return symbolic list entry (all arguments optional).
14966:
14967: Args: filename is the filename (including path) for the file for which a symb
14968: is required; donotrecurse, if true will prevent calls to allowed() being made
14969: to check access status if more than one resource was found in the bighash
14970: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14971: a randompick); ignorecachednull, if true will prevent a symb of '' being
14972: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14973: cause possible symbs to be checked to determine if they are subject to content
14974: blocking, if so they will not be included as possible symbs; possibles is a
14975: ref to a hash, which, as a side effect, will be populated with all possible
14976: symbs (content blocking not tested).
14977:
1.243 albertel 14978: returns the data handle
1.191 harris41 14979:
14980: =item *
14981:
1.1172.2.17 raeburn 14982: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 14983: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14984: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 14985: on failure, user must be in a course, as it assumes the existence of
14986: the course initial hash, and uses $env('request.course.id'}. The third
14987: arg is an optional reference to a scalar. If this arg is passed in the
14988: call to symbverify, it will be set to 1 if the symb has been set to be
14989: encrypted; otherwise it will be null.
1.243 albertel 14990:
1.191 harris41 14991: =item *
14992:
1.243 albertel 14993: symbclean($symb) : removes versions numbers from a symb, returns the
14994: cleaned symb
1.191 harris41 14995:
14996: =item *
14997:
1.243 albertel 14998: is_on_map($uri) : checks if the $uri is somewhere on the current
14999: course map, user must be in a course for it to work.
1.191 harris41 15000:
15001: =item *
15002:
1.243 albertel 15003: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15004:
15005: =item *
15006:
1.243 albertel 15007: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15008: a random seed, all arguments are optional, if they aren't sent it uses the
15009: environment to derive them. Note: if symb isn't sent and it can't get one
15010: from &symbread it will use the current time as its return value
1.191 harris41 15011:
15012: =item *
15013:
1.243 albertel 15014: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15015: unfakeable, receipt
1.191 harris41 15016:
15017: =item *
15018:
1.620 albertel 15019: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15020:
15021: =item *
15022:
1.243 albertel 15023: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15024:
15025: =item *
15026:
1.243 albertel 15027: 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 15028:
15029: =item *
15030:
1.243 albertel 15031: 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 15032:
15033: =item *
15034:
1.243 albertel 15035: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15036:
15037: =item *
15038:
1.243 albertel 15039: devalidate($symb) : devalidate temporary spreadsheet calculations,
15040: forcing spreadsheet to reevaluate the resource scores next time.
15041:
1.1172.2.13 raeburn 15042: =item *
15043:
15044: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15045: when viewing in course context.
15046:
15047: input: six args -- filename (decluttered), course number, course domain,
15048: url, symb (if registered) and group (if this is a
15049: group item -- e.g., bulletin board, group page etc.).
15050:
15051: output: array of five scalars --
15052: $cfile -- url for file editing if editable on current server
15053: $home -- homeserver of resource (i.e., for author if published,
15054: or course if uploaded.).
15055: $switchserver -- 1 if server switch will be needed.
15056: $forceedit -- 1 if icon/link should be to go to edit mode
15057: $forceview -- 1 if icon/link should be to go to view mode
15058:
15059: =item *
15060:
15061: is_course_upload($file,$cnum,$cdom)
15062:
15063: Used in course context to determine if current file was uploaded to
15064: the course (i.e., would be found in /userfiles/docs on the course's
15065: homeserver.
15066:
15067: input: 3 args -- filename (decluttered), course number and course domain.
15068: output: boolean -- 1 if file was uploaded.
15069:
1.243 albertel 15070: =back
15071:
15072: =head2 Storing/Retreiving Data
15073:
15074: =over 4
1.191 harris41 15075:
15076: =item *
15077:
1.1172.2.64 raeburn 15078: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15079: permanently for this url; hashref needs to be given and should be a \%hashname;
15080: the remaining args aren't required and if they aren't passed or are '' they will
15081: be derived from the env (with the exception of $laststore, which is an
15082: optional arg used when a user's submission is stored in grading).
15083: $laststore is $version=$timestamp, where $version is the most recent version
15084: number retrieved for the corresponding $symb in the $namespace db file, and
15085: $timestamp is the timestamp for that transaction (UNIX time).
15086: $laststore is currently only passed when cstore() is called by
15087: structuretags::finalize_storage().
1.191 harris41 15088:
15089: =item *
15090:
1.1172.2.64 raeburn 15091: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15092: but uses critical subroutine
1.191 harris41 15093:
15094: =item *
15095:
1.243 albertel 15096: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15097: all args are optional
1.191 harris41 15098:
15099: =item *
15100:
1.717 albertel 15101: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15102: dumps the complete (or key matching regexp) namespace into a hash
15103: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15104: normally &store()ed into
15105:
15106: $range should be either an integer '100' (give me the first 100
15107: matching records)
15108: or be two integers sperated by a - with no spaces
15109: '30-50' (give me the 30th through the 50th matching
15110: records)
15111:
15112:
15113: =item *
15114:
1.1172.2.59 raeburn 15115: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15116: replaces a &store() version of data with a replacement set of data
15117: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 15118: reference. If $tolog is true, the transaction is logged in the courselog
15119: with an action=PUTSTORE.
1.717 albertel 15120:
15121: =item *
15122:
1.243 albertel 15123: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15124: works very similar to store/cstore, but all data is stored in a
15125: temporary location and can be reset using tmpreset, $storehash should
15126: be a hash reference, returns nothing on success
1.191 harris41 15127:
15128: =item *
15129:
1.243 albertel 15130: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15131: similar to restore, but all data is stored in a temporary location and
15132: can be reset using tmpreset. Returns a hash of values on success,
15133: error string otherwise.
1.191 harris41 15134:
15135: =item *
15136:
1.243 albertel 15137: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15138: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15139:
15140: =item *
15141:
1.243 albertel 15142: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15143: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15144:
15145: =item *
15146:
1.243 albertel 15147: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15148: namesp ($udom and $uname are optional)
1.191 harris41 15149:
15150: =item *
15151:
1.702 albertel 15152: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15153: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15154: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15155:
1.702 albertel 15156: $range should be either an integer '100' (give me the first 100
15157: matching records)
15158: or be two integers sperated by a - with no spaces
15159: '30-50' (give me the 30th through the 50th matching
15160: records)
1.449 matthew 15161: =item *
15162:
15163: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15164: $store can be a scalar, an array reference, or if the amount to be
15165: incremented is > 1, a hash reference.
15166:
15167: ($udom and $uname are optional)
1.191 harris41 15168:
15169: =item *
15170:
1.243 albertel 15171: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15172: ($udom and $uname are optional)
1.191 harris41 15173:
15174: =item *
15175:
1.243 albertel 15176: cput($namespace,$storehash,$udom,$uname) : critical put
15177: ($udom and $uname are optional)
1.191 harris41 15178:
15179: =item *
15180:
1.748 albertel 15181: newput($namespace,$storehash,$udom,$uname) :
15182:
15183: Attempts to store the items in the $storehash, but only if they don't
15184: currently exist, if this succeeds you can be certain that you have
15185: successfully created a new key value pair in the $namespace db.
15186:
15187:
15188: Args:
15189: $namespace: name of database to store values to
15190: $storehash: hashref to store to the db
15191: $udom: (optional) domain of user containing the db
15192: $uname: (optional) name of user caontaining the db
15193:
15194: Returns:
15195: 'ok' -> succeeded in storing all keys of $storehash
15196: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15197: least <key> already existed in the db (other
15198: requested keys may also already exist)
1.967 bisitz 15199: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15200: 'con_lost' -> unable to contact request server
15201: 'refused' -> action was not allowed by remote machine
15202:
15203:
15204: =item *
15205:
1.243 albertel 15206: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15207: reference filled in from namesp (encrypts the return communication)
15208: ($udom and $uname are optional)
1.191 harris41 15209:
15210: =item *
15211:
1.243 albertel 15212: log($udom,$name,$home,$message) : write to permanent log for user; use
15213: critical subroutine
15214:
1.806 raeburn 15215: =item *
15216:
1.860 raeburn 15217: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15218: array reference filled in from namespace found in domain level on either
15219: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15220:
15221: =item *
15222:
1.860 raeburn 15223: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15224: domain level either on specified domain server ($uhome) or primary domain
15225: server ($udom and $uhome are optional)
1.806 raeburn 15226:
1.943 raeburn 15227: =item *
15228:
1.1172.2.35 raeburn 15229: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15230: for: authentication, language, quotas, timezone, date locale, and portal URL in
15231: the target domain.
15232:
15233: May also include additional key => value pairs for the following groups:
15234:
15235: =over
15236:
15237: =item
15238: disk quotas (MB allocated by default to portfolios and authoring spaces).
15239:
15240: =over
15241:
15242: =item defaultquota, authorquota
15243:
15244: =back
15245:
15246: =item
15247: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15248: portfolio for users).
15249:
15250: =over
15251:
15252: =item
15253: aboutme, blog, webdav, portfolio
15254:
15255: =back
15256:
15257: =item
15258: requestcourses: ability to request courses, and how requests are processed.
15259:
15260: =over
15261:
15262: =item
1.1172.2.37 raeburn 15263: official, unofficial, community, textbook
1.1172.2.35 raeburn 15264:
15265: =back
15266:
15267: =item
15268: inststatus: types of institutional affiliation, and order in which they are displayed.
15269:
15270: =over
15271:
15272: =item
1.1172.2.44 raeburn 15273: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 15274:
15275: =back
15276:
15277: =item
15278: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15279: for course's uploaded content.
15280:
15281: =over
15282:
15283: =item
1.1172.2.68 raeburn 15284: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15285: communityquota, textbookquota
1.1172.2.35 raeburn 15286:
15287: =back
15288:
15289: =item
15290: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15291: on your servers.
15292:
15293: =over
15294:
15295: =item
15296: remotesessions, hostedsessions
15297:
15298: =back
15299:
15300: =back
15301:
15302: In cases where a domain coordinator has never used the "Set Domain Configuration"
15303: utility to create a configuration.db file on a domain's primary library server
15304: only the following domain defaults: auth_def, auth_arg_def, lang_def
15305: -- corresponding values are authentication type (internal, krb4, krb5,
15306: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15307: will be available. Values are retrieved from cache (if current), unless the
15308: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15309: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15310:
15311: Typical usage:
1.943 raeburn 15312:
1.1172.2.35 raeburn 15313: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 15314:
1.243 albertel 15315: =back
15316:
15317: =head2 Network Status Functions
15318:
15319: =over 4
1.191 harris41 15320:
15321: =item *
15322:
1.1137 raeburn 15323: dirlist() : return directory list based on URI (first arg).
15324:
15325: Inputs: 1 required, 5 optional.
15326:
15327: =over
15328:
15329: =item
15330: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15331:
15332: =item
15333: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15334:
15335: =item
15336: $username - username of user/course to be listed. Extracted from $uri if absent.
15337:
15338: =item
15339: $getpropath - boolean: 1 if prepend path using &propath().
15340:
15341: =item
15342: $getuserdir - boolean: 1 if prepend path for "userfiles".
15343:
15344: =item
15345: $alternateRoot - path to prepend in place of path from $uri.
15346:
15347: =back
15348:
15349: Returns: Array of up to two items.
15350:
15351: =over
15352:
15353: a reference to an array of files/subdirectories
15354:
15355: =over
15356:
15357: Each element in the array of files/subdirectories is a & separated list of
15358: item name and the result of running stat on the item. If dirlist was requested
15359: for a file instead of a directory, the item name will be ''. For a directory
15360: listing, if the item is a metadata file, the element will end &N&M
15361: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15362: default copyright set (1).
15363:
15364: =back
15365:
15366: a scalar containing error condition (if encountered).
15367:
15368: =over
15369:
15370: =item
15371: no_host (no homeserver identified for $username:$domain).
15372:
15373: =item
15374: no_such_host (server contacted for listing not identified as valid host).
15375:
15376: =item
15377: con_lost (connection to remote server failed).
15378:
15379: =item
15380: refused (invalid $username:$domain received on lond side).
15381:
15382: =item
15383: no_such_dir (directory at specified path on lond side does not exist).
15384:
15385: =item
15386: empty (directory at specified path on lond side is empty).
15387:
15388: =over
15389:
15390: This is currently not encountered because the &ls3, &ls2,
15391: &ls (_handler) routines on the lond side do not filter out
15392: . and .. from a directory listing.
15393:
15394: =back
15395:
15396: =back
15397:
15398: =back
1.191 harris41 15399:
15400: =item *
15401:
1.243 albertel 15402: spareserver() : find server with least workload from spare.tab
15403:
1.986 foxr 15404:
15405: =item *
15406:
15407: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15408: if there is no corresponding loncapa host.
15409:
1.243 albertel 15410: =back
15411:
1.986 foxr 15412:
1.243 albertel 15413: =head2 Apache Request
15414:
15415: =over 4
1.191 harris41 15416:
15417: =item *
15418:
1.243 albertel 15419: ssi($url,%hash) : server side include, does a complete request cycle on url to
15420: localhost, posts hash
15421:
15422: =back
15423:
15424: =head2 Data to String to Data
15425:
15426: =over 4
1.191 harris41 15427:
15428: =item *
15429:
1.243 albertel 15430: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15431: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15432:
15433: =item *
15434:
1.243 albertel 15435: hashref2str($hashref) : convert a hashref into a string complete with
15436: escaping and '=' and '&' separators, supports elements that are
15437: arrayrefs and hashrefs
1.191 harris41 15438:
15439: =item *
15440:
1.243 albertel 15441: arrayref2str($arrayref) : convert an arrayref into a string complete
15442: with escaping and '&' separators, supports elements that are arrayrefs
15443: and hashrefs
1.191 harris41 15444:
15445: =item *
15446:
1.243 albertel 15447: str2hash($string) : convert string to hash using unescaping and
15448: splitting on '=' and '&', supports elements that are arrayrefs and
15449: hashrefs
1.191 harris41 15450:
15451: =item *
15452:
1.243 albertel 15453: str2array($string) : convert string to hash using unescaping and
15454: splitting on '&', supports elements that are arrayrefs and hashrefs
15455:
15456: =back
15457:
15458: =head2 Logging Routines
15459:
15460:
15461: These routines allow one to make log messages in the lonnet.log and
15462: lonnet.perm logfiles.
1.191 harris41 15463:
1.1119 foxr 15464: =over 4
15465:
1.191 harris41 15466: =item *
15467:
1.243 albertel 15468: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15469:
15470: =item *
15471:
1.243 albertel 15472: logthis() : append message to the normal lonnet.log file, it gets
15473: preiodically rolled over and deleted.
1.191 harris41 15474:
15475: =item *
15476:
1.243 albertel 15477: logperm() : append a permanent message to lonnet.perm.log, this log
15478: file never gets deleted by any automated portion of the system, only
15479: messages of critical importance should go in here.
15480:
1.1119 foxr 15481:
1.243 albertel 15482: =back
15483:
15484: =head2 General File Helper Routines
15485:
15486: =over 4
1.191 harris41 15487:
15488: =item *
15489:
1.481 raeburn 15490: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15491: (a) files in /uploaded
15492: (i) If a local copy of the file exists -
15493: compares modification date of local copy with last-modified date for
15494: definitive version stored on home server for course. If local copy is
15495: stale, requests a new version from the home server and stores it.
15496: If the original has been removed from the home server, then local copy
15497: is unlinked.
15498: (ii) If local copy does not exist -
15499: requests the file from the home server and stores it.
15500:
15501: If $caller is 'uploadrep':
15502: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15503: for request for files originally uploaded via DOCS.
15504: - returns 'ok' if fresh local copy now available, -1 otherwise.
15505:
15506: Otherwise:
15507: This indicates a call from the content generation phase of the request.
15508: - returns the entire contents of the file or -1.
15509:
15510: (b) files in /res
15511: - returns the entire contents of a file or -1;
15512: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 15513:
1.712 albertel 15514:
15515: =item *
15516:
15517: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15518: reference
15519:
15520: returns either a stat() list of data about the file or an empty list
15521: if the file doesn't exist or couldn't find out about it (connection
15522: problems or user unknown)
15523:
1.191 harris41 15524: =item *
15525:
1.243 albertel 15526: filelocation($dir,$file) : returns file system location of a file
15527: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15528: directory that relative $file lookups are to looked in ($dir of /a/dir
15529: and a file of ../bob will become /a/bob)
1.191 harris41 15530:
15531: =item *
15532:
15533: hreflocation($dir,$file) : returns file system location or a URL; same as
15534: filelocation except for hrefs
15535:
15536: =item *
15537:
1.1172.2.49 raeburn 15538: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15539: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 15540:
1.243 albertel 15541: =back
15542:
1.608 albertel 15543: =head2 Usererfile file routines (/uploaded*)
15544:
15545: =over 4
15546:
15547: =item *
15548:
15549: userfileupload(): main rotine for putting a file in a user or course's
15550: filespace, arguments are,
15551:
1.620 albertel 15552: formname - required - this is the name of the element in $env where the
1.608 albertel 15553: filename, and the contents of the file to create/modifed exist
1.620 albertel 15554: the filename is in $env{'form.'.$formname.'.filename'} and the
15555: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 15556: context - if coursedoc, store the file in the course of the active role
15557: of the current user;
15558: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15559: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 15560: subdir - required - subdirectory to put the file in under ../userfiles/
15561: if undefined, it will be placed in "unknown"
15562:
15563: (This routine calls clean_filename() to remove any dangerous
15564: characters from the filename, and then calls finuserfileupload() to
15565: complete the transaction)
15566:
15567: returns either the url of the uploaded file (/uploaded/....) if successful
15568: and /adm/notfound.html if unsuccessful
15569:
15570: =item *
15571:
15572: clean_filename(): routine for cleaing a filename up for storage in
15573: userfile space, argument is:
15574:
15575: filename - proposed filename
15576:
15577: returns: the new clean filename
15578:
15579: =item *
15580:
1.1090 raeburn 15581: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 15582: userspace, probably shouldn't be called directly
15583:
15584: docuname: username or courseid of destination for the file
15585: docudom: domain of user/course of destination for the file
15586: formname: same as for userfileupload()
1.1090 raeburn 15587: fname: filename (including subdirectories) for the file
15588: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 15589: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 15590: allfiles: reference to hash used to store objects found by parser
15591: codebase: reference to hash used for codebases of java objects found by parser
15592: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15593: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15594: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15595: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15596: context: if 'overwrite', will move the uploaded file from its temporary location to
15597: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 15598: mimetype: reference to scalar to accommodate mime type determined
15599: from File::MMagic if $parser = parse.
1.608 albertel 15600:
15601: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 15602: and /adm/notfound.html if unsuccessful (or an error message if context
15603: was 'overwrite').
15604:
1.608 albertel 15605:
15606: =item *
15607:
15608: renameuserfile(): renames an existing userfile to a new name
15609:
15610: Args:
15611: docuname: username or courseid of destination for the file
15612: docudom: domain of user/course of destination for the file
15613: old: current file name (including any subdirs under userfiles)
15614: new: desired file name (including any subdirs under userfiles)
15615:
15616: =item *
15617:
15618: mkdiruserfile(): creates a directory is a userfiles dir
15619:
15620: Args:
15621: docuname: username or courseid of destination for the file
15622: docudom: domain of user/course of destination for the file
15623: dir: dir to create (including any subdirs under userfiles)
15624:
15625: =item *
15626:
15627: removeuserfile(): removes a file that exists in userfiles
15628:
15629: Args:
15630: docuname: username or courseid of destination for the file
15631: docudom: domain of user/course of destination for the file
15632: fname: filname to delete (including any subdirs under userfiles)
15633:
15634: =item *
15635:
15636: removeuploadedurl(): convience function for removeuserfile()
15637:
15638: Args:
15639: url: a full /uploaded/... url to delete
15640:
1.747 albertel 15641: =item *
15642:
15643: get_portfile_permissions():
15644: Args:
15645: domain: domain of user or course contain the portfolio files
15646: user: name of user or num of course contain the portfolio files
15647: Returns:
15648: hashref of a dump of the proper file_permissions.db
15649:
15650:
15651: =item *
15652:
15653: get_access_controls():
15654:
15655: Args:
15656: current_permissions: the hash ref returned from get_portfile_permissions()
15657: group: (optional) the group you want the files associated with
15658: file: (optional) the file you want access info on
15659:
15660: Returns:
1.749 raeburn 15661: a hash (keys are file names) of hashes containing
15662: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15663: values are XML containing access control settings (see below)
1.747 albertel 15664:
15665: Internal notes:
15666:
1.749 raeburn 15667: access controls are stored in file_permissions.db as key=value pairs.
15668: key -> path to file/file_name\0uniqueID:scope_end_start
15669: where scope -> public,guest,course,group,domains or users.
15670: end -> UNIX time for end of access (0 -> no end date)
15671: start -> UNIX time for start of access
15672:
15673: value -> XML description of access control
15674: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15675: <start></start>
15676: <end></end>
15677:
15678: <password></password> for scope type = guest
15679:
15680: <domain></domain> for scope type = course or group
15681: <number></number>
15682: <roles id="">
15683: <role></role>
15684: <access></access>
15685: <section></section>
15686: <group></group>
15687: </roles>
15688:
15689: <dom></dom> for scope type = domains
15690:
15691: <users> for scope type = users
15692: <user>
15693: <uname></uname>
15694: <udom></udom>
15695: </user>
15696: </users>
15697: </scope>
15698:
15699: Access data is also aggregated for each file in an additional key=value pair:
15700: key -> path to file/file_name\0accesscontrol
15701: value -> reference to hash
15702: hash contains key = value pairs
15703: where key = uniqueID:scope_end_start
15704: value = UNIX time record was last updated
15705:
15706: Used to improve speed of look-ups of access controls for each file.
15707:
15708: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15709:
1.1172.2.13 raeburn 15710: =item *
15711:
1.749 raeburn 15712: modify_access_controls():
15713:
15714: Modifies access controls for a portfolio file
15715: Args
15716: 1. file name
15717: 2. reference to hash of required changes,
15718: 3. domain
15719: 4. username
15720: where domain,username are the domain of the portfolio owner
15721: (either a user or a course)
15722:
15723: Returns:
15724: 1. result of additions or updates ('ok' or 'error', with error message).
15725: 2. result of deletions ('ok' or 'error', with error message).
15726: 3. reference to hash of any new or updated access controls.
15727: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15728: key = integer (inbound ID)
1.1172.2.13 raeburn 15729: value = uniqueID
15730:
15731: =item *
15732:
15733: get_timebased_id():
15734:
15735: Attempts to get a unique timestamp-based suffix for use with items added to a
15736: course via the Course Editor (e.g., folders, composite pages,
15737: group bulletin boards).
15738:
15739: Args: (first three required; six others optional)
15740:
15741: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15742: docssequence, or name of group
15743:
15744: 2. keyid (alphanumeric): name of temporary locking key in hash,
15745: e.g., num, boardids
15746:
15747: 3. namespace: name of gdbm file used to store suffixes already assigned;
15748: file will be named nohist_namespace.db
15749:
15750: 4. cdom: domain of course; default is current course domain from %env
15751:
15752: 5. cnum: course number; default is current course number from %env
15753:
15754: 6. idtype: set to concat if an additional digit is to be appended to the
15755: unix timestamp to form the suffix, if the plain timestamp is already
15756: in use. Default is to not do this, but simply increment the unix
15757: timestamp by 1 until a unique key is obtained.
15758:
15759: 7. who: holder of locking key; defaults to user:domain for user.
15760:
15761: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15762: retrying); default is 3.
15763:
15764: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15765:
15766: Returns:
15767:
15768: 1. suffix obtained (numeric)
15769:
15770: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15771:
15772: 3. error: contains (localized) error message if an error occurred.
15773:
1.747 albertel 15774:
1.608 albertel 15775: =back
15776:
1.243 albertel 15777: =head2 HTTP Helper Routines
15778:
15779: =over 4
15780:
1.191 harris41 15781: =item *
15782:
15783: escape() : unpack non-word characters into CGI-compatible hex codes
15784:
15785: =item *
15786:
15787: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15788:
1.243 albertel 15789: =back
15790:
15791: =head1 PRIVATE SUBROUTINES
15792:
15793: =head2 Underlying communication routines (Shouldn't call)
15794:
15795: =over 4
15796:
15797: =item *
15798:
15799: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15800:
15801: =item *
15802:
15803: reply() : uses subreply to send a message to remote machine, logs all failures
15804:
15805: =item *
15806:
15807: critical() : passes a critical message to another server; if cannot
15808: get through then place message in connection buffer directory and
15809: returns con_delayed, if incapable of saving message, returns
15810: con_failed
15811:
15812: =item *
15813:
15814: reconlonc() : tries to reconnect lonc client processes.
15815:
15816: =back
15817:
15818: =head2 Resource Access Logging
15819:
15820: =over 4
15821:
15822: =item *
15823:
15824: flushcourselogs() : flush (save) buffer logs and access logs
15825:
15826: =item *
15827:
15828: courselog($what) : save message for course in hash
15829:
15830: =item *
15831:
15832: courseacclog($what) : save message for course using &courselog(). Perform
15833: special processing for specific resource types (problems, exams, quizzes, etc).
15834:
1.191 harris41 15835: =item *
15836:
15837: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15838: as a PerlChildExitHandler
1.243 albertel 15839:
15840: =back
15841:
15842: =head2 Other
15843:
15844: =over 4
15845:
15846: =item *
15847:
15848: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15849:
15850: =back
15851:
15852: =cut
1.877 foxr 15853:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>