Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.128
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.128! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.127 2020/10/01 10:24:06 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='';
1.1172.2.66 raeburn 8393: # Cached blockers for this user (a hash of blocking items).
8394: my %cachedblockers=();
8395: # When the data were last cached.
8396: my $cachedlast='';
8397:
8398: sub load_all_blockers {
1.1172.2.128! raeburn 8399: my ($uname,$udom)=@_;
1.1172.2.66 raeburn 8400: if (($uname ne '') && ($udom ne '')) {
8401: if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126 raeburn 8402: ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128! raeburn 8403: (abs($cachedlast-time)<5)) {
1.1172.2.66 raeburn 8404: return;
8405: }
8406: }
8407: $cachedlast=time;
8408: $cacheduser=$uname.':'.$udom;
1.1172.2.126 raeburn 8409: $cachedcid=$env{'request.course.id'};
1.1172.2.128! raeburn 8410: %cachedblockers = &get_commblock_resources();
1.1172.2.126 raeburn 8411: return;
1.1172.2.66 raeburn 8412: }
8413:
1.1162 raeburn 8414: sub get_comm_blocks {
8415: my ($cdom,$cnum) = @_;
8416: if ($cdom eq '' || $cnum eq '') {
8417: return unless ($env{'request.course.id'});
8418: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8419: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8420: }
8421: my %commblocks;
8422: my $hashid=$cdom.'_'.$cnum;
8423: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8424: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8425: %commblocks = %{$blocksref};
8426: } else {
8427: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8428: my $cachetime = 600;
8429: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8430: }
8431: return %commblocks;
8432: }
8433:
1.1172.2.66 raeburn 8434: sub get_commblock_resources {
8435: my ($blocks) = @_;
8436: my %blockers = ();
8437: return %blockers unless ($env{'request.course.id'});
8438: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8439: my %commblocks;
8440: if (ref($blocks) eq 'HASH') {
8441: %commblocks = %{$blocks};
8442: } else {
8443: %commblocks = &get_comm_blocks();
8444: }
1.1172.2.66 raeburn 8445: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 8446: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 8447: return %blockers unless (ref($navmap));
8448: my $now = time;
1.1162 raeburn 8449: foreach my $block (keys(%commblocks)) {
8450: if ($block =~ /^(\d+)____(\d+)$/) {
8451: my ($start,$end) = ($1,$2);
8452: if ($start <= $now && $end >= $now) {
8453: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8454: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8455: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 8456: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8457: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8458: }
8459: }
8460: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 8461: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8462: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8463: }
8464: }
8465: }
8466: }
8467: }
8468: } elsif ($block =~ /^firstaccess____(.+)$/) {
8469: my $item = $1;
1.1163 raeburn 8470: my @to_test;
1.1162 raeburn 8471: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8472: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 8473: my @interval;
8474: my $type = 'map';
8475: if ($item eq 'course') {
8476: $type = 'course';
8477: @interval=&EXT("resource.0.interval");
8478: } else {
8479: if ($item =~ /___\d+___/) {
8480: $type = 'resource';
8481: @interval=&EXT("resource.0.interval",$item);
8482: if (ref($navmap)) {
8483: my $res = $navmap->getBySymb($item);
8484: push(@to_test,$res);
8485: }
1.1162 raeburn 8486: } else {
1.1172.2.66 raeburn 8487: my $mapsymb = &symbread($item,1);
8488: if ($mapsymb) {
8489: if (ref($navmap)) {
8490: my $mapres = $navmap->getBySymb($mapsymb);
8491: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8492: foreach my $res (@to_test) {
8493: my $symb = $res->symb();
8494: next if ($symb eq $mapsymb);
8495: if ($symb ne '') {
8496: @interval=&EXT("resource.0.interval",$symb);
8497: if ($interval[1] eq 'map') {
8498: last;
1.1162 raeburn 8499: }
8500: }
8501: }
8502: }
8503: }
8504: }
1.1172.2.66 raeburn 8505: }
8506: if ($interval[0] =~ /^\d+$/) {
8507: my $first_access;
8508: if ($type eq 'resource') {
8509: $first_access=&get_first_access($interval[1],$item);
8510: } elsif ($type eq 'map') {
8511: $first_access=&get_first_access($interval[1],undef,$item);
8512: } else {
8513: $first_access=&get_first_access($interval[1]);
8514: }
8515: if ($first_access) {
8516: my $timesup = $first_access+$interval[0];
8517: if ($timesup > $now) {
8518: my $activeblock;
8519: foreach my $res (@to_test) {
8520: if ($res->answerable()) {
8521: $activeblock = 1;
8522: last;
8523: }
8524: }
8525: if ($activeblock) {
8526: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8527: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8528: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8529: }
8530: }
8531: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8532: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8533: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8534: }
1.1162 raeburn 8535: }
8536: }
8537: }
8538: }
8539: }
8540: }
8541: }
8542: }
8543: }
1.1172.2.66 raeburn 8544: return %blockers;
1.1162 raeburn 8545: }
8546:
1.1172.2.66 raeburn 8547: sub has_comm_blocking {
1.1172.2.128! raeburn 8548: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66 raeburn 8549: my @blockers;
8550: return unless ($env{'request.course.id'});
8551: return unless ($priv eq 'bre');
8552: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8553: return if ($env{'request.state'} eq 'construct');
1.1172.2.128! raeburn 8554: my %blockinfo;
! 8555: if (ref($blocks) eq 'HASH') {
! 8556: %blockinfo = &get_commblock_resources($blocks);
! 8557: } else {
! 8558: &load_all_blockers($env{'user.name'},$env{'user.domain'});
! 8559: %blockinfo = %cachedblockers;
! 8560: }
! 8561: return unless (keys(%blockinfo) > 0);
1.1172.2.66 raeburn 8562: my (%possibles,@symbs);
8563: if (!$symb) {
1.1172.2.128! raeburn 8564: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 8565: }
1.1172.2.66 raeburn 8566: if ($symb) {
8567: @symbs = ($symb);
8568: } elsif (keys(%possibles)) {
8569: @symbs = keys(%possibles);
8570: }
8571: my $noblock;
8572: foreach my $symb (@symbs) {
8573: last if ($noblock);
8574: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128! raeburn 8575: foreach my $block (keys(%blockinfo)) {
1.1172.2.66 raeburn 8576: if ($block =~ /^firstaccess____(.+)$/) {
8577: my $item = $1;
1.1172.2.126 raeburn 8578: unless ($blocked) {
8579: if (($item eq $map) || ($item eq $symb)) {
8580: $noblock = 1;
8581: last;
8582: }
1.1172.2.66 raeburn 8583: }
1.1162 raeburn 8584: }
1.1172.2.128! raeburn 8585: if (ref($blockinfo{$block}) eq 'HASH') {
! 8586: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
! 8587: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66 raeburn 8588: unless (grep(/^\Q$block\E$/,@blockers)) {
8589: push(@blockers,$block);
8590: }
8591: }
8592: }
1.1172.2.128! raeburn 8593: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
! 8594: if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126 raeburn 8595: unless (grep(/^\Q$block\E$/,@blockers)) {
8596: push(@blockers,$block);
8597: }
1.1172.2.66 raeburn 8598: }
8599: }
1.1162 raeburn 8600: }
8601: }
8602: }
1.1172.2.126 raeburn 8603: unless ($noblock) {
8604: return @blockers;
8605: }
8606: return;
1.1172.2.66 raeburn 8607: }
1.1162 raeburn 8608: }
8609:
1.1172.2.66 raeburn 8610: # -------------------------------- Deversion and split uri into path an filename
8611:
1.1133 foxr 8612: #
1.1172.2.66 raeburn 8613: # Removes the version from a URI and
1.1133 foxr 8614: # splits it in to its filename and path to the filename.
8615: # Seems like File::Basename could have done this more clearly.
8616: # Parameters:
8617: # $uri - input URI
8618: # Returns:
8619: # Two element list consisting of
8620: # $pathname - the URI up to and excluding the trailing /
8621: # $filename - The part of the URI following the last /
8622: # NOTE:
8623: # Another realization of this is simply:
8624: # use File::Basename;
8625: # ...
8626: # $uri = shift;
8627: # $filename = basename($uri);
8628: # $path = dirname($uri);
8629: # return ($filename, $path);
8630: #
8631: # The implementation below is probably faster however.
8632: #
1.710 albertel 8633: sub split_uri_for_cond {
8634: my $uri=&deversion(&declutter(shift));
8635: my @uriparts=split(/\//,$uri);
8636: my $filename=pop(@uriparts);
8637: my $pathname=join('/',@uriparts);
8638: return ($pathname,$filename);
8639: }
1.232 www 8640: # --------------------------------------------------- Is a resource on the map?
8641:
8642: sub is_on_map {
1.710 albertel 8643: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8644: #Trying to find the conditional for the file
1.620 albertel 8645: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8646: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8647: if ($match) {
1.289 bowersj2 8648: return (1,$1);
8649: } else {
1.434 www 8650: return (0,0);
1.289 bowersj2 8651: }
1.12 www 8652: }
8653:
1.427 www 8654: # --------------------------------------------------------- Get symb from alias
8655:
8656: sub get_symb_from_alias {
8657: my $symb=shift;
8658: my ($map,$resid,$url)=&decode_symb($symb);
8659: # Already is a symb
8660: if ($url) { return $symb; }
8661: # Must be an alias
8662: my $aliassymb='';
8663: my %bighash;
1.620 albertel 8664: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8665: &GDBM_READER(),0640)) {
8666: my $rid=$bighash{'mapalias_'.$symb};
8667: if ($rid) {
8668: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8669: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8670: $resid,$bighash{'src_'.$rid});
1.427 www 8671: }
8672: untie %bighash;
8673: }
8674: return $aliassymb;
8675: }
8676:
1.12 www 8677: # ----------------------------------------------------------------- Define Role
8678:
8679: sub definerole {
8680: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8681: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8682: foreach my $role (split(':',$sysrole)) {
8683: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8684: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8685: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8686: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8687: return "refused:s:$crole&$cqual";
8688: }
8689: }
1.191 harris41 8690: }
1.800 albertel 8691: foreach my $role (split(':',$domrole)) {
8692: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8693: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8694: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8695: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8696: return "refused:d:$crole&$cqual";
8697: }
8698: }
1.191 harris41 8699: }
1.800 albertel 8700: foreach my $role (split(':',$courole)) {
8701: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8702: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8703: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8704: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8705: return "refused:c:$crole&$cqual";
8706: }
8707: }
1.191 harris41 8708: }
1.1172.2.84 raeburn 8709: my $uhome;
8710: if (($uname ne '') && ($udom ne '')) {
8711: $uhome = &homeserver($uname,$udom);
8712: return $uhome if ($uhome eq 'no_host');
8713: } else {
8714: $uname = $env{'user.name'};
8715: $udom = $env{'user.domain'};
8716: $uhome = $env{'user.home'};
8717: }
1.620 albertel 8718: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8719: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8720: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8721: return reply($command,$uhome);
1.12 www 8722: } else {
8723: return 'refused';
8724: }
1.105 harris41 8725: }
8726:
8727: # ---------------- Make a metadata query against the network of library servers
8728:
8729: sub metadata_query {
1.1172.2.33 raeburn 8730: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8731: my %rhash;
1.845 albertel 8732: my %libserv = &all_library();
1.244 matthew 8733: my @server_list = (defined($server_array) ? @$server_array
8734: : keys(%libserv) );
8735: for my $server (@server_list) {
1.1172.2.33 raeburn 8736: my $domains = '';
8737: if (ref($domains_hash) eq 'HASH') {
8738: $domains = $domains_hash->{$server};
8739: }
1.118 harris41 8740: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8741: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8742: $rhash{$server}=$reply;
8743: }
8744: else {
8745: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8746: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8747: $server);
8748: $rhash{$server}=$reply;
8749: }
1.112 harris41 8750: }
1.118 harris41 8751: return \%rhash;
1.240 www 8752: }
8753:
8754: # ----------------------------------------- Send log queries and wait for reply
8755:
8756: sub log_query {
8757: my ($uname,$udom,$query,%filters)=@_;
8758: my $uhome=&homeserver($uname,$udom);
8759: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8760: my $uhost=&hostname($uhome);
1.800 albertel 8761: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8762: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8763: $uhome);
1.479 albertel 8764: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8765: return get_query_reply($queryid);
8766: }
8767:
1.818 raeburn 8768: # -------------------------- Update MySQL table for portfolio file
8769:
8770: sub update_portfolio_table {
1.821 raeburn 8771: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8772: if ($group ne '') {
8773: $file_name =~s /^\Q$group\E//;
8774: }
1.818 raeburn 8775: my $homeserver = &homeserver($uname,$udom);
8776: my $queryid=
1.821 raeburn 8777: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8778: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8779: my $reply = &get_query_reply($queryid);
8780: return $reply;
8781: }
8782:
1.899 raeburn 8783: # -------------------------- Update MySQL allusers table
8784:
8785: sub update_allusers_table {
8786: my ($uname,$udom,$names) = @_;
8787: my $homeserver = &homeserver($uname,$udom);
8788: my $queryid=
8789: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8790: 'lastname='.&escape($names->{'lastname'}).'%%'.
8791: 'firstname='.&escape($names->{'firstname'}).'%%'.
8792: 'middlename='.&escape($names->{'middlename'}).'%%'.
8793: 'generation='.&escape($names->{'generation'}).'%%'.
8794: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8795: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8796: return;
1.899 raeburn 8797: }
8798:
1.508 raeburn 8799: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8800:
8801: sub fetch_enrollment_query {
1.511 raeburn 8802: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8803: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8804: my $maxtries = 1;
1.508 raeburn 8805: if ($context eq 'automated') {
8806: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8807: $sleep = 2;
8808: $loopmax = 100;
1.547 raeburn 8809: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8810: } else {
8811: $homeserver = &homeserver($cnum,$dom);
8812: }
1.838 albertel 8813: my $host=&hostname($homeserver);
1.506 raeburn 8814: my $cmd = '';
1.1000 raeburn 8815: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8816: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8817: }
8818: $cmd =~ s/%%$//;
8819: $cmd = &escape($cmd);
8820: my $query = 'fetchenrollment';
1.620 albertel 8821: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8822: unless ($queryid=~/^\Q$host\E\_/) {
8823: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8824: return 'error: '.$queryid;
8825: }
1.1172.2.93 raeburn 8826: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8827: my $tries = 1;
8828: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8829: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8830: $tries ++;
8831: }
1.526 raeburn 8832: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8833: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8834: } else {
1.901 albertel 8835: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8836: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8837: foreach my $line (@responses) {
8838: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8839: $$replyref{$key} = $value;
8840: }
8841: } else {
1.1117 foxr 8842: my $pathname = LONCAPA::tempdir();
1.800 albertel 8843: foreach my $line (@responses) {
8844: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8845: $$replyref{$key} = $value;
8846: if ($value > 0) {
1.800 albertel 8847: foreach my $item (@{$$affiliatesref{$key}}) {
8848: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8849: my $destname = $pathname.'/'.$filename;
8850: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8851: if ($xml_classlist =~ /^error/) {
8852: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8853: } else {
1.1172.2.96 raeburn 8854: if ( open(FILE,">",$destname) ) {
1.506 raeburn 8855: print FILE &unescape($xml_classlist);
8856: close(FILE);
1.526 raeburn 8857: } else {
8858: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8859: }
8860: }
8861: }
8862: }
8863: }
8864: }
8865: return 'ok';
8866: }
8867: return 'error';
8868: }
8869:
1.242 www 8870: sub get_query_reply {
1.1172.2.79 raeburn 8871: my ($queryid,$sleep,$loopmax) = @_;
8872: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8873: $sleep = 0.2;
8874: }
8875: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8876: $loopmax = 100;
8877: }
1.1117 foxr 8878: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8879: my $reply='';
1.1172.2.79 raeburn 8880: for (1..$loopmax) {
8881: sleep($sleep);
1.240 www 8882: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 8883: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 8884: $reply = join('',<$fh>);
8885: close($fh);
1.240 www 8886: } else { return 'error: reply_file_error'; }
1.242 www 8887: return &unescape($reply);
8888: }
1.240 www 8889: }
1.242 www 8890: return 'timeout:'.$queryid;
1.240 www 8891: }
8892:
8893: sub courselog_query {
1.241 www 8894: #
8895: # possible filters:
8896: # url: url or symb
8897: # username
8898: # domain
8899: # action: view, submit, grade
8900: # start: timestamp
8901: # end: timestamp
8902: #
1.240 www 8903: my (%filters)=@_;
1.620 albertel 8904: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8905: if ($filters{'url'}) {
8906: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8907: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8908: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8909: }
1.620 albertel 8910: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8911: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8912: return &log_query($cname,$cdom,'courselog',%filters);
8913: }
8914:
8915: sub userlog_query {
1.858 raeburn 8916: #
8917: # possible filters:
8918: # action: log check role
8919: # start: timestamp
8920: # end: timestamp
8921: #
1.240 www 8922: my ($uname,$udom,%filters)=@_;
8923: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8924: }
8925:
1.506 raeburn 8926: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8927:
8928: sub auto_run {
1.508 raeburn 8929: my ($cnum,$cdom) = @_;
1.876 raeburn 8930: my $response = 0;
8931: my $settings;
8932: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8933: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8934: $settings = $domconfig{'autoenroll'};
8935: if ($settings->{'run'} eq '1') {
8936: $response = 1;
8937: }
8938: } else {
1.934 raeburn 8939: my $homeserver;
8940: if (&is_course($cdom,$cnum)) {
8941: $homeserver = &homeserver($cnum,$cdom);
8942: } else {
8943: $homeserver = &domain($cdom,'primary');
8944: }
8945: if ($homeserver ne 'no_host') {
8946: $response = &reply('autorun:'.$cdom,$homeserver);
8947: }
1.876 raeburn 8948: }
1.506 raeburn 8949: return $response;
8950: }
1.776 albertel 8951:
1.506 raeburn 8952: sub auto_get_sections {
1.508 raeburn 8953: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8954: my $homeserver;
8955: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8956: $homeserver = &homeserver($cnum,$cdom);
8957: }
8958: if (!defined($homeserver)) {
8959: if ($cdom =~ /^$match_domain$/) {
8960: $homeserver = &domain($cdom,'primary');
8961: }
8962: }
8963: my @secs;
8964: if (defined($homeserver)) {
8965: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8966: unless ($response eq 'refused') {
8967: @secs = split(/:/,$response);
8968: }
1.506 raeburn 8969: }
8970: return @secs;
8971: }
1.776 albertel 8972:
1.506 raeburn 8973: sub auto_new_course {
1.1099 raeburn 8974: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8975: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8976: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8977: return $response;
8978: }
1.776 albertel 8979:
1.506 raeburn 8980: sub auto_validate_courseID {
1.508 raeburn 8981: my ($cnum,$cdom,$inst_course_id) = @_;
8982: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8983: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8984: return $response;
8985: }
1.776 albertel 8986:
1.1007 raeburn 8987: sub auto_validate_instcode {
1.1020 raeburn 8988: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8989: my ($homeserver,$response);
8990: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8991: $homeserver = &homeserver($cnum,$cdom);
8992: }
8993: if (!defined($homeserver)) {
8994: if ($cdom =~ /^$match_domain$/) {
8995: $homeserver = &domain($cdom,'primary');
8996: }
8997: }
1.1065 raeburn 8998: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8999: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 9000: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9001: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9002: }
9003:
1.506 raeburn 9004: sub auto_create_password {
1.873 raeburn 9005: my ($cnum,$cdom,$authparam,$udom) = @_;
9006: my ($homeserver,$response);
1.506 raeburn 9007: my $create_passwd = 0;
9008: my $authchk = '';
1.873 raeburn 9009: if ($udom =~ /^$match_domain$/) {
9010: $homeserver = &domain($udom,'primary');
9011: }
9012: if ($homeserver eq '') {
9013: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9014: $homeserver = &homeserver($cnum,$cdom);
9015: }
9016: }
9017: if ($homeserver eq '') {
9018: $authchk = 'nodomain';
1.506 raeburn 9019: } else {
1.873 raeburn 9020: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9021: if ($response eq 'refused') {
9022: $authchk = 'refused';
9023: } else {
1.901 albertel 9024: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9025: }
1.506 raeburn 9026: }
9027: return ($authparam,$create_passwd,$authchk);
9028: }
9029:
1.706 raeburn 9030: sub auto_photo_permission {
9031: my ($cnum,$cdom,$students) = @_;
9032: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9033: my ($outcome,$perm_reqd,$conditions) =
9034: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9035: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9036: return (undef,undef);
9037: }
1.706 raeburn 9038: return ($outcome,$perm_reqd,$conditions);
9039: }
9040:
9041: sub auto_checkphotos {
9042: my ($uname,$udom,$pid) = @_;
9043: my $homeserver = &homeserver($uname,$udom);
9044: my ($result,$resulttype);
9045: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9046: &escape($uname).':'.&escape($pid),
9047: $homeserver));
1.709 albertel 9048: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9049: return (undef,undef);
9050: }
1.706 raeburn 9051: if ($outcome) {
9052: ($result,$resulttype) = split(/:/,$outcome);
9053: }
9054: return ($result,$resulttype);
9055: }
9056:
9057: sub auto_photochoice {
9058: my ($cnum,$cdom) = @_;
9059: my $homeserver = &homeserver($cnum,$cdom);
9060: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9061: &escape($cdom),
9062: $homeserver)));
1.709 albertel 9063: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9064: return (undef,undef);
9065: }
1.706 raeburn 9066: return ($update,$comment);
9067: }
9068:
9069: sub auto_photoupdate {
9070: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9071: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9072: my $host=&hostname($homeserver);
1.706 raeburn 9073: my $cmd = '';
9074: my $maxtries = 1;
1.800 albertel 9075: foreach my $affiliate (keys(%{$affiliatesref})) {
9076: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9077: }
9078: $cmd =~ s/%%$//;
9079: $cmd = &escape($cmd);
9080: my $query = 'institutionalphotos';
9081: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9082: unless ($queryid=~/^\Q$host\E\_/) {
9083: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9084: return 'error: '.$queryid;
9085: }
9086: my $reply = &get_query_reply($queryid);
9087: my $tries = 1;
9088: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9089: $reply = &get_query_reply($queryid);
9090: $tries ++;
9091: }
9092: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9093: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9094: } else {
9095: my @responses = split(/:/,$reply);
9096: my $outcome = shift(@responses);
9097: foreach my $item (@responses) {
9098: my ($key,$value) = split(/=/,$item);
9099: $$photo{$key} = $value;
9100: }
9101: return $outcome;
9102: }
9103: return 'error';
9104: }
9105:
1.521 raeburn 9106: sub auto_instcode_format {
1.793 albertel 9107: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9108: $cat_order) = @_;
1.521 raeburn 9109: my $courses = '';
1.772 raeburn 9110: my @homeservers;
1.521 raeburn 9111: if ($caller eq 'global') {
1.841 albertel 9112: my %servers = &get_servers($codedom,'library');
9113: foreach my $tryserver (keys(%servers)) {
9114: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9115: push(@homeservers,$tryserver);
9116: }
1.584 raeburn 9117: }
1.1022 raeburn 9118: } elsif ($caller eq 'requests') {
9119: if ($codedom =~ /^$match_domain$/) {
9120: my $chome = &domain($codedom,'primary');
9121: unless ($chome eq 'no_host') {
9122: push(@homeservers,$chome);
9123: }
9124: }
1.521 raeburn 9125: } else {
1.772 raeburn 9126: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9127: }
1.793 albertel 9128: foreach my $code (keys(%{$instcodes})) {
9129: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9130: }
9131: chop($courses);
1.772 raeburn 9132: my $ok_response = 0;
9133: my $response;
9134: while (@homeservers > 0 && $ok_response == 0) {
9135: my $server = shift(@homeservers);
9136: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9137: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9138: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9139: split(/:/,$response);
1.772 raeburn 9140: %{$codes} = (%{$codes},&str2hash($codes_str));
9141: push(@{$codetitles},&str2array($codetitles_str));
9142: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9143: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9144: $ok_response = 1;
9145: }
9146: }
9147: if ($ok_response) {
1.521 raeburn 9148: return 'ok';
1.772 raeburn 9149: } else {
9150: return $response;
1.521 raeburn 9151: }
9152: }
9153:
1.792 raeburn 9154: sub auto_instcode_defaults {
9155: my ($domain,$returnhash,$code_order) = @_;
9156: my @homeservers;
1.841 albertel 9157:
9158: my %servers = &get_servers($domain,'library');
9159: foreach my $tryserver (keys(%servers)) {
9160: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9161: push(@homeservers,$tryserver);
9162: }
1.792 raeburn 9163: }
1.841 albertel 9164:
1.792 raeburn 9165: my $response;
1.841 albertel 9166: foreach my $server (@homeservers) {
1.792 raeburn 9167: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9168: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9169:
9170: foreach my $pair (split(/\&/,$response)) {
9171: my ($name,$value)=split(/\=/,$pair);
9172: if ($name eq 'code_order') {
9173: @{$code_order} = split(/\&/,&unescape($value));
9174: } else {
9175: $returnhash->{&unescape($name)}=&unescape($value);
9176: }
9177: }
9178: return 'ok';
1.792 raeburn 9179: }
1.841 albertel 9180:
9181: return $response;
1.1003 raeburn 9182: }
9183:
9184: sub auto_possible_instcodes {
1.1007 raeburn 9185: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9186: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9187: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9188: return;
9189: }
1.1003 raeburn 9190: my (@homeservers,$uhome);
9191: if (defined(&domain($domain,'primary'))) {
9192: $uhome=&domain($domain,'primary');
9193: push(@homeservers,&domain($domain,'primary'));
9194: } else {
9195: my %servers = &get_servers($domain,'library');
9196: foreach my $tryserver (keys(%servers)) {
9197: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9198: push(@homeservers,$tryserver);
9199: }
9200: }
9201: }
9202: my $response;
9203: foreach my $server (@homeservers) {
9204: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9205: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9206: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9207: split(':',$response);
9208: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9209: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9210: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9211: my ($name,$value)=split('=',$item);
9212: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9213: }
9214: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9215: my ($name,$value)=split('=',$item);
9216: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9217: }
9218: return 'ok';
9219: }
9220: return $response;
9221: }
1.792 raeburn 9222:
1.1010 raeburn 9223: sub auto_courserequest_checks {
9224: my ($dom) = @_;
1.1020 raeburn 9225: my ($homeserver,%validations);
9226: if ($dom =~ /^$match_domain$/) {
9227: $homeserver = &domain($dom,'primary');
9228: }
9229: unless ($homeserver eq 'no_host') {
9230: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9231: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9232: my @items = split(/&/,$response);
9233: foreach my $item (@items) {
9234: my ($key,$value) = split('=',$item);
9235: $validations{&unescape($key)} = &thaw_unescape($value);
9236: }
9237: }
9238: }
1.1010 raeburn 9239: return %validations;
9240: }
9241:
1.1020 raeburn 9242: sub auto_courserequest_validation {
1.1172.2.43 raeburn 9243: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9244: my ($homeserver,$response);
9245: if ($dom =~ /^$match_domain$/) {
9246: $homeserver = &domain($dom,'primary');
9247: }
1.1172.2.43 raeburn 9248: unless ($homeserver eq 'no_host') {
9249: my $customdata;
9250: if (ref($custominfo) eq 'HASH') {
9251: $customdata = &freeze_escape($custominfo);
9252: }
1.1020 raeburn 9253: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9254: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 9255: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9256: $customdata,$homeserver));
1.1020 raeburn 9257: }
9258: return $response;
9259: }
9260:
1.777 albertel 9261: sub auto_validate_class_sec {
1.918 raeburn 9262: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9263: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9264: my $ownerlist;
9265: if (ref($owners) eq 'ARRAY') {
9266: $ownerlist = join(',',@{$owners});
9267: } else {
9268: $ownerlist = $owners;
9269: }
1.773 raeburn 9270: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9271: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9272: return $response;
9273: }
9274:
1.1172.2.94 raeburn 9275: sub auto_validate_instclasses {
9276: my ($cdom,$cnum,$owners,$classesref) = @_;
9277: my ($homeserver,%validations);
9278: $homeserver = &homeserver($cnum,$cdom);
9279: unless ($homeserver eq 'no_host') {
9280: my $ownerlist;
9281: if (ref($owners) eq 'ARRAY') {
9282: $ownerlist = join(',',@{$owners});
9283: } else {
9284: $ownerlist = $owners;
9285: }
9286: if (ref($classesref) eq 'HASH') {
9287: my $classes = &freeze_escape($classesref);
9288: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9289: ':'.$cdom.':'.$classes,$homeserver);
9290: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9291: my @items = split(/&/,$response);
9292: foreach my $item (@items) {
9293: my ($key,$value) = split('=',$item);
9294: $validations{&unescape($key)} = &thaw_unescape($value);
9295: }
9296: }
9297: }
9298: }
9299: return %validations;
9300: }
9301:
1.1172.2.38 raeburn 9302: sub auto_crsreq_update {
9303: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 9304: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 9305: my ($homeserver,%crsreqresponse);
9306: if ($cdom =~ /^$match_domain$/) {
9307: $homeserver = &domain($cdom,'primary');
9308: }
9309: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9310: my $info;
9311: if (ref($inbound) eq 'HASH') {
9312: $info = &freeze_escape($inbound);
9313: }
9314: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9315: ':'.&escape($action).':'.&escape($ownername).':'.
9316: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 9317: &escape($title).':'.&escape($code).':'.
9318: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 9319: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9320: my @items = split(/&/,$response);
9321: foreach my $item (@items) {
9322: my ($key,$value) = split('=',$item);
9323: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9324: }
9325: }
9326: }
9327: return \%crsreqresponse;
9328: }
9329:
1.1172.2.78 raeburn 9330: sub auto_export_grades {
9331: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9332: my ($homeserver,%exportresponse);
9333: if ($cdom =~ /^$match_domain$/) {
9334: $homeserver = &domain($cdom,'primary');
9335: }
9336: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9337: my $info;
9338: if (ref($inforef) eq 'HASH') {
9339: $info = &freeze_escape($inforef);
9340: }
9341: if (ref($gradesref) eq 'HASH') {
9342: my $grades = &freeze_escape($gradesref);
9343: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9344: $info.':'.$grades,$homeserver);
9345: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9346: my @items = split(/&/,$response);
9347: foreach my $item (@items) {
9348: my ($key,$value) = split('=',$item);
9349: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9350: }
9351: }
9352: }
9353: }
9354: return \%exportresponse;
9355: }
9356:
1.1172.2.68 raeburn 9357: sub check_instcode_cloning {
9358: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9359: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9360: return;
9361: }
9362: my $canclone;
9363: if (@{$code_order} > 0) {
9364: my $instcoderegexp ='^';
9365: my @clonecodes = split(/\&/,$cloner);
9366: foreach my $item (@{$code_order}) {
9367: if (grep(/^\Q$item\E=/,@clonecodes)) {
9368: foreach my $pair (@clonecodes) {
9369: my ($key,$val) = split(/\=/,$pair,2);
9370: $val = &unescape($val);
9371: if ($key eq $item) {
9372: $instcoderegexp .= '('.$val.')';
9373: last;
9374: }
9375: }
9376: } else {
9377: $instcoderegexp .= $codedefaults->{$item};
9378: }
9379: }
9380: $instcoderegexp .= '$';
9381: my (@from,@to);
9382: eval {
9383: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9384: (@to) = ($clonetocode =~ /$instcoderegexp/);
9385: };
9386: if ((@from > 0) && (@to > 0)) {
9387: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9388: if (!@diffs) {
9389: $canclone = 1;
9390: }
9391: }
9392: }
9393: return $canclone;
9394: }
9395:
9396: sub default_instcode_cloning {
9397: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9398: my (%codedefaults,@code_order,$canclone);
9399: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9400: %codedefaults = %{$codedefaultsref};
9401: @code_order = @{$codeorderref};
9402: } elsif ($clonedom) {
9403: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9404: }
9405: if (($domdefclone) && (@code_order)) {
9406: my @clonecodes = split(/\+/,$domdefclone);
9407: my $instcoderegexp ='^';
9408: foreach my $item (@code_order) {
9409: if (grep(/^\Q$item\E$/,@clonecodes)) {
9410: $instcoderegexp .= '('.$codedefaults{$item}.')';
9411: } else {
9412: $instcoderegexp .= $codedefaults{$item};
9413: }
9414: }
9415: $instcoderegexp .= '$';
9416: my (@from,@to);
9417: eval {
9418: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9419: (@to) = ($clonetocode =~ /$instcoderegexp/);
9420: };
9421: if ((@from > 0) && (@to > 0)) {
9422: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9423: if (!@diffs) {
9424: $canclone = 1;
9425: }
9426: }
9427: }
9428: return $canclone;
9429: }
9430:
1.679 raeburn 9431: # ------------------------------------------------------- Course Group routines
9432:
9433: sub get_coursegroups {
1.809 raeburn 9434: my ($cdom,$cnum,$group,$namespace) = @_;
9435: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9436: }
9437:
1.679 raeburn 9438: sub modify_coursegroup {
9439: my ($cdom,$cnum,$groupsettings) = @_;
9440: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9441: }
9442:
1.809 raeburn 9443: sub toggle_coursegroup_status {
9444: my ($cdom,$cnum,$group,$action) = @_;
9445: my ($from_namespace,$to_namespace);
9446: if ($action eq 'delete') {
9447: $from_namespace = 'coursegroups';
9448: $to_namespace = 'deleted_groups';
9449: } else {
9450: $from_namespace = 'deleted_groups';
9451: $to_namespace = 'coursegroups';
9452: }
9453: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9454: if (my $tmp = &error(%curr_group)) {
9455: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9456: return ('read error',$tmp);
9457: } else {
9458: my %savedsettings = %curr_group;
1.809 raeburn 9459: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9460: my $deloutcome;
9461: if ($result eq 'ok') {
1.809 raeburn 9462: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9463: } else {
9464: return ('write error',$result);
9465: }
9466: if ($deloutcome eq 'ok') {
9467: return 'ok';
9468: } else {
9469: return ('delete error',$deloutcome);
9470: }
9471: }
9472: }
9473:
1.679 raeburn 9474: sub modify_group_roles {
1.957 raeburn 9475: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9476: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9477: my $role = 'gr/'.&escape($userprivs);
9478: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9479: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9480: if ($result eq 'ok') {
9481: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9482: }
1.679 raeburn 9483: return $result;
9484: }
9485:
9486: sub modify_coursegroup_membership {
9487: my ($cdom,$cnum,$membership) = @_;
9488: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9489: return $result;
9490: }
9491:
1.682 raeburn 9492: sub get_active_groups {
9493: my ($udom,$uname,$cdom,$cnum) = @_;
9494: my $now = time;
9495: my %groups = ();
9496: foreach my $key (keys(%env)) {
1.811 albertel 9497: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9498: my ($start,$end) = split(/\./,$env{$key});
9499: if (($end!=0) && ($end<$now)) { next; }
9500: if (($start!=0) && ($start>$now)) { next; }
9501: if ($1 eq $cdom && $2 eq $cnum) {
9502: $groups{$3} = $env{$key} ;
9503: }
9504: }
9505: }
9506: return %groups;
9507: }
9508:
1.683 raeburn 9509: sub get_group_membership {
9510: my ($cdom,$cnum,$group) = @_;
9511: return(&dump('groupmembership',$cdom,$cnum,$group));
9512: }
9513:
9514: sub get_users_groups {
9515: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9516: my @usersgroups;
1.683 raeburn 9517: my $cachetime=1800;
9518:
9519: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9520: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9521: if (defined($cached)) {
1.734 albertel 9522: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9523: } else {
9524: $grouplist = '';
1.816 raeburn 9525: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9526: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9527: my $access_end = $env{'course.'.$courseid.
9528: '.default_enrollment_end_date'};
9529: my $now = time;
9530: foreach my $key (keys(%roleshash)) {
9531: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9532: my $group = $1;
9533: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9534: my $start = $2;
9535: my $end = $1;
9536: if ($start == -1) { next; } # deleted from group
9537: if (($start!=0) && ($start>$now)) { next; }
9538: if (($end!=0) && ($end<$now)) {
9539: if ($access_end && $access_end < $now) {
9540: if ($access_end - $end < 86400) {
9541: push(@usersgroups,$group);
1.733 raeburn 9542: }
9543: }
1.817 raeburn 9544: next;
1.733 raeburn 9545: }
1.817 raeburn 9546: push(@usersgroups,$group);
1.683 raeburn 9547: }
9548: }
9549: }
1.817 raeburn 9550: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9551: $grouplist = join(':',@usersgroups);
9552: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9553: }
1.733 raeburn 9554: return @usersgroups;
1.683 raeburn 9555: }
9556:
9557: sub devalidate_getgroups_cache {
9558: my ($udom,$uname,$cdom,$cnum)=@_;
9559: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9560:
1.683 raeburn 9561: my $hashid="$udom:$uname:$courseid";
9562: &devalidate_cache_new('getgroups',$hashid);
9563: }
9564:
1.12 www 9565: # ------------------------------------------------------------------ Plain Text
9566:
9567: sub plaintext {
1.988 raeburn 9568: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9569: if ($short =~ m{^cr/}) {
1.758 albertel 9570: return (split('/',$short))[-1];
9571: }
1.742 raeburn 9572: if (!defined($cid)) {
9573: $cid = $env{'request.course.id'};
9574: }
9575: my %rolenames = (
1.1008 raeburn 9576: Course => 'std',
9577: Community => 'alt1',
1.742 raeburn 9578: );
1.1037 raeburn 9579: if ($cid ne '') {
9580: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9581: unless ($forcedefault) {
9582: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9583: &Apache::lonlocal::mt_escape(\$roletext);
9584: return &Apache::lonlocal::mt($roletext);
9585: }
9586: }
9587: }
9588: if ((defined($type)) && (defined($rolenames{$type})) &&
9589: (defined($rolenames{$type})) &&
9590: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9591: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9592: } elsif ($cid ne '') {
9593: my $crstype = $env{'course.'.$cid.'.type'};
9594: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9595: (defined($prp{$short}{$rolenames{$crstype}}))) {
9596: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9597: }
1.742 raeburn 9598: }
1.1037 raeburn 9599: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9600: }
9601:
9602: # ----------------------------------------------------------------- Assign Role
9603:
9604: sub assignrole {
1.957 raeburn 9605: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9606: $context)=@_;
1.21 www 9607: my $mrole;
9608: if ($role =~ /^cr\//) {
1.393 www 9609: my $cwosec=$url;
1.811 albertel 9610: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9611: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9612: my $refused = 1;
9613: if ($context eq 'requestcourses') {
9614: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9615: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9616: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9617: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9618: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9619: if ($crsenv{'internal.courseowner'} eq
9620: $env{'user.name'}.':'.$env{'user.domain'}) {
9621: $refused = '';
9622: }
9623: }
9624: }
9625: }
9626: }
9627: if ($refused) {
9628: &logthis('Refused custom assignrole: '.
9629: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9630: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9631: return 'refused';
9632: }
1.104 www 9633: }
1.21 www 9634: $mrole='cr';
1.678 raeburn 9635: } elsif ($role =~ /^gr\//) {
9636: my $cwogrp=$url;
1.811 albertel 9637: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9638: unless (&allowed('mdg',$cwogrp)) {
9639: &logthis('Refused group assignrole: '.
9640: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9641: $env{'user.name'}.' at '.$env{'user.domain'});
9642: return 'refused';
9643: }
9644: $mrole='gr';
1.21 www 9645: } else {
1.82 www 9646: my $cwosec=$url;
1.811 albertel 9647: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9648: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9649: my $refused;
9650: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9651: if (!(&allowed('c'.$role,$url))) {
9652: $refused = 1;
9653: }
9654: } else {
9655: $refused = 1;
9656: }
1.947 raeburn 9657: if ($refused) {
1.1045 raeburn 9658: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9659: if (!$selfenroll && $context eq 'course') {
9660: my %crsenv;
9661: if ($role eq 'cc' || $role eq 'co') {
9662: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9663: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9664: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9665: if ($crsenv{'internal.courseowner'} eq
9666: $env{'user.name'}.':'.$env{'user.domain'}) {
9667: $refused = '';
9668: }
9669: }
9670: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9671: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9672: if ($crsenv{'internal.courseowner'} eq
9673: $env{'user.name'}.':'.$env{'user.domain'}) {
9674: $refused = '';
9675: }
9676: }
9677: }
9678: }
9679: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9680: $refused = '';
1.1017 raeburn 9681: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9682: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9683: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9684: my $wrongcc;
9685: if ($cnum =~ /^$match_community$/) {
9686: $wrongcc = 1 if ($role eq 'cc');
9687: } else {
9688: $wrongcc = 1 if ($role eq 'co');
9689: }
9690: unless ($wrongcc) {
9691: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9692: if ($crsenv{'internal.courseowner'} eq
9693: $env{'user.name'}.':'.$env{'user.domain'}) {
9694: $refused = '';
9695: }
1.1017 raeburn 9696: }
9697: }
1.1172.2.9 raeburn 9698: } elsif ($context eq 'requestauthor') {
9699: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9700: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9701: if ($env{'environment.requestauthor'} eq 'automatic') {
9702: $refused = '';
9703: } else {
9704: my %domdefaults = &get_domain_defaults($udom);
9705: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9706: my $checkbystatus;
9707: if ($env{'user.adv'}) {
9708: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9709: if ($disposition eq 'automatic') {
9710: $refused = '';
9711: } elsif ($disposition eq '') {
9712: $checkbystatus = 1;
9713: }
9714: } else {
9715: $checkbystatus = 1;
9716: }
9717: if ($checkbystatus) {
9718: if ($env{'environment.inststatus'}) {
9719: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9720: foreach my $type (@inststatuses) {
9721: if (($type ne '') &&
9722: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9723: $refused = '';
9724: }
9725: }
9726: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9727: $refused = '';
9728: }
9729: }
9730: }
9731: }
9732: }
1.1017 raeburn 9733: }
9734: if ($refused) {
1.947 raeburn 9735: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9736: ' '.$role.' '.$end.' '.$start.' by '.
9737: $env{'user.name'}.' at '.$env{'user.domain'});
9738: return 'refused';
9739: }
1.932 raeburn 9740: }
1.1131 raeburn 9741: } elsif ($role eq 'au') {
9742: if ($url ne '/'.$udom.'/') {
9743: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9744: ' to assign author role for '.$uname.':'.$udom.
9745: ' in domain: '.$url.' refused (wrong domain).');
9746: return 'refused';
9747: }
1.104 www 9748: }
1.21 www 9749: $mrole=$role;
9750: }
1.620 albertel 9751: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9752: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9753: if ($end) { $command.='_'.$end; }
1.21 www 9754: if ($start) {
9755: if ($end) {
1.81 www 9756: $command.='_'.$start;
1.21 www 9757: } else {
1.81 www 9758: $command.='_0_'.$start;
1.21 www 9759: }
9760: }
1.739 raeburn 9761: my $origstart = $start;
9762: my $origend = $end;
1.957 raeburn 9763: my $delflag;
1.357 www 9764: # actually delete
9765: if ($deleteflag) {
1.373 www 9766: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9767: # modify command to delete the role
1.620 albertel 9768: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9769: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9770: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9771: # set start and finish to negative values for userrolelog
9772: $start=-1;
9773: $end=-1;
1.957 raeburn 9774: $delflag = 1;
1.357 www 9775: }
9776: }
9777: # send command
1.349 www 9778: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9779: # log new user role if status is ok
1.349 www 9780: if ($answer eq 'ok') {
1.663 raeburn 9781: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9782: if (($role eq 'cc') || ($role eq 'in') ||
9783: ($role eq 'ep') || ($role eq 'ad') ||
9784: ($role eq 'ta') || ($role eq 'st') ||
9785: ($role=~/^cr/) || ($role eq 'gr') ||
9786: ($role eq 'co')) {
1.1172.2.13 raeburn 9787: # for course roles, perform group memberships changes triggered by role change.
9788: unless ($role =~ /^gr/) {
9789: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9790: $origstart,$selfenroll,$context);
9791: }
1.1172.2.9 raeburn 9792: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9793: $selfenroll,$context);
9794: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9795: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9796: ($role eq 'da')) {
1.1172.2.9 raeburn 9797: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9798: $context);
9799: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9800: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9801: $context);
9802: }
1.1053 raeburn 9803: if ($role eq 'cc') {
9804: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9805: }
1.349 www 9806: }
9807: return $answer;
1.169 harris41 9808: }
9809:
1.1053 raeburn 9810: sub autoupdate_coowners {
9811: my ($url,$end,$start,$uname,$udom) = @_;
9812: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9813: if (($cdom ne '') && ($cnum ne '')) {
9814: my $now = time;
9815: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9816: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9817: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9818: my $instcode = $coursehash{'internal.coursecode'};
9819: if ($instcode ne '') {
1.1056 raeburn 9820: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9821: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9822: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9823: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9824: if ($result eq 'valid') {
9825: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9826: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9827: push(@newcoowners,$coowner);
9828: }
9829: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9830: push(@newcoowners,$uname.':'.$udom);
9831: }
9832: @newcoowners = sort(@newcoowners);
9833: } else {
9834: push(@newcoowners,$uname.':'.$udom);
9835: }
9836: } else {
9837: if ($coursehash{'internal.co-owners'}) {
9838: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9839: unless ($coowner eq $uname.':'.$udom) {
9840: push(@newcoowners,$coowner);
9841: }
9842: }
9843: unless (@newcoowners > 0) {
9844: $delcoowners = 1;
9845: $coowners = '';
9846: }
9847: }
9848: }
9849: if (@newcoowners || $delcoowners) {
9850: &store_coowners($cdom,$cnum,$coursehash{'home'},
9851: $delcoowners,@newcoowners);
9852: }
9853: }
9854: }
9855: }
9856: }
9857: }
9858: }
9859:
9860: sub store_coowners {
9861: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9862: my $cid = $cdom.'_'.$cnum;
9863: my ($coowners,$delresult,$putresult);
9864: if (@newcoowners) {
9865: $coowners = join(',',@newcoowners);
9866: my %coownershash = (
9867: 'internal.co-owners' => $coowners,
9868: );
9869: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9870: if ($putresult eq 'ok') {
9871: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9872: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9873: }
9874: }
9875: }
9876: if ($delcoowners) {
9877: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9878: if ($delresult eq 'ok') {
9879: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9880: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9881: }
9882: }
9883: }
9884: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9885: my %crsinfo =
9886: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9887: if (ref($crsinfo{$cid}) eq 'HASH') {
9888: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9889: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9890: }
9891: }
9892: }
9893:
1.169 harris41 9894: # -------------------------------------------------- Modify user authentication
1.197 www 9895: # Overrides without validation
9896:
1.169 harris41 9897: sub modifyuserauth {
9898: my ($udom,$uname,$umode,$upass)=@_;
9899: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 9900: my $allowed;
9901: if (&allowed('mau',$udom)) {
9902: $allowed = 1;
9903: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
9904: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
9905: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
9906: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9907: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9908: if (($cdom ne '') && ($cnum ne '')) {
9909: my $is_owner = &is_course_owner($cdom,$cnum);
9910: if ($is_owner) {
9911: $allowed = 1;
9912: }
9913: }
9914: }
9915: unless ($allowed) { return 'refused'; }
1.197 www 9916: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9917: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9918: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9919: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9920: &escape($upass),$uhome);
1.620 albertel 9921: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9922: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9923: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9924: &log($udom,,$uname,$uhome,
1.620 albertel 9925: 'Authentication changed by '.$env{'user.domain'}.', '.
9926: $env{'user.name'}.', '.$umode.
1.197 www 9927: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9928: unless ($reply eq 'ok') {
1.197 www 9929: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9930: return 'error: '.$reply;
9931: }
1.170 harris41 9932: return 'ok';
1.80 www 9933: }
9934:
1.81 www 9935: # --------------------------------------------------------------- Modify a user
1.80 www 9936:
1.81 www 9937: sub modifyuser {
1.206 matthew 9938: my ($udom, $uname, $uid,
9939: $umode, $upass, $first,
9940: $middle, $last, $gene,
1.1058 raeburn 9941: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9942: $udom= &LONCAPA::clean_domain($udom);
9943: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9944: my $showcandelete = 'none';
9945: if (ref($candelete) eq 'ARRAY') {
9946: if (@{$candelete} > 0) {
9947: $showcandelete = join(', ',@{$candelete});
9948: }
9949: }
1.81 www 9950: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9951: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9952: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9953: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9954: ' desiredhome not specified').
1.620 albertel 9955: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9956: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9957: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9958: my $newuser;
9959: if ($uhome eq 'no_host') {
9960: $newuser = 1;
9961: }
1.80 www 9962: # ----------------------------------------------------------------- Create User
1.406 albertel 9963: if (($uhome eq 'no_host') &&
9964: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9965: my $unhome='';
1.844 albertel 9966: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9967: $unhome = $desiredhome;
1.620 albertel 9968: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9969: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9970: } else { # load balancing routine for determining $unhome
1.81 www 9971: my $loadm=10000000;
1.841 albertel 9972: my %servers = &get_servers($udom,'library');
9973: foreach my $tryserver (keys(%servers)) {
9974: my $answer=reply('load',$tryserver);
9975: if (($answer=~/\d+/) && ($answer<$loadm)) {
9976: $loadm=$answer;
9977: $unhome=$tryserver;
9978: }
1.80 www 9979: }
9980: }
9981: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9982: return 'error: unable to find a home server for '.$uname.
9983: ' in domain '.$udom;
1.80 www 9984: }
9985: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9986: &escape($upass),$unhome);
9987: unless ($reply eq 'ok') {
9988: return 'error: '.$reply;
9989: }
1.230 stredwic 9990: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9991: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9992: return 'error: unable verify users home machine.';
1.80 www 9993: }
1.209 matthew 9994: } # End of creation of new user
1.80 www 9995: # ---------------------------------------------------------------------- Add ID
9996: if ($uid) {
9997: $uid=~tr/A-Z/a-z/;
9998: my %uidhash=&idrget($udom,$uname);
1.196 www 9999: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10000: && (!$forceid)) {
1.80 www 10001: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10002: return 'error: user id "'.$uid.'" does not match '.
10003: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10004: }
10005: } else {
10006: &idput($udom,($uname => $uid));
10007: }
10008: }
10009: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10010: my @tmp=&get('environment',
1.899 raeburn 10011: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10012: 'permanentemail','inststatus'],
1.134 albertel 10013: $udom,$uname);
1.1075 raeburn 10014: my (%names,%oldnames);
1.313 matthew 10015: if ($tmp[0] =~ m/^error:.*/) {
10016: %names=();
10017: } else {
10018: %names = @tmp;
1.1075 raeburn 10019: %oldnames = %names;
1.313 matthew 10020: }
1.388 www 10021: #
1.1058 raeburn 10022: # If name, email and/or uid are blank (e.g., because an uploaded file
10023: # of users did not contain them), do not overwrite existing values
10024: # unless field is in $candelete array ref.
10025: #
10026:
10027: my @fields = ('firstname','middlename','lastname','generation',
10028: 'permanentemail','id');
10029: my %newvalues;
10030: if (ref($candelete) eq 'ARRAY') {
10031: foreach my $field (@fields) {
10032: if (grep(/^\Q$field\E$/,@{$candelete})) {
10033: if ($field eq 'firstname') {
10034: $names{$field} = $first;
10035: } elsif ($field eq 'middlename') {
10036: $names{$field} = $middle;
10037: } elsif ($field eq 'lastname') {
10038: $names{$field} = $last;
10039: } elsif ($field eq 'generation') {
10040: $names{$field} = $gene;
10041: } elsif ($field eq 'permanentemail') {
10042: $names{$field} = $email;
10043: } elsif ($field eq 'id') {
10044: $names{$field} = $uid;
10045: }
10046: }
10047: }
10048: }
1.388 www 10049: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10050: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10051: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10052: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10053: if ($email) {
10054: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10055: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10056: }
1.899 raeburn 10057: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10058: if (defined($inststatus)) {
10059: $names{'inststatus'} = '';
10060: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10061: if (ref($usertypes) eq 'HASH') {
10062: my @okstatuses;
10063: foreach my $item (split(/:/,$inststatus)) {
10064: if (defined($usertypes->{$item})) {
10065: push(@okstatuses,$item);
10066: }
10067: }
10068: if (@okstatuses) {
10069: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10070: }
10071: }
10072: }
1.1075 raeburn 10073: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10074: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10075: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10076: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10077: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10078: } else {
10079: $logmsg .= ' during self creation';
10080: }
1.1075 raeburn 10081: my $changed;
10082: if ($newuser) {
10083: $changed = 1;
10084: } else {
10085: foreach my $field (@fields) {
10086: if ($names{$field} ne $oldnames{$field}) {
10087: $changed = 1;
10088: last;
10089: }
10090: }
10091: }
10092: unless ($changed) {
10093: $logmsg = 'No changes in user information needed for: '.$logmsg;
10094: &logthis($logmsg);
10095: return 'ok';
10096: }
10097: my $reply = &put('environment', \%names, $udom,$uname);
10098: if ($reply ne 'ok') {
10099: return 'error: '.$reply;
10100: }
1.1087 raeburn 10101: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10102: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10103: }
1.1075 raeburn 10104: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10105: &devalidate_cache_new('namescache',$uname.':'.$udom);
10106: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10107: &logthis($logmsg);
1.134 albertel 10108: return 'ok';
1.80 www 10109: }
10110:
1.81 www 10111: # -------------------------------------------------------------- Modify student
1.80 www 10112:
1.81 www 10113: sub modifystudent {
10114: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10115: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10116: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10117: if (!$cid) {
1.620 albertel 10118: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10119: return 'not_in_class';
10120: }
1.80 www 10121: }
10122: # --------------------------------------------------------------- Make the user
1.81 www 10123: my $reply=&modifyuser
1.209 matthew 10124: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10125: $desiredhome,$email,$inststatus);
1.80 www 10126: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10127: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10128: # student's environment
1.297 matthew 10129: $uid = undef if (!$forceid);
1.455 albertel 10130: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10131: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10132: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10133: return $reply;
10134: }
10135:
10136: sub modify_student_enrollment {
1.1172.2.23 raeburn 10137: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10138: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10139: my ($cdom,$cnum,$chome);
10140: if (!$cid) {
1.620 albertel 10141: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10142: return 'not_in_class';
10143: }
1.620 albertel 10144: $cdom=$env{'course.'.$cid.'.domain'};
10145: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10146: } else {
10147: ($cdom,$cnum)=split(/_/,$cid);
10148: }
1.620 albertel 10149: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10150: if (!$chome) {
1.457 raeburn 10151: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10152: }
1.455 albertel 10153: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10154: # Make sure the user exists
1.81 www 10155: my $uhome=&homeserver($uname,$udom);
10156: if (($uhome eq '') || ($uhome eq 'no_host')) {
10157: return 'error: no such user';
10158: }
1.297 matthew 10159: # Get student data if we were not given enough information
10160: if (!defined($first) || $first eq '' ||
10161: !defined($last) || $last eq '' ||
10162: !defined($uid) || $uid eq '' ||
10163: !defined($middle) || $middle eq '' ||
10164: !defined($gene) || $gene eq '') {
1.294 matthew 10165: # They did not supply us with enough data to enroll the student, so
10166: # we need to pick up more information.
1.297 matthew 10167: my %tmp = &get('environment',
1.294 matthew 10168: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10169: ,$udom,$uname);
10170:
1.800 albertel 10171: #foreach my $key (keys(%tmp)) {
10172: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10173: #}
1.294 matthew 10174: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10175: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10176: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10177: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10178: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10179: }
1.556 albertel 10180: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10181: my $user = "$uname:$udom";
10182: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10183: my $reply=cput('classlist',
1.1148 raeburn 10184: {$user =>
1.1172.2.76 raeburn 10185: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10186: $cdom,$cnum);
1.1148 raeburn 10187: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10188: &devalidate_getsection_cache($udom,$uname,$cid);
10189: } else {
1.81 www 10190: return 'error: '.$reply;
10191: }
1.297 matthew 10192: # Add student role to user
1.83 www 10193: my $uurl='/'.$cid;
1.81 www 10194: $uurl=~s/\_/\//g;
10195: if ($usec) {
10196: $uurl.='/'.$usec;
10197: }
1.1148 raeburn 10198: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10199: $selfenroll,$context);
10200: if ($result ne 'ok') {
10201: if ($old_entry{$user} ne '') {
10202: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10203: } else {
10204: $reply = &del('classlist',[$user],$cdom,$cnum);
10205: }
10206: }
10207: return $result;
1.21 www 10208: }
10209:
1.556 albertel 10210: sub format_name {
10211: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10212: my $name;
10213: if ($first ne 'lastname') {
10214: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10215: } else {
10216: if ($lastname=~/\S/) {
10217: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10218: $name=~s/\s+,/,/;
10219: } else {
10220: $name.= $firstname.' '.$middlename.' '.$generation;
10221: }
10222: }
10223: $name=~s/^\s+//;
10224: $name=~s/\s+$//;
10225: $name=~s/\s+/ /g;
10226: return $name;
10227: }
10228:
1.84 www 10229: # ------------------------------------------------- Write to course preferences
10230:
10231: sub writecoursepref {
10232: my ($courseid,%prefs)=@_;
10233: $courseid=~s/^\///;
10234: $courseid=~s/\_/\//g;
10235: my ($cdomain,$cnum)=split(/\//,$courseid);
10236: my $chome=homeserver($cnum,$cdomain);
10237: if (($chome eq '') || ($chome eq 'no_host')) {
10238: return 'error: no such course';
10239: }
10240: my $cstring='';
1.800 albertel 10241: foreach my $pref (keys(%prefs)) {
10242: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10243: }
1.84 www 10244: $cstring=~s/\&$//;
10245: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10246: }
10247:
10248: # ---------------------------------------------------------- Make/modify course
10249:
10250: sub createcourse {
1.741 raeburn 10251: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10252: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10253: $url=&declutter($url);
10254: my $cid='';
1.1028 raeburn 10255: if ($context eq 'requestcourses') {
10256: my $can_create = 0;
10257: my ($ownername,$ownerdom) = split(':',$course_owner);
10258: if ($udom eq $ownerdom) {
10259: if (&usertools_access($ownername,$ownerdom,$category,undef,
10260: $context)) {
10261: $can_create = 1;
10262: }
10263: } else {
10264: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10265: $category);
10266: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10267: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10268: if (@curr > 0) {
10269: my @options = qw(approval validate autolimit);
10270: my $optregex = join('|',@options);
10271: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10272: $can_create = 1;
10273: }
10274: }
10275: }
10276: }
10277: if ($can_create) {
10278: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10279: unless (&allowed('ccc',$udom)) {
10280: return 'refused';
10281: }
1.1017 raeburn 10282: }
10283: } else {
10284: return 'refused';
10285: }
1.1028 raeburn 10286: } elsif (!&allowed('ccc',$udom)) {
10287: return 'refused';
1.84 www 10288: }
1.1011 raeburn 10289: # --------------------------------------------------------------- Get Unique ID
10290: my $uname;
10291: if ($cnum =~ /^$match_courseid$/) {
10292: my $chome=&homeserver($cnum,$udom,'true');
10293: if (($chome eq '') || ($chome eq 'no_host')) {
10294: $uname = $cnum;
10295: } else {
1.1038 raeburn 10296: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10297: }
10298: } else {
1.1038 raeburn 10299: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10300: }
10301: return $uname if ($uname =~ /^error/);
10302: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10303: if (!defined($course_server)) {
10304: if (defined(&domain($udom,'primary'))) {
10305: $course_server = &domain($udom,'primary');
10306: } else {
10307: $course_server = $env{'user.home'};
10308: }
10309: }
10310: my %host_servers =
10311: &Apache::lonnet::get_servers($udom,'library');
10312: unless ($host_servers{$course_server}) {
10313: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10314: }
1.84 www 10315: # ------------------------------------------------------------- Make the course
10316: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10317: $course_server);
1.84 www 10318: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10319: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10320: if (($uhome eq '') || ($uhome eq 'no_host')) {
10321: return 'error: no such course';
10322: }
1.271 www 10323: # ----------------------------------------------------------------- Course made
1.516 raeburn 10324: # log existence
1.1029 raeburn 10325: my $now = time;
1.918 raeburn 10326: my $newcourse = {
10327: $udom.'_'.$uname => {
1.921 raeburn 10328: description => $description,
10329: inst_code => $inst_code,
10330: owner => $course_owner,
10331: type => $crstype,
1.1029 raeburn 10332: creator => $env{'user.name'}.':'.
10333: $env{'user.domain'},
10334: created => $now,
10335: context => $context,
1.918 raeburn 10336: },
10337: };
1.921 raeburn 10338: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10339: # set toplevel url
1.271 www 10340: my $topurl=$url;
10341: unless ($nonstandard) {
10342: # ------------------------------------------ For standard courses, make top url
10343: my $mapurl=&clutter($url);
1.278 www 10344: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10345: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10346: <map>
10347: <resource id="1" type="start"></resource>
10348: <resource id="2" src="$mapurl"></resource>
10349: <resource id="3" type="finish"></resource>
10350: <link index="1" from="1" to="2"></link>
10351: <link index="2" from="2" to="3"></link>
10352: </map>
10353: ENDINITMAP
10354: $topurl=&declutter(
1.638 albertel 10355: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10356: );
10357: }
10358: # ----------------------------------------------------------- Write preferences
1.84 www 10359: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10360: ('description' => $description,
10361: 'url' => $topurl,
10362: 'internal.creator' => $env{'user.name'}.':'.
10363: $env{'user.domain'},
10364: 'internal.created' => $now,
10365: 'internal.creationcontext' => $context)
10366: );
1.84 www 10367: return '/'.$udom.'/'.$uname;
10368: }
10369:
1.1011 raeburn 10370: # ------------------------------------------------------------------- Create ID
10371: sub generate_coursenum {
1.1038 raeburn 10372: my ($udom,$crstype) = @_;
1.1011 raeburn 10373: my $domdesc = &domain($udom);
10374: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10375: my $first;
10376: if ($crstype eq 'Community') {
10377: $first = '0';
10378: } else {
10379: $first = int(1+rand(9));
10380: }
10381: my $uname=$first.
1.1011 raeburn 10382: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10383: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10384: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10385: # ----------------------------------------------- Make sure that does not exist
10386: my $uhome=&homeserver($uname,$udom,'true');
10387: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10388: if ($crstype eq 'Community') {
10389: $first = '0';
10390: } else {
10391: $first = int(1+rand(9));
10392: }
10393: $uname=$first.
1.1011 raeburn 10394: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10395: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10396: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10397: $uhome=&homeserver($uname,$udom,'true');
10398: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10399: return 'error: unable to generate unique course-ID';
10400: }
10401: }
10402: return $uname;
10403: }
10404:
1.813 albertel 10405: sub is_course {
1.1167 droeschl 10406: my ($cdom, $cnum) = scalar(@_) == 1 ?
10407: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 10408: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10409: my $uhome=&homeserver($cnum,$cdom);
10410: my $iscourse;
10411: if (grep { $_ eq $uhome } current_machine_ids()) {
10412: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10413: } else {
10414: my $hashid = $cdom.':'.$cnum;
10415: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10416: unless (defined($cached)) {
10417: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10418: $cnum,undef,undef,'.');
10419: $iscourse = 0;
10420: if (exists($courses{$cdom.'_'.$cnum})) {
10421: $iscourse = 1;
10422: }
10423: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10424: }
10425: }
10426: return unless($iscourse);
1.1167 droeschl 10427: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10428: }
10429:
1.1015 raeburn 10430: sub store_userdata {
10431: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10432: my $result;
1.1016 raeburn 10433: if ($datakey ne '') {
1.1013 raeburn 10434: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10435: if ($udom eq '' || $uname eq '') {
10436: $udom = $env{'user.domain'};
10437: $uname = $env{'user.name'};
10438: }
10439: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10440: if (($uhome eq '') || ($uhome eq 'no_host')) {
10441: $result = 'error: no_host';
10442: } else {
10443: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10444: $storehash->{'host'} = $perlvar{'lonHostID'};
10445:
10446: my $namevalue='';
10447: foreach my $key (keys(%{$storehash})) {
10448: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10449: }
10450: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 10451: unless ($namespace eq 'courserequests') {
10452: $datakey = &escape($datakey);
10453: }
1.1105 raeburn 10454: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10455: $namevalue,$uhome);
1.1013 raeburn 10456: }
10457: } else {
10458: $result = 'error: data to store was not a hash reference';
10459: }
10460: } else {
10461: $result= 'error: invalid requestkey';
10462: }
10463: return $result;
10464: }
10465:
1.21 www 10466: # ---------------------------------------------------------- Assign Custom Role
10467:
10468: sub assigncustomrole {
1.957 raeburn 10469: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10470: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10471: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10472: }
10473:
10474: # ----------------------------------------------------------------- Revoke Role
10475:
10476: sub revokerole {
1.957 raeburn 10477: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10478: my $now=time;
1.965 raeburn 10479: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10480: }
10481:
10482: # ---------------------------------------------------------- Revoke Custom Role
10483:
10484: sub revokecustomrole {
1.957 raeburn 10485: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10486: my $now=time;
1.357 www 10487: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10488: $deleteflag,$selfenroll,$context);
1.17 www 10489: }
10490:
1.533 banghart 10491: # ------------------------------------------------------------ Disk usage
1.535 albertel 10492: sub diskusage {
1.955 raeburn 10493: my ($udom,$uname,$directorypath,$getpropath)=@_;
10494: $directorypath =~ s/\/$//;
10495: my $listing=&reply('du2:'.&escape($directorypath).':'
10496: .&escape($getpropath).':'.&escape($uname).':'
10497: .&escape($udom),homeserver($uname,$udom));
10498: if ($listing eq 'unknown_cmd') {
10499: if ($getpropath) {
10500: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10501: }
10502: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10503: }
1.514 albertel 10504: return $listing;
1.512 banghart 10505: }
10506:
1.566 banghart 10507: sub is_locked {
1.1096 raeburn 10508: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10509: my @check;
10510: my $is_locked;
1.1093 raeburn 10511: push (@check,$file_name);
1.613 albertel 10512: my %locked = &get('file_permissions',\@check,
1.620 albertel 10513: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10514: my ($tmp)=keys(%locked);
10515: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10516:
1.566 banghart 10517: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10518: $is_locked = 'false';
10519: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10520: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10521: $is_locked = 'true';
1.1096 raeburn 10522: if (ref($which) eq 'ARRAY') {
10523: push(@{$which},$entry);
10524: } else {
10525: last;
10526: }
1.745 raeburn 10527: }
10528: }
1.566 banghart 10529: } else {
10530: $is_locked = 'false';
10531: }
1.1093 raeburn 10532: return $is_locked;
1.566 banghart 10533: }
10534:
1.759 albertel 10535: sub declutter_portfile {
10536: my ($file) = @_;
1.833 albertel 10537: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10538: return $file;
10539: }
10540:
1.559 banghart 10541: # ------------------------------------------------------------- Mark as Read Only
10542:
10543: sub mark_as_readonly {
10544: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10545: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10546: my ($tmp)=keys(%current_permissions);
10547: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10548: foreach my $file (@{$files}) {
1.759 albertel 10549: $file = &declutter_portfile($file);
1.561 banghart 10550: push(@{$current_permissions{$file}},$what);
1.559 banghart 10551: }
1.613 albertel 10552: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10553: return;
10554: }
10555:
1.572 banghart 10556: # ------------------------------------------------------------Save Selected Files
10557:
10558: sub save_selected_files {
10559: my ($user, $path, @files) = @_;
10560: my $filename = $user."savedfiles";
1.573 banghart 10561: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 10562: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10563: foreach my $file (@files) {
1.620 albertel 10564: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10565: }
10566: foreach my $file (@other_files) {
1.574 banghart 10567: print (OUT $file."\n");
1.572 banghart 10568: }
1.574 banghart 10569: close (OUT);
1.572 banghart 10570: return 'ok';
10571: }
10572:
1.574 banghart 10573: sub clear_selected_files {
10574: my ($user) = @_;
10575: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 10576: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10577: print (OUT undef);
10578: close (OUT);
10579: return ("ok");
10580: }
10581:
1.572 banghart 10582: sub files_in_path {
10583: my ($user, $path) = @_;
10584: my $filename = $user."savedfiles";
10585: my %return_files;
1.1172.2.96 raeburn 10586: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10587: while (my $line_in = <IN>) {
1.574 banghart 10588: chomp ($line_in);
10589: my @paths_and_file = split (m!/!, $line_in);
10590: my $file_part = pop (@paths_and_file);
10591: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10592: $path_part.='/';
10593: my $path_and_file = $path_part.$file_part;
10594: if ($path_part eq $path) {
10595: $return_files{$file_part}= 'selected';
10596: }
10597: }
1.574 banghart 10598: close (IN);
10599: return (\%return_files);
1.572 banghart 10600: }
10601:
10602: # called in portfolio select mode, to show files selected NOT in current directory
10603: sub files_not_in_path {
10604: my ($user, $path) = @_;
10605: my $filename = $user."savedfiles";
10606: my @return_files;
10607: my $path_part;
1.1172.2.96 raeburn 10608: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10609: while (my $line = <IN>) {
1.572 banghart 10610: #ok, I know it's clunky, but I want it to work
1.800 albertel 10611: my @paths_and_file = split(m|/|, $line);
10612: my $file_part = pop(@paths_and_file);
10613: chomp($file_part);
10614: my $path_part = join('/', @paths_and_file);
1.572 banghart 10615: $path_part .= '/';
10616: my $path_and_file = $path_part.$file_part;
10617: if ($path_part ne $path) {
1.800 albertel 10618: push(@return_files, ($path_and_file));
1.572 banghart 10619: }
10620: }
1.800 albertel 10621: close(OUT);
1.574 banghart 10622: return (@return_files);
1.572 banghart 10623: }
10624:
1.745 raeburn 10625: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10626:
1.745 raeburn 10627: sub get_portfile_permissions {
10628: my ($domain,$user) = @_;
1.613 albertel 10629: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10630: my ($tmp)=keys(%current_permissions);
10631: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10632: return \%current_permissions;
10633: }
10634:
10635: #---------------------------------------------Get portfolio file access controls
10636:
1.749 raeburn 10637: sub get_access_controls {
1.745 raeburn 10638: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10639: my %access;
10640: my $real_file = $file;
10641: $file =~ s/\.meta$//;
1.745 raeburn 10642: if (defined($file)) {
1.749 raeburn 10643: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10644: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10645: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10646: }
10647: }
1.745 raeburn 10648: } else {
1.749 raeburn 10649: foreach my $key (keys(%{$current_permissions})) {
10650: if ($key =~ /\0accesscontrol$/) {
10651: if (defined($group)) {
10652: if ($key !~ m-^\Q$group\E/-) {
10653: next;
10654: }
10655: }
10656: my ($fullpath) = split(/\0/,$key);
10657: if (ref($$current_permissions{$key}) eq 'HASH') {
10658: foreach my $control (keys(%{$$current_permissions{$key}})) {
10659: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10660: }
10661: }
10662: }
10663: }
10664: }
10665: return %access;
10666: }
10667:
10668: sub modify_access_controls {
10669: my ($file_name,$changes,$domain,$user)=@_;
10670: my ($outcome,$deloutcome);
10671: my %store_permissions;
10672: my %new_values;
10673: my %new_control;
10674: my %translation;
10675: my @deletions = ();
10676: my $now = time;
10677: if (exists($$changes{'activate'})) {
10678: if (ref($$changes{'activate'}) eq 'HASH') {
10679: my @newitems = sort(keys(%{$$changes{'activate'}}));
10680: my $numnew = scalar(@newitems);
10681: for (my $i=0; $i<$numnew; $i++) {
10682: my $newkey = $newitems[$i];
10683: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10684: if ($newkey =~ /^\d+:/) {
10685: $newkey =~ s/^(\d+)/$newid/;
10686: $translation{$1} = $newid;
10687: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10688: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10689: $translation{$1} = $newid;
10690: }
1.749 raeburn 10691: $new_values{$file_name."\0".$newkey} =
10692: $$changes{'activate'}{$newitems[$i]};
10693: $new_control{$newkey} = $now;
10694: }
10695: }
10696: }
10697: my %todelete;
10698: my %changed_items;
10699: foreach my $action ('delete','update') {
10700: if (exists($$changes{$action})) {
10701: if (ref($$changes{$action}) eq 'HASH') {
10702: foreach my $key (keys(%{$$changes{$action}})) {
10703: my ($itemnum) = ($key =~ /^([^:]+):/);
10704: if ($action eq 'delete') {
10705: $todelete{$itemnum} = 1;
10706: } else {
10707: $changed_items{$itemnum} = $key;
10708: }
10709: }
1.745 raeburn 10710: }
10711: }
1.749 raeburn 10712: }
10713: # get lock on access controls for file.
10714: my $lockhash = {
10715: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10716: ':'.$env{'user.domain'},
10717: };
10718: my $tries = 0;
10719: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10720:
1.1172.2.79 raeburn 10721: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10722: $tries ++;
1.1172.2.79 raeburn 10723: sleep(0.1);
1.749 raeburn 10724: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10725: }
10726: if ($gotlock eq 'ok') {
10727: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10728: my ($tmp)=keys(%curr_permissions);
10729: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10730: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10731: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10732: if (ref($curr_controls) eq 'HASH') {
10733: foreach my $control_item (keys(%{$curr_controls})) {
10734: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10735: if (defined($todelete{$itemnum})) {
10736: push(@deletions,$file_name."\0".$control_item);
10737: } else {
10738: if (defined($changed_items{$itemnum})) {
10739: $new_control{$changed_items{$itemnum}} = $now;
10740: push(@deletions,$file_name."\0".$control_item);
10741: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10742: } else {
10743: $new_control{$control_item} = $$curr_controls{$control_item};
10744: }
10745: }
1.745 raeburn 10746: }
10747: }
10748: }
1.970 raeburn 10749: my ($group);
10750: if (&is_course($domain,$user)) {
10751: ($group,my $file) = split(/\//,$file_name,2);
10752: }
1.749 raeburn 10753: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10754: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10755: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10756: # remove lock
10757: my @del_lock = ($file_name."\0".'locked_access_records');
10758: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10759: my $sqlresult =
1.970 raeburn 10760: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10761: $group);
1.749 raeburn 10762: } else {
10763: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10764: }
1.749 raeburn 10765: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10766: }
10767:
1.827 raeburn 10768: sub make_public_indefinitely {
10769: my ($requrl) = @_;
10770: my $now = time;
10771: my $action = 'activate';
10772: my $aclnum = 0;
10773: if (&is_portfolio_url($requrl)) {
10774: my (undef,$udom,$unum,$file_name,$group) =
10775: &parse_portfolio_url($requrl);
10776: my $current_perms = &get_portfile_permissions($udom,$unum);
10777: my %access_controls = &get_access_controls($current_perms,
10778: $group,$file_name);
10779: foreach my $key (keys(%{$access_controls{$file_name}})) {
10780: my ($num,$scope,$end,$start) =
10781: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10782: if ($scope eq 'public') {
10783: if ($start <= $now && $end == 0) {
10784: $action = 'none';
10785: } else {
10786: $action = 'update';
10787: $aclnum = $num;
10788: }
10789: last;
10790: }
10791: }
10792: if ($action eq 'none') {
10793: return 'ok';
10794: } else {
10795: my %changes;
10796: my $newend = 0;
10797: my $newstart = $now;
10798: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10799: $changes{$action}{$newkey} = {
10800: type => 'public',
10801: time => {
10802: start => $newstart,
10803: end => $newend,
10804: },
10805: };
10806: my ($outcome,$deloutcome,$new_values,$translation) =
10807: &modify_access_controls($file_name,\%changes,$udom,$unum);
10808: return $outcome;
10809: }
10810: } else {
10811: return 'invalid';
10812: }
10813: }
10814:
1.745 raeburn 10815: #------------------------------------------------------Get Marked as Read Only
10816:
10817: sub get_marked_as_readonly {
10818: my ($domain,$user,$what,$group) = @_;
10819: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10820: my @readonly_files;
1.629 banghart 10821: my $cmp1=$what;
10822: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10823: while (my ($file_name,$value) = each(%{$current_permissions})) {
10824: if (defined($group)) {
10825: if ($file_name !~ m-^\Q$group\E/-) {
10826: next;
10827: }
10828: }
1.561 banghart 10829: if (ref($value) eq "ARRAY"){
10830: foreach my $stored_what (@{$value}) {
1.629 banghart 10831: my $cmp2=$stored_what;
1.759 albertel 10832: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10833: $cmp2=join('',@{$stored_what});
1.745 raeburn 10834: }
1.629 banghart 10835: if ($cmp1 eq $cmp2) {
1.561 banghart 10836: push(@readonly_files, $file_name);
1.745 raeburn 10837: last;
1.563 banghart 10838: } elsif (!defined($what)) {
10839: push(@readonly_files, $file_name);
1.745 raeburn 10840: last;
1.561 banghart 10841: }
10842: }
1.745 raeburn 10843: }
1.561 banghart 10844: }
10845: return @readonly_files;
10846: }
1.577 banghart 10847: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10848:
1.577 banghart 10849: sub get_marked_as_readonly_hash {
1.745 raeburn 10850: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10851: my %readonly_files;
1.745 raeburn 10852: while (my ($file_name,$value) = each(%{$current_permissions})) {
10853: if (defined($group)) {
10854: if ($file_name !~ m-^\Q$group\E/-) {
10855: next;
10856: }
10857: }
1.577 banghart 10858: if (ref($value) eq "ARRAY"){
10859: foreach my $stored_what (@{$value}) {
1.745 raeburn 10860: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10861: foreach my $lock_descriptor(@{$stored_what}) {
10862: if ($lock_descriptor eq 'graded') {
10863: $readonly_files{$file_name} = 'graded';
10864: } elsif ($lock_descriptor eq 'handback') {
10865: $readonly_files{$file_name} = 'handback';
10866: } else {
10867: if (!exists($readonly_files{$file_name})) {
10868: $readonly_files{$file_name} = 'locked';
10869: }
10870: }
1.745 raeburn 10871: }
1.750 banghart 10872: }
1.577 banghart 10873: }
10874: }
10875: }
10876: return %readonly_files;
10877: }
1.559 banghart 10878: # ------------------------------------------------------------ Unmark as Read Only
10879:
10880: sub unmark_as_readonly {
1.629 banghart 10881: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10882: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10883: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10884: $file_name = &declutter_portfile($file_name);
1.634 albertel 10885: my $symb_crs = $what;
10886: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10887: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10888: my ($tmp)=keys(%current_permissions);
10889: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10890: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10891: foreach my $file (@readonly_files) {
1.759 albertel 10892: my $clean_file = &declutter_portfile($file);
10893: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10894: my $current_locks = $current_permissions{$file};
1.563 banghart 10895: my @new_locks;
10896: my @del_keys;
10897: if (ref($current_locks) eq "ARRAY"){
10898: foreach my $locker (@{$current_locks}) {
1.632 albertel 10899: my $compare=$locker;
1.749 raeburn 10900: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10901: $compare=join('',@{$locker});
1.746 raeburn 10902: if ($compare ne $symb_crs) {
10903: push(@new_locks, $locker);
10904: }
1.563 banghart 10905: }
10906: }
1.650 albertel 10907: if (scalar(@new_locks) > 0) {
1.563 banghart 10908: $current_permissions{$file} = \@new_locks;
10909: } else {
10910: push(@del_keys, $file);
1.613 albertel 10911: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10912: delete($current_permissions{$file});
1.563 banghart 10913: }
10914: }
1.561 banghart 10915: }
1.613 albertel 10916: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10917: return;
10918: }
1.512 banghart 10919:
1.17 www 10920: # ------------------------------------------------------------ Directory lister
10921:
10922: sub dirlist {
1.955 raeburn 10923: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10924: $uri=~s/^\///;
10925: $uri=~s/\/$//;
1.253 stredwic 10926: my ($udom, $uname);
1.955 raeburn 10927: if ($getuserdir) {
1.253 stredwic 10928: $udom = $userdomain;
10929: $uname = $username;
1.955 raeburn 10930: } else {
10931: (undef,$udom,$uname)=split(/\//,$uri);
10932: if(defined($userdomain)) {
10933: $udom = $userdomain;
10934: }
10935: if(defined($username)) {
10936: $uname = $username;
10937: }
1.253 stredwic 10938: }
1.955 raeburn 10939: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10940:
1.955 raeburn 10941: $dirRoot = $perlvar{'lonDocRoot'};
10942: if (defined($getpropath)) {
10943: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10944: $dirRoot =~ s/\/$//;
1.955 raeburn 10945: } elsif (defined($getuserdir)) {
10946: my $subdir=$uname.'__';
10947: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10948: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10949: ."/$udom/$subdir/$uname";
10950: } elsif (defined($alternateRoot)) {
10951: $dirRoot = $alternateRoot;
1.751 banghart 10952: }
1.253 stredwic 10953:
10954: if($udom) {
10955: if($uname) {
1.1135 raeburn 10956: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10957: if ($uhome eq 'no_host') {
10958: return ([],'no_host');
10959: }
1.955 raeburn 10960: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10961: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10962: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10963: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10964: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10965: } else {
10966: @listing_results = map { &unescape($_); } split(/:/,$listing);
10967: }
1.605 matthew 10968: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10969: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10970: @listing_results = split(/:/,$listing);
10971: } else {
10972: @listing_results = map { &unescape($_); } split(/:/,$listing);
10973: }
1.1135 raeburn 10974: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10975: ($listing eq 'rejected') || ($listing eq 'refused') ||
10976: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10977: return ([],$listing);
10978: } else {
10979: return (\@listing_results);
1.1135 raeburn 10980: }
1.955 raeburn 10981: } elsif(!$alternateRoot) {
1.1136 raeburn 10982: my (%allusers,%listerror);
1.841 albertel 10983: my %servers = &get_servers($udom,'library');
1.955 raeburn 10984: foreach my $tryserver (keys(%servers)) {
10985: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10986: &escape($udom),$tryserver);
10987: if ($listing eq 'unknown_cmd') {
10988: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10989: $udom, $tryserver);
10990: } else {
10991: @listing_results = map { &unescape($_); } split(/:/,$listing);
10992: }
1.841 albertel 10993: if ($listing eq 'unknown_cmd') {
10994: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10995: $udom, $tryserver);
10996: @listing_results = split(/:/,$listing);
10997: } else {
10998: @listing_results =
10999: map { &unescape($_); } split(/:/,$listing);
11000: }
1.1136 raeburn 11001: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11002: ($listing eq 'rejected') || ($listing eq 'refused') ||
11003: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11004: $listerror{$tryserver} = $listing;
11005: } else {
1.841 albertel 11006: foreach my $line (@listing_results) {
11007: my ($entry) = split(/&/,$line,2);
11008: $allusers{$entry} = 1;
11009: }
11010: }
1.253 stredwic 11011: }
1.1136 raeburn 11012: my @alluserslist=();
1.800 albertel 11013: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11014: push(@alluserslist,$user.'&user');
1.253 stredwic 11015: }
1.1172.2.80 raeburn 11016: if (!%listerror) {
11017: # no errors
11018: return (\@alluserslist);
11019: } elsif (scalar(keys(%servers)) == 1) {
11020: # one library server, one error
11021: my ($key) = keys(%listerror);
11022: return (\@alluserslist, $listerror{$key});
11023: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11024: # con_lost indicates that we might miss data from at least one
11025: # library server
11026: return (\@alluserslist, 'con_lost');
11027: } else {
11028: # multiple library servers and no con_lost -> data should be
11029: # complete.
11030: return (\@alluserslist);
11031: }
11032:
1.253 stredwic 11033: } else {
1.1136 raeburn 11034: return ([],'missing username');
1.253 stredwic 11035: }
1.955 raeburn 11036: } elsif(!defined($getpropath)) {
1.1136 raeburn 11037: my $path = $perlvar{'lonDocRoot'}.'/res/';
11038: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11039: return (\@all_domains);
1.955 raeburn 11040: } else {
1.1136 raeburn 11041: return ([],'missing domain');
1.275 stredwic 11042: }
11043: }
11044:
11045: # --------------------------------------------- GetFileTimestamp
11046: # This function utilizes dirlist and returns the date stamp for
11047: # when it was last modified. It will also return an error of -1
11048: # if an error occurs
11049:
11050: sub GetFileTimestamp {
1.955 raeburn 11051: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11052: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11053: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11054: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11055: undef,$getuserdir);
11056: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11057: return -1;
11058: }
11059: if (ref($fileref) eq 'ARRAY') {
11060: my @stats = split('&',$fileref->[0]);
1.375 matthew 11061: # @stats contains first the filename, then the stat output
11062: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11063: } else {
11064: return -1;
1.253 stredwic 11065: }
1.26 www 11066: }
11067:
1.712 albertel 11068: sub stat_file {
11069: my ($uri) = @_;
1.787 albertel 11070: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11071:
1.955 raeburn 11072: my ($udom,$uname,$file);
1.712 albertel 11073: if ($uri =~ m-^/(uploaded|editupload)/-) {
11074: ($udom,$uname,$file) =
1.811 albertel 11075: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11076: $file = 'userfiles/'.$file;
11077: }
11078: if ($uri =~ m-^/res/-) {
11079: ($udom,$uname) =
1.807 albertel 11080: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11081: $file = $uri;
11082: }
11083:
11084: if (!$udom || !$uname || !$file) {
11085: # unable to handle the uri
11086: return ();
11087: }
1.956 raeburn 11088: my $getpropath;
11089: if ($file =~ /^userfiles\//) {
11090: $getpropath = 1;
11091: }
1.1136 raeburn 11092: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11093: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11094: return ();
11095: } else {
11096: if (ref($listref) eq 'ARRAY') {
11097: my @stats = split('&',$listref->[0]);
11098: shift(@stats); #filename is first
11099: return @stats;
11100: }
1.712 albertel 11101: }
11102: return ();
11103: }
11104:
1.26 www 11105: # -------------------------------------------------------- Value of a Condition
11106:
1.713 albertel 11107: # gets the value of a specific preevaluated condition
11108: # stored in the string $env{user.state.<cid>}
11109: # or looks up a condition reference in the bighash and if if hasn't
11110: # already been evaluated recurses into docondval to get the value of
11111: # the condition, then memoizing it to
11112: # $env{user.state.<cid>.<condition>}
1.40 www 11113: sub directcondval {
11114: my $number=shift;
1.620 albertel 11115: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11116: &Apache::lonuserstate::evalstate();
11117: }
1.713 albertel 11118: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11119: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11120: } elsif ($number =~ /^_/) {
11121: my $sub_condition;
11122: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11123: &GDBM_READER(),0640)) {
11124: $sub_condition=$bighash{'conditions'.$number};
11125: untie(%bighash);
11126: }
11127: my $value = &docondval($sub_condition);
1.949 raeburn 11128: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11129: return $value;
11130: }
1.620 albertel 11131: if ($env{'user.state.'.$env{'request.course.id'}}) {
11132: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11133: } else {
11134: return 2;
11135: }
11136: }
11137:
1.713 albertel 11138: # get the collection of conditions for this resource
1.26 www 11139: sub condval {
11140: my $condidx=shift;
1.54 www 11141: my $allpathcond='';
1.713 albertel 11142: foreach my $cond (split(/\|/,$condidx)) {
11143: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11144: $allpathcond.=
11145: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11146: }
1.191 harris41 11147: }
1.54 www 11148: $allpathcond=~s/\|$//;
1.713 albertel 11149: return &docondval($allpathcond);
11150: }
11151:
11152: #evaluates an expression of conditions
11153: sub docondval {
11154: my ($allpathcond) = @_;
11155: my $result=0;
11156: if ($env{'request.course.id'}
11157: && defined($allpathcond)) {
11158: my $operand='|';
11159: my @stack;
11160: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11161: if ($chunk eq '(') {
11162: push @stack,($operand,$result);
11163: } elsif ($chunk eq ')') {
11164: my $before=pop @stack;
11165: if (pop @stack eq '&') {
11166: $result=$result>$before?$before:$result;
11167: } else {
11168: $result=$result>$before?$result:$before;
11169: }
11170: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11171: $operand=$chunk;
11172: } else {
11173: my $new=directcondval($chunk);
11174: if ($operand eq '&') {
11175: $result=$result>$new?$new:$result;
11176: } else {
11177: $result=$result>$new?$result:$new;
11178: }
11179: }
11180: }
1.26 www 11181: }
11182: return $result;
1.421 albertel 11183: }
11184:
11185: # ---------------------------------------------------- Devalidate courseresdata
11186:
11187: sub devalidatecourseresdata {
11188: my ($coursenum,$coursedomain)=@_;
11189: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11190: &devalidate_cache_new('courseres',$hashid);
1.28 www 11191: }
11192:
1.763 www 11193:
1.200 www 11194: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11195: #
11196: # Parameters:
11197: # $coursenum - Number of the course.
11198: # $coursedomain - Domain at which the course was created.
11199: # Returns:
11200: # A hash of the course parameters along (I think) with timestamps
11201: # and version info.
1.877 foxr 11202:
1.624 albertel 11203: sub get_courseresdata {
11204: my ($coursenum,$coursedomain)=@_;
1.200 www 11205: my $coursehom=&homeserver($coursenum,$coursedomain);
11206: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11207: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11208: my %dumpreply;
1.417 albertel 11209: unless (defined($cached)) {
1.624 albertel 11210: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11211: $result=\%dumpreply;
1.251 albertel 11212: my ($tmp) = keys(%dumpreply);
11213: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11214: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11215: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11216: return $tmp;
1.416 albertel 11217: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11218: $result=undef;
1.599 albertel 11219: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11220: }
11221: }
1.624 albertel 11222: return $result;
11223: }
11224:
1.633 albertel 11225: sub devalidateuserresdata {
11226: my ($uname,$udom)=@_;
11227: my $hashid="$udom:$uname";
11228: &devalidate_cache_new('userres',$hashid);
11229: }
11230:
1.624 albertel 11231: sub get_userresdata {
11232: my ($uname,$udom)=@_;
11233: #most student don\'t have any data set, check if there is some data
11234: if (&EXT_cache_status($udom,$uname)) { return undef; }
11235:
11236: my $hashid="$udom:$uname";
11237: my ($result,$cached)=&is_cached_new('userres',$hashid);
11238: if (!defined($cached)) {
11239: my %resourcedata=&dump('resourcedata',$udom,$uname);
11240: $result=\%resourcedata;
11241: &do_cache_new('userres',$hashid,$result,600);
11242: }
11243: my ($tmp)=keys(%$result);
11244: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11245: return $result;
11246: }
11247: #error 2 occurs when the .db doesn't exist
11248: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 11249: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11250: &logthis("<font color=\"blue\">WARNING:".
11251: " Trying to get resource data for ".
11252: $uname." at ".$udom.": ".
11253: $tmp."</font>");
11254: }
1.624 albertel 11255: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11256: #&EXT_cache_set($udom,$uname);
11257: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11258: undef($tmp); # not really an error so don't send it back
1.624 albertel 11259: }
11260: return $tmp;
11261: }
1.879 foxr 11262: #----------------------------------------------- resdata - return resource data
11263: # Purpose:
11264: # Return resource data for either users or for a course.
11265: # Parameters:
11266: # $name - Course/user name.
11267: # $domain - Name of the domain the user/course is registered on.
11268: # $type - Type of thing $name is (must be 'course' or 'user'
11269: # @which - Array of names of resources desired.
11270: # Returns:
11271: # The value of the first reasource in @which that is found in the
11272: # resource hash.
11273: # Exceptional Conditions:
11274: # If the $type passed in is not valid (not the string 'course' or
11275: # 'user', an undefined reference is returned.
11276: # If none of the resources are found, an undef is returned
1.624 albertel 11277: sub resdata {
11278: my ($name,$domain,$type,@which)=@_;
11279: my $result;
11280: if ($type eq 'course') {
11281: $result=&get_courseresdata($name,$domain);
11282: } elsif ($type eq 'user') {
11283: $result=&get_userresdata($name,$domain);
11284: }
11285: if (!ref($result)) { return $result; }
1.251 albertel 11286: foreach my $item (@which) {
1.927 albertel 11287: if (defined($result->{$item->[0]})) {
11288: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11289: }
1.250 albertel 11290: }
1.291 albertel 11291: return undef;
1.200 www 11292: }
11293:
1.1172.2.31 raeburn 11294: sub get_numsuppfiles {
11295: my ($cnum,$cdom,$ignorecache)=@_;
11296: my $hashid=$cnum.':'.$cdom;
11297: my ($suppcount,$cached);
11298: unless ($ignorecache) {
11299: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11300: }
11301: unless (defined($cached)) {
11302: my $chome=&homeserver($cnum,$cdom);
11303: unless ($chome eq 'no_host') {
11304: ($suppcount,my $errors) = (0,0);
11305: my $suppmap = 'supplemental.sequence';
11306: ($suppcount,$errors) =
11307: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11308: }
11309: &do_cache_new('suppcount',$hashid,$suppcount,600);
11310: }
11311: return $suppcount;
11312: }
11313:
1.379 matthew 11314: #
11315: # EXT resource caching routines
11316: #
11317:
11318: sub clear_EXT_cache_status {
1.383 albertel 11319: &delenv('cache.EXT.');
1.379 matthew 11320: }
11321:
11322: sub EXT_cache_status {
11323: my ($target_domain,$target_user) = @_;
1.383 albertel 11324: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11325: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11326: # We know already the user has no data
11327: return 1;
11328: } else {
11329: return 0;
11330: }
11331: }
11332:
11333: sub EXT_cache_set {
11334: my ($target_domain,$target_user) = @_;
1.383 albertel 11335: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11336: #&appenv({$cachename => time});
1.379 matthew 11337: }
11338:
1.28 www 11339: # --------------------------------------------------------- Value of a Variable
1.58 www 11340: sub EXT {
1.715 albertel 11341:
1.1172.2.28 raeburn 11342: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11343: unless ($varname) { return ''; }
1.218 albertel 11344: #get real user name/domain, courseid and symb
11345: my $courseid;
1.359 albertel 11346: my $publicuser;
1.427 www 11347: if ($symbparm) {
11348: $symbparm=&get_symb_from_alias($symbparm);
11349: }
1.218 albertel 11350: if (!($uname && $udom)) {
1.790 albertel 11351: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11352: if (!$symbparm) { $symbparm=$cursymb; }
11353: } else {
1.620 albertel 11354: $courseid=$env{'request.course.id'};
1.218 albertel 11355: }
1.48 www 11356: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11357: my $rest;
1.320 albertel 11358: if (defined($therest[0])) {
1.48 www 11359: $rest=join('.',@therest);
11360: } else {
11361: $rest='';
11362: }
1.320 albertel 11363:
1.57 www 11364: my $qualifierrest=$qualifier;
11365: if ($rest) { $qualifierrest.='.'.$rest; }
11366: my $spacequalifierrest=$space;
11367: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11368: if ($realm eq 'user') {
1.48 www 11369: # --------------------------------------------------------------- user.resource
11370: if ($space eq 'resource') {
1.651 albertel 11371: if ( (defined($Apache::lonhomework::parsing_a_problem)
11372: || defined($Apache::lonhomework::parsing_a_task))
11373: &&
1.744 albertel 11374: ($symbparm eq &symbread()) ) {
11375: # if we are in the middle of processing the resource the
11376: # get the value we are planning on committing
11377: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11378: return $Apache::lonhomework::results{$qualifierrest};
11379: } else {
11380: return $Apache::lonhomework::history{$qualifierrest};
11381: }
1.335 albertel 11382: } else {
1.359 albertel 11383: my %restored;
1.620 albertel 11384: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11385: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11386: } else {
11387: %restored=&restore($symbparm,$courseid,$udom,$uname);
11388: }
1.335 albertel 11389: return $restored{$qualifierrest};
11390: }
1.48 www 11391: # ----------------------------------------------------------------- user.access
11392: } elsif ($space eq 'access') {
1.218 albertel 11393: # FIXME - not supporting calls for a specific user
1.48 www 11394: return &allowed($qualifier,$rest);
11395: # ------------------------------------------ user.preferences, user.environment
11396: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11397: if (($uname eq $env{'user.name'}) &&
11398: ($udom eq $env{'user.domain'})) {
11399: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11400: } else {
1.359 albertel 11401: my %returnhash;
11402: if (!$publicuser) {
11403: %returnhash=&userenvironment($udom,$uname,
11404: $qualifierrest);
11405: }
1.218 albertel 11406: return $returnhash{$qualifierrest};
11407: }
1.48 www 11408: # ----------------------------------------------------------------- user.course
11409: } elsif ($space eq 'course') {
1.218 albertel 11410: # FIXME - not supporting calls for a specific user
1.620 albertel 11411: return $env{join('.',('request.course',$qualifier))};
1.48 www 11412: # ------------------------------------------------------------------- user.role
11413: } elsif ($space eq 'role') {
1.218 albertel 11414: # FIXME - not supporting calls for a specific user
1.620 albertel 11415: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11416: if ($qualifier eq 'value') {
11417: return $role;
11418: } elsif ($qualifier eq 'extent') {
11419: return $where;
11420: }
11421: # ----------------------------------------------------------------- user.domain
11422: } elsif ($space eq 'domain') {
1.218 albertel 11423: return $udom;
1.48 www 11424: # ------------------------------------------------------------------- user.name
11425: } elsif ($space eq 'name') {
1.218 albertel 11426: return $uname;
1.48 www 11427: # ---------------------------------------------------- Any other user namespace
1.29 www 11428: } else {
1.359 albertel 11429: my %reply;
11430: if (!$publicuser) {
11431: %reply=&get($space,[$qualifierrest],$udom,$uname);
11432: }
11433: return $reply{$qualifierrest};
1.48 www 11434: }
1.236 www 11435: } elsif ($realm eq 'query') {
11436: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11437: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11438: [$spacequalifierrest]);
1.620 albertel 11439: return $env{'form.'.$spacequalifierrest};
1.236 www 11440: } elsif ($realm eq 'request') {
1.48 www 11441: # ------------------------------------------------------------- request.browser
11442: if ($space eq 'browser') {
1.1145 bisitz 11443: return $env{'browser.'.$qualifier};
1.57 www 11444: # ------------------------------------------------------------ request.filename
11445: } else {
1.620 albertel 11446: return $env{'request.'.$spacequalifierrest};
1.29 www 11447: }
1.28 www 11448: } elsif ($realm eq 'course') {
1.48 www 11449: # ---------------------------------------------------------- course.description
1.620 albertel 11450: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11451: } elsif ($realm eq 'resource') {
1.165 www 11452:
1.620 albertel 11453: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11454: if (!$symbparm) { $symbparm=&symbread(); }
11455: }
1.693 albertel 11456:
1.1172.2.30 raeburn 11457: if ($qualifier eq '') {
11458: if ($space eq 'title') {
11459: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11460: return &gettitle($symbparm);
11461: }
1.693 albertel 11462:
1.1172.2.30 raeburn 11463: if ($space eq 'map') {
11464: my ($map) = &decode_symb($symbparm);
11465: return &symbread($map);
11466: }
11467: if ($space eq 'maptitle') {
11468: my ($map) = &decode_symb($symbparm);
11469: return &gettitle($map);
11470: }
11471: if ($space eq 'filename') {
11472: if ($symbparm) {
11473: return &clutter((&decode_symb($symbparm))[2]);
11474: }
11475: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11476: }
1.1172.2.30 raeburn 11477:
11478: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11479: if ($space eq 'visibleparts') {
11480: my $navmap = Apache::lonnavmaps::navmap->new();
11481: my $item;
11482: if (ref($navmap)) {
11483: my $res = $navmap->getBySymb($symbparm);
11484: my $parts = $res->parts();
11485: if (ref($parts) eq 'ARRAY') {
11486: $item = join(',',@{$parts});
11487: }
11488: undef($navmap);
11489: }
11490: return $item;
11491: }
11492: }
11493: }
1.693 albertel 11494:
11495: my ($section, $group, @groups);
1.593 albertel 11496: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 11497: if (($courseid eq '') && ($cid)) {
11498: $courseid = $cid;
11499: }
11500: if (($symbparm && $courseid) &&
11501: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11502:
1.218 albertel 11503: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11504:
1.60 www 11505: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11506: my $symbp=$symbparm;
1.735 albertel 11507: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11508:
11509: my $symbparm=$symbp.'.'.$spacequalifierrest;
11510: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11511:
1.620 albertel 11512: if (($env{'user.name'} eq $uname) &&
11513: ($env{'user.domain'} eq $udom)) {
11514: $section=$env{'request.course.sec'};
1.733 raeburn 11515: @groups = split(/:/,$env{'request.course.groups'});
11516: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11517: } else {
1.539 albertel 11518: if (! defined($usection)) {
1.551 albertel 11519: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11520: } else {
11521: $section = $usection;
11522: }
1.733 raeburn 11523: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11524: }
11525:
11526: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11527: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11528: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11529:
1.593 albertel 11530: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11531: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 11532: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11533:
1.60 www 11534: # ----------------------------------------------------------- first, check user
1.624 albertel 11535:
11536: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 11537: ([$courselevelr,'resource'],
11538: [$courselevelm,'map' ],
11539: [$courselevel, 'course' ]));
1.931 albertel 11540: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11541:
1.594 albertel 11542: # ------------------------------------------------ second, check some of course
1.684 raeburn 11543: my $coursereply;
1.691 raeburn 11544: if (@groups > 0) {
11545: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11546: $mapparm,$spacequalifierrest);
1.927 albertel 11547: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11548: }
1.96 www 11549:
1.684 raeburn 11550: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11551: $env{'course.'.$courseid.'.domain'},
11552: 'course',
11553: ([$seclevelr, 'resource'],
11554: [$seclevelm, 'map' ],
11555: [$seclevel, 'course' ],
11556: [$courselevelr,'resource']));
11557: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11558:
1.60 www 11559: # ------------------------------------------------------ third, check map parms
1.218 albertel 11560: my %parmhash=();
11561: my $thisparm='';
11562: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11563: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11564: &GDBM_READER(),0640)) {
1.218 albertel 11565: $thisparm=$parmhash{$symbparm};
11566: untie(%parmhash);
11567: }
1.927 albertel 11568: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11569: }
1.594 albertel 11570: # ------------------------------------------ fourth, look in resource metadata
1.71 www 11571:
1.218 albertel 11572: $spacequalifierrest=~s/\./\_/;
1.282 albertel 11573: my $filename;
11574: if (!$symbparm) { $symbparm=&symbread(); }
11575: if ($symbparm) {
1.409 www 11576: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11577: } else {
1.620 albertel 11578: $filename=$env{'request.filename'};
1.282 albertel 11579: }
11580: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 11581: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 11582: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 11583: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11584:
1.927 albertel 11585: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 11586: if ($symbparm && defined($courseid) &&
1.620 albertel 11587: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11588: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11589: $env{'course.'.$courseid.'.domain'},
11590: 'course',
1.927 albertel 11591: ([$courselevelm,'map' ],
11592: [$courselevel, 'course']));
11593: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11594: }
1.145 www 11595: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11596: unless ($space eq '0') {
1.336 albertel 11597: my @parts=split(/_/,$space);
11598: my $id=pop(@parts);
11599: my $part=join('_',@parts);
11600: if ($part eq '') { $part='0'; }
1.927 albertel 11601: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11602: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11603: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11604: }
1.395 albertel 11605: if ($recurse) { return undef; }
11606: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11607: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11608: # ---------------------------------------------------- Any other user namespace
11609: } elsif ($realm eq 'environment') {
11610: # ----------------------------------------------------------------- environment
1.620 albertel 11611: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11612: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11613: } else {
1.770 albertel 11614: if ($uname eq 'anonymous' && $udom eq '') {
11615: return '';
11616: }
1.219 albertel 11617: my %returnhash=&userenvironment($udom,$uname,
11618: $spacequalifierrest);
11619: return $returnhash{$spacequalifierrest};
11620: }
1.28 www 11621: } elsif ($realm eq 'system') {
1.48 www 11622: # ----------------------------------------------------------------- system.time
11623: if ($space eq 'time') {
11624: return time;
11625: }
1.696 albertel 11626: } elsif ($realm eq 'server') {
11627: # ----------------------------------------------------------------- system.time
11628: if ($space eq 'name') {
11629: return $ENV{'SERVER_NAME'};
11630: }
1.28 www 11631: }
1.48 www 11632: return '';
1.61 www 11633: }
11634:
1.927 albertel 11635: sub get_reply {
11636: my ($reply_value) = @_;
1.940 raeburn 11637: if (ref($reply_value) eq 'ARRAY') {
11638: if (wantarray) {
11639: return @$reply_value;
11640: }
11641: return $reply_value->[0];
11642: } else {
11643: return $reply_value;
1.927 albertel 11644: }
11645: }
11646:
1.691 raeburn 11647: sub check_group_parms {
11648: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11649: my @groupitems = ();
11650: my $resultitem;
1.927 albertel 11651: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11652: foreach my $group (@{$groups}) {
11653: foreach my $level (@levels) {
1.927 albertel 11654: my $item = $courseid.'.['.$group.'].'.$level->[0];
11655: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11656: }
11657: }
11658: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11659: $env{'course.'.$courseid.'.domain'},
11660: 'course',@groupitems);
11661: return $coursereply;
11662: }
11663:
11664: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11665: my ($courseid,@groups) = @_;
11666: @groups = sort(@groups);
1.691 raeburn 11667: return @groups;
11668: }
11669:
1.395 albertel 11670: sub packages_tab_default {
11671: my ($uri,$varname)=@_;
11672: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11673:
11674: my (@extension,@specifics,$do_default);
11675: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11676: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11677: if ($pack_type eq 'default') {
11678: $do_default=1;
11679: } elsif ($pack_type eq 'extension') {
11680: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11681: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11682: # only look at packages defaults for packages that this id is
1.738 albertel 11683: push(@specifics,[$package,$pack_type,$pack_part]);
11684: }
11685: }
11686: # first look for a package that matches the requested part id
11687: foreach my $package (@specifics) {
11688: my (undef,$pack_type,$pack_part)=@{$package};
11689: next if ($pack_part ne $part);
11690: if (defined($packagetab{"$pack_type&$name&default"})) {
11691: return $packagetab{"$pack_type&$name&default"};
11692: }
11693: }
11694: # look for any possible matching non extension_ package
11695: foreach my $package (@specifics) {
11696: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11697: if (defined($packagetab{"$pack_type&$name&default"})) {
11698: return $packagetab{"$pack_type&$name&default"};
11699: }
1.585 albertel 11700: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11701: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11702: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11703: }
11704: }
1.738 albertel 11705: # look for any posible extension_ match
11706: foreach my $package (@extension) {
11707: my ($package,$pack_type)=@{$package};
11708: if (defined($packagetab{"$pack_type&$name&default"})) {
11709: return $packagetab{"$pack_type&$name&default"};
11710: }
11711: if (defined($packagetab{$package."&$name&default"})) {
11712: return $packagetab{$package."&$name&default"};
11713: }
11714: }
11715: # look for a global default setting
11716: if ($do_default && defined($packagetab{"default&$name&default"})) {
11717: return $packagetab{"default&$name&default"};
11718: }
1.395 albertel 11719: return undef;
11720: }
11721:
1.334 albertel 11722: sub add_prefix_and_part {
11723: my ($prefix,$part)=@_;
11724: my $keyroot;
11725: if (defined($prefix) && $prefix !~ /^__/) {
11726: # prefix that has a part already
11727: $keyroot=$prefix;
11728: } elsif (defined($prefix)) {
11729: # prefix that is missing a part
11730: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11731: } else {
11732: # no prefix at all
11733: if (defined($part)) { $keyroot='_'.$part; }
11734: }
11735: return $keyroot;
11736: }
11737:
1.71 www 11738: # ---------------------------------------------------------------- Get metadata
11739:
1.599 albertel 11740: my %metaentry;
1.1070 www 11741: my %importedpartids;
1.1172.2.99 raeburn 11742: my %importedrespids;
1.71 www 11743: sub metadata {
1.176 www 11744: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11745: $uri=&declutter($uri);
1.288 albertel 11746: # if it is a non metadata possible uri return quickly
1.529 albertel 11747: if (($uri eq '') ||
11748: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 11749: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 11750: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11751: return undef;
11752: }
1.1172.2.49 raeburn 11753: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11754: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11755: return undef;
1.288 albertel 11756: }
1.73 www 11757: my $filename=$uri;
11758: $uri=~s/\.meta$//;
1.172 www 11759: #
11760: # Is the metadata already cached?
1.177 www 11761: # Look at timestamp of caching
1.172 www 11762: # Everything is cached by the main uri, libraries are never directly cached
11763: #
1.428 albertel 11764: if (!defined($liburi)) {
1.599 albertel 11765: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11766: if (defined($cached)) { return $result->{':'.$what}; }
11767: }
11768: {
1.1069 www 11769: # Imported parts would go here
1.1172.2.99 raeburn 11770: my @origfiletagids=();
1.1069 www 11771: my $importedparts=0;
1.1172.2.99 raeburn 11772:
11773: # Imported responseids would go here
11774: my $importedresponses=0;
1.172 www 11775: #
11776: # Is this a recursive call for a library?
11777: #
1.599 albertel 11778: # if (! exists($metacache{$uri})) {
11779: # $metacache{$uri}={};
11780: # }
1.924 albertel 11781: my $cachetime = 60*60;
1.171 www 11782: if ($liburi) {
11783: $liburi=&declutter($liburi);
11784: $filename=$liburi;
1.401 bowersj2 11785: } else {
1.599 albertel 11786: &devalidate_cache_new('meta',$uri);
11787: undef(%metaentry);
1.401 bowersj2 11788: }
1.140 www 11789: my %metathesekeys=();
1.73 www 11790: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11791: my $metastring;
1.1140 www 11792: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11793: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11794: $metastring =
1.929 albertel 11795: &Apache::lonnet::ssi_body($which,
1.924 albertel 11796: ('grade_target' => 'meta'));
11797: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11798: } elsif (($uri !~ m -^(editupload)/-) &&
11799: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11800: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11801: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11802: $metastring=&getfile($file);
1.489 albertel 11803: }
1.208 albertel 11804: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11805: my $token;
1.140 www 11806: undef %metathesekeys;
1.71 www 11807: while ($token=$parser->get_token) {
1.339 albertel 11808: if ($token->[0] eq 'S') {
11809: if (defined($token->[2]->{'package'})) {
1.172 www 11810: #
11811: # This is a package - get package info
11812: #
1.339 albertel 11813: my $package=$token->[2]->{'package'};
11814: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11815: if (defined($token->[2]->{'id'})) {
11816: $keyroot.='_'.$token->[2]->{'id'};
11817: }
1.599 albertel 11818: if ($metaentry{':packages'}) {
11819: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11820: } else {
1.599 albertel 11821: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11822: }
1.736 albertel 11823: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11824: my $part=$keyroot;
11825: $part=~s/^\_//;
1.736 albertel 11826: if ($pack_entry=~/^\Q$package\E\&/ ||
11827: $pack_entry=~/^\Q$package\E_0\&/) {
11828: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11829: # ignore package.tab specified default values
11830: # here &package_tab_default() will fetch those
11831: if ($subp eq 'default') { next; }
1.736 albertel 11832: my $value=$packagetab{$pack_entry};
1.432 albertel 11833: my $unikey;
11834: if ($pack =~ /_0$/) {
11835: $unikey='parameter_0_'.$name;
11836: $part=0;
11837: } else {
11838: $unikey='parameter'.$keyroot.'_'.$name;
11839: }
1.339 albertel 11840: if ($subp eq 'display') {
11841: $value.=' [Part: '.$part.']';
11842: }
1.599 albertel 11843: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11844: $metathesekeys{$unikey}=1;
1.599 albertel 11845: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11846: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11847: }
1.599 albertel 11848: if (defined($metaentry{':'.$unikey.'.default'})) {
11849: $metaentry{':'.$unikey}=
11850: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11851: }
1.339 albertel 11852: }
11853: }
11854: } else {
1.172 www 11855: #
11856: # This is not a package - some other kind of start tag
1.339 albertel 11857: #
11858: my $entry=$token->[1];
1.1068 www 11859: my $unikey='';
1.175 www 11860:
1.339 albertel 11861: if ($entry eq 'import') {
1.175 www 11862: #
11863: # Importing a library here
1.339 albertel 11864: #
1.1067 www 11865: my $location=$parser->get_text('/import');
11866: my $dir=$filename;
11867: $dir=~s|[^/]*$||;
11868: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 11869:
11870: my $importid=$token->[2]->{'id'};
1.1068 www 11871: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 11872: #
11873: # Check metadata for imported file to
11874: # see if it contained response items
11875: #
11876: my %currmetaentry = %metaentry;
11877: my $libresponseorder = &metadata($location,'responseorder');
11878: my $origfile;
11879: if ($libresponseorder ne '') {
11880: if ($#origfiletagids<0) {
11881: undef(%importedrespids);
11882: undef(%importedpartids);
11883: }
11884: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11885: if (@{$importedrespids{$importid}} > 0) {
11886: $importedresponses = 1;
11887: # We need to get the original file and the imported file to get the response order correct
11888: # Load and inspect original file
11889: if ($#origfiletagids<0) {
11890: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11891: $origfile=&getfile($origfilelocation);
11892: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11893: }
11894: }
11895: }
11896: # Do not overwrite contents of %metaentry hash for resource itself with
11897: # hash populated for imported library file
11898: %metaentry = %currmetaentry;
11899: undef(%currmetaentry);
1.1068 www 11900: if ($importmode eq 'problem') {
1.1069 www 11901: # Import as problem/response
1.1068 www 11902: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11903: } elsif ($importmode eq 'part') {
11904: # Import as part(s)
1.1069 www 11905: $importedparts=1;
11906: # We need to get the original file and the imported file to get the part order correct
11907: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 11908: # Load and inspect original file if we didn't do that already
11909: if ($#origfiletagids<0) {
11910: undef(%importedrespids);
11911: undef(%importedpartids);
11912: if ($origfile eq '') {
11913: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11914: $origfile=&getfile($origfilelocation);
11915: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11916: }
1.1070 www 11917: }
11918:
1.1069 www 11919: # Load and inspect imported file
11920: my $impfile=&getfile($location);
11921: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11922: if ($#impfilepartids>=0) {
11923: # This problem had parts
1.1070 www 11924: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11925: } else {
11926: # Importing by turning a single problem into a problem part
11927: # It gets the import-tags ID as part-ID
11928: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11929: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11930: }
1.1068 www 11931: } else {
11932: # Normal import
11933: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11934: if (defined($token->[2]->{'id'})) {
11935: $unikey.='_'.$token->[2]->{'id'};
11936: }
1.1067 www 11937: }
11938:
1.339 albertel 11939: if ($depthcount<20) {
1.736 albertel 11940: my $metadata =
11941: &metadata($uri,'keys', $location,$unikey,
11942: $depthcount+1);
11943: foreach my $meta (split(',',$metadata)) {
11944: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11945: $metathesekeys{$meta}=1;
1.339 albertel 11946: }
1.1068 www 11947:
11948: }
1.1067 www 11949: } else {
11950: #
11951: # Not importing, some other kind of non-package, non-library start tag
11952: #
11953: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11954: if (defined($token->[2]->{'id'})) {
11955: $unikey.='_'.$token->[2]->{'id'};
11956: }
1.339 albertel 11957: if (defined($token->[2]->{'name'})) {
11958: $unikey.='_'.$token->[2]->{'name'};
11959: }
11960: $metathesekeys{$unikey}=1;
1.736 albertel 11961: foreach my $param (@{$token->[3]}) {
11962: $metaentry{':'.$unikey.'.'.$param} =
11963: $token->[2]->{$param};
1.339 albertel 11964: }
11965: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11966: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11967: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11968: # only ws inside the tag, and not in default, so use default
11969: # as value
1.599 albertel 11970: $metaentry{':'.$unikey}=$default;
1.908 albertel 11971: } elsif ( $internaltext =~ /\S/ ) {
11972: # something interesting inside the tag
11973: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11974: } else {
1.908 albertel 11975: # no interesting values, don't set a default
1.339 albertel 11976: }
1.172 www 11977: # end of not-a-package not-a-library import
1.339 albertel 11978: }
1.172 www 11979: # end of not-a-package start tag
1.339 albertel 11980: }
1.172 www 11981: # the next is the end of "start tag"
1.339 albertel 11982: }
11983: }
1.483 albertel 11984: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11985: $extension = lc($extension);
11986: if ($extension eq 'htm') { $extension='html'; }
11987:
1.737 albertel 11988: foreach my $key (keys(%packagetab)) {
1.483 albertel 11989: #no specific packages #how's our extension
11990: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11991: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11992: \%metathesekeys);
11993: }
1.883 albertel 11994:
11995: if (!exists($metaentry{':packages'})
11996: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11997: foreach my $key (keys(%packagetab)) {
1.483 albertel 11998: #no specific packages well let's get default then
11999: if ($key!~/^default&/) { next; }
1.488 albertel 12000: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12001: \%metathesekeys);
12002: }
12003: }
1.338 www 12004: # are there custom rights to evaluate
1.599 albertel 12005: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12006:
1.338 www 12007: #
12008: # Importing a rights file here
1.339 albertel 12009: #
12010: unless ($depthcount) {
1.599 albertel 12011: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12012: my $dir=$filename;
12013: $dir=~s|[^/]*$||;
12014: $location=&filelocation($dir,$location);
1.736 albertel 12015: my $rights_metadata =
12016: &metadata($uri,'keys',$location,'_rights',
12017: $depthcount+1);
12018: foreach my $rights (split(',',$rights_metadata)) {
12019: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12020: $metathesekeys{$rights}=1;
1.339 albertel 12021: }
12022: }
12023: }
1.737 albertel 12024: # uniqifiy package listing
12025: my %seen;
12026: my @uniq_packages =
12027: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12028: $metaentry{':packages'} = join(',',@uniq_packages);
12029:
1.1172.2.99 raeburn 12030: if (($importedresponses) || ($importedparts)) {
12031: if ($importedparts) {
1.1070 www 12032: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 12033: $metaentry{':partorder'}='';
12034: $metathesekeys{'partorder'}=1;
12035: }
12036: if ($importedresponses) {
12037: # We had imported responses and need to rebuild responseorder
12038: $metaentry{':responseorder'}='';
12039: $metathesekeys{'responseorder'}=1;
12040: }
12041: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12042: my $origid = $origfiletagids[$index+1];
12043: if ($origfiletagids[$index] eq 'part') {
12044: # Original part, part of the problem
12045: if ($importedparts) {
12046: $metaentry{':partorder'}.=','.$origid;
12047: }
12048: } elsif ($origfiletagids[$index] eq 'import') {
12049: if ($importedparts) {
12050: # We have imported parts at this position
12051: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12052: }
12053: if ($importedresponses) {
12054: # We have imported responses at this position
12055: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12056: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12057: }
12058: }
12059: } else {
12060: # Original response item, part of the problem
12061: if ($importedresponses) {
12062: $metaentry{':responseorder'}.=','.$origid;
12063: }
12064: }
12065: }
12066: if ($importedparts) {
12067: $metaentry{':partorder'}=~s/^\,//;
12068: }
12069: if ($importedresponses) {
12070: $metaentry{':responseorder'}=~s/^\,//;
12071: }
1.1070 www 12072: }
12073:
1.737 albertel 12074: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12075: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 12076: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 12077: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 12078: # this is the end of "was not already recently cached
1.71 www 12079: }
1.599 albertel 12080: return $metaentry{':'.$what};
1.261 albertel 12081: }
12082:
1.488 albertel 12083: sub metadata_create_package_def {
1.483 albertel 12084: my ($uri,$key,$package,$metathesekeys)=@_;
12085: my ($pack,$name,$subp)=split(/\&/,$key);
12086: if ($subp eq 'default') { next; }
12087:
1.599 albertel 12088: if (defined($metaentry{':packages'})) {
12089: $metaentry{':packages'}.=','.$package;
1.483 albertel 12090: } else {
1.599 albertel 12091: $metaentry{':packages'}=$package;
1.483 albertel 12092: }
12093: my $value=$packagetab{$key};
12094: my $unikey;
12095: $unikey='parameter_0_'.$name;
1.599 albertel 12096: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12097: $$metathesekeys{$unikey}=1;
1.599 albertel 12098: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12099: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12100: }
1.599 albertel 12101: if (defined($metaentry{':'.$unikey.'.default'})) {
12102: $metaentry{':'.$unikey}=
12103: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12104: }
12105: }
12106:
1.261 albertel 12107: sub metadata_generate_part0 {
12108: my ($metadata,$metacache,$uri) = @_;
12109: my %allnames;
1.737 albertel 12110: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12111: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12112: my $part=$$metacache{':'.$metakey.'.part'};
12113: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12114: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12115: $allnames{$name}=$part;
12116: }
12117: }
12118: }
12119: foreach my $name (keys(%allnames)) {
12120: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12121: my $key=":parameter_0_$name";
1.261 albertel 12122: $$metacache{"$key.part"}='0';
12123: $$metacache{"$key.name"}=$name;
1.428 albertel 12124: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12125: $allnames{$name}.'_'.$name.
12126: '.type'};
1.428 albertel 12127: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12128: '.display'};
1.644 www 12129: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12130: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12131: $$metacache{"$key.display"}=$olddis;
12132: }
1.71 www 12133: }
12134:
1.764 albertel 12135: # ------------------------------------------------------ Devalidate title cache
12136:
12137: sub devalidate_title_cache {
12138: my ($url)=@_;
12139: if (!$env{'request.course.id'}) { return; }
12140: my $symb=&symbread($url);
12141: if (!$symb) { return; }
12142: my $key=$env{'request.course.id'}."\0".$symb;
12143: &devalidate_cache_new('title',$key);
12144: }
12145:
1.1014 droeschl 12146: # ------------------------------------------------- Get the title of a course
12147:
12148: sub current_course_title {
12149: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12150: }
1.301 www 12151: # ------------------------------------------------- Get the title of a resource
12152:
12153: sub gettitle {
12154: my $urlsymb=shift;
12155: my $symb=&symbread($urlsymb);
1.534 albertel 12156: if ($symb) {
1.620 albertel 12157: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12158: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12159: if (defined($cached)) {
12160: return $result;
12161: }
1.534 albertel 12162: my ($map,$resid,$url)=&decode_symb($symb);
12163: my $title='';
1.907 albertel 12164: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12165: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12166: } else {
12167: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12168: &GDBM_READER(),0640)) {
12169: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12170: $title=$bighash{'title_'.$mapid.'.'.$resid};
12171: untie(%bighash);
12172: }
1.534 albertel 12173: }
12174: $title=~s/\&colon\;/\:/gs;
12175: if ($title) {
1.1159 www 12176: # Remember both $symb and $title for dynamic metadata
12177: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12178: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12179: # Cache this title and then return it
1.599 albertel 12180: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12181: }
12182: $urlsymb=$url;
12183: }
12184: my $title=&metadata($urlsymb,'title');
12185: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12186: return $title;
1.301 www 12187: }
1.613 albertel 12188:
1.614 albertel 12189: sub get_slot {
12190: my ($which,$cnum,$cdom)=@_;
12191: if (!$cnum || !$cdom) {
1.790 albertel 12192: (undef,my $courseid)=&whichuser();
1.620 albertel 12193: $cdom=$env{'course.'.$courseid.'.domain'};
12194: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12195: }
1.703 albertel 12196: my $key=join("\0",'slots',$cdom,$cnum,$which);
12197: my %slotinfo;
12198: if (exists($remembered{$key})) {
12199: $slotinfo{$which} = $remembered{$key};
12200: } else {
12201: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12202: &Apache::lonhomework::showhash(%slotinfo);
12203: my ($tmp)=keys(%slotinfo);
12204: if ($tmp=~/^error:/) { return (); }
12205: $remembered{$key} = $slotinfo{$which};
12206: }
1.616 albertel 12207: if (ref($slotinfo{$which}) eq 'HASH') {
12208: return %{$slotinfo{$which}};
12209: }
12210: return $slotinfo{$which};
1.614 albertel 12211: }
1.1150 raeburn 12212:
12213: sub get_reservable_slots {
12214: my ($cnum,$cdom,$uname,$udom) = @_;
12215: my $now = time;
12216: my $reservable_info;
12217: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12218: if (exists($remembered{$key})) {
12219: $reservable_info = $remembered{$key};
12220: } else {
12221: my %resv;
12222: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12223: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12224: $reservable_info = \%resv;
12225: $remembered{$key} = $reservable_info;
12226: }
12227: return $reservable_info;
12228: }
12229:
12230: sub get_course_slots {
12231: my ($cnum,$cdom) = @_;
12232: my $hashid=$cnum.':'.$cdom;
12233: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12234: if (defined($cached)) {
12235: if (ref($result) eq 'HASH') {
12236: return %{$result};
12237: }
12238: } else {
12239: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12240: my ($tmp) = keys(%slots);
12241: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 12242: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12243: return %slots;
12244: }
12245: }
12246: return;
12247: }
12248:
12249: sub devalidate_slots_cache {
12250: my ($cnum,$cdom)=@_;
12251: my $hashid=$cnum.':'.$cdom;
12252: &devalidate_cache_new('allslots',$hashid);
12253: }
12254:
1.1172.2.8 raeburn 12255: sub get_coursechange {
12256: my ($cdom,$cnum) = @_;
12257: if ($cdom eq '' || $cnum eq '') {
12258: return unless ($env{'request.course.id'});
12259: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12260: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12261: }
12262: my $hashid=$cdom.'_'.$cnum;
12263: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12264: if ((defined($cached)) && ($change ne '')) {
12265: return $change;
12266: } else {
12267: my %crshash;
12268: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12269: if ($crshash{'internal.contentchange'} eq '') {
12270: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12271: if ($change eq '') {
12272: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12273: $change = $crshash{'internal.created'};
12274: }
12275: } else {
12276: $change = $crshash{'internal.contentchange'};
12277: }
12278: my $cachetime = 600;
12279: &do_cache_new('crschange',$hashid,$change,$cachetime);
12280: }
12281: return $change;
12282: }
12283:
12284: sub devalidate_coursechange_cache {
12285: my ($cnum,$cdom)=@_;
12286: my $hashid=$cnum.':'.$cdom;
12287: &devalidate_cache_new('crschange',$hashid);
12288: }
12289:
1.31 www 12290: # ------------------------------------------------- Update symbolic store links
12291:
12292: sub symblist {
12293: my ($mapname,%newhash)=@_;
1.438 www 12294: $mapname=&deversion(&declutter($mapname));
1.31 www 12295: my %hash;
1.620 albertel 12296: if (($env{'request.course.fn'}) && (%newhash)) {
12297: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12298: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12299: foreach my $url (keys(%newhash)) {
1.711 albertel 12300: next if ($url eq 'last_known'
12301: && $env{'form.no_update_last_known'});
12302: $hash{declutter($url)}=&encode_symb($mapname,
12303: $newhash{$url}->[1],
12304: $newhash{$url}->[0]);
1.191 harris41 12305: }
1.31 www 12306: if (untie(%hash)) {
12307: return 'ok';
12308: }
12309: }
12310: }
12311: return 'error';
1.212 www 12312: }
12313:
12314: # --------------------------------------------------------------- Verify a symb
12315:
12316: sub symbverify {
1.1172.2.11 raeburn 12317: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12318: my $thisfn=$thisurl;
1.439 www 12319: $thisfn=&declutter($thisfn);
1.215 www 12320: # direct jump to resource in page or to a sequence - will construct own symbs
12321: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12322: # check URL part
1.409 www 12323: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12324:
1.431 www 12325: unless ($url eq $thisfn) { return 0; }
1.213 www 12326:
1.216 www 12327: $symb=&symbclean($symb);
1.510 www 12328: $thisurl=&deversion($thisurl);
1.439 www 12329: $thisfn=&deversion($thisfn);
1.213 www 12330:
12331: my %bighash;
12332: my $okay=0;
1.431 www 12333:
1.620 albertel 12334: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12335: &GDBM_READER(),0640)) {
1.1032 raeburn 12336: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12337: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 12338: if ($map =~ m{^uploaded/.+\.page$}) {
12339: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12340: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12341: }
12342: }
12343: my $ids;
1.1172.2.122 raeburn 12344: if ($map =~ m{^uploaded/.+\.page$}) {
12345: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 12346: } else {
12347: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12348: }
1.1102 raeburn 12349: unless ($ids) {
1.1172.2.13 raeburn 12350: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 12351: $ids=$bighash{$idkey};
1.216 www 12352: }
12353: if ($ids) {
12354: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 12355: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12356: $symb =~ s/\?.+$//;
12357: }
1.800 albertel 12358: foreach my $id (split(/\,/,$ids)) {
12359: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12360: if (
12361: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 12362: eq $symb) {
1.1172.2.11 raeburn 12363: if (ref($encstate)) {
12364: $$encstate = $bighash{'encrypted_'.$id};
12365: }
1.1172.2.13 raeburn 12366: if (($env{'request.role.adv'}) ||
12367: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 12368: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 12369: $okay=1;
12370: last;
12371: }
12372: }
12373: }
1.216 www 12374: }
1.213 www 12375: untie(%bighash);
12376: }
12377: return $okay;
1.31 www 12378: }
12379:
1.210 www 12380: # --------------------------------------------------------------- Clean-up symb
12381:
12382: sub symbclean {
12383: my $symb=shift;
1.568 albertel 12384: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12385: # remove version from map
12386: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12387:
1.210 www 12388: # remove version from URL
12389: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12390:
1.507 www 12391: # remove wrapper
12392:
1.510 www 12393: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12394: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12395: return $symb;
1.409 www 12396: }
12397:
12398: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12399:
12400: sub encode_symb {
12401: my ($map,$resid,$url)=@_;
12402: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12403: }
1.409 www 12404:
12405: sub decode_symb {
1.568 albertel 12406: my $symb=shift;
12407: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12408: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12409: return (&fixversion($map),$resid,&fixversion($url));
12410: }
12411:
12412: sub fixversion {
12413: my $fn=shift;
1.609 banghart 12414: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12415: my %bighash;
12416: my $uri=&clutter($fn);
1.620 albertel 12417: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12418: # is this cached?
1.599 albertel 12419: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12420: if (defined($cached)) { return $result; }
12421: # unfortunately not cached, or expired
1.620 albertel 12422: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12423: &GDBM_READER(),0640)) {
12424: if ($bighash{'version_'.$uri}) {
12425: my $version=$bighash{'version_'.$uri};
1.444 www 12426: unless (($version eq 'mostrecent') ||
12427: ($version==&getversion($uri))) {
1.440 www 12428: $uri=~s/\.(\w+)$/\.$version\.$1/;
12429: }
12430: }
12431: untie %bighash;
1.413 www 12432: }
1.599 albertel 12433: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12434: }
12435:
12436: sub deversion {
12437: my $url=shift;
12438: $url=~s/\.\d+\.(\w+)$/\.$1/;
12439: return $url;
1.210 www 12440: }
12441:
1.31 www 12442: # ------------------------------------------------------ Return symb list entry
12443:
12444: sub symbread {
1.1172.2.126 raeburn 12445: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128! raeburn 12446: $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54 raeburn 12447: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128! raeburn 12448: if (defined($env{$cache_str})) {
1.1172.2.126 raeburn 12449: unless (ref($possibles) eq 'HASH') {
12450: if ($ignorecachednull) {
12451: return $env{$cache_str} unless ($env{$cache_str} eq '');
12452: } else {
12453: return $env{$cache_str};
12454: }
1.1172.2.66 raeburn 12455: }
12456: }
1.242 www 12457: # no filename provided? try from environment
1.1172.2.54 raeburn 12458: unless ($thisfn) {
1.620 albertel 12459: if ($env{'request.symb'}) {
1.1172.2.128! raeburn 12460: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13 raeburn 12461: }
12462: $thisfn=$env{'request.filename'};
1.44 www 12463: }
1.569 albertel 12464: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12465: # is that filename actually a symb? Verify, clean, and return
12466: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12467: if (&symbverify($thisfn,$1)) {
1.1172.2.128! raeburn 12468: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12469: }
1.242 www 12470: }
1.44 www 12471: $thisfn=declutter($thisfn);
1.31 www 12472: my %hash;
1.37 www 12473: my %bighash;
12474: my $syval='';
1.620 albertel 12475: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12476: my $targetfn = $thisfn;
1.609 banghart 12477: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12478: $targetfn = 'adm/wrapper/'.$thisfn;
12479: }
1.687 albertel 12480: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12481: $targetfn=$1;
12482: }
1.1172.2.128! raeburn 12483: unless ($ignoresymbdb) {
1.1172.2.126 raeburn 12484: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12485: &GDBM_READER(),0640)) {
12486: $syval=$hash{$targetfn};
12487: untie(%hash);
12488: }
1.1172.2.128! raeburn 12489: if ($syval && $checkforblock) {
! 12490: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126 raeburn 12491: if (@blockers) {
12492: $syval='';
12493: }
12494: }
1.37 www 12495: }
12496: # ---------------------------------------------------------- There was an entry
12497: if ($syval) {
1.601 albertel 12498: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12499: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12500: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12501: #return $env{$cache_str}='';
1.601 albertel 12502: #}
12503: #$syval.=$1;
12504: #}
1.37 www 12505: } else {
12506: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12507: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12508: &GDBM_READER(),0640)) {
1.37 www 12509: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12510: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12511: unless ($ids) {
12512: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12513: }
12514: unless ($ids) {
12515: # alias?
12516: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12517: }
1.37 www 12518: if ($ids) {
12519: # ------------------------------------------------------------------- Has ID(s)
12520: my @possibilities=split(/\,/,$ids);
1.39 www 12521: if ($#possibilities==0) {
12522: # ----------------------------------------------- There is only one possibility
1.37 www 12523: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12524: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12525: $resid,$thisfn);
1.1172.2.66 raeburn 12526: if (ref($possibles) eq 'HASH') {
1.1172.2.126 raeburn 12527: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12528: $possibles->{$syval} = 1;
12529: }
1.1172.2.66 raeburn 12530: }
12531: if ($checkforblock) {
1.1172.2.126 raeburn 12532: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127 raeburn 12533: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126 raeburn 12534: if (@blockers) {
12535: $syval = '';
12536: untie(%bighash);
12537: return $env{$cache_str}='';
12538: }
1.1172.2.66 raeburn 12539: }
12540: }
12541: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12542: # ------------------------------------------ There is more than one possibility
12543: my $realpossible=0;
1.800 albertel 12544: foreach my $id (@possibilities) {
12545: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 12546: my $canaccess;
12547: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12548: $canaccess = 1;
12549: } else {
12550: $canaccess = &allowed('bre',$file);
12551: }
12552: if ($canaccess) {
12553: my ($mapid,$resid)=split(/\./,$id);
12554: if ($bighash{'map_type_'.$mapid} ne 'page') {
12555: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12556: $resid,$thisfn);
1.1172.2.126 raeburn 12557: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127 raeburn 12558: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66 raeburn 12559: if ($checkforblock) {
1.1172.2.127 raeburn 12560: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126 raeburn 12561: if (@blockers > 0) {
12562: $syval = '';
12563: } else {
1.1172.2.66 raeburn 12564: $syval = $poss_syval;
12565: $realpossible++;
12566: }
12567: } else {
12568: $syval = $poss_syval;
12569: $realpossible++;
12570: }
1.1172.2.126 raeburn 12571: if ($syval) {
12572: if (ref($possibles) eq 'HASH') {
12573: $possibles->{$syval} = 1;
12574: }
12575: }
1.1172.2.66 raeburn 12576: }
1.39 www 12577: }
1.191 harris41 12578: }
1.39 www 12579: if ($realpossible!=1) { $syval=''; }
1.249 www 12580: } else {
12581: $syval='';
1.37 www 12582: }
12583: }
1.1172.2.66 raeburn 12584: untie(%bighash);
1.481 raeburn 12585: }
1.31 www 12586: }
1.62 www 12587: if ($syval) {
1.1172.2.128! raeburn 12588: return $env{$cache_str}=$syval;
1.62 www 12589: }
1.31 www 12590: }
1.949 raeburn 12591: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12592: return $env{$cache_str}='';
1.31 www 12593: }
12594:
12595: # ---------------------------------------------------------- Return random seed
12596:
1.32 www 12597: sub numval {
12598: my $txt=shift;
12599: $txt=~tr/A-J/0-9/;
12600: $txt=~tr/a-j/0-9/;
12601: $txt=~tr/K-T/0-9/;
12602: $txt=~tr/k-t/0-9/;
12603: $txt=~tr/U-Z/0-5/;
12604: $txt=~tr/u-z/0-5/;
12605: $txt=~s/\D//g;
1.564 albertel 12606: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12607: return int($txt);
1.368 albertel 12608: }
12609:
1.484 albertel 12610: sub numval2 {
12611: my $txt=shift;
12612: $txt=~tr/A-J/0-9/;
12613: $txt=~tr/a-j/0-9/;
12614: $txt=~tr/K-T/0-9/;
12615: $txt=~tr/k-t/0-9/;
12616: $txt=~tr/U-Z/0-5/;
12617: $txt=~tr/u-z/0-5/;
12618: $txt=~s/\D//g;
12619: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12620: my $total;
12621: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12622: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12623: return int($total);
12624: }
12625:
1.575 albertel 12626: sub numval3 {
12627: use integer;
12628: my $txt=shift;
12629: $txt=~tr/A-J/0-9/;
12630: $txt=~tr/a-j/0-9/;
12631: $txt=~tr/K-T/0-9/;
12632: $txt=~tr/k-t/0-9/;
12633: $txt=~tr/U-Z/0-5/;
12634: $txt=~tr/u-z/0-5/;
12635: $txt=~s/\D//g;
12636: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12637: my $total;
12638: foreach my $val (@txts) { $total+=$val; }
12639: if ($_64bit) { $total=(($total<<32)>>32); }
12640: return $total;
12641: }
12642:
1.675 albertel 12643: sub digest {
12644: my ($data)=@_;
12645: my $digest=&Digest::MD5::md5($data);
12646: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12647: my ($e,$f);
12648: {
12649: use integer;
12650: $e=($a+$b);
12651: $f=($c+$d);
12652: if ($_64bit) {
12653: $e=(($e<<32)>>32);
12654: $f=(($f<<32)>>32);
12655: }
12656: }
12657: if (wantarray) {
12658: return ($e,$f);
12659: } else {
12660: my $g;
12661: {
12662: use integer;
12663: $g=($e+$f);
12664: if ($_64bit) {
12665: $g=(($g<<32)>>32);
12666: }
12667: }
12668: return $g;
12669: }
12670: }
12671:
1.368 albertel 12672: sub latest_rnd_algorithm_id {
1.675 albertel 12673: return '64bit5';
1.366 albertel 12674: }
1.32 www 12675:
1.503 albertel 12676: sub get_rand_alg {
12677: my ($courseid)=@_;
1.790 albertel 12678: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12679: if ($courseid) {
1.620 albertel 12680: return $env{"course.$courseid.rndseed"};
1.503 albertel 12681: }
12682: return &latest_rnd_algorithm_id();
12683: }
12684:
1.562 albertel 12685: sub validCODE {
12686: my ($CODE)=@_;
12687: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12688: return 0;
12689: }
12690:
1.491 albertel 12691: sub getCODE {
1.620 albertel 12692: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12693: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12694: defined($Apache::lonhomework::parsing_a_task) ) &&
12695: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12696: return $Apache::lonhomework::history{'resource.CODE'};
12697: }
12698: return undef;
12699: }
1.1133 foxr 12700: #
12701: # Determines the random seed for a specific context:
12702: #
12703: # parameters:
12704: # symb - in course context the symb for the seed.
12705: # course_id - The course id of the form domain_coursenum.
12706: # domain - Domain for the user.
12707: # course - Course for the user.
12708: # cenv - environment of the course.
12709: #
12710: # NOTE:
12711: # All parameters are picked out of the environment if missing
12712: # or not defined.
12713: # If a symb cannot be determined the current time is used instead.
12714: #
12715: # For a given well defined symb, courside, domain, username,
12716: # and course environment, the seed is reproducible.
12717: #
1.31 www 12718: sub rndseed {
1.1133 foxr 12719: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12720: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12721: if (!defined($symb)) {
1.366 albertel 12722: unless ($symb=$wsymb) { return time; }
12723: }
1.1146 foxr 12724: if (!defined $courseid) {
12725: $courseid=$wcourseid;
12726: }
12727: if (!defined $domain) { $domain=$wdomain; }
12728: if (!defined $username) { $username=$wusername }
1.1133 foxr 12729:
12730: my $which;
12731: if (defined($cenv->{'rndseed'})) {
12732: $which = $cenv->{'rndseed'};
12733: } else {
12734: $which =&get_rand_alg($courseid);
12735: }
1.491 albertel 12736: if (defined(&getCODE())) {
1.675 albertel 12737: if ($which eq '64bit5') {
12738: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12739: } elsif ($which eq '64bit4') {
1.575 albertel 12740: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12741: } else {
12742: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12743: }
1.675 albertel 12744: } elsif ($which eq '64bit5') {
12745: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12746: } elsif ($which eq '64bit4') {
12747: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12748: } elsif ($which eq '64bit3') {
12749: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12750: } elsif ($which eq '64bit2') {
12751: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12752: } elsif ($which eq '64bit') {
12753: return &rndseed_64bit($symb,$courseid,$domain,$username);
12754: }
12755: return &rndseed_32bit($symb,$courseid,$domain,$username);
12756: }
12757:
12758: sub rndseed_32bit {
12759: my ($symb,$courseid,$domain,$username)=@_;
12760: {
12761: use integer;
12762: my $symbchck=unpack("%32C*",$symb) << 27;
12763: my $symbseed=numval($symb) << 22;
12764: my $namechck=unpack("%32C*",$username) << 17;
12765: my $nameseed=numval($username) << 12;
12766: my $domainseed=unpack("%32C*",$domain) << 7;
12767: my $courseseed=unpack("%32C*",$courseid);
12768: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12769: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12770: #&logthis("rndseed :$num:$symb");
1.564 albertel 12771: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12772: return $num;
12773: }
12774: }
12775:
12776: sub rndseed_64bit {
12777: my ($symb,$courseid,$domain,$username)=@_;
12778: {
12779: use integer;
12780: my $symbchck=unpack("%32S*",$symb) << 21;
12781: my $symbseed=numval($symb) << 10;
12782: my $namechck=unpack("%32S*",$username);
12783:
12784: my $nameseed=numval($username) << 21;
12785: my $domainseed=unpack("%32S*",$domain) << 10;
12786: my $courseseed=unpack("%32S*",$courseid);
12787:
12788: my $num1=$symbchck+$symbseed+$namechck;
12789: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12790: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12791: #&logthis("rndseed :$num:$symb");
1.564 albertel 12792: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12793: return "$num1,$num2";
1.155 albertel 12794: }
1.366 albertel 12795: }
12796:
1.443 albertel 12797: sub rndseed_64bit2 {
12798: my ($symb,$courseid,$domain,$username)=@_;
12799: {
12800: use integer;
12801: # strings need to be an even # of cahracters long, it it is odd the
12802: # last characters gets thrown away
12803: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12804: my $symbseed=numval($symb) << 10;
12805: my $namechck=unpack("%32S*",$username.' ');
12806:
12807: my $nameseed=numval($username) << 21;
1.501 albertel 12808: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12809: my $courseseed=unpack("%32S*",$courseid.' ');
12810:
12811: my $num1=$symbchck+$symbseed+$namechck;
12812: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12813: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12814: #&logthis("rndseed :$num:$symb");
1.803 albertel 12815: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12816: return "$num1,$num2";
12817: }
12818: }
12819:
12820: sub rndseed_64bit3 {
12821: my ($symb,$courseid,$domain,$username)=@_;
12822: {
12823: use integer;
12824: # strings need to be an even # of cahracters long, it it is odd the
12825: # last characters gets thrown away
12826: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12827: my $symbseed=numval2($symb) << 10;
12828: my $namechck=unpack("%32S*",$username.' ');
12829:
12830: my $nameseed=numval2($username) << 21;
1.443 albertel 12831: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12832: my $courseseed=unpack("%32S*",$courseid.' ');
12833:
12834: my $num1=$symbchck+$symbseed+$namechck;
12835: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12836: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12837: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12838: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12839:
1.503 albertel 12840: return "$num1:$num2";
1.443 albertel 12841: }
12842: }
12843:
1.575 albertel 12844: sub rndseed_64bit4 {
12845: my ($symb,$courseid,$domain,$username)=@_;
12846: {
12847: use integer;
12848: # strings need to be an even # of cahracters long, it it is odd the
12849: # last characters gets thrown away
12850: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12851: my $symbseed=numval3($symb) << 10;
12852: my $namechck=unpack("%32S*",$username.' ');
12853:
12854: my $nameseed=numval3($username) << 21;
12855: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12856: my $courseseed=unpack("%32S*",$courseid.' ');
12857:
12858: my $num1=$symbchck+$symbseed+$namechck;
12859: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12860: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12861: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12862: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12863:
1.575 albertel 12864: return "$num1:$num2";
12865: }
12866: }
12867:
1.675 albertel 12868: sub rndseed_64bit5 {
12869: my ($symb,$courseid,$domain,$username)=@_;
12870: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12871: return "$num1:$num2";
12872: }
12873:
1.366 albertel 12874: sub rndseed_CODE_64bit {
12875: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12876: {
1.366 albertel 12877: use integer;
1.443 albertel 12878: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12879: my $symbseed=numval2($symb);
1.491 albertel 12880: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12881: my $CODEseed=numval(&getCODE());
1.443 albertel 12882: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12883: my $num1=$symbseed+$CODEchck;
12884: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12885: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12886: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12887: if ($_64bit) { $num1=(($num1<<32)>>32); }
12888: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12889: return "$num1:$num2";
1.366 albertel 12890: }
12891: }
12892:
1.575 albertel 12893: sub rndseed_CODE_64bit4 {
12894: my ($symb,$courseid,$domain,$username)=@_;
12895: {
12896: use integer;
12897: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12898: my $symbseed=numval3($symb);
12899: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12900: my $CODEseed=numval3(&getCODE());
12901: my $courseseed=unpack("%32S*",$courseid.' ');
12902: my $num1=$symbseed+$CODEchck;
12903: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12904: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12905: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12906: if ($_64bit) { $num1=(($num1<<32)>>32); }
12907: if ($_64bit) { $num2=(($num2<<32)>>32); }
12908: return "$num1:$num2";
12909: }
12910: }
12911:
1.675 albertel 12912: sub rndseed_CODE_64bit5 {
12913: my ($symb,$courseid,$domain,$username)=@_;
12914: my $code = &getCODE();
12915: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12916: return "$num1:$num2";
12917: }
12918:
1.366 albertel 12919: sub setup_random_from_rndseed {
12920: my ($rndseed)=@_;
1.503 albertel 12921: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 12922: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12923: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12924: &Math::Random::random_set_seed_from_phrase($rndseed);
12925: } else {
12926: &Math::Random::random_set_seed($num1,$num2);
12927: }
1.366 albertel 12928: } else {
12929: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12930: }
1.36 albertel 12931: }
12932:
1.474 albertel 12933: sub latest_receipt_algorithm_id {
1.835 albertel 12934: return 'receipt3';
1.474 albertel 12935: }
12936:
1.480 www 12937: sub recunique {
12938: my $fucourseid=shift;
12939: my $unique;
1.835 albertel 12940: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12941: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12942: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12943: } else {
12944: $unique=$perlvar{'lonReceipt'};
12945: }
12946: return unpack("%32C*",$unique);
12947: }
12948:
12949: sub recprefix {
12950: my $fucourseid=shift;
12951: my $prefix;
1.835 albertel 12952: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12953: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12954: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12955: } else {
12956: $prefix=$perlvar{'lonHostID'};
12957: }
12958: return unpack("%32C*",$prefix);
12959: }
12960:
1.76 www 12961: sub ireceipt {
1.474 albertel 12962: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12963:
12964: my $return =&recprefix($fucourseid).'-';
12965:
12966: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12967: $env{'request.state'} eq 'construct') {
12968: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12969: return $return;
12970: }
12971:
1.76 www 12972: my $cuname=unpack("%32C*",$funame);
12973: my $cudom=unpack("%32C*",$fudom);
12974: my $cucourseid=unpack("%32C*",$fucourseid);
12975: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12976: my $cunique=&recunique($fucourseid);
1.474 albertel 12977: my $cpart=unpack("%32S*",$part);
1.835 albertel 12978: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12979:
1.790 albertel 12980: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12981:
12982: $return.= ($cunique%$cuname+
12983: $cunique%$cudom+
12984: $cusymb%$cuname+
12985: $cusymb%$cudom+
12986: $cucourseid%$cuname+
12987: $cucourseid%$cudom+
12988: $cpart%$cuname+
12989: $cpart%$cudom);
12990: } else {
12991: $return.= ($cunique%$cuname+
12992: $cunique%$cudom+
12993: $cusymb%$cuname+
12994: $cusymb%$cudom+
12995: $cucourseid%$cuname+
12996: $cucourseid%$cudom);
12997: }
12998: return $return;
1.76 www 12999: }
13000:
13001: sub receipt {
1.474 albertel 13002: my ($part)=@_;
1.790 albertel 13003: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13004: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13005: }
1.260 ng 13006:
1.790 albertel 13007: sub whichuser {
13008: my ($passedsymb)=@_;
13009: my ($symb,$courseid,$domain,$name,$publicuser);
13010: if (defined($env{'form.grade_symb'})) {
13011: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13012: my $allowed=&allowed('vgr',$tmp_courseid);
13013: if (!$allowed &&
13014: exists($env{'request.course.sec'}) &&
13015: $env{'request.course.sec'} !~ /^\s*$/) {
13016: $allowed=&allowed('vgr',$tmp_courseid.
13017: '/'.$env{'request.course.sec'});
13018: }
13019: if ($allowed) {
13020: ($symb)=&get_env_multiple('form.grade_symb');
13021: $courseid=$tmp_courseid;
13022: ($domain)=&get_env_multiple('form.grade_domain');
13023: ($name)=&get_env_multiple('form.grade_username');
13024: return ($symb,$courseid,$domain,$name,$publicuser);
13025: }
13026: }
13027: if (!$passedsymb) {
13028: $symb=&symbread();
13029: } else {
13030: $symb=$passedsymb;
13031: }
13032: $courseid=$env{'request.course.id'};
13033: $domain=$env{'user.domain'};
13034: $name=$env{'user.name'};
13035: if ($name eq 'public' && $domain eq 'public') {
13036: if (!defined($env{'form.username'})) {
13037: $env{'form.username'}.=time.rand(10000000);
13038: }
13039: $name.=$env{'form.username'};
13040: }
13041: return ($symb,$courseid,$domain,$name,$publicuser);
13042:
13043: }
13044:
1.36 albertel 13045: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13046: # returns either the contents of the file or
13047: # -1 if the file doesn't exist
1.481 raeburn 13048: #
13049: # if the target is a file that was uploaded via DOCS,
13050: # a check will be made to see if a current copy exists on the local server,
13051: # if it does this will be served, otherwise a copy will be retrieved from
13052: # the home server for the course and stored in /home/httpd/html/userfiles on
13053: # the local server.
1.472 albertel 13054:
1.36 albertel 13055: sub getfile {
1.538 albertel 13056: my ($file) = @_;
1.609 banghart 13057: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13058: &repcopy($file);
13059: return &readfile($file);
13060: }
13061:
13062: sub repcopy_userfile {
13063: my ($file)=@_;
1.1142 raeburn 13064: my $londocroot = $perlvar{'lonDocRoot'};
13065: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13066: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13067: my ($cdom,$cnum,$filename) =
1.811 albertel 13068: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13069: my $uri="/uploaded/$cdom/$cnum/$filename";
13070: if (-e "$file") {
1.828 www 13071: # we already have a local copy, check it out
1.538 albertel 13072: my @fileinfo = stat($file);
1.828 www 13073: my $rtncode;
13074: my $info;
1.538 albertel 13075: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13076: if ($lwpresp ne 'ok') {
1.828 www 13077: # there is no such file anymore, even though we had a local copy
1.482 albertel 13078: if ($rtncode eq '404') {
1.538 albertel 13079: unlink($file);
1.482 albertel 13080: }
13081: return -1;
13082: }
13083: if ($info < $fileinfo[9]) {
1.828 www 13084: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13085: return 'ok';
1.828 www 13086: } else {
13087: # the file is outdated, get rid of it
13088: unlink($file);
1.482 albertel 13089: }
1.828 www 13090: }
13091: # one way or the other, at this point, we don't have the file
13092: # construct the correct path for the file
13093: my @parts = ($cdom,$cnum);
13094: if ($filename =~ m|^(.+)/[^/]+$|) {
13095: push @parts, split(/\//,$1);
13096: }
13097: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13098: foreach my $part (@parts) {
13099: $path .= '/'.$part;
13100: if (!-e $path) {
13101: mkdir($path,0770);
1.482 albertel 13102: }
13103: }
1.828 www 13104: # now the path exists for sure
13105: # get a user agent
13106: my $ua=new LWP::UserAgent;
13107: my $transferfile=$file.'.in.transfer';
13108: # FIXME: this should flock
13109: if (-e $transferfile) { return 'ok'; }
13110: my $request;
13111: $uri=~s/^\///;
1.980 raeburn 13112: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13113: my $hostname = &hostname($homeserver);
1.980 raeburn 13114: my $protocol = $protocol{$homeserver};
13115: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13116: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 13117: my $response=$ua->request($request,$transferfile);
13118: # did it work?
13119: if ($response->is_error()) {
13120: unlink($transferfile);
13121: &logthis("Userfile repcopy failed for $uri");
13122: return -1;
13123: }
13124: # worked, rename the transfer file
13125: rename($transferfile,$file);
1.607 raeburn 13126: return 'ok';
1.481 raeburn 13127: }
13128:
1.517 albertel 13129: sub tokenwrapper {
13130: my $uri=shift;
1.980 raeburn 13131: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13132: $uri=~s|^/||;
1.620 albertel 13133: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13134: my $token=$1;
1.552 albertel 13135: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13136: if ($udom && $uname && $file) {
13137: $file=~s|(\?\.*)*$||;
1.949 raeburn 13138: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13139: my $homeserver = &homeserver($uname,$udom);
1.1172.2.120 raeburn 13140: my $hostname = &hostname($homeserver);
1.980 raeburn 13141: my $protocol = $protocol{$homeserver};
13142: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13143: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13144: (($uri=~/\?/)?'&':'?').'token='.$token.
13145: '&tokenissued='.$perlvar{'lonHostID'};
13146: } else {
13147: return '/adm/notfound.html';
13148: }
13149: }
13150:
1.828 www 13151: # call with reqtype HEAD: get last modification time
13152: # call with reqtype GET: get the file contents
13153: # Do not call this with reqtype GET for large files! It loads everything into memory
13154: #
1.481 raeburn 13155: sub getuploaded {
13156: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13157: $uri=~s/^\///;
1.980 raeburn 13158: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13159: my $hostname = &hostname($homeserver);
1.980 raeburn 13160: my $protocol = $protocol{$homeserver};
13161: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13162: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13163: my $ua=new LWP::UserAgent;
13164: my $request=new HTTP::Request($reqtype,$uri);
13165: my $response=$ua->request($request);
13166: $$rtncode = $response->code;
1.482 albertel 13167: if (! $response->is_success()) {
13168: return 'failed';
13169: }
13170: if ($reqtype eq 'HEAD') {
1.486 www 13171: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13172: } elsif ($reqtype eq 'GET') {
13173: $$info = $response->content;
1.472 albertel 13174: }
1.482 albertel 13175: return 'ok';
1.36 albertel 13176: }
13177:
1.481 raeburn 13178: sub readfile {
13179: my $file = shift;
13180: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13181: my $fh;
1.1172.2.96 raeburn 13182: open($fh,"<",$file);
1.481 raeburn 13183: my $a='';
1.800 albertel 13184: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13185: return $a;
13186: }
13187:
1.36 albertel 13188: sub filelocation {
1.590 banghart 13189: my ($dir,$file) = @_;
13190: my $location;
13191: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13192:
13193: if ($file =~ m-^/adm/-) {
13194: $file=~s-^/adm/wrapper/-/-;
13195: $file=~s-^/adm/coursedocs/showdoc/-/-;
13196: }
1.882 albertel 13197:
1.1139 www 13198: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13199: $location = $file;
1.609 banghart 13200: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13201: my ($udom,$uname,$filename)=
1.811 albertel 13202: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13203: my $home=&homeserver($uname,$udom);
13204: my $is_me=0;
13205: my @ids=¤t_machine_ids();
13206: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13207: if ($is_me) {
1.1117 foxr 13208: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13209: } else {
13210: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13211: $udom.'/'.$uname.'/'.$filename;
13212: }
1.882 albertel 13213: } elsif ($file =~ m-^/adm/-) {
13214: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13215: } else {
13216: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13217: $file=~s:^/(res|priv)/:/:;
13218: my $space=$1;
1.590 banghart 13219: if ( !( $file =~ m:^/:) ) {
13220: $location = $dir. '/'.$file;
13221: } else {
1.1142 raeburn 13222: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13223: }
1.59 albertel 13224: }
1.590 banghart 13225: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13226: while ($location=~m{/\.\./}) {
13227: if ($location =~ m{/[^/]+/\.\./}) {
13228: $location=~ s{/[^/]+/\.\./}{/}g;
13229: } else {
13230: $location=~ s{/\.\./}{/}g;
13231: }
13232: } #remove dir/..
1.590 banghart 13233: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13234: return $location;
1.46 www 13235: }
1.36 albertel 13236:
1.46 www 13237: sub hreflocation {
13238: my ($dir,$file)=@_;
1.980 raeburn 13239: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13240: $file=filelocation($dir,$file);
1.700 albertel 13241: } elsif ($file=~m-^/adm/-) {
13242: $file=~s-^/adm/wrapper/-/-;
13243: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13244: }
13245: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13246: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13247: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13248: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13249: {/uploaded/$1/$2/}x;
1.46 www 13250: }
1.913 albertel 13251: if ($file=~ m{^/userfiles/}) {
13252: $file =~ s{^/userfiles/}{/uploaded/};
13253: }
1.462 albertel 13254: return $file;
1.465 albertel 13255: }
13256:
1.1139 www 13257:
13258:
13259:
13260:
1.465 albertel 13261: sub current_machine_domains {
1.853 albertel 13262: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13263: }
13264:
13265: sub machine_domains {
13266: my ($hostname) = @_;
1.465 albertel 13267: my @domains;
1.838 albertel 13268: my %hostname = &all_hostnames();
1.465 albertel 13269: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13270: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13271: if ($hostname eq $name) {
1.844 albertel 13272: push(@domains,&host_domain($id));
1.465 albertel 13273: }
13274: }
13275: return @domains;
13276: }
13277:
13278: sub current_machine_ids {
1.853 albertel 13279: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13280: }
13281:
13282: sub machine_ids {
13283: my ($hostname) = @_;
13284: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13285: my @ids;
1.888 albertel 13286: my %name_to_host = &all_names();
1.889 albertel 13287: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13288: return @{ $name_to_host{$hostname} };
13289: }
13290: return;
1.31 www 13291: }
13292:
1.824 raeburn 13293: sub additional_machine_domains {
13294: my @domains;
1.1172.2.96 raeburn 13295: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 13296: while( my $line = <$fh>) {
13297: $line =~ s/\s//g;
13298: push(@domains,$line);
13299: }
13300: return @domains;
13301: }
13302:
13303: sub default_login_domain {
13304: my $domain = $perlvar{'lonDefDomain'};
13305: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13306: foreach my $posdom (¤t_machine_domains(),
13307: &additional_machine_domains()) {
13308: if (lc($posdom) eq lc($testdomain)) {
13309: $domain=$posdom;
13310: last;
13311: }
13312: }
13313: return $domain;
13314: }
13315:
1.1172.2.106 raeburn 13316: sub shared_institution {
13317: my ($dom) = @_;
13318: my $same_intdom;
13319: my $hostintdom = &internet_dom($perlvar{'lonHostID'});
13320: if ($hostintdom ne '') {
13321: my %iphost = &get_iphost();
13322: my $primary_id = &domain($dom,'primary');
13323: my $primary_ip = &get_host_ip($primary_id);
13324: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13325: foreach my $id (@{$iphost{$primary_ip}}) {
13326: my $intdom = &internet_dom($id);
13327: if ($intdom eq $hostintdom) {
13328: $same_intdom = 1;
13329: last;
13330: }
13331: }
13332: }
13333: }
13334: return $same_intdom;
13335: }
13336:
1.1172.2.120 raeburn 13337: sub uses_sts {
13338: my ($ignore_cache) = @_;
13339: my $lonhost = $perlvar{'lonHostID'};
13340: my $hostname = &hostname($lonhost);
13341: my $sts_on;
13342: if ($protocol{$lonhost} eq 'https') {
13343: my $cachetime = 12*3600;
13344: if (!$ignore_cache) {
13345: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13346: if (defined($cached)) {
13347: return $sts_on;
13348: }
13349: }
1.1172.2.121 raeburn 13350: my $ua=new LWP::UserAgent;
1.1172.2.120 raeburn 13351: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13352: my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121 raeburn 13353: my $response=$ua->request($request);
1.1172.2.120 raeburn 13354: if ($response->is_success) {
13355: my $has_sts = $response->header('Strict-Transport-Security');
13356: if ($has_sts eq '') {
13357: $sts_on = 0;
13358: } else {
13359: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13360: my $maxage = $1;
13361: if ($maxage) {
13362: $sts_on = 1;
13363: } else {
13364: $sts_on = 0;
13365: }
13366: } else {
13367: $sts_on = 0;
13368: }
13369: }
13370: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13371: }
13372: }
13373: return;
13374: }
13375:
1.31 www 13376: # ------------------------------------------------------------- Declutters URLs
13377:
13378: sub declutter {
13379: my $thisfn=shift;
1.569 albertel 13380: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 13381: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13382: $thisfn=~s{^/home/httpd/html}{};
13383: }
1.31 www 13384: $thisfn=~s/^\///;
1.697 albertel 13385: $thisfn=~s|^adm/wrapper/||;
13386: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13387: $thisfn=~s/^res\///;
1.1172 bisitz 13388: $thisfn=~s/^priv\///;
1.1032 raeburn 13389: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13390: $thisfn=~s/\?.+$//;
13391: }
1.268 www 13392: return $thisfn;
13393: }
13394:
13395: # ------------------------------------------------------------- Clutter up URLs
13396:
13397: sub clutter {
13398: my $thisfn='/'.&declutter(shift);
1.887 albertel 13399: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13400: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13401: $thisfn='/res'.$thisfn;
13402: }
1.1031 raeburn 13403: if ($thisfn !~m|^/adm|) {
13404: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13405: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13406: } else {
13407: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13408: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13409: if ($embstyle eq 'ssi'
13410: || ($embstyle eq 'hdn')
13411: || ($embstyle eq 'rat')
13412: || ($embstyle eq 'prv')
13413: || ($embstyle eq 'ign')) {
13414: #do nothing with these
13415: } elsif (($embstyle eq 'img')
1.695 albertel 13416: || ($embstyle eq 'emb')
13417: || ($embstyle eq 'wrp')) {
13418: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13419: } elsif ($embstyle eq 'unk'
13420: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13421: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13422: } else {
1.718 www 13423: # &logthis("Got a blank emb style");
1.695 albertel 13424: }
1.694 albertel 13425: }
13426: }
1.31 www 13427: return $thisfn;
1.12 www 13428: }
13429:
1.787 albertel 13430: sub clutter_with_no_wrapper {
13431: my $uri = &clutter(shift);
13432: if ($uri =~ m-^/adm/-) {
13433: $uri =~ s-^/adm/wrapper/-/-;
13434: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13435: }
13436: return $uri;
13437: }
13438:
1.557 albertel 13439: sub freeze_escape {
13440: my ($value)=@_;
13441: if (ref($value)) {
13442: $value=&nfreeze($value);
13443: return '__FROZEN__'.&escape($value);
13444: }
13445: return &escape($value);
13446: }
13447:
1.11 www 13448:
1.557 albertel 13449: sub thaw_unescape {
13450: my ($value)=@_;
13451: if ($value =~ /^__FROZEN__/) {
13452: substr($value,0,10,undef);
13453: $value=&unescape($value);
13454: return &thaw($value);
13455: }
13456: return &unescape($value);
13457: }
13458:
1.436 albertel 13459: sub correct_line_ends {
13460: my ($result)=@_;
13461: $$result =~s/\r\n/\n/mg;
13462: $$result =~s/\r/\n/mg;
1.415 albertel 13463: }
1.1 albertel 13464: # ================================================================ Main Program
13465:
1.184 www 13466: sub goodbye {
1.204 albertel 13467: &logthis("Starting Shut down");
1.443 albertel 13468: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13469: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13470: #converted
1.599 albertel 13471: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13472: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13473: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13474: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13475: #1.1 only
1.870 albertel 13476: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13477: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13478: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13479: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13480: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13481: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13482: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13483: &flushcourselogs();
13484: &logthis("Shutting down");
13485: }
13486:
1.852 albertel 13487: sub get_dns {
1.1172.2.17 raeburn 13488: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13489: if (!$ignore_cache) {
13490: my ($content,$cached)=
13491: &Apache::lonnet::is_cached_new('dns',$url);
13492: if ($cached) {
1.1172.2.17 raeburn 13493: &$func($content,$hashref);
1.869 albertel 13494: return;
13495: }
13496: }
13497:
13498: my %alldns;
1.1172.2.96 raeburn 13499: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13500: foreach my $dns (<$config>) {
13501: next if ($dns !~ /^\^(\S*)/x);
13502: my $line = $1;
13503: my ($host,$protocol) = split(/:/,$line);
13504: if ($protocol ne 'https') {
13505: $protocol = 'http';
13506: }
13507: $alldns{$host} = $protocol;
1.979 raeburn 13508: }
1.1172.2.96 raeburn 13509: close($config);
1.869 albertel 13510: }
13511: while (%alldns) {
1.1172.2.52 raeburn 13512: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 13513: my $ua=new LWP::UserAgent;
1.1134 raeburn 13514: $ua->timeout(30);
1.979 raeburn 13515: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 13516: my $response=$ua->request($request);
1.979 raeburn 13517: delete($alldns{$dns});
1.852 albertel 13518: next if ($response->is_error());
13519: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 13520: unless ($nocache) {
1.1172.2.23 raeburn 13521: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 13522: }
13523: &$func(\@content,$hashref);
1.869 albertel 13524: return;
1.852 albertel 13525: }
1.871 albertel 13526: my $which = (split('/',$url))[3];
13527: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 13528: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13529: my @content = <$config>;
13530: &$func(\@content,$hashref);
13531: }
1.1172.2.17 raeburn 13532: return;
13533: }
13534:
13535: # ------------------------------------------------------Get DNS checksums file
13536: sub parse_dns_checksums_tab {
13537: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 13538: my $lonhost = $perlvar{'lonHostID'};
13539: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 13540: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 13541: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13542: my $webconfdir = '/etc/httpd/conf';
13543: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13544: $webconfdir = '/etc/apache2';
13545: } elsif ($distro =~ /^sles(\d+)$/) {
13546: if ($1 >= 10) {
13547: $webconfdir = '/etc/apache2';
13548: }
13549: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13550: if ($1 >= 10.0) {
13551: $webconfdir = '/etc/apache2';
13552: }
13553: }
1.1172.2.17 raeburn 13554: my ($release,$timestamp) = split(/\-/,$loncaparev);
13555: my (%chksum,%revnum);
13556: if (ref($lines) eq 'ARRAY') {
13557: chomp(@{$lines});
1.1172.2.34 raeburn 13558: my $version = shift(@{$lines});
13559: if ($version eq $release) {
1.1172.2.17 raeburn 13560: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 13561: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 13562: if ($file =~ m{^/etc/httpd/conf}) {
13563: if ($webconfdir eq '/etc/apache2') {
13564: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13565: }
13566: }
1.1172.2.34 raeburn 13567: $chksum{$file} = $shasum;
13568: $revnum{$file} = $version;
1.1172.2.17 raeburn 13569: }
13570: if (ref($hashref) eq 'HASH') {
13571: %{$hashref} = (
13572: sums => \%chksum,
13573: versions => \%revnum,
13574: );
13575: }
13576: }
13577: }
1.869 albertel 13578: return;
1.852 albertel 13579: }
1.1172.2.17 raeburn 13580:
13581: sub fetch_dns_checksums {
13582: my %checksums;
1.1172.2.34 raeburn 13583: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 13584: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 13585: my ($release,$timestamp) = split(/\-/,$loncaparev);
13586: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 13587: \%checksums);
13588: return \%checksums;
13589: }
13590:
1.327 albertel 13591: # ------------------------------------------------------------ Read domain file
13592: {
1.852 albertel 13593: my $loaded;
1.846 albertel 13594: my %domain;
13595:
1.852 albertel 13596: sub parse_domain_tab {
13597: my ($lines) = @_;
13598: foreach my $line (@$lines) {
13599: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 13600:
1.846 albertel 13601: chomp($line);
1.852 albertel 13602: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 13603: my %this_domain;
13604: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13605: 'lang_def', 'city', 'longi', 'lati',
13606: 'primary') {
13607: $this_domain{$field} = shift(@elements);
13608: }
13609: $domain{$name} = \%this_domain;
1.852 albertel 13610: }
13611: }
1.864 albertel 13612:
13613: sub reset_domain_info {
13614: undef($loaded);
13615: undef(%domain);
13616: }
13617:
1.852 albertel 13618: sub load_domain_tab {
1.1172.2.70 raeburn 13619: my ($ignore_cache,$nocache) = @_;
13620: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 13621: my $fh;
1.1172.2.96 raeburn 13622: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 13623: my @lines = <$fh>;
13624: &parse_domain_tab(\@lines);
1.448 albertel 13625: }
1.852 albertel 13626: close($fh);
13627: $loaded = 1;
1.327 albertel 13628: }
1.846 albertel 13629:
13630: sub domain {
1.852 albertel 13631: &load_domain_tab() if (!$loaded);
13632:
1.846 albertel 13633: my ($name,$what) = @_;
13634: return if ( !exists($domain{$name}) );
13635:
13636: if (!$what) {
13637: return $domain{$name}{'description'};
13638: }
13639: return $domain{$name}{$what};
13640: }
1.974 raeburn 13641:
13642: sub domain_info {
13643: &load_domain_tab() if (!$loaded);
13644: return %domain;
13645: }
13646:
1.327 albertel 13647: }
13648:
13649:
1.1 albertel 13650: # ------------------------------------------------------------- Read hosts file
13651: {
1.838 albertel 13652: my %hostname;
1.844 albertel 13653: my %hostdom;
1.845 albertel 13654: my %libserv;
1.852 albertel 13655: my $loaded;
1.888 albertel 13656: my %name_to_host;
1.1074 raeburn 13657: my %internetdom;
1.1107 raeburn 13658: my %LC_dns_serv;
1.852 albertel 13659:
13660: sub parse_hosts_tab {
13661: my ($file) = @_;
13662: foreach my $configline (@$file) {
13663: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 13664: chomp($configline);
13665: if ($configline =~ /^\^/) {
13666: if ($configline =~ /^\^([\w.\-]+)/) {
13667: $LC_dns_serv{$1} = 1;
13668: }
13669: next;
13670: }
1.1074 raeburn 13671: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 13672: $name=~s/\s//g;
13673: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 13674: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13675: my $curr = $hostname{$id};
13676: my $skip;
13677: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13678: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13679: $skip = 1;
13680: } else {
13681: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13682: }
13683: }
13684: unless ($skip) {
13685: push(@{$name_to_host{$name}},$id);
13686: }
13687: } else {
13688: push(@{$name_to_host{$name}},$id);
13689: }
1.852 albertel 13690: $hostname{$id}=$name;
13691: $hostdom{$id}=$domain;
13692: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 13693: if (defined($protocol)) {
13694: if ($protocol eq 'https') {
13695: $protocol{$id} = $protocol;
13696: } else {
13697: $protocol{$id} = 'http';
13698: }
1.968 raeburn 13699: } else {
1.969 raeburn 13700: $protocol{$id} = 'http';
1.968 raeburn 13701: }
1.1074 raeburn 13702: if (defined($intdom)) {
13703: $internetdom{$id} = $intdom;
13704: }
1.852 albertel 13705: }
13706: }
13707: }
1.864 albertel 13708:
13709: sub reset_hosts_info {
1.897 albertel 13710: &purge_remembered();
1.864 albertel 13711: &reset_domain_info();
13712: &reset_hosts_ip_info();
1.892 albertel 13713: undef(%name_to_host);
1.864 albertel 13714: undef(%hostname);
13715: undef(%hostdom);
13716: undef(%libserv);
13717: undef($loaded);
13718: }
1.1 albertel 13719:
1.852 albertel 13720: sub load_hosts_tab {
1.1172.2.70 raeburn 13721: my ($ignore_cache,$nocache) = @_;
13722: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 13723: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 13724: my @config = <$config>;
13725: &parse_hosts_tab(\@config);
13726: close($config);
13727: $loaded=1;
1.1 albertel 13728: }
1.852 albertel 13729:
1.838 albertel 13730: sub hostname {
1.852 albertel 13731: &load_hosts_tab() if (!$loaded);
13732:
1.838 albertel 13733: my ($lonid) = @_;
13734: return $hostname{$lonid};
13735: }
1.845 albertel 13736:
1.838 albertel 13737: sub all_hostnames {
1.852 albertel 13738: &load_hosts_tab() if (!$loaded);
13739:
1.838 albertel 13740: return %hostname;
13741: }
1.845 albertel 13742:
1.888 albertel 13743: sub all_names {
1.1172.2.70 raeburn 13744: my ($ignore_cache,$nocache) = @_;
13745: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13746:
13747: return %name_to_host;
13748: }
13749:
1.974 raeburn 13750: sub all_host_domain {
13751: &load_hosts_tab() if (!$loaded);
13752: return %hostdom;
13753: }
13754:
1.845 albertel 13755: sub is_library {
1.852 albertel 13756: &load_hosts_tab() if (!$loaded);
13757:
1.845 albertel 13758: return exists($libserv{$_[0]});
13759: }
13760:
13761: sub all_library {
1.852 albertel 13762: &load_hosts_tab() if (!$loaded);
13763:
1.845 albertel 13764: return %libserv;
13765: }
13766:
1.1062 droeschl 13767: sub unique_library {
13768: #2x reverse removes all hostnames that appear more than once
13769: my %unique = reverse &all_library();
13770: return reverse %unique;
13771: }
13772:
1.841 albertel 13773: sub get_servers {
1.852 albertel 13774: &load_hosts_tab() if (!$loaded);
13775:
1.841 albertel 13776: my ($domain,$type) = @_;
13777: my %possible_hosts = ($type eq 'library') ? %libserv
13778: : %hostname;
13779: my %result;
1.842 albertel 13780: if (ref($domain) eq 'ARRAY') {
13781: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13782: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13783: $result{$host} = $hostname;
13784: }
13785: }
13786: } else {
13787: while ( my ($host,$hostname) = each(%possible_hosts)) {
13788: if ($hostdom{$host} eq $domain) {
13789: $result{$host} = $hostname;
13790: }
1.841 albertel 13791: }
13792: }
13793: return %result;
13794: }
1.845 albertel 13795:
1.1062 droeschl 13796: sub get_unique_servers {
13797: my %unique = reverse &get_servers(@_);
13798: return reverse %unique;
13799: }
13800:
1.844 albertel 13801: sub host_domain {
1.852 albertel 13802: &load_hosts_tab() if (!$loaded);
13803:
1.844 albertel 13804: my ($lonid) = @_;
13805: return $hostdom{$lonid};
13806: }
13807:
1.841 albertel 13808: sub all_domains {
1.852 albertel 13809: &load_hosts_tab() if (!$loaded);
13810:
1.841 albertel 13811: my %seen;
13812: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13813: return @uniq;
13814: }
1.1074 raeburn 13815:
13816: sub internet_dom {
13817: &load_hosts_tab() if (!$loaded);
13818:
13819: my ($lonid) = @_;
13820: return $internetdom{$lonid};
13821: }
1.1107 raeburn 13822:
13823: sub is_LC_dns {
13824: &load_hosts_tab() if (!$loaded);
13825:
13826: my ($hostname) = @_;
13827: return exists($LC_dns_serv{$hostname});
13828: }
13829:
1.1 albertel 13830: }
13831:
1.847 albertel 13832: {
13833: my %iphost;
1.856 albertel 13834: my %name_to_ip;
13835: my %lonid_to_ip;
1.869 albertel 13836:
1.847 albertel 13837: sub get_hosts_from_ip {
13838: my ($ip) = @_;
13839: my %iphosts = &get_iphost();
13840: if (ref($iphosts{$ip})) {
13841: return @{$iphosts{$ip}};
13842: }
13843: return;
1.839 albertel 13844: }
1.864 albertel 13845:
13846: sub reset_hosts_ip_info {
13847: undef(%iphost);
13848: undef(%name_to_ip);
13849: undef(%lonid_to_ip);
13850: }
1.856 albertel 13851:
13852: sub get_host_ip {
13853: my ($lonid) = @_;
13854: if (exists($lonid_to_ip{$lonid})) {
13855: return $lonid_to_ip{$lonid};
13856: }
13857: my $name=&hostname($lonid);
13858: my $ip = gethostbyname($name);
13859: return if (!$ip || length($ip) ne 4);
13860: $ip=inet_ntoa($ip);
13861: $name_to_ip{$name} = $ip;
13862: $lonid_to_ip{$lonid} = $ip;
13863: return $ip;
13864: }
1.847 albertel 13865:
13866: sub get_iphost {
1.1172.2.70 raeburn 13867: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13868:
1.869 albertel 13869: if (!$ignore_cache) {
13870: if (%iphost) {
13871: return %iphost;
13872: }
13873: my ($ip_info,$cached)=
13874: &Apache::lonnet::is_cached_new('iphost','iphost');
13875: if ($cached) {
13876: %iphost = %{$ip_info->[0]};
13877: %name_to_ip = %{$ip_info->[1]};
13878: %lonid_to_ip = %{$ip_info->[2]};
13879: return %iphost;
13880: }
13881: }
1.894 albertel 13882:
13883: # get yesterday's info for fallback
13884: my %old_name_to_ip;
13885: my ($ip_info,$cached)=
13886: &Apache::lonnet::is_cached_new('iphost','iphost');
13887: if ($cached) {
13888: %old_name_to_ip = %{$ip_info->[1]};
13889: }
13890:
1.1172.2.70 raeburn 13891: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13892: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13893: my $ip;
13894: if (!exists($name_to_ip{$name})) {
13895: $ip = gethostbyname($name);
13896: if (!$ip || length($ip) ne 4) {
1.894 albertel 13897: if (defined($old_name_to_ip{$name})) {
13898: $ip = $old_name_to_ip{$name};
13899: &logthis("Can't find $name defaulting to old $ip");
13900: } else {
13901: &logthis("Name $name no IP found");
13902: next;
13903: }
13904: } else {
13905: $ip=inet_ntoa($ip);
1.847 albertel 13906: }
13907: $name_to_ip{$name} = $ip;
13908: } else {
13909: $ip = $name_to_ip{$name};
1.653 albertel 13910: }
1.888 albertel 13911: foreach my $id (@{ $name_to_host{$name} }) {
13912: $lonid_to_ip{$id} = $ip;
13913: }
13914: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13915: }
1.1172.2.70 raeburn 13916: unless ($nocache) {
13917: &do_cache_new('iphost','iphost',
13918: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13919: 48*60*60);
13920: }
1.869 albertel 13921:
1.847 albertel 13922: return %iphost;
1.598 albertel 13923: }
13924:
1.992 raeburn 13925: #
13926: # Given a DNS returns the loncapa host name for that DNS
13927: #
13928: sub host_from_dns {
13929: my ($dns) = @_;
13930: my @hosts;
13931: my $ip;
13932:
1.993 raeburn 13933: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13934: $ip = $name_to_ip{$dns};
13935: }
13936: if (!$ip) {
13937: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13938: if (length($ip) == 4) {
13939: $ip = &IO::Socket::inet_ntoa($ip);
13940: }
13941: }
13942: if ($ip) {
13943: @hosts = get_hosts_from_ip($ip);
13944: return $hosts[0];
13945: }
13946: return undef;
1.986 foxr 13947: }
1.992 raeburn 13948:
1.1074 raeburn 13949: sub get_internet_names {
13950: my ($lonid) = @_;
13951: return if ($lonid eq '');
13952: my ($idnref,$cached)=
13953: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13954: if ($cached) {
13955: return $idnref;
13956: }
13957: my $ip = &get_host_ip($lonid);
13958: my @hosts = &get_hosts_from_ip($ip);
13959: my %iphost = &get_iphost();
13960: my (@idns,%seen);
13961: foreach my $id (@hosts) {
13962: my $dom = &host_domain($id);
13963: my $prim_id = &domain($dom,'primary');
13964: my $prim_ip = &get_host_ip($prim_id);
13965: next if ($seen{$prim_ip});
13966: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13967: foreach my $id (@{$iphost{$prim_ip}}) {
13968: my $intdom = &internet_dom($id);
13969: unless (grep(/^\Q$intdom\E$/,@idns)) {
13970: push(@idns,$intdom);
13971: }
13972: }
13973: }
13974: $seen{$prim_ip} = 1;
13975: }
1.1172.2.23 raeburn 13976: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13977: }
13978:
1.986 foxr 13979: }
13980:
1.1079 raeburn 13981: sub all_loncaparevs {
1.1172.2.39 raeburn 13982: 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 13983: }
13984:
1.1172.2.27 raeburn 13985: # ------------------------------------------------------- Read loncaparev table
13986: {
13987: sub load_loncaparevs {
13988: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 13989: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 13990: while (my $configline=<$config>) {
13991: chomp($configline);
13992: my ($hostid,$loncaparev)=split(/:/,$configline);
13993: $loncaparevs{$hostid}=$loncaparev;
13994: }
13995: close($config);
13996: }
13997: }
13998: }
13999: }
14000:
14001: # ----------------------------------------------------- Read serverhostID table
14002: {
14003: sub load_serverhomeIDs {
14004: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 14005: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 14006: while (my $configline=<$config>) {
14007: chomp($configline);
14008: my ($name,$id)=split(/:/,$configline);
14009: $serverhomeIDs{$name}=$id;
14010: }
14011: close($config);
14012: }
14013: }
14014: }
14015: }
14016:
14017:
1.862 albertel 14018: BEGIN {
14019:
14020: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14021: unless ($readit) {
14022: {
14023: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14024: %perlvar = (%perlvar,%{$configvars});
14025: }
14026:
14027:
1.1 albertel 14028: # ------------------------------------------------------ Read spare server file
14029: {
1.1172.2.96 raeburn 14030: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14031:
14032: while (my $configline=<$config>) {
14033: chomp($configline);
1.284 matthew 14034: if ($configline) {
1.784 albertel 14035: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14036: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14037: push(@{ $spareid{$type} }, $host);
1.1 albertel 14038: }
14039: }
1.448 albertel 14040: close($config);
1.1 albertel 14041: }
1.11 www 14042: # ------------------------------------------------------------ Read permissions
14043: {
1.1172.2.96 raeburn 14044: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14045:
14046: while (my $configline=<$config>) {
1.448 albertel 14047: chomp($configline);
14048: if ($configline) {
14049: my ($role,$perm)=split(/ /,$configline);
14050: if ($perm ne '') { $pr{$role}=$perm; }
14051: }
1.11 www 14052: }
1.448 albertel 14053: close($config);
1.11 www 14054: }
14055:
14056: # -------------------------------------------- Read plain texts for permissions
14057: {
1.1172.2.96 raeburn 14058: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14059:
14060: while (my $configline=<$config>) {
1.448 albertel 14061: chomp($configline);
14062: if ($configline) {
1.742 raeburn 14063: my ($short,@plain)=split(/:/,$configline);
14064: %{$prp{$short}} = ();
14065: if (@plain > 0) {
14066: $prp{$short}{'std'} = $plain[0];
14067: for (my $i=1; $i<@plain; $i++) {
14068: $prp{$short}{'alt'.$i} = $plain[$i];
14069: }
14070: }
1.448 albertel 14071: }
1.135 www 14072: }
1.448 albertel 14073: close($config);
1.135 www 14074: }
14075:
14076: # ---------------------------------------------------------- Read package table
14077: {
1.1172.2.96 raeburn 14078: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14079:
14080: while (my $configline=<$config>) {
1.483 albertel 14081: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14082: chomp($configline);
14083: my ($short,$plain)=split(/:/,$configline);
14084: my ($pack,$name)=split(/\&/,$short);
14085: if ($plain ne '') {
14086: $packagetab{$pack.'&'.$name.'&name'}=$name;
14087: $packagetab{$short}=$plain;
14088: }
1.11 www 14089: }
1.448 albertel 14090: close($config);
1.329 matthew 14091: }
14092:
1.1172.2.27 raeburn 14093: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 14094:
1.1172.2.27 raeburn 14095: &load_loncaparevs();
14096:
14097: # ------------------------------------------------------- Read serverhostID table
14098:
14099: &load_serverhomeIDs();
1.1074 raeburn 14100:
1.1172.2.27 raeburn 14101: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14102: {
14103: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14104: if (-e $file) {
14105: my $parser = HTML::LCParser->new($file);
14106: while (my $token = $parser->get_token()) {
14107: if ($token->[0] eq 'S') {
14108: my $item = $token->[1];
14109: my $name = $token->[2]{'name'};
14110: my $value = $token->[2]{'value'};
14111: if ($item ne '' && $name ne '' && $value ne '') {
14112: my $release = $parser->get_text();
14113: $release =~ s/(^\s*|\s*$ )//gx;
14114: $needsrelease{$item.':'.$name.':'.$value} = $release;
14115: }
14116: }
14117: }
14118: }
1.1073 raeburn 14119: }
14120:
1.1138 raeburn 14121: # ---------------------------------------------------------- Read managers table
14122: {
14123: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 14124: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14125: while (my $configline=<$config>) {
14126: chomp($configline);
14127: next if ($configline =~ /^\#/);
14128: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14129: $managerstab{$configline} = 1;
14130: }
14131: }
14132: close($config);
14133: }
14134: }
14135: }
14136:
1.329 matthew 14137: # ------------- set up temporary directory
14138: {
1.1117 foxr 14139: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14140:
1.11 www 14141: }
14142:
1.1172.2.104 raeburn 14143: # ------------- set default texengine (domain default overrides this)
14144: {
14145: $deftex = LONCAPA::texengine();
14146: }
14147:
1.1172.2.114 raeburn 14148: # ------------- set default minimum length for passwords for internal auth users
14149: {
14150: $passwdmin = LONCAPA::passwd_min();
14151: }
14152:
1.794 albertel 14153: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14154: 'compress_threshold'=> 20_000,
14155: });
1.185 www 14156:
1.281 www 14157: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14158: $dumpcount=0;
1.958 www 14159: $locknum=0;
1.22 www 14160:
1.163 harris41 14161: &logtouch();
1.672 albertel 14162: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14163: $readit=1;
1.564 albertel 14164: {
14165: use integer;
14166: my $test=(2**32)+1;
1.568 albertel 14167: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14168: &logthis(" Detected 64bit platform ($_64bit)");
14169: }
1.195 www 14170: }
1.1 albertel 14171: }
1.179 www 14172:
1.1 albertel 14173: 1;
1.191 harris41 14174: __END__
14175:
1.243 albertel 14176: =pod
14177:
1.191 harris41 14178: =head1 NAME
14179:
1.243 albertel 14180: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14181:
14182: =head1 SYNOPSIS
14183:
1.243 albertel 14184: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14185:
14186: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14187:
1.243 albertel 14188: Common parameters:
14189:
14190: =over 4
14191:
14192: =item *
14193:
14194: $uname : an internal username (if $cname expecting a course Id specifically)
14195:
14196: =item *
14197:
14198: $udom : a domain (if $cdom expecting a course's domain specifically)
14199:
14200: =item *
14201:
14202: $symb : a resource instance identifier
14203:
14204: =item *
14205:
14206: $namespace : the name of a .db file that contains the data needed or
14207: being set.
14208:
14209: =back
14210:
1.394 bowersj2 14211: =head1 OVERVIEW
1.191 harris41 14212:
1.394 bowersj2 14213: lonnet provides subroutines which interact with the
14214: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14215: about classes, users, and resources.
1.243 albertel 14216:
14217: For many of these objects you can also use this to store data about
14218: them or modify them in various ways.
1.191 harris41 14219:
1.394 bowersj2 14220: =head2 Symbs
1.191 harris41 14221:
1.394 bowersj2 14222: To identify a specific instance of a resource, LON-CAPA uses symbols
14223: or "symbs"X<symb>. These identifiers are built from the URL of the
14224: map, the resource number of the resource in the map, and the URL of
14225: the resource itself. The latter is somewhat redundant, but might help
14226: if maps change.
14227:
14228: An example is
14229:
14230: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14231:
14232: The respective map entry is
14233:
14234: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14235: title="Problem 2">
14236: </resource>
14237:
14238: Symbs are used by the random number generator, as well as to store and
14239: restore data specific to a certain instance of for example a problem.
14240:
14241: =head2 Storing And Retrieving Data
14242:
14243: X<store()>X<cstore()>X<restore()>Three of the most important functions
14244: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14245: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14246: is is the non-critical message twin of cstore. These functions are for
14247: handlers to store a perl hash to a user's permanent data space in an
14248: easy manner, and to retrieve it again on another call. It is expected
14249: that a handler would use this once at the beginning to retrieve data,
14250: and then again once at the end to send only the new data back.
14251:
14252: The data is stored in the user's data directory on the user's
14253: homeserver under the ID of the course.
14254:
14255: The hash that is returned by restore will have all of the previous
14256: value for all of the elements of the hash.
14257:
14258: Example:
14259:
14260: #creating a hash
14261: my %hash;
14262: $hash{'foo'}='bar';
14263:
14264: #storing it
14265: &Apache::lonnet::cstore(\%hash);
14266:
14267: #changing a value
14268: $hash{'foo'}='notbar';
14269:
14270: #adding a new value
14271: $hash{'bar'}='foo';
14272: &Apache::lonnet::cstore(\%hash);
14273:
14274: #retrieving the hash
14275: my %history=&Apache::lonnet::restore();
14276:
14277: #print the hash
14278: foreach my $key (sort(keys(%history))) {
14279: print("\%history{$key} = $history{$key}");
14280: }
14281:
14282: Will print out:
1.191 harris41 14283:
1.394 bowersj2 14284: %history{1:foo} = bar
14285: %history{1:keys} = foo:timestamp
14286: %history{1:timestamp} = 990455579
14287: %history{2:bar} = foo
14288: %history{2:foo} = notbar
14289: %history{2:keys} = foo:bar:timestamp
14290: %history{2:timestamp} = 990455580
14291: %history{bar} = foo
14292: %history{foo} = notbar
14293: %history{timestamp} = 990455580
14294: %history{version} = 2
14295:
14296: Note that the special hash entries C<keys>, C<version> and
14297: C<timestamp> were added to the hash. C<version> will be equal to the
14298: total number of versions of the data that have been stored. The
14299: C<timestamp> attribute will be the UNIX time the hash was
14300: stored. C<keys> is available in every historical section to list which
14301: keys were added or changed at a specific historical revision of a
14302: hash.
14303:
14304: B<Warning>: do not store the hash that restore returns directly. This
14305: will cause a mess since it will restore the historical keys as if the
14306: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14307:
1.394 bowersj2 14308: Calling convention:
1.191 harris41 14309:
1.1172.2.27 raeburn 14310: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 14311: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14312:
1.394 bowersj2 14313: For more detailed information, see lonnet specific documentation.
1.191 harris41 14314:
1.394 bowersj2 14315: =head1 RETURN MESSAGES
1.191 harris41 14316:
1.394 bowersj2 14317: =over 4
1.191 harris41 14318:
1.394 bowersj2 14319: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14320:
1.394 bowersj2 14321: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14322: when the connection is brought back up
1.191 harris41 14323:
1.394 bowersj2 14324: =item * B<con_failed>: unable to contact remote host and unable to save message
14325: for later delivery
1.191 harris41 14326:
1.967 bisitz 14327: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14328:
1.394 bowersj2 14329: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14330: that was requested
1.191 harris41 14331:
1.243 albertel 14332: =back
1.191 harris41 14333:
1.243 albertel 14334: =head1 PUBLIC SUBROUTINES
1.191 harris41 14335:
1.243 albertel 14336: =head2 Session Environment Functions
1.191 harris41 14337:
1.243 albertel 14338: =over 4
1.191 harris41 14339:
1.394 bowersj2 14340: =item *
14341: X<appenv()>
1.949 raeburn 14342: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14343: the user envirnoment file, and will be restored for each access this
1.620 albertel 14344: user makes during this session, also modifies the %env for the current
1.949 raeburn 14345: process. Optional rolesarrayref - if defined contains a reference to an array
14346: of roles which are exempt from the restriction on modifying user.role entries
14347: in the user's environment.db and in %env.
1.191 harris41 14348:
14349: =item *
1.394 bowersj2 14350: X<delenv()>
1.987 raeburn 14351: B<delenv($delthis,$regexp)>: removes all items from the session
14352: environment file that begin with $delthis. If the
14353: optional second arg - $regexp - is true, $delthis is treated as a
14354: regular expression, otherwise \Q$delthis\E is used.
14355: The values are also deleted from the current processes %env.
1.191 harris41 14356:
1.795 albertel 14357: =item * get_env_multiple($name)
14358:
14359: gets $name from the %env hash, it seemlessly handles the cases where multiple
14360: values may be defined and end up as an array ref.
14361:
14362: returns an array of values
14363:
1.243 albertel 14364: =back
14365:
14366: =head2 User Information
1.191 harris41 14367:
1.243 albertel 14368: =over 4
1.191 harris41 14369:
14370: =item *
1.394 bowersj2 14371: X<queryauthenticate()>
14372: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14373: authentication scheme
14374:
14375: =item *
1.394 bowersj2 14376: X<authenticate()>
1.1073 raeburn 14377: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14378: authenticate user from domain's lib servers (first use the current
14379: one). C<$upass> should be the users password.
1.1073 raeburn 14380: $checkdefauth is optional (value is 1 if a check should be made to
14381: authenticate user using default authentication method, and allow
14382: account creation if username does not have account in the domain).
14383: $clientcancheckhost is optional (value is 1 if checking whether the
14384: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14385:
14386: =item *
1.394 bowersj2 14387: X<homeserver()>
14388: B<homeserver($uname,$udom)>: find the server which has
14389: the user's directory and files (there must be only one), this caches
14390: the answer, and also caches if there is a borken connection.
1.191 harris41 14391:
14392: =item *
1.394 bowersj2 14393: X<idget()>
14394: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14395: (IDs are a unique resource in a domain, there must be only 1 ID per
14396: username, and only 1 username per ID in a specific domain) (returns
14397: hash: id=>name,id=>name)
1.191 harris41 14398:
14399: =item *
1.394 bowersj2 14400: X<idrget()>
14401: B<idrget($udom,@unames)>: find the IDs behind a list of
14402: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14403:
14404: =item *
1.394 bowersj2 14405: X<idput()>
14406: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 14407:
14408: =item *
1.394 bowersj2 14409: X<rolesinit()>
1.1169 droeschl 14410: B<rolesinit($udom,$username)>: get user privileges.
14411: returns user role, first access and timer interval hashes
1.243 albertel 14412:
14413: =item *
1.1171 droeschl 14414: X<privileged()>
14415: B<privileged($username,$domain)>: returns a true if user has a
14416: privileged and active role (i.e. su or dc), false otherwise.
14417:
14418: =item *
1.551 albertel 14419: X<getsection()>
14420: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14421: course $cname, return section name/number or '' for "not in course"
14422: and '-1' for "no section"
14423:
14424: =item *
1.394 bowersj2 14425: X<userenvironment()>
14426: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14427: passed in @what from the requested user's environment, returns a hash
14428:
1.858 raeburn 14429: =item *
14430: X<userlog_query()>
1.859 albertel 14431: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14432: activity.log file. %filters defines filters applied when parsing the
14433: log file. These can be start or end timestamps, or the type of action
14434: - log to look for Login or Logout events, check for Checkin or
14435: Checkout, role for role selection. The response is in the form
14436: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14437: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14438:
1.243 albertel 14439: =back
14440:
14441: =head2 User Roles
14442:
14443: =over 4
14444:
14445: =item *
14446:
1.1172.2.65 raeburn 14447: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14448: returns codes for allowed actions.
14449:
14450: The first argument is required, all others are optional.
14451:
14452: $priv is the privilege being checked.
14453: $uri contains additional information about what is being checked for access (e.g.,
14454: URL, course ID etc.).
14455: $symb is the unique resource instance identifier in a course; if needed,
14456: but not provided, it will be retrieved via a call to &symbread().
14457: $role is the role for which a priv is being checked (only used if priv is evb).
14458: $clientip is the user's IP address (only used when checking for access to portfolio
14459: files).
14460: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14461: prevents recursive calls to &allowed.
14462:
1.243 albertel 14463: F: full access
14464: U,I,K: authentication modes (cxx only)
14465: '': forbidden
14466: 1: user needs to choose course
14467: 2: browse allowed
1.766 albertel 14468: A: passphrase authentication needed
1.1172.2.65 raeburn 14469: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14470:
14471: =item *
14472:
1.1172.2.13 raeburn 14473: constructaccess($url,$setpriv) : check for access to construction space URL
14474:
14475: See if the owner domain and name in the URL match those in the
14476: expected environment. If so, return three element list
14477: ($ownername,$ownerdomain,$ownerhome).
14478:
14479: Otherwise return the null string.
14480:
14481: If second argument 'setpriv' is true, it assigns the privileges,
14482: and returns the same three element list, unless the owner has
14483: blocked "ad hoc" Domain Coordinator access to the Author Space,
14484: in which case the null string is returned.
14485:
14486: =item *
14487:
1.1172.2.84 raeburn 14488: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14489: define a custom role rolename set privileges in format of lonTabs/roles.tab
14490: for system, domain, and course level. $uname and $udom are optional (current
14491: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14492:
14493: =item *
14494:
1.988 raeburn 14495: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14496: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14497: $type is Course (default) or Community.
1.988 raeburn 14498: If $forcedefault evaluates to true, text returned will be default
14499: text for $type. Otherwise, if this is a course, the text returned
14500: will be a custom name for the role (if defined in the course's
14501: environment). If no custom name is defined the default is returned.
14502:
1.832 raeburn 14503: =item *
14504:
1.1172.2.23 raeburn 14505: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14506: All arguments are optional. Returns a hash of a roles, either for
14507: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14508: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14509: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14510: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14511: For each key, value is set to colon-separated start and end times for
14512: the role. If no username and domain are specified, will default to
1.934 raeburn 14513: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14514: of role statuses (active, future or previous), roles
14515: (e.g., cc,in, st etc.) and domains of the roles which can be used
14516: to restrict the list of roles reported. If no array ref is
14517: provided for types, will default to return only active roles.
1.834 albertel 14518:
1.1172.2.13 raeburn 14519: =item *
14520:
14521: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14522: user: $uname:$udom has a role in the course: $cdom_$cnum.
14523:
14524: Additional optional arguments are: $type (if role checking is to be restricted
14525: to certain user status types -- previous (expired roles), active (currently
14526: available roles) or future (roles available in the future), and
14527: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 14528: have active Domain Coordinator role in course's domain or in additional
14529: domains (specified in 'Domains to check for privileged users' in course
14530: environment -- set via: Course Settings -> Classlists and staff listing).
14531:
14532: =item *
14533:
14534: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14535: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14536: $possdomains and $possroles are optional array refs -- to domains to check and
14537: roles to check. If $possdomains is not specified, a dump will be done of the
14538: users' roles.db to check for a dc or su role in any domain. This can be
14539: time consuming if &privileged is called repeatedly (e.g., when displaying a
14540: classlist), so in such cases, supplying a $possdomains array is preferred, as
14541: this then allows &privileged_by_domain() to be used, which caches the identity
14542: of privileged users, eliminating the need for repeated calls to &dump().
14543:
14544: =item *
14545:
14546: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14547: where the outer hash keys are domains specified in the $possdomains array ref,
14548: next inner hash keys are privileged roles specified in the $roles array ref,
14549: and the innermost hash contains key = value pairs for username:domain = end:start
14550: for active or future "privileged" users with that role in that domain. To avoid
14551: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14552: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 14553:
1.243 albertel 14554: =back
14555:
14556: =head2 User Modification
14557:
14558: =over 4
14559:
14560: =item *
14561:
1.957 raeburn 14562: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 14563: user for the level given by URL. Optional start and end dates (leave empty
14564: string or zero for "no date")
1.191 harris41 14565:
14566: =item *
14567:
1.243 albertel 14568: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14569: change a users, password, possible return values are: ok,
14570: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14571: refused
1.191 harris41 14572:
14573: =item *
14574:
1.243 albertel 14575: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 14576:
14577: =item *
14578:
1.1058 raeburn 14579: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14580: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14581:
14582: will update user information (firstname,middlename,lastname,generation,
14583: permanentemail), and if forceid is true, student/employee ID also.
14584: A user's institutional affiliation(s) can also be updated.
14585: User information fields will not be overwritten with empty entries
14586: unless the field is included in the $candelete array reference.
14587: This array is included when a single user is modified via "Manage Users",
14588: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 14589:
14590: =item *
14591:
1.286 matthew 14592: modifystudent
14593:
1.957 raeburn 14594: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 14595: The course id is resolved based on the current user's environment.
14596: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 14597: associated with a course.
14598:
1.297 matthew 14599: This call is essentially a wrapper for lonnet::modifyuser and
14600: lonnet::modify_student_enrollment
1.286 matthew 14601:
14602: Inputs:
14603:
14604: =over 4
14605:
1.957 raeburn 14606: =item B<$udom> Student's loncapa domain
1.286 matthew 14607:
1.957 raeburn 14608: =item B<$uname> Student's loncapa login name
1.286 matthew 14609:
1.964 bisitz 14610: =item B<$uid> Student/Employee ID
1.286 matthew 14611:
1.957 raeburn 14612: =item B<$umode> Student's authentication mode
1.286 matthew 14613:
1.957 raeburn 14614: =item B<$upass> Student's password
1.286 matthew 14615:
1.957 raeburn 14616: =item B<$first> Student's first name
1.286 matthew 14617:
1.957 raeburn 14618: =item B<$middle> Student's middle name
1.286 matthew 14619:
1.957 raeburn 14620: =item B<$last> Student's last name
1.286 matthew 14621:
1.957 raeburn 14622: =item B<$gene> Student's generation
1.286 matthew 14623:
1.957 raeburn 14624: =item B<$usec> Student's section in course
1.286 matthew 14625:
14626: =item B<$end> Unix time of the roles expiration
14627:
14628: =item B<$start> Unix time of the roles start date
14629:
14630: =item B<$forceid> If defined, allow $uid to be changed
14631:
14632: =item B<$desiredhome> server to use as home server for student
14633:
1.957 raeburn 14634: =item B<$email> Student's permanent e-mail address
14635:
14636: =item B<$type> Type of enrollment (auto or manual)
14637:
1.963 raeburn 14638: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14639:
14640: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 14641:
1.963 raeburn 14642: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 14643:
1.963 raeburn 14644: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 14645:
1.1172.2.19 raeburn 14646: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14647:
14648: =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 14649:
1.286 matthew 14650: =back
1.297 matthew 14651:
14652: =item *
14653:
14654: modify_student_enrollment
14655:
1.1172.2.31 raeburn 14656: Change a student's enrollment status in a class. The environment variable
1.297 matthew 14657: 'role.request.course' must be defined for this function to proceed.
14658:
14659: Inputs:
14660:
14661: =over 4
14662:
1.1172.2.31 raeburn 14663: =item $udom, student's domain
1.297 matthew 14664:
1.1172.2.31 raeburn 14665: =item $uname, student's name
1.297 matthew 14666:
1.1172.2.31 raeburn 14667: =item $uid, student's user id
1.297 matthew 14668:
1.1172.2.31 raeburn 14669: =item $first, student's first name
1.297 matthew 14670:
14671: =item $middle
14672:
14673: =item $last
14674:
14675: =item $gene
14676:
14677: =item $usec
14678:
14679: =item $end
14680:
14681: =item $start
14682:
1.957 raeburn 14683: =item $type
14684:
14685: =item $locktype
14686:
14687: =item $cid
14688:
14689: =item $selfenroll
14690:
14691: =item $context
14692:
1.1172.2.19 raeburn 14693: =item $credits, number of credits student will earn from this class
14694:
1.1172.2.76 raeburn 14695: =item $instsec, institutional course section code for student
14696:
1.297 matthew 14697: =back
14698:
1.191 harris41 14699:
14700: =item *
14701:
1.243 albertel 14702: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14703: custom role; give a custom role to a user for the level given by URL. Specify
14704: name and domain of role author, and role name
1.191 harris41 14705:
14706: =item *
14707:
1.243 albertel 14708: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14709:
14710: =item *
14711:
1.243 albertel 14712: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14713:
14714: =back
14715:
14716: =head2 Course Infomation
14717:
14718: =over 4
1.191 harris41 14719:
14720: =item *
14721:
1.1118 foxr 14722: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14723: specified course id, including all environment settings for the
14724: course, the description of the course will be in the hash under the
14725: key 'description'
1.191 harris41 14726:
1.1118 foxr 14727: $options is an optional parameter that if supplied is a hash reference that controls
14728: what how this function works. It has the following key/values:
14729:
14730: =over 4
14731:
14732: =item freshen_cache
14733:
14734: If defined, and the environment cache for the course is valid, it is
14735: returned in the returned hash.
14736:
14737: =item one_time
14738:
14739: If defined, the last cache time is set to _now_
14740:
14741: =item user
14742:
14743: If defined, the supplied username is used instead of the current user.
14744:
14745:
14746: =back
14747:
1.191 harris41 14748: =item *
14749:
1.624 albertel 14750: resdata($name,$domain,$type,@which) : request for current parameter
14751: setting for a specific $type, where $type is either 'course' or 'user',
14752: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 14753: answers for 10 minutes.
1.243 albertel 14754:
1.877 foxr 14755: =item *
14756:
14757: get_courseresdata($courseid, $domain) : dump the entire course resource
14758: data base, returning a hash that is keyed by the resource name and has
14759: values that are the resource value. I believe that the timestamps and
14760: versions are also returned.
14761:
1.1172.2.31 raeburn 14762: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14763: supplemental content area. This routine caches the number of files for
14764: 10 minutes.
14765:
1.243 albertel 14766: =back
14767:
14768: =head2 Course Modification
14769:
14770: =over 4
1.191 harris41 14771:
14772: =item *
14773:
1.243 albertel 14774: writecoursepref($courseid,%prefs) : write preferences (environment
14775: database) for a course
1.191 harris41 14776:
14777: =item *
14778:
1.1011 raeburn 14779: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14780:
14781: =item *
14782:
1.1038 raeburn 14783: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14784:
1.1167 droeschl 14785: =item *
14786:
14787: is_course($courseid), is_course($cdom, $cnum)
14788:
14789: Accepts either a combined $courseid (in the form of domain_courseid) or the
14790: two component version $cdom, $cnum. It checks if the specified course exists.
14791:
14792: Returns:
14793: undef if the course doesn't exist, otherwise
14794: in scalar context the combined courseid.
14795: in list context the two components of the course identifier, domain and
14796: courseid.
14797:
1.243 albertel 14798: =back
14799:
1.1172.2.109 raeburn 14800: =head2 Bubblesheet Configuration
14801:
14802: =over 4
14803:
14804: =item *
14805:
14806: get_scantron_config($which)
14807:
14808: $which - the name of the configuration to parse from the file.
14809:
14810: Parses and returns the bubblesheet configuration line selected as a
14811: hash of configuration file fields.
14812:
14813:
14814: Returns:
14815: If the named configuration is not in the file, an empty
14816: hash is returned.
14817:
14818: a hash with the fields
14819: name - internal name for the this configuration setup
14820: description - text to display to operator that describes this config
14821: CODElocation - if 0 or the string 'none'
14822: - no CODE exists for this config
14823: if -1 || the string 'letter'
14824: - a CODE exists for this config and is
14825: a string of letters
14826: Unsupported value (but planned for future support)
14827: if a positive integer
14828: - The CODE exists as the first n items from
14829: the question section of the form
14830: if the string 'number'
14831: - The CODE exists for this config and is
14832: a string of numbers
14833: CODEstart - (only matter if a CODE exists) column in the line where
14834: the CODE starts
14835: CODElength - length of the CODE
14836: IDstart - column where the student/employee ID starts
14837: IDlength - length of the student/employee ID info
14838: Qstart - column where the information from the bubbled
14839: 'questions' start
14840: Qlength - number of columns comprising a single bubble line from
14841: the sheet. (usually either 1 or 10)
14842: Qon - either a single character representing the character used
14843: to signal a bubble was chosen in the positional setup, or
14844: the string 'letter' if the letter of the chosen bubble is
14845: in the final, or 'number' if a number representing the
14846: chosen bubble is in the file (1->A 0->J)
14847: Qoff - the character used to represent that a bubble was
14848: left blank
14849: PaperID - if the scanning process generates a unique number for each
14850: sheet scanned the column that this ID number starts in
14851: PaperIDlength - number of columns that comprise the unique ID number
14852: for the sheet of paper
14853: FirstName - column that the first name starts in
14854: FirstNameLength - number of columns that the first name spans
14855: LastName - column that the last name starts in
14856: LastNameLength - number of columns that the last name spans
14857: BubblesPerRow - number of bubbles available in each row used to
14858: bubble an answer. (If not specified, 10 assumed).
14859:
14860:
14861: =item *
14862:
14863: get_scantronformat_file($cdom)
14864:
14865: $cdom - the course's domain (optional); if not supplied, uses
14866: domain for current $env{'request.course.id'}.
14867:
14868: Returns an array containing lines from the scantron format file for
14869: the domain of the course.
14870:
14871: If a url for a custom.tab file is listed in domain's configuration.db,
14872: lines are from this file.
14873:
14874: Otherwise, if a default.tab has been published in RES space by the
14875: domainconfig user, lines are from this file.
14876:
14877: Otherwise, fall back to getting lines from the legacy file on the
14878: local server: /home/httpd/lonTabs/default_scantronformat.tab
14879:
14880: =back
14881:
1.243 albertel 14882: =head2 Resource Subroutines
14883:
14884: =over 4
1.191 harris41 14885:
14886: =item *
14887:
1.243 albertel 14888: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14889:
14890: =item *
14891:
1.243 albertel 14892: repcopy($filename) : subscribes to the requested file, and attempts to
14893: replicate from the owning library server, Might return
1.607 raeburn 14894: 'unavailable', 'not_found', 'forbidden', 'ok', or
14895: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14896: resource. Expects the local filesystem pathname
14897: (/home/httpd/html/res/....)
14898:
14899: =back
14900:
14901: =head2 Resource Information
14902:
14903: =over 4
1.191 harris41 14904:
14905: =item *
14906:
1.1172.2.28 raeburn 14907: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14908: and returns the value of a variety of different possible values,
14909: $varname should be a request string, and the other parameters can be
14910: used to specify who and what one is asking about. Ordinarily, $cid
14911: does not need to be specified, as it is retrived from
14912: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14913: within lonuserstate::loadmap() when initializing a course, before
14914: $env{'request.course.id'} has been set, so it needs to be provided
14915: in that one case.
1.243 albertel 14916:
14917: Possible values for $varname are environment.lastname (or other item
14918: from the envirnment hash), user.name (or someother aspect about the
14919: user), resource.0.maxtries (or some other part and parameter of a
14920: resource)
1.204 albertel 14921:
14922: =item *
14923:
1.243 albertel 14924: directcondval($number) : get current value of a condition; reads from a state
14925: string
1.204 albertel 14926:
14927: =item *
14928:
1.243 albertel 14929: condval($condidx) : value of condition index based on state
1.204 albertel 14930:
14931: =item *
14932:
1.243 albertel 14933: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14934: resource's metadata, $what should be either a specific key, or either
14935: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14936: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14937:
14938: this function automatically caches all requests
1.191 harris41 14939:
14940: =item *
14941:
1.243 albertel 14942: metadata_query($query,$custom,$customshow) : make a metadata query against the
14943: network of library servers; returns file handle of where SQL and regex results
14944: will be stored for query
1.191 harris41 14945:
14946: =item *
14947:
1.1172.2.66 raeburn 14948: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14949: return symbolic list entry (all arguments optional).
14950:
14951: Args: filename is the filename (including path) for the file for which a symb
14952: is required; donotrecurse, if true will prevent calls to allowed() being made
14953: to check access status if more than one resource was found in the bighash
14954: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14955: a randompick); ignorecachednull, if true will prevent a symb of '' being
14956: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14957: cause possible symbs to be checked to determine if they are subject to content
14958: blocking, if so they will not be included as possible symbs; possibles is a
14959: ref to a hash, which, as a side effect, will be populated with all possible
14960: symbs (content blocking not tested).
14961:
1.243 albertel 14962: returns the data handle
1.191 harris41 14963:
14964: =item *
14965:
1.1172.2.17 raeburn 14966: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 14967: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14968: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 14969: on failure, user must be in a course, as it assumes the existence of
14970: the course initial hash, and uses $env('request.course.id'}. The third
14971: arg is an optional reference to a scalar. If this arg is passed in the
14972: call to symbverify, it will be set to 1 if the symb has been set to be
14973: encrypted; otherwise it will be null.
1.243 albertel 14974:
1.191 harris41 14975: =item *
14976:
1.243 albertel 14977: symbclean($symb) : removes versions numbers from a symb, returns the
14978: cleaned symb
1.191 harris41 14979:
14980: =item *
14981:
1.243 albertel 14982: is_on_map($uri) : checks if the $uri is somewhere on the current
14983: course map, user must be in a course for it to work.
1.191 harris41 14984:
14985: =item *
14986:
1.243 albertel 14987: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14988:
14989: =item *
14990:
1.243 albertel 14991: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14992: a random seed, all arguments are optional, if they aren't sent it uses the
14993: environment to derive them. Note: if symb isn't sent and it can't get one
14994: from &symbread it will use the current time as its return value
1.191 harris41 14995:
14996: =item *
14997:
1.243 albertel 14998: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14999: unfakeable, receipt
1.191 harris41 15000:
15001: =item *
15002:
1.620 albertel 15003: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15004:
15005: =item *
15006:
1.243 albertel 15007: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15008:
15009: =item *
15010:
1.243 albertel 15011: 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 15012:
15013: =item *
15014:
1.243 albertel 15015: 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 15016:
15017: =item *
15018:
1.243 albertel 15019: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15020:
15021: =item *
15022:
1.243 albertel 15023: devalidate($symb) : devalidate temporary spreadsheet calculations,
15024: forcing spreadsheet to reevaluate the resource scores next time.
15025:
1.1172.2.13 raeburn 15026: =item *
15027:
15028: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15029: when viewing in course context.
15030:
15031: input: six args -- filename (decluttered), course number, course domain,
15032: url, symb (if registered) and group (if this is a
15033: group item -- e.g., bulletin board, group page etc.).
15034:
15035: output: array of five scalars --
15036: $cfile -- url for file editing if editable on current server
15037: $home -- homeserver of resource (i.e., for author if published,
15038: or course if uploaded.).
15039: $switchserver -- 1 if server switch will be needed.
15040: $forceedit -- 1 if icon/link should be to go to edit mode
15041: $forceview -- 1 if icon/link should be to go to view mode
15042:
15043: =item *
15044:
15045: is_course_upload($file,$cnum,$cdom)
15046:
15047: Used in course context to determine if current file was uploaded to
15048: the course (i.e., would be found in /userfiles/docs on the course's
15049: homeserver.
15050:
15051: input: 3 args -- filename (decluttered), course number and course domain.
15052: output: boolean -- 1 if file was uploaded.
15053:
1.243 albertel 15054: =back
15055:
15056: =head2 Storing/Retreiving Data
15057:
15058: =over 4
1.191 harris41 15059:
15060: =item *
15061:
1.1172.2.64 raeburn 15062: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15063: permanently for this url; hashref needs to be given and should be a \%hashname;
15064: the remaining args aren't required and if they aren't passed or are '' they will
15065: be derived from the env (with the exception of $laststore, which is an
15066: optional arg used when a user's submission is stored in grading).
15067: $laststore is $version=$timestamp, where $version is the most recent version
15068: number retrieved for the corresponding $symb in the $namespace db file, and
15069: $timestamp is the timestamp for that transaction (UNIX time).
15070: $laststore is currently only passed when cstore() is called by
15071: structuretags::finalize_storage().
1.191 harris41 15072:
15073: =item *
15074:
1.1172.2.64 raeburn 15075: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15076: but uses critical subroutine
1.191 harris41 15077:
15078: =item *
15079:
1.243 albertel 15080: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15081: all args are optional
1.191 harris41 15082:
15083: =item *
15084:
1.717 albertel 15085: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15086: dumps the complete (or key matching regexp) namespace into a hash
15087: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15088: normally &store()ed into
15089:
15090: $range should be either an integer '100' (give me the first 100
15091: matching records)
15092: or be two integers sperated by a - with no spaces
15093: '30-50' (give me the 30th through the 50th matching
15094: records)
15095:
15096:
15097: =item *
15098:
1.1172.2.59 raeburn 15099: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15100: replaces a &store() version of data with a replacement set of data
15101: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 15102: reference. If $tolog is true, the transaction is logged in the courselog
15103: with an action=PUTSTORE.
1.717 albertel 15104:
15105: =item *
15106:
1.243 albertel 15107: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15108: works very similar to store/cstore, but all data is stored in a
15109: temporary location and can be reset using tmpreset, $storehash should
15110: be a hash reference, returns nothing on success
1.191 harris41 15111:
15112: =item *
15113:
1.243 albertel 15114: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15115: similar to restore, but all data is stored in a temporary location and
15116: can be reset using tmpreset. Returns a hash of values on success,
15117: error string otherwise.
1.191 harris41 15118:
15119: =item *
15120:
1.243 albertel 15121: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15122: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15123:
15124: =item *
15125:
1.243 albertel 15126: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15127: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15128:
15129: =item *
15130:
1.243 albertel 15131: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15132: namesp ($udom and $uname are optional)
1.191 harris41 15133:
15134: =item *
15135:
1.702 albertel 15136: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15137: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15138: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15139:
1.702 albertel 15140: $range should be either an integer '100' (give me the first 100
15141: matching records)
15142: or be two integers sperated by a - with no spaces
15143: '30-50' (give me the 30th through the 50th matching
15144: records)
1.449 matthew 15145: =item *
15146:
15147: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15148: $store can be a scalar, an array reference, or if the amount to be
15149: incremented is > 1, a hash reference.
15150:
15151: ($udom and $uname are optional)
1.191 harris41 15152:
15153: =item *
15154:
1.243 albertel 15155: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15156: ($udom and $uname are optional)
1.191 harris41 15157:
15158: =item *
15159:
1.243 albertel 15160: cput($namespace,$storehash,$udom,$uname) : critical put
15161: ($udom and $uname are optional)
1.191 harris41 15162:
15163: =item *
15164:
1.748 albertel 15165: newput($namespace,$storehash,$udom,$uname) :
15166:
15167: Attempts to store the items in the $storehash, but only if they don't
15168: currently exist, if this succeeds you can be certain that you have
15169: successfully created a new key value pair in the $namespace db.
15170:
15171:
15172: Args:
15173: $namespace: name of database to store values to
15174: $storehash: hashref to store to the db
15175: $udom: (optional) domain of user containing the db
15176: $uname: (optional) name of user caontaining the db
15177:
15178: Returns:
15179: 'ok' -> succeeded in storing all keys of $storehash
15180: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15181: least <key> already existed in the db (other
15182: requested keys may also already exist)
1.967 bisitz 15183: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15184: 'con_lost' -> unable to contact request server
15185: 'refused' -> action was not allowed by remote machine
15186:
15187:
15188: =item *
15189:
1.243 albertel 15190: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15191: reference filled in from namesp (encrypts the return communication)
15192: ($udom and $uname are optional)
1.191 harris41 15193:
15194: =item *
15195:
1.243 albertel 15196: log($udom,$name,$home,$message) : write to permanent log for user; use
15197: critical subroutine
15198:
1.806 raeburn 15199: =item *
15200:
1.860 raeburn 15201: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15202: array reference filled in from namespace found in domain level on either
15203: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15204:
15205: =item *
15206:
1.860 raeburn 15207: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15208: domain level either on specified domain server ($uhome) or primary domain
15209: server ($udom and $uhome are optional)
1.806 raeburn 15210:
1.943 raeburn 15211: =item *
15212:
1.1172.2.35 raeburn 15213: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15214: for: authentication, language, quotas, timezone, date locale, and portal URL in
15215: the target domain.
15216:
15217: May also include additional key => value pairs for the following groups:
15218:
15219: =over
15220:
15221: =item
15222: disk quotas (MB allocated by default to portfolios and authoring spaces).
15223:
15224: =over
15225:
15226: =item defaultquota, authorquota
15227:
15228: =back
15229:
15230: =item
15231: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15232: portfolio for users).
15233:
15234: =over
15235:
15236: =item
15237: aboutme, blog, webdav, portfolio
15238:
15239: =back
15240:
15241: =item
15242: requestcourses: ability to request courses, and how requests are processed.
15243:
15244: =over
15245:
15246: =item
1.1172.2.37 raeburn 15247: official, unofficial, community, textbook
1.1172.2.35 raeburn 15248:
15249: =back
15250:
15251: =item
15252: inststatus: types of institutional affiliation, and order in which they are displayed.
15253:
15254: =over
15255:
15256: =item
1.1172.2.44 raeburn 15257: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 15258:
15259: =back
15260:
15261: =item
15262: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15263: for course's uploaded content.
15264:
15265: =over
15266:
15267: =item
1.1172.2.68 raeburn 15268: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15269: communityquota, textbookquota
1.1172.2.35 raeburn 15270:
15271: =back
15272:
15273: =item
15274: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15275: on your servers.
15276:
15277: =over
15278:
15279: =item
15280: remotesessions, hostedsessions
15281:
15282: =back
15283:
15284: =back
15285:
15286: In cases where a domain coordinator has never used the "Set Domain Configuration"
15287: utility to create a configuration.db file on a domain's primary library server
15288: only the following domain defaults: auth_def, auth_arg_def, lang_def
15289: -- corresponding values are authentication type (internal, krb4, krb5,
15290: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15291: will be available. Values are retrieved from cache (if current), unless the
15292: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15293: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15294:
15295: Typical usage:
1.943 raeburn 15296:
1.1172.2.35 raeburn 15297: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 15298:
1.243 albertel 15299: =back
15300:
15301: =head2 Network Status Functions
15302:
15303: =over 4
1.191 harris41 15304:
15305: =item *
15306:
1.1137 raeburn 15307: dirlist() : return directory list based on URI (first arg).
15308:
15309: Inputs: 1 required, 5 optional.
15310:
15311: =over
15312:
15313: =item
15314: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15315:
15316: =item
15317: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15318:
15319: =item
15320: $username - username of user/course to be listed. Extracted from $uri if absent.
15321:
15322: =item
15323: $getpropath - boolean: 1 if prepend path using &propath().
15324:
15325: =item
15326: $getuserdir - boolean: 1 if prepend path for "userfiles".
15327:
15328: =item
15329: $alternateRoot - path to prepend in place of path from $uri.
15330:
15331: =back
15332:
15333: Returns: Array of up to two items.
15334:
15335: =over
15336:
15337: a reference to an array of files/subdirectories
15338:
15339: =over
15340:
15341: Each element in the array of files/subdirectories is a & separated list of
15342: item name and the result of running stat on the item. If dirlist was requested
15343: for a file instead of a directory, the item name will be ''. For a directory
15344: listing, if the item is a metadata file, the element will end &N&M
15345: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15346: default copyright set (1).
15347:
15348: =back
15349:
15350: a scalar containing error condition (if encountered).
15351:
15352: =over
15353:
15354: =item
15355: no_host (no homeserver identified for $username:$domain).
15356:
15357: =item
15358: no_such_host (server contacted for listing not identified as valid host).
15359:
15360: =item
15361: con_lost (connection to remote server failed).
15362:
15363: =item
15364: refused (invalid $username:$domain received on lond side).
15365:
15366: =item
15367: no_such_dir (directory at specified path on lond side does not exist).
15368:
15369: =item
15370: empty (directory at specified path on lond side is empty).
15371:
15372: =over
15373:
15374: This is currently not encountered because the &ls3, &ls2,
15375: &ls (_handler) routines on the lond side do not filter out
15376: . and .. from a directory listing.
15377:
15378: =back
15379:
15380: =back
15381:
15382: =back
1.191 harris41 15383:
15384: =item *
15385:
1.243 albertel 15386: spareserver() : find server with least workload from spare.tab
15387:
1.986 foxr 15388:
15389: =item *
15390:
15391: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15392: if there is no corresponding loncapa host.
15393:
1.243 albertel 15394: =back
15395:
1.986 foxr 15396:
1.243 albertel 15397: =head2 Apache Request
15398:
15399: =over 4
1.191 harris41 15400:
15401: =item *
15402:
1.243 albertel 15403: ssi($url,%hash) : server side include, does a complete request cycle on url to
15404: localhost, posts hash
15405:
15406: =back
15407:
15408: =head2 Data to String to Data
15409:
15410: =over 4
1.191 harris41 15411:
15412: =item *
15413:
1.243 albertel 15414: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15415: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15416:
15417: =item *
15418:
1.243 albertel 15419: hashref2str($hashref) : convert a hashref into a string complete with
15420: escaping and '=' and '&' separators, supports elements that are
15421: arrayrefs and hashrefs
1.191 harris41 15422:
15423: =item *
15424:
1.243 albertel 15425: arrayref2str($arrayref) : convert an arrayref into a string complete
15426: with escaping and '&' separators, supports elements that are arrayrefs
15427: and hashrefs
1.191 harris41 15428:
15429: =item *
15430:
1.243 albertel 15431: str2hash($string) : convert string to hash using unescaping and
15432: splitting on '=' and '&', supports elements that are arrayrefs and
15433: hashrefs
1.191 harris41 15434:
15435: =item *
15436:
1.243 albertel 15437: str2array($string) : convert string to hash using unescaping and
15438: splitting on '&', supports elements that are arrayrefs and hashrefs
15439:
15440: =back
15441:
15442: =head2 Logging Routines
15443:
15444:
15445: These routines allow one to make log messages in the lonnet.log and
15446: lonnet.perm logfiles.
1.191 harris41 15447:
1.1119 foxr 15448: =over 4
15449:
1.191 harris41 15450: =item *
15451:
1.243 albertel 15452: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15453:
15454: =item *
15455:
1.243 albertel 15456: logthis() : append message to the normal lonnet.log file, it gets
15457: preiodically rolled over and deleted.
1.191 harris41 15458:
15459: =item *
15460:
1.243 albertel 15461: logperm() : append a permanent message to lonnet.perm.log, this log
15462: file never gets deleted by any automated portion of the system, only
15463: messages of critical importance should go in here.
15464:
1.1119 foxr 15465:
1.243 albertel 15466: =back
15467:
15468: =head2 General File Helper Routines
15469:
15470: =over 4
1.191 harris41 15471:
15472: =item *
15473:
1.481 raeburn 15474: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15475: (a) files in /uploaded
15476: (i) If a local copy of the file exists -
15477: compares modification date of local copy with last-modified date for
15478: definitive version stored on home server for course. If local copy is
15479: stale, requests a new version from the home server and stores it.
15480: If the original has been removed from the home server, then local copy
15481: is unlinked.
15482: (ii) If local copy does not exist -
15483: requests the file from the home server and stores it.
15484:
15485: If $caller is 'uploadrep':
15486: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15487: for request for files originally uploaded via DOCS.
15488: - returns 'ok' if fresh local copy now available, -1 otherwise.
15489:
15490: Otherwise:
15491: This indicates a call from the content generation phase of the request.
15492: - returns the entire contents of the file or -1.
15493:
15494: (b) files in /res
15495: - returns the entire contents of a file or -1;
15496: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 15497:
1.712 albertel 15498:
15499: =item *
15500:
15501: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15502: reference
15503:
15504: returns either a stat() list of data about the file or an empty list
15505: if the file doesn't exist or couldn't find out about it (connection
15506: problems or user unknown)
15507:
1.191 harris41 15508: =item *
15509:
1.243 albertel 15510: filelocation($dir,$file) : returns file system location of a file
15511: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15512: directory that relative $file lookups are to looked in ($dir of /a/dir
15513: and a file of ../bob will become /a/bob)
1.191 harris41 15514:
15515: =item *
15516:
15517: hreflocation($dir,$file) : returns file system location or a URL; same as
15518: filelocation except for hrefs
15519:
15520: =item *
15521:
1.1172.2.49 raeburn 15522: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15523: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 15524:
1.243 albertel 15525: =back
15526:
1.608 albertel 15527: =head2 Usererfile file routines (/uploaded*)
15528:
15529: =over 4
15530:
15531: =item *
15532:
15533: userfileupload(): main rotine for putting a file in a user or course's
15534: filespace, arguments are,
15535:
1.620 albertel 15536: formname - required - this is the name of the element in $env where the
1.608 albertel 15537: filename, and the contents of the file to create/modifed exist
1.620 albertel 15538: the filename is in $env{'form.'.$formname.'.filename'} and the
15539: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 15540: context - if coursedoc, store the file in the course of the active role
15541: of the current user;
15542: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15543: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 15544: subdir - required - subdirectory to put the file in under ../userfiles/
15545: if undefined, it will be placed in "unknown"
15546:
15547: (This routine calls clean_filename() to remove any dangerous
15548: characters from the filename, and then calls finuserfileupload() to
15549: complete the transaction)
15550:
15551: returns either the url of the uploaded file (/uploaded/....) if successful
15552: and /adm/notfound.html if unsuccessful
15553:
15554: =item *
15555:
15556: clean_filename(): routine for cleaing a filename up for storage in
15557: userfile space, argument is:
15558:
15559: filename - proposed filename
15560:
15561: returns: the new clean filename
15562:
15563: =item *
15564:
1.1090 raeburn 15565: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 15566: userspace, probably shouldn't be called directly
15567:
15568: docuname: username or courseid of destination for the file
15569: docudom: domain of user/course of destination for the file
15570: formname: same as for userfileupload()
1.1090 raeburn 15571: fname: filename (including subdirectories) for the file
15572: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 15573: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 15574: allfiles: reference to hash used to store objects found by parser
15575: codebase: reference to hash used for codebases of java objects found by parser
15576: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15577: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15578: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15579: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15580: context: if 'overwrite', will move the uploaded file from its temporary location to
15581: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 15582: mimetype: reference to scalar to accommodate mime type determined
15583: from File::MMagic if $parser = parse.
1.608 albertel 15584:
15585: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 15586: and /adm/notfound.html if unsuccessful (or an error message if context
15587: was 'overwrite').
15588:
1.608 albertel 15589:
15590: =item *
15591:
15592: renameuserfile(): renames an existing userfile to a new name
15593:
15594: Args:
15595: docuname: username or courseid of destination for the file
15596: docudom: domain of user/course of destination for the file
15597: old: current file name (including any subdirs under userfiles)
15598: new: desired file name (including any subdirs under userfiles)
15599:
15600: =item *
15601:
15602: mkdiruserfile(): creates a directory is a userfiles dir
15603:
15604: Args:
15605: docuname: username or courseid of destination for the file
15606: docudom: domain of user/course of destination for the file
15607: dir: dir to create (including any subdirs under userfiles)
15608:
15609: =item *
15610:
15611: removeuserfile(): removes a file that exists in userfiles
15612:
15613: Args:
15614: docuname: username or courseid of destination for the file
15615: docudom: domain of user/course of destination for the file
15616: fname: filname to delete (including any subdirs under userfiles)
15617:
15618: =item *
15619:
15620: removeuploadedurl(): convience function for removeuserfile()
15621:
15622: Args:
15623: url: a full /uploaded/... url to delete
15624:
1.747 albertel 15625: =item *
15626:
15627: get_portfile_permissions():
15628: Args:
15629: domain: domain of user or course contain the portfolio files
15630: user: name of user or num of course contain the portfolio files
15631: Returns:
15632: hashref of a dump of the proper file_permissions.db
15633:
15634:
15635: =item *
15636:
15637: get_access_controls():
15638:
15639: Args:
15640: current_permissions: the hash ref returned from get_portfile_permissions()
15641: group: (optional) the group you want the files associated with
15642: file: (optional) the file you want access info on
15643:
15644: Returns:
1.749 raeburn 15645: a hash (keys are file names) of hashes containing
15646: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15647: values are XML containing access control settings (see below)
1.747 albertel 15648:
15649: Internal notes:
15650:
1.749 raeburn 15651: access controls are stored in file_permissions.db as key=value pairs.
15652: key -> path to file/file_name\0uniqueID:scope_end_start
15653: where scope -> public,guest,course,group,domains or users.
15654: end -> UNIX time for end of access (0 -> no end date)
15655: start -> UNIX time for start of access
15656:
15657: value -> XML description of access control
15658: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15659: <start></start>
15660: <end></end>
15661:
15662: <password></password> for scope type = guest
15663:
15664: <domain></domain> for scope type = course or group
15665: <number></number>
15666: <roles id="">
15667: <role></role>
15668: <access></access>
15669: <section></section>
15670: <group></group>
15671: </roles>
15672:
15673: <dom></dom> for scope type = domains
15674:
15675: <users> for scope type = users
15676: <user>
15677: <uname></uname>
15678: <udom></udom>
15679: </user>
15680: </users>
15681: </scope>
15682:
15683: Access data is also aggregated for each file in an additional key=value pair:
15684: key -> path to file/file_name\0accesscontrol
15685: value -> reference to hash
15686: hash contains key = value pairs
15687: where key = uniqueID:scope_end_start
15688: value = UNIX time record was last updated
15689:
15690: Used to improve speed of look-ups of access controls for each file.
15691:
15692: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15693:
1.1172.2.13 raeburn 15694: =item *
15695:
1.749 raeburn 15696: modify_access_controls():
15697:
15698: Modifies access controls for a portfolio file
15699: Args
15700: 1. file name
15701: 2. reference to hash of required changes,
15702: 3. domain
15703: 4. username
15704: where domain,username are the domain of the portfolio owner
15705: (either a user or a course)
15706:
15707: Returns:
15708: 1. result of additions or updates ('ok' or 'error', with error message).
15709: 2. result of deletions ('ok' or 'error', with error message).
15710: 3. reference to hash of any new or updated access controls.
15711: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15712: key = integer (inbound ID)
1.1172.2.13 raeburn 15713: value = uniqueID
15714:
15715: =item *
15716:
15717: get_timebased_id():
15718:
15719: Attempts to get a unique timestamp-based suffix for use with items added to a
15720: course via the Course Editor (e.g., folders, composite pages,
15721: group bulletin boards).
15722:
15723: Args: (first three required; six others optional)
15724:
15725: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15726: docssequence, or name of group
15727:
15728: 2. keyid (alphanumeric): name of temporary locking key in hash,
15729: e.g., num, boardids
15730:
15731: 3. namespace: name of gdbm file used to store suffixes already assigned;
15732: file will be named nohist_namespace.db
15733:
15734: 4. cdom: domain of course; default is current course domain from %env
15735:
15736: 5. cnum: course number; default is current course number from %env
15737:
15738: 6. idtype: set to concat if an additional digit is to be appended to the
15739: unix timestamp to form the suffix, if the plain timestamp is already
15740: in use. Default is to not do this, but simply increment the unix
15741: timestamp by 1 until a unique key is obtained.
15742:
15743: 7. who: holder of locking key; defaults to user:domain for user.
15744:
15745: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15746: retrying); default is 3.
15747:
15748: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15749:
15750: Returns:
15751:
15752: 1. suffix obtained (numeric)
15753:
15754: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15755:
15756: 3. error: contains (localized) error message if an error occurred.
15757:
1.747 albertel 15758:
1.608 albertel 15759: =back
15760:
1.243 albertel 15761: =head2 HTTP Helper Routines
15762:
15763: =over 4
15764:
1.191 harris41 15765: =item *
15766:
15767: escape() : unpack non-word characters into CGI-compatible hex codes
15768:
15769: =item *
15770:
15771: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15772:
1.243 albertel 15773: =back
15774:
15775: =head1 PRIVATE SUBROUTINES
15776:
15777: =head2 Underlying communication routines (Shouldn't call)
15778:
15779: =over 4
15780:
15781: =item *
15782:
15783: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15784:
15785: =item *
15786:
15787: reply() : uses subreply to send a message to remote machine, logs all failures
15788:
15789: =item *
15790:
15791: critical() : passes a critical message to another server; if cannot
15792: get through then place message in connection buffer directory and
15793: returns con_delayed, if incapable of saving message, returns
15794: con_failed
15795:
15796: =item *
15797:
15798: reconlonc() : tries to reconnect lonc client processes.
15799:
15800: =back
15801:
15802: =head2 Resource Access Logging
15803:
15804: =over 4
15805:
15806: =item *
15807:
15808: flushcourselogs() : flush (save) buffer logs and access logs
15809:
15810: =item *
15811:
15812: courselog($what) : save message for course in hash
15813:
15814: =item *
15815:
15816: courseacclog($what) : save message for course using &courselog(). Perform
15817: special processing for specific resource types (problems, exams, quizzes, etc).
15818:
1.191 harris41 15819: =item *
15820:
15821: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15822: as a PerlChildExitHandler
1.243 albertel 15823:
15824: =back
15825:
15826: =head2 Other
15827:
15828: =over 4
15829:
15830: =item *
15831:
15832: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15833:
15834: =back
15835:
15836: =cut
1.877 foxr 15837:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>