Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.148
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.148! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.147 2022/02/27 02:19:13 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.1172.2.142 raeburn 98: use Net::CIDR;
99: use Sys::Hostname::FQDN();
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 103: use LONCAPA::Lond;
1.1172.2.110 raeburn 104: use LONCAPA::transliterate;
1.1117 foxr 105:
1.1090 raeburn 106: use File::Copy;
1.676 albertel 107:
1.195 www 108: my $readit;
1.1172.2.79 raeburn 109: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 110:
1.619 albertel 111: require Exporter;
112:
113: our @ISA = qw (Exporter);
114: our @EXPORT = qw(%env);
115:
1.1172.2.9 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1172.2.9 raeburn 119: sub write_log {
120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1172.2.13 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.134 raeburn 130: my $ip = &get_requestor_ip();
1.1172.2.9 raeburn 131: my $logentry = {
132: $id => {
133: 'exe_uname' => $env{'user.name'},
134: 'exe_udom' => $env{'user.domain'},
135: 'exe_time' => $now,
1.1172.2.134 raeburn 136: 'exe_ip' => $ip,
1.1172.2.9 raeburn 137: 'delflag' => $delflag,
138: 'logentry' => $storehash,
139: 'uname' => $uname,
140: 'udom' => $udom,
141: }
142: };
143: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 144: }
145: }
1.1 albertel 146:
1.163 harris41 147: sub logtouch {
148: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 149: unless (-e "$execdir/logs/lonnet.log") {
1.1172.2.96 raeburn 150: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 151: close $fh;
152: }
153: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
154: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
155: }
156:
1.1 albertel 157: sub logthis {
158: my $message=shift;
159: my $execdir=$perlvar{'lonDaemons'};
160: my $now=time;
161: my $local=localtime($now);
1.1172.2.96 raeburn 162: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 163: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
164: print $fh $logstring;
1.448 albertel 165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
170: sub logperm {
171: my $message=shift;
172: my $execdir=$perlvar{'lonDaemons'};
173: my $now=time;
174: my $local=localtime($now);
1.1172.2.96 raeburn 175: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 176: print $fh "$now:$message:$local\n";
177: close($fh);
178: }
1.1 albertel 179: return 1;
180: }
181:
1.850 albertel 182: sub create_connection {
1.853 albertel 183: my ($hostname,$lonid) = @_;
1.851 albertel 184: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 185: Type => SOCK_STREAM,
186: Timeout => 10);
187: return 0 if (!$client);
1.890 albertel 188: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 189: my $result = <$client>;
190: chomp($result);
191: return 1 if ($result eq 'done');
192: return 0;
193: }
194:
1.983 raeburn 195: sub get_server_timezone {
196: my ($cnum,$cdom) = @_;
197: my $home=&homeserver($cnum,$cdom);
198: if ($home ne 'no_host') {
199: my $cachetime = 24*3600;
200: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
201: if (defined($cached)) {
202: return $timezone;
203: } else {
204: my $timezone = &reply('servertimezone',$home);
205: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
206: }
207: }
208: }
1.850 albertel 209:
1.1106 raeburn 210: sub get_server_distarch {
211: my ($lonhost,$ignore_cache) = @_;
212: if (defined($lonhost)) {
213: if (!defined(&hostname($lonhost))) {
214: return;
215: }
216: my $cachetime = 12*3600;
217: if (!$ignore_cache) {
218: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
219: if (defined($cached)) {
220: return $distarch;
221: }
222: }
223: my $rep = &reply('serverdistarch',$lonhost);
224: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
225: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
226: $rep eq '') {
227: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
228: }
229: }
230: return;
231: }
232:
1.993 raeburn 233: sub get_server_loncaparev {
1.1073 raeburn 234: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 235: if (defined($lonhost)) {
236: if (!defined(&hostname($lonhost))) {
237: undef($lonhost);
238: }
239: }
240: if (!defined($lonhost)) {
241: if (defined(&domain($dom,'primary'))) {
242: $lonhost=&domain($dom,'primary');
243: if ($lonhost eq 'no_host') {
244: undef($lonhost);
245: }
246: }
247: }
248: if (defined($lonhost)) {
1.1073 raeburn 249: my $cachetime = 12*3600;
250: if (!$ignore_cache) {
251: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
252: if (defined($cached)) {
253: return $loncaparev;
254: }
255: }
256: my ($answer,$loncaparev);
257: my @ids=¤t_machine_ids();
258: if (grep(/^\Q$lonhost\E$/,@ids)) {
259: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 260: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 261: $loncaparev = $1;
262: }
263: } else {
264: $answer = &reply('serverloncaparev',$lonhost);
265: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
266: if ($caller eq 'loncron') {
267: my $ua=new LWP::UserAgent;
1.1082 raeburn 268: $ua->timeout(4);
1.1172.2.120 raeburn 269: my $hostname = &hostname($lonhost);
1.1073 raeburn 270: my $protocol = $protocol{$lonhost};
271: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 272: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 273: my $request=new HTTP::Request('GET',$url);
274: my $response=$ua->request($request);
275: unless ($response->is_error()) {
276: my $content = $response->content;
1.1081 raeburn 277: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 278: $loncaparev = $1;
279: }
280: }
281: } else {
282: $loncaparev = $loncaparevs{$lonhost};
283: }
1.1081 raeburn 284: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 285: $loncaparev = $1;
286: }
1.993 raeburn 287: }
1.1073 raeburn 288: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 289: }
290: }
291:
1.1074 raeburn 292: sub get_server_homeID {
293: my ($hostname,$ignore_cache,$caller) = @_;
294: unless ($ignore_cache) {
295: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
296: if (defined($cached)) {
297: return $serverhomeID;
298: }
299: }
300: my $cachetime = 12*3600;
301: my $serverhomeID;
302: if ($caller eq 'loncron') {
303: my @machine_ids = &machine_ids($hostname);
304: foreach my $id (@machine_ids) {
305: my $response = &reply('serverhomeID',$id);
306: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
307: $serverhomeID = $response;
308: last;
309: }
310: }
311: if ($serverhomeID eq '') {
312: $serverhomeID = $machine_ids[-1];
313: }
314: } else {
315: $serverhomeID = $serverhomeIDs{$hostname};
316: }
317: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
318: }
319:
1.1121 raeburn 320: sub get_remote_globals {
321: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 322: my ($result,%returnhash,%whatneeded);
323: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 324: foreach my $what (sort(keys(%{$whathash}))) {
325: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 326: my ($response,$cached);
1.1121 raeburn 327: unless ($ignore_cache) {
1.1125 raeburn 328: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 329: }
330: if (defined($cached)) {
1.1125 raeburn 331: $returnhash{$what} = $response;
1.1121 raeburn 332: } else {
1.1125 raeburn 333: $whatneeded{$what} = 1;
1.1121 raeburn 334: }
335: }
1.1125 raeburn 336: if (keys(%whatneeded) == 0) {
337: $result = 'ok';
338: } else {
1.1121 raeburn 339: my $requested = &freeze_escape(\%whatneeded);
340: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 341: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
342: ($rep eq 'unknown_cmd')) {
343: $result = $rep;
344: } else {
345: $result = 'ok';
1.1121 raeburn 346: my @pairs=split(/\&/,$rep);
1.1125 raeburn 347: foreach my $item (@pairs) {
348: my ($key,$value)=split(/=/,$item,2);
349: my $what = &unescape($key);
350: my $hashid = $lonhost.'-'.$what;
351: $returnhash{$what}=&thaw_unescape($value);
352: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 353: }
354: }
355: }
356: }
1.1125 raeburn 357: return ($result,\%returnhash);
1.1121 raeburn 358: }
359:
1.1124 raeburn 360: sub remote_devalidate_cache {
1.1172.2.35 raeburn 361: my ($lonhost,$cachekeys) = @_;
362: my $items;
363: return unless (ref($cachekeys) eq 'ARRAY');
364: my $cachestr = join('&',@{$cachekeys});
365: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 366: }
367:
1.1 albertel 368: # -------------------------------------------------- Non-critical communication
369: sub subreply {
370: my ($cmd,$server)=@_;
1.838 albertel 371: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 372: #
373: # With loncnew process trimming, there's a timing hole between lonc server
374: # process exit and the master server picking up the listen on the AF_UNIX
375: # socket. In that time interval, a lock file will exist:
376:
377: my $lockfile=$peerfile.".lock";
378: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 379: sleep(0.1);
1.549 foxr 380: }
381: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 382: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 383: #
1.550 foxr 384: # We'll give the connection a few tries before abandoning it. If
385: # connection is not possible, we'll con_lost back to the client.
386: #
387: my $client;
388: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
389: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
390: Type => SOCK_STREAM,
391: Timeout => 10);
1.869 albertel 392: if ($client) {
1.550 foxr 393: last; # Connected!
1.850 albertel 394: } else {
1.853 albertel 395: &create_connection(&hostname($server),$server);
1.550 foxr 396: }
1.1172.2.79 raeburn 397: sleep(0.1); # Try again later if failed connection.
1.550 foxr 398: }
399: my $answer;
400: if ($client) {
1.704 albertel 401: print $client "sethost:$server:$cmd\n";
1.550 foxr 402: $answer=<$client>;
403: if (!$answer) { $answer="con_lost"; }
404: chomp($answer);
405: } else {
406: $answer = 'con_lost'; # Failed connection.
407: }
1.1 albertel 408: return $answer;
409: }
410:
411: sub reply {
412: my ($cmd,$server)=@_;
1.838 albertel 413: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 414: my $answer=subreply($cmd,$server);
1.65 www 415: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111 raeburn 416: my $logged = $cmd;
417: if ($cmd =~ /^encrypt:([^:]+):/) {
418: my $subcmd = $1;
419: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
420: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
421: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
422: (undef,undef,my @rest) = split(/:/,$cmd);
423: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
424: splice(@rest,2,1,'Hidden');
425: } elsif ($subcmd eq 'passwd') {
426: splice(@rest,2,2,('Hidden','Hidden'));
427: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
428: ($subcmd eq 'autoexportgrades')) {
429: splice(@rest,3,1,'Hidden');
430: }
431: $logged = join(':',('encrypt:'.$subcmd,@rest));
432: }
433: }
434: &logthis("<font color=\"blue\">WARNING:".
435: " $logged to $server returned $answer</font>");
1.12 www 436: }
1.1 albertel 437: return $answer;
438: }
439:
440: # ----------------------------------------------------------- Send USR1 to lonc
441:
442: sub reconlonc {
1.891 albertel 443: my ($lonid) = @_;
444: if ($lonid) {
1.1172.2.72 raeburn 445: my $hostname = &hostname($lonid);
1.891 albertel 446: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
447: if ($hostname && -e $peerfile) {
448: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
449: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
450: Type => SOCK_STREAM,
451: Timeout => 10);
452: if ($client) {
453: print $client ("reset_retries\n");
454: my $answer=<$client>;
455: #reset just this one.
456: }
457: }
458: return;
459: }
460:
1.836 www 461: &logthis("Trying to reconnect lonc");
1.1 albertel 462: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96 raeburn 463: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 464: my $loncpid=<$fh>;
465: chomp($loncpid);
466: if (kill 0 => $loncpid) {
467: &logthis("lonc at pid $loncpid responding, sending USR1");
468: kill USR1 => $loncpid;
469: sleep 1;
1.836 www 470: } else {
1.12 www 471: &logthis(
1.672 albertel 472: "<font color=\"blue\">WARNING:".
1.12 www 473: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 474: }
475: } else {
1.836 www 476: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 477: }
478: }
479:
480: # ------------------------------------------------------ Critical communication
1.12 www 481:
1.1 albertel 482: sub critical {
483: my ($cmd,$server)=@_;
1.838 albertel 484: unless (&hostname($server)) {
1.672 albertel 485: &logthis("<font color=\"blue\">WARNING:".
1.89 www 486: " Critical message to unknown server ($server)</font>");
487: return 'no_such_host';
488: }
1.1 albertel 489: my $answer=reply($cmd,$server);
490: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 491: &reconlonc($server);
1.589 albertel 492: my $answer=reply($cmd,$server);
1.1 albertel 493: if ($answer eq 'con_lost') {
494: my $now=time;
495: my $middlename=$cmd;
1.5 www 496: $middlename=substr($middlename,0,16);
1.1 albertel 497: $middlename=~s/\W//g;
498: my $dfilename=
1.305 www 499: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
500: $dumpcount++;
1.1 albertel 501: {
1.448 albertel 502: my $dfh;
1.1172.2.96 raeburn 503: if (open($dfh,">",$dfilename)) {
1.448 albertel 504: print $dfh "$cmd\n";
505: close($dfh);
506: }
1.1 albertel 507: }
1.1172.2.79 raeburn 508: sleep 1;
1.1 albertel 509: my $wcmd='';
510: {
1.448 albertel 511: my $dfh;
1.1172.2.96 raeburn 512: if (open($dfh,"<",$dfilename)) {
1.448 albertel 513: $wcmd=<$dfh>;
514: close($dfh);
515: }
1.1 albertel 516: }
517: chomp($wcmd);
1.7 www 518: if ($wcmd eq $cmd) {
1.672 albertel 519: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 520: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 521: &logperm("D:$server:$cmd");
522: return 'con_delayed';
523: } else {
1.672 albertel 524: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 525: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 526: &logperm("F:$server:$cmd");
527: return 'con_failed';
528: }
529: }
530: }
531: return $answer;
1.405 albertel 532: }
533:
1.755 albertel 534: # ------------------------------------------- check if return value is an error
535:
536: sub error {
537: my ($result) = @_;
1.756 albertel 538: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 539: if ($2 == 2) { return undef; }
540: return $1;
541: }
542: return undef;
543: }
544:
1.783 albertel 545: sub convert_and_load_session_env {
546: my ($lonidsdir,$handle)=@_;
547: my @profile;
548: {
1.917 albertel 549: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
550: if (!$opened) {
1.915 albertel 551: return 0;
552: }
1.783 albertel 553: flock($idf,LOCK_SH);
554: @profile=<$idf>;
555: close($idf);
556: }
557: my %temp_env;
558: foreach my $line (@profile) {
1.786 albertel 559: if ($line !~ m/=/) {
560: return 0;
561: }
1.783 albertel 562: chomp($line);
563: my ($envname,$envvalue)=split(/=/,$line,2);
564: $temp_env{&unescape($envname)} = &unescape($envvalue);
565: }
566: unlink("$lonidsdir/$handle.id");
567: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
568: 0640)) {
569: %disk_env = %temp_env;
570: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
571: untie(%disk_env);
572: }
1.786 albertel 573: return 1;
1.783 albertel 574: }
575:
1.374 www 576: # ------------------------------------------- Transfer profile into environment
1.780 albertel 577: my $env_loaded;
578: sub transfer_profile_to_env {
1.788 albertel 579: my ($lonidsdir,$handle,$force_transfer) = @_;
580: if (!$force_transfer && $env_loaded) { return; }
1.374 www 581:
1.720 albertel 582: if (!defined($lonidsdir)) {
583: $lonidsdir = $perlvar{'lonIDsDir'};
584: }
585: if (!defined($handle)) {
586: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
587: }
588:
1.786 albertel 589: my $convert;
590: {
1.917 albertel 591: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
592: if (!$opened) {
1.915 albertel 593: return;
594: }
1.786 albertel 595: flock($idf,LOCK_SH);
596: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
597: &GDBM_READER(),0640)) {
598: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
599: untie(%disk_env);
600: } else {
601: $convert = 1;
602: }
603: }
604: if ($convert) {
605: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
606: &logthis("Failed to load session, or convert session.");
607: }
1.374 www 608: }
1.783 albertel 609:
1.786 albertel 610: my %remove;
1.783 albertel 611: while ( my $envname = each(%env) ) {
1.433 matthew 612: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
613: if ($time < time-300) {
1.783 albertel 614: $remove{$key}++;
1.433 matthew 615: }
616: }
617: }
1.783 albertel 618:
1.619 albertel 619: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 620: $env_loaded=1;
1.783 albertel 621: foreach my $expired_key (keys(%remove)) {
1.433 matthew 622: &delenv($expired_key);
1.374 www 623: }
1.1 albertel 624: }
625:
1.916 albertel 626: # ---------------------------------------------------- Check for valid session
627: sub check_for_valid_session {
1.1172.2.96 raeburn 628: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 629: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108 raeburn 630: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155 raeburn 631: if ($name eq 'lonDAV') {
632: $lonidsdir=$r->dir_config('lonDAVsessDir');
633: } else {
634: $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108 raeburn 635: if ($name eq '') {
636: $name = 'lonID';
637: }
638: }
639: if ($name eq 'lonID') {
640: $secure = 'lonSID';
641: $linkname = 'lonLinkID';
642: $pubname = 'lonPubID';
643: if (exists($cookies{$secure})) {
644: $lonid=$cookies{$secure};
645: } elsif (exists($cookies{$name})) {
646: $lonid=$cookies{$name};
647: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
648: $lonid=$cookies{$linkname};
649: } elsif (exists($cookies{$pubname})) {
650: $lonid=$cookies{$pubname};
651: }
652: } else {
653: $lonid=$cookies{$name};
654: }
655: return undef if (!$lonid);
656:
657: my $handle=&LONCAPA::clean_handle($lonid->value);
658: if (-l "$lonidsdir/$handle.id") {
659: my $link = readlink("$lonidsdir/$handle.id");
660: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
661: $handle = $1;
662: }
1.1155 raeburn 663: }
1.1172.2.96 raeburn 664: if (!-e "$lonidsdir/$handle.id") {
665: if ((ref($domref)) && ($name eq 'lonID') &&
666: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
667: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
668: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
669: $$domref = $possudom;
670: }
671: }
672: return undef;
673: }
1.916 albertel 674:
1.917 albertel 675: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
676: return undef if (!$opened);
1.916 albertel 677:
678: flock($idf,LOCK_SH);
679: my %disk_env;
680: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
681: &GDBM_READER(),0640)) {
682: return undef;
683: }
684:
685: if (!defined($disk_env{'user.name'})
686: || !defined($disk_env{'user.domain'})) {
1.1172.2.107 raeburn 687: untie(%disk_env);
1.916 albertel 688: return undef;
689: }
1.1172.2.18 raeburn 690:
1.1172.2.36 raeburn 691: if (ref($userhashref) eq 'HASH') {
692: $userhashref->{'name'} = $disk_env{'user.name'};
693: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.142 raeburn 694: if ($disk_env{'request.role'}) {
695: $userhashref->{'role'} = $disk_env{'request.role'};
696: }
1.1172.2.18 raeburn 697: }
1.1172.2.107 raeburn 698: untie(%disk_env);
1.1172.2.18 raeburn 699:
1.916 albertel 700: return $handle;
701: }
702:
1.830 albertel 703: sub timed_flock {
704: my ($file,$lock_type) = @_;
705: my $failed=0;
706: eval {
707: local $SIG{__DIE__}='DEFAULT';
708: local $SIG{ALRM}=sub {
709: $failed=1;
710: die("failed lock");
711: };
712: alarm(13);
713: flock($file,$lock_type);
714: alarm(0);
715: };
716: if ($failed) {
717: return undef;
718: } else {
719: return 1;
720: }
721: }
722:
1.1172.2.107 raeburn 723: sub get_sessionfile_vars {
724: my ($handle,$lonidsdir,$storearr) = @_;
725: my %returnhash;
726: unless (ref($storearr) eq 'ARRAY') {
727: return %returnhash;
728: }
729: if (-l "$lonidsdir/$handle.id") {
730: my $link = readlink("$lonidsdir/$handle.id");
731: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
732: $handle = $1;
733: }
734: }
735: if ((-e "$lonidsdir/$handle.id") &&
736: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
737: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
738: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
739: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
740: flock($idf,LOCK_SH);
741: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
742: &GDBM_READER(),0640)) {
743: foreach my $item (@{$storearr}) {
744: $returnhash{$item} = $disk_env{$item};
745: }
746: untie(%disk_env);
747: }
748: }
749: }
750: }
751: return %returnhash;
752: }
753:
1.5 www 754: # ---------------------------------------------------------- Append Environment
755:
756: sub appenv {
1.949 raeburn 757: my ($newenv,$roles) = @_;
758: if (ref($newenv) eq 'HASH') {
759: foreach my $key (keys(%{$newenv})) {
760: my $refused = 0;
761: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
762: $refused = 1;
763: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 764: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 765: if (grep(/^\Q$role\E$/,@{$roles})) {
766: $refused = 0;
767: }
768: }
769: }
770: if ($refused) {
771: &logthis("<font color=\"blue\">WARNING: ".
772: "Attempt to modify environment ".$key." to ".$newenv->{$key}
773: .'</font>');
774: delete($newenv->{$key});
775: } else {
776: $env{$key}=$newenv->{$key};
777: }
778: }
1.1172.2.96 raeburn 779: my $lonids = $perlvar{'lonIDsDir'};
780: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
781: my $opened = open(my $env_file,'+<',$env{'user.environment'});
782: if ($opened
783: && &timed_flock($env_file,LOCK_EX)
784: &&
785: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
786: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
787: while (my ($key,$value) = each(%{$newenv})) {
788: $disk_env{$key} = $value;
789: }
790: untie(%disk_env);
791: }
1.35 www 792: }
1.191 harris41 793: }
1.56 www 794: return 'ok';
795: }
796: # ----------------------------------------------------- Delete from Environment
797:
798: sub delenv {
1.1104 raeburn 799: my ($delthis,$regexp,$roles) = @_;
800: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
801: my $refused = 1;
802: if (ref($roles) eq 'ARRAY') {
803: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
804: if (grep(/^\Q$role\E$/,@{$roles})) {
805: $refused = 0;
806: }
807: }
808: if ($refused) {
809: &logthis("<font color=\"blue\">WARNING: ".
810: "Attempt to delete from environment ".$delthis);
811: return 'error';
812: }
1.56 www 813: }
1.917 albertel 814: my $opened = open(my $env_file,'+<',$env{'user.environment'});
815: if ($opened
1.915 albertel 816: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 817: &&
818: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
819: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 820: foreach my $key (keys(%disk_env)) {
1.987 raeburn 821: if ($regexp) {
822: if ($key=~/^$delthis/) {
823: delete($env{$key});
824: delete($disk_env{$key});
825: }
826: } else {
827: if ($key=~/^\Q$delthis\E/) {
828: delete($env{$key});
829: delete($disk_env{$key});
830: }
831: }
1.448 albertel 832: }
1.783 albertel 833: untie(%disk_env);
1.5 www 834: }
835: return 'ok';
1.369 albertel 836: }
837:
1.790 albertel 838: sub get_env_multiple {
839: my ($name) = @_;
840: my @values;
841: if (defined($env{$name})) {
842: # exists is it an array
843: if (ref($env{$name})) {
844: @values=@{ $env{$name} };
845: } else {
846: $values[0]=$env{$name};
847: }
848: }
849: return(@values);
850: }
851:
1.958 www 852: # ------------------------------------------------------------------- Locking
853:
854: sub set_lock {
855: my ($text)=@_;
856: $locknum++;
857: my $id=$$.'-'.$locknum;
858: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
859: 'session.lock.'.$id => $text});
860: return $id;
861: }
862:
863: sub get_locks {
864: my $num=0;
865: my %texts=();
866: foreach my $lock (split(/\,/,$env{'session.locks'})) {
867: if ($lock=~/\w/) {
868: $num++;
869: $texts{$lock}=$env{'session.lock.'.$lock};
870: }
871: }
872: return ($num,%texts);
873: }
874:
875: sub remove_lock {
876: my ($id)=@_;
877: my $newlocks='';
878: foreach my $lock (split(/\,/,$env{'session.locks'})) {
879: if (($lock=~/\w/) && ($lock ne $id)) {
880: $newlocks.=','.$lock;
881: }
882: }
883: &appenv({'session.locks' => $newlocks});
884: &delenv('session.lock.'.$id);
885: }
886:
887: sub remove_all_locks {
888: my $activelocks=$env{'session.locks'};
889: foreach my $lock (split(/\,/,$env{'session.locks'})) {
890: if ($lock=~/\w/) {
891: &remove_lock($lock);
892: }
893: }
894: }
895:
896:
1.369 albertel 897: # ------------------------------------------ Find out current server userload
898: sub userload {
899: my $numusers=0;
900: {
901: opendir(LONIDS,$perlvar{'lonIDsDir'});
902: my $filename;
903: my $curtime=time;
904: while ($filename=readdir(LONIDS)) {
1.925 albertel 905: next if ($filename eq '.' || $filename eq '..');
906: next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112 raeburn 907: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 908: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 909: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 910: }
911: closedir(LONIDS);
912: }
913: my $userloadpercent=0;
914: my $maxuserload=$perlvar{'lonUserLoadLim'};
915: if ($maxuserload) {
1.371 albertel 916: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 917: }
1.372 albertel 918: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 919: return $userloadpercent;
1.283 www 920: }
921:
1.1 albertel 922: # ------------------------------ Find server with least workload from spare.tab
1.11 www 923:
1.1 albertel 924: sub spareserver {
1.1172.2.142 raeburn 925: my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 926: my $spare_server;
1.370 albertel 927: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 928: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
929: : $userloadpercent;
1.1083 raeburn 930: my ($uint_dom,$remotesessions);
931: if (($udom ne '') && (&domain($udom) ne '')) {
932: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
933: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
934: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
935: $remotesessions = $udomdefaults{'remotesessions'};
936: }
1.1123 raeburn 937: my $spareshash = &this_host_spares($udom);
938: if (ref($spareshash) eq 'HASH') {
939: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
940: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 941: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
942: $try_server));
1.1123 raeburn 943: ($spare_server, $lowest_load) =
944: &compare_server_load($try_server, $spare_server, $lowest_load);
945: }
1.1083 raeburn 946: }
1.784 albertel 947:
1.1123 raeburn 948: my $found_server = ($spare_server ne '' && $lowest_load < 100);
949:
950: if (!$found_server) {
951: if (ref($spareshash->{'default'}) eq 'ARRAY') {
952: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 953: next unless (&spare_can_host($udom,$uint_dom,
954: $remotesessions,$try_server));
1.1123 raeburn 955: ($spare_server, $lowest_load) =
956: &compare_server_load($try_server, $spare_server, $lowest_load);
957: }
958: }
959: }
1.784 albertel 960: }
961:
962: if (!$want_server_name) {
1.1001 raeburn 963: if (defined($spare_server)) {
964: my $hostname = &hostname($spare_server);
1.1083 raeburn 965: if (defined($hostname)) {
1.1172.2.120 raeburn 966: my $protocol = 'http';
967: if ($protocol{$spare_server} eq 'https') {
968: $protocol = $protocol{$spare_server};
969: }
1.1172.2.142 raeburn 970: my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
971: $hostname = $alias if ($alias ne '');
1.1001 raeburn 972: $spare_server = $protocol.'://'.$hostname;
973: }
974: }
1.784 albertel 975: }
976: return $spare_server;
977: }
978:
979: sub compare_server_load {
1.1172.2.41 raeburn 980: my ($try_server, $spare_server, $lowest_load, $required) = @_;
981:
982: if ($required) {
983: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
984: my $remoterev = &get_server_loncaparev(undef,$try_server);
985: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
986: if (($major eq '' && $minor eq '') ||
987: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
988: return ($spare_server,$lowest_load);
989: }
990: }
1.784 albertel 991:
992: my $loadans = &reply('load', $try_server);
993: my $userloadans = &reply('userload',$try_server);
994:
995: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 996: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 997: }
998:
999: my $load;
1000: if ($loadans =~ /\d/) {
1001: if ($userloadans =~ /\d/) {
1002: #both are numbers, pick the bigger one
1003: $load = ($loadans > $userloadans) ? $loadans
1004: : $userloadans;
1.411 albertel 1005: } else {
1.784 albertel 1006: $load = $loadans;
1.411 albertel 1007: }
1.784 albertel 1008: } else {
1009: $load = $userloadans;
1010: }
1011:
1012: if (($load =~ /\d/) && ($load < $lowest_load)) {
1013: $spare_server = $try_server;
1014: $lowest_load = $load;
1.370 albertel 1015: }
1.784 albertel 1016: return ($spare_server,$lowest_load);
1.202 matthew 1017: }
1.914 albertel 1018:
1019: # --------------------------- ask offload servers if user already has a session
1020: sub find_existing_session {
1021: my ($udom,$uname) = @_;
1.1123 raeburn 1022: my $spareshash = &this_host_spares($udom);
1023: if (ref($spareshash) eq 'HASH') {
1024: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1025: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1026: return $try_server if (&has_user_session($try_server, $udom, $uname));
1027: }
1028: }
1029: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1030: foreach my $try_server (@{ $spareshash->{'default'} }) {
1031: return $try_server if (&has_user_session($try_server, $udom, $uname));
1032: }
1033: }
1.914 albertel 1034: }
1035: return;
1036: }
1037:
1.1172.2.107 raeburn 1038: # check if user's browser sent load balancer cookie and server still has session
1039: # and is not overloaded.
1040: sub check_for_balancer_cookie {
1041: my ($r,$update_mtime) = @_;
1042: my ($otherserver,$cookie);
1043: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1044: if (exists($cookies{'balanceID'})) {
1045: my $balid = $cookies{'balanceID'};
1046: $cookie=&LONCAPA::clean_handle($balid->value);
1047: my $balancedir=$r->dir_config('lonBalanceDir');
1048: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1049: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1050: my ($possudom,$possuname) = ($1,$2);
1051: my $has_session = 0;
1052: if ((&domain($possudom) ne '') &&
1053: (&homeserver($possuname,$possudom) ne 'no_host')) {
1054: my $try_server;
1055: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1056: if ($opened) {
1057: flock($idf,LOCK_SH);
1058: while (my $line = <$idf>) {
1059: chomp($line);
1060: if (&hostname($line) ne '') {
1061: $try_server = $line;
1062: last;
1063: }
1064: }
1065: close($idf);
1066: if (($try_server) &&
1067: (&has_user_session($try_server,$possudom,$possuname))) {
1068: my $lowest_load = 30000;
1069: ($otherserver,$lowest_load) =
1070: &compare_server_load($try_server,undef,$lowest_load);
1071: if ($otherserver ne '' && $lowest_load < 100) {
1072: $has_session = 1;
1073: } else {
1074: undef($otherserver);
1075: }
1076: }
1077: }
1078: }
1079: if ($has_session) {
1080: if ($update_mtime) {
1081: my $atime = my $mtime = time;
1082: utime($atime,$mtime,"$balancedir/$cookie.id");
1083: }
1084: } else {
1085: unlink("$balancedir/$cookie.id");
1086: }
1087: }
1088: }
1089: }
1090: return ($otherserver,$cookie);
1091: }
1092:
1.1172.2.130 raeburn 1093: sub updatebalcookie {
1094: my ($cookie,$balancer,$lastentry)=@_;
1095: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1096: my ($udom,$uname) = ($1,$2);
1097: my $uprimary_id = &domain($udom,'primary');
1098: my $uintdom = &internet_dom($uprimary_id);
1099: my $intdom = &internet_dom($balancer);
1100: my $serverhomedom = &host_domain($balancer);
1101: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1102: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1103: }
1104: }
1105: return;
1106: }
1107:
1.1172.2.107 raeburn 1108: sub delbalcookie {
1109: my ($cookie,$balancer) =@_;
1110: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1111: my ($udom,$uname) = ($1,$2);
1112: my $uprimary_id = &domain($udom,'primary');
1113: my $uintdom = &internet_dom($uprimary_id);
1114: my $intdom = &internet_dom($balancer);
1115: my $serverhomedom = &host_domain($balancer);
1116: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130 raeburn 1117: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107 raeburn 1118: }
1119: }
1120: }
1121:
1.914 albertel 1122: # -------------------------------- ask if server already has a session for user
1123: sub has_user_session {
1124: my ($lonid,$udom,$uname) = @_;
1125: my $result = &reply(join(':','userhassession',
1126: map {&escape($_)} ($udom,$uname)),$lonid);
1127: return 1 if ($result eq 'ok');
1128:
1129: return 0;
1130: }
1131:
1.1076 raeburn 1132: # --------- determine least loaded server in a user's domain which allows login
1133:
1134: sub choose_server {
1.1172.2.47 raeburn 1135: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1136: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1137: my %servers = &get_servers($udom);
1.1076 raeburn 1138: my $lowest_load = 30000;
1.1172.2.47 raeburn 1139: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1140: if ($skiploadbal) {
1141: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1142: unless (defined($cached)) {
1143: my $cachetime = 60*60*24;
1144: my %domconfig =
1145: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1146: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1147: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1148: $cachetime);
1149: }
1150: }
1151: }
1.1076 raeburn 1152: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 1153: my $loginvia;
1.1172.2.47 raeburn 1154: if ($skiploadbal) {
1155: if (ref($balancers) eq 'HASH') {
1156: next if (exists($balancers->{$lonhost}));
1157: }
1158: }
1.1115 raeburn 1159: if ($checkloginvia) {
1160: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1161: if ($loginvia) {
1162: my ($server,$path) = split(/:/,$loginvia);
1163: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1164: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1165: if ($login_host eq $server) {
1166: $portal_path = $path;
1.1151 raeburn 1167: $isredirect = 1;
1.1116 raeburn 1168: }
1169: } else {
1170: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1171: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1172: if ($login_host eq $lonhost) {
1173: $portal_path = '';
1.1151 raeburn 1174: $isredirect = '';
1.1116 raeburn 1175: }
1176: }
1177: } else {
1.1076 raeburn 1178: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1179: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1180: }
1181: }
1182: if ($login_host ne '') {
1.1116 raeburn 1183: $hostname = &hostname($login_host);
1.1076 raeburn 1184: }
1.1172.2.88 raeburn 1185: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1186: }
1187:
1.1172.2.123 raeburn 1188: sub get_course_sessions {
1189: my ($cnum,$cdom,$lastactivity) = @_;
1190: my %servers = &internet_dom_servers($cdom);
1191: my %returnhash;
1192: foreach my $server (sort(keys(%servers))) {
1193: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1194: my @pairs=split(/\&/,$rep);
1195: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1196: foreach my $item (@pairs) {
1197: my ($key,$value)=split(/=/,$item,2);
1198: $key = &unescape($key);
1199: next if ($key =~ /^error: 2 /);
1200: if (exists($returnhash{$key})) {
1201: next if ($value < $returnhash{$key});
1202: }
1203: $returnhash{$key}=$value;
1204: }
1205: }
1206: }
1207: return %returnhash;
1208: }
1209:
1.202 matthew 1210: # --------------------------------------------- Try to change a user's password
1211:
1212: sub changepass {
1.799 raeburn 1213: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1214: $currentpass = &escape($currentpass);
1215: $newpass = &escape($newpass);
1.1030 raeburn 1216: my $lonhost = $perlvar{'lonHostID'};
1217: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1218: $server);
1219: if (! $answer) {
1220: &logthis("No reply on password change request to $server ".
1221: "by $uname in domain $udom.");
1222: } elsif ($answer =~ "^ok") {
1223: &logthis("$uname in $udom successfully changed their password ".
1224: "on $server.");
1225: } elsif ($answer =~ "^pwchange_failure") {
1226: &logthis("$uname in $udom was unable to change their password ".
1227: "on $server. The action was blocked by either lcpasswd ".
1228: "or pwchange");
1229: } elsif ($answer =~ "^non_authorized") {
1230: &logthis("$uname in $udom did not get their password correct when ".
1231: "attempting to change it on $server.");
1232: } elsif ($answer =~ "^auth_mode_error") {
1233: &logthis("$uname in $udom attempted to change their password despite ".
1234: "not being locally or internally authenticated on $server.");
1235: } elsif ($answer =~ "^unknown_user") {
1236: &logthis("$uname in $udom attempted to change their password ".
1237: "on $server but were unable to because $server is not ".
1238: "their home server.");
1239: } elsif ($answer =~ "^refused") {
1240: &logthis("$server refused to change $uname in $udom password because ".
1241: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1242: } elsif ($answer =~ "invalid_client") {
1243: &logthis("$server refused to change $uname in $udom password because ".
1244: "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113 raeburn 1245: } elsif ($answer =~ "^prioruse") {
1246: &logthis("$server refused to change $uname in $udom password because ".
1247: "the password had been used before");
1.202 matthew 1248: }
1249: return $answer;
1.1 albertel 1250: }
1251:
1.169 harris41 1252: # ----------------------- Try to determine user's current authentication scheme
1253:
1254: sub queryauthenticate {
1255: my ($uname,$udom)=@_;
1.456 albertel 1256: my $uhome=&homeserver($uname,$udom);
1.1172.2.147 raeburn 1257: if ((!$uhome) || ($uhome eq 'no_host')) {
1.456 albertel 1258: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1259: return 'no_host';
1260: }
1261: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1262: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1263: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1264: }
1.456 albertel 1265: return $answer;
1.169 harris41 1266: }
1267:
1.1 albertel 1268: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1269:
1.1 albertel 1270: sub authenticate {
1.1073 raeburn 1271: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1272: $upass=&escape($upass);
1273: $uname= &LONCAPA::clean_username($uname);
1.836 www 1274: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1275: my $newhome;
1.836 www 1276: if ((!$uhome) || ($uhome eq 'no_host')) {
1277: # Maybe the machine was offline and only re-appeared again recently?
1278: &reconlonc();
1279: # One more
1.952 raeburn 1280: $uhome=&homeserver($uname,$udom,1);
1281: if (($uhome eq 'no_host') && $checkdefauth) {
1282: if (defined(&domain($udom,'primary'))) {
1283: $newhome=&domain($udom,'primary');
1284: }
1285: if ($newhome ne '') {
1286: $uhome = $newhome;
1287: }
1288: }
1.836 www 1289: if ((!$uhome) || ($uhome eq 'no_host')) {
1290: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1291: return 'no_host';
1292: }
1.1 albertel 1293: }
1.1073 raeburn 1294: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1295: if ($answer eq 'authorized') {
1.952 raeburn 1296: if ($newhome) {
1297: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1298: return 'no_account_on_host';
1299: } else {
1300: &logthis("User $uname at $udom authorized by $uhome");
1301: return $uhome;
1302: }
1.471 albertel 1303: }
1304: if ($answer eq 'non_authorized') {
1305: &logthis("User $uname at $udom rejected by $uhome");
1.1172.2.147 raeburn 1306: return 'no_host';
1.9 www 1307: }
1.471 albertel 1308: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1309: return 'no_host';
1310: }
1311:
1.1073 raeburn 1312: sub can_host_session {
1.1074 raeburn 1313: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1314: my $canhost = 1;
1.1074 raeburn 1315: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1316: if (ref($remotesessions) eq 'HASH') {
1317: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1318: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1319: $canhost = 0;
1320: } else {
1321: $canhost = 1;
1322: }
1323: }
1324: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1325: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1326: $canhost = 1;
1327: } else {
1328: $canhost = 0;
1329: }
1330: }
1331: if ($canhost) {
1332: if ($remotesessions->{'version'} ne '') {
1333: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1334: if ($reqmajor ne '' && $reqminor ne '') {
1335: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1336: my $major = $1;
1337: my $minor = $2;
1338: if (($major < $reqmajor ) ||
1339: (($major == $reqmajor) && ($minor < $reqminor))) {
1340: $canhost = 0;
1341: }
1342: } else {
1343: $canhost = 0;
1344: }
1345: }
1346: }
1347: }
1348: }
1349: if ($canhost) {
1350: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1351: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1352: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1353: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1354: if (($uint_dom ne '') &&
1355: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1356: $canhost = 0;
1357: } else {
1358: $canhost = 1;
1359: }
1360: }
1361: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1362: if (($uint_dom ne '') &&
1363: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1364: $canhost = 1;
1365: } else {
1366: $canhost = 0;
1367: }
1368: }
1369: }
1370: }
1371: return $canhost;
1372: }
1373:
1.1083 raeburn 1374: sub spare_can_host {
1375: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1376: my $canhost=1;
1.1172.2.62 raeburn 1377: my $try_server_hostname = &hostname($try_server);
1378: my $serverhomeID = &get_server_homeID($try_server_hostname);
1379: my $serverhomedom = &host_domain($serverhomeID);
1380: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1381: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1382: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1383: $canhost = 0;
1384: }
1385: }
1.1172.2.136 raeburn 1386: if ($canhost) {
1387: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1388: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1389: unless (&shared_institution($udom,$try_server)) {
1390: $canhost = 0;
1391: }
1392: }
1393: }
1394: }
1.1172.2.62 raeburn 1395: if (($canhost) && ($uint_dom)) {
1396: my @intdoms;
1397: my $internet_names = &get_internet_names($try_server);
1398: if (ref($internet_names) eq 'ARRAY') {
1399: @intdoms = @{$internet_names};
1400: }
1401: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1402: my $remoterev = &get_server_loncaparev(undef,$try_server);
1403: $canhost = &can_host_session($udom,$try_server,$remoterev,
1404: $remotesessions,
1405: $defdomdefaults{'hostedsessions'});
1406: }
1.1083 raeburn 1407: }
1408: return $canhost;
1409: }
1410:
1.1123 raeburn 1411: sub this_host_spares {
1412: my ($dom) = @_;
1.1126 raeburn 1413: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1414: my @hosts = ¤t_machine_ids();
1415: foreach my $lonhost (@hosts) {
1416: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1417: $dom_in_use = $dom;
1418: $lonhost_in_use = $lonhost;
1.1123 raeburn 1419: last;
1420: }
1421: }
1.1126 raeburn 1422: if ($dom_in_use ne '') {
1423: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1424: }
1425: if (ref($result) ne 'HASH') {
1426: $lonhost_in_use = $perlvar{'lonHostID'};
1427: $dom_in_use = &host_domain($lonhost_in_use);
1428: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1429: if (ref($result) ne 'HASH') {
1430: $result = \%spareid;
1431: }
1432: }
1433: return $result;
1434: }
1435:
1436: sub spares_for_offload {
1437: my ($dom_in_use,$lonhost_in_use) = @_;
1438: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1439: if (defined($cached)) {
1440: return $result;
1441: } else {
1.1126 raeburn 1442: my $cachetime = 60*60*24;
1443: my %domconfig =
1444: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1445: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1446: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1447: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1448: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1449: }
1450: }
1451: }
1452: }
1.1126 raeburn 1453: return;
1.1123 raeburn 1454: }
1455:
1.1129 raeburn 1456: sub get_lonbalancer_config {
1457: my ($servers) = @_;
1458: my ($currbalancer,$currtargets);
1459: if (ref($servers) eq 'HASH') {
1460: foreach my $server (keys(%{$servers})) {
1461: my %what = (
1462: spareid => 1,
1463: perlvar => 1,
1464: );
1465: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1466: if ($result eq 'ok') {
1467: if (ref($returnhash) eq 'HASH') {
1468: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1469: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1470: $currbalancer = $server;
1471: $currtargets = {};
1472: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1473: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1474: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1475: }
1476: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1477: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1478: }
1479: }
1480: last;
1481: }
1482: }
1483: }
1484: }
1485: }
1486: }
1487: return ($currbalancer,$currtargets);
1488: }
1489:
1490: sub check_loadbalancing {
1.1172.2.88 raeburn 1491: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1492: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107 raeburn 1493: $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129 raeburn 1494: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1495: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1496: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1497: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1498: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1499: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1500: my $domneedscache;
1.1129 raeburn 1501: my $cachetime = 60*60*24;
1502:
1503: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1504: $dom_in_use = $udom;
1505: $homeintdom = 1;
1506: } else {
1507: $dom_in_use = $serverhomedom;
1508: }
1509: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1510: unless (defined($cached)) {
1511: my %domconfig =
1512: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1513: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1514: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1515: } else {
1516: $domneedscache = $dom_in_use;
1.1129 raeburn 1517: }
1518: }
1519: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1520: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1521: &check_balancer_result($result,@hosts);
1.1129 raeburn 1522: if ($is_balancer) {
1523: if (ref($currrules) eq 'HASH') {
1524: if ($homeintdom) {
1525: if ($uname ne '') {
1526: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1527: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1528: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1529: $rule_in_effect = $currrules->{'_LC_author'};
1530: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1531: $rule_in_effect = $currrules->{'_LC_adv'}
1532: }
1533: }
1534: if ($rule_in_effect eq '') {
1535: my %userenv = &userenvironment($udom,$uname,'inststatus');
1536: if ($userenv{'inststatus'} ne '') {
1537: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1538: my ($othertitle,$usertypes,$types) =
1539: &Apache::loncommon::sorted_inst_types($udom);
1540: if (ref($types) eq 'ARRAY') {
1541: foreach my $type (@{$types}) {
1542: if (grep(/^\Q$type\E$/,@statuses)) {
1543: if (exists($currrules->{$type})) {
1544: $rule_in_effect = $currrules->{$type};
1545: }
1546: }
1547: }
1548: }
1549: } else {
1550: if (exists($currrules->{'default'})) {
1551: $rule_in_effect = $currrules->{'default'};
1552: }
1553: }
1554: }
1555: } else {
1556: if (exists($currrules->{'default'})) {
1557: $rule_in_effect = $currrules->{'default'};
1558: }
1559: }
1560: } else {
1561: if ($currrules->{'_LC_external'} ne '') {
1562: $rule_in_effect = $currrules->{'_LC_external'};
1563: }
1564: }
1565: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1566: $uname,$udom);
1567: }
1568: }
1569: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1570: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1571: unless (defined($cached)) {
1572: my %domconfig =
1573: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1574: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1575: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1576: } else {
1577: $domneedscache = $serverhomedom;
1.1129 raeburn 1578: }
1579: }
1580: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1581: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1582: &check_balancer_result($result,@hosts);
1583: if ($is_balancer) {
1.1129 raeburn 1584: if (ref($currrules) eq 'HASH') {
1585: if ($currrules->{'_LC_internetdom'} ne '') {
1586: $rule_in_effect = $currrules->{'_LC_internetdom'};
1587: }
1588: }
1589: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1590: $uname,$udom);
1591: }
1592: } else {
1593: if ($perlvar{'lonBalancer'} eq 'yes') {
1594: $is_balancer = 1;
1595: $offloadto = &this_host_spares($dom_in_use);
1596: }
1.1172.2.75 raeburn 1597: unless (defined($cached)) {
1598: $domneedscache = $serverhomedom;
1599: }
1.1129 raeburn 1600: }
1601: } else {
1602: if ($perlvar{'lonBalancer'} eq 'yes') {
1603: $is_balancer = 1;
1604: $offloadto = &this_host_spares($dom_in_use);
1605: }
1.1172.2.75 raeburn 1606: unless (defined($cached)) {
1607: $domneedscache = $serverhomedom;
1608: }
1609: }
1610: if ($domneedscache) {
1611: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1612: }
1.1172.2.130 raeburn 1613: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5 raeburn 1614: my $lowest_load = 30000;
1615: if (ref($offloadto) eq 'HASH') {
1616: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1617: foreach my $try_server (@{$offloadto->{'primary'}}) {
1618: ($otherserver,$lowest_load) =
1619: &compare_server_load($try_server,$otherserver,$lowest_load);
1620: }
1.1129 raeburn 1621: }
1.1172.2.5 raeburn 1622: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1623:
1.1172.2.5 raeburn 1624: if (!$found_server) {
1625: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1626: foreach my $try_server (@{$offloadto->{'default'}}) {
1627: ($otherserver,$lowest_load) =
1628: &compare_server_load($try_server,$otherserver,$lowest_load);
1629: }
1630: }
1631: }
1632: } elsif (ref($offloadto) eq 'ARRAY') {
1633: if (@{$offloadto} == 1) {
1634: $otherserver = $offloadto->[0];
1635: } elsif (@{$offloadto} > 1) {
1636: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1637: ($otherserver,$lowest_load) =
1638: &compare_server_load($try_server,$otherserver,$lowest_load);
1639: }
1640: }
1641: }
1.1172.2.88 raeburn 1642: unless ($caller eq 'login') {
1643: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1644: $is_balancer = 0;
1645: if ($uname ne '' && $udom ne '') {
1646: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1647: &appenv({'user.loadbalexempt' => $lonhost,
1648: 'user.loadbalcheck.time' => time});
1649: }
1.1172.2.5 raeburn 1650: }
1.1129 raeburn 1651: }
1652: }
1.1172.2.130 raeburn 1653: }
1654: if (($is_balancer) && (!$homeintdom)) {
1655: undef($setcookie);
1.1129 raeburn 1656: }
1.1172.2.107 raeburn 1657: return ($is_balancer,$otherserver,$setcookie);
1.1129 raeburn 1658: }
1659:
1.1172.2.12 raeburn 1660: sub check_balancer_result {
1661: my ($result,@hosts) = @_;
1.1172.2.107 raeburn 1662: my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1663: if (ref($result) eq 'HASH') {
1664: if ($result->{'lonhost'} ne '') {
1665: my $currbalancer = $result->{'lonhost'};
1666: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1667: $is_balancer = 1;
1668: $currtargets = $result->{'targets'};
1669: $currrules = $result->{'rules'};
1670: }
1671: } else {
1672: foreach my $key (keys(%{$result})) {
1673: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1674: (ref($result->{$key}) eq 'HASH')) {
1675: $is_balancer = 1;
1676: $currrules = $result->{$key}{'rules'};
1677: $currtargets = $result->{$key}{'targets'};
1.1172.2.107 raeburn 1678: $setcookie = $result->{$key}{'cookie'};
1.1172.2.12 raeburn 1679: last;
1680: }
1681: }
1682: }
1683: }
1.1172.2.107 raeburn 1684: return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1685: }
1686:
1.1129 raeburn 1687: sub get_loadbalancer_targets {
1688: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1689: my $offloadto;
1.1172.2.4 raeburn 1690: if ($rule_in_effect eq 'none') {
1691: return [$perlvar{'lonHostID'}];
1692: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1693: $offloadto = $currtargets;
1694: } else {
1695: if ($rule_in_effect eq 'homeserver') {
1696: my $homeserver = &homeserver($uname,$udom);
1697: if ($homeserver ne 'no_host') {
1698: $offloadto = [$homeserver];
1699: }
1700: } elsif ($rule_in_effect eq 'externalbalancer') {
1701: my %domconfig =
1702: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1703: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1704: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1705: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1706: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1707: }
1708: }
1709: } else {
1.1172.2.7 raeburn 1710: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1711: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1712: if (&hostname($remotebalancer) ne '') {
1713: $offloadto = [$remotebalancer];
1714: }
1715: }
1716: } elsif (&hostname($rule_in_effect) ne '') {
1717: $offloadto = [$rule_in_effect];
1718: }
1719: }
1720: return $offloadto;
1721: }
1722:
1.1127 raeburn 1723: sub internet_dom_servers {
1724: my ($dom) = @_;
1725: my (%uniqservers,%servers);
1726: my $primaryserver = &hostname(&domain($dom,'primary'));
1727: my @machinedoms = &machine_domains($primaryserver);
1728: foreach my $mdom (@machinedoms) {
1729: my %currservers = %servers;
1730: my %server = &get_servers($mdom);
1731: %servers = (%currservers,%server);
1732: }
1733: my %by_hostname;
1734: foreach my $id (keys(%servers)) {
1735: push(@{$by_hostname{$servers{$id}}},$id);
1736: }
1737: foreach my $hostname (sort(keys(%by_hostname))) {
1738: if (@{$by_hostname{$hostname}} > 1) {
1739: my $match = 0;
1740: foreach my $id (@{$by_hostname{$hostname}}) {
1741: if (&host_domain($id) eq $dom) {
1742: $uniqservers{$id} = $hostname;
1743: $match = 1;
1744: }
1745: }
1746: unless ($match) {
1747: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1748: }
1749: } else {
1750: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1751: }
1752: }
1753: return %uniqservers;
1754: }
1755:
1.1 albertel 1756: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1757:
1.599 albertel 1758: my %homecache;
1.1 albertel 1759: sub homeserver {
1.230 stredwic 1760: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1761: my $index="$uname:$udom";
1.426 albertel 1762:
1.599 albertel 1763: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1764:
1765: my %servers = &get_servers($udom,'library');
1766: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1767: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1768: exists($badServerCache{$tryserver}));
1.841 albertel 1769:
1770: my $answer=reply("home:$udom:$uname",$tryserver);
1771: if ($answer eq 'found') {
1772: delete($badServerCache{$tryserver});
1773: return $homecache{$index}=$tryserver;
1774: } elsif ($answer eq 'no_host') {
1775: $badServerCache{$tryserver}=1;
1776: }
1.1 albertel 1777: }
1778: return 'no_host';
1.70 www 1779: }
1780:
1781: # ------------------------------------- Find the usernames behind a list of IDs
1782:
1783: sub idget {
1784: my ($udom,@ids)=@_;
1785: my %returnhash=();
1786:
1.841 albertel 1787: my %servers = &get_servers($udom,'library');
1788: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1789: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1790: $idlist=~tr/A-Z/a-z/;
1791: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1792: my @answer=();
1793: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1794: @answer=split(/\&/,$reply);
1795: } ;
1796: my $i;
1797: for ($i=0;$i<=$#ids;$i++) {
1798: if ($answer[$i]) {
1.1172.2.73 raeburn 1799: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1800: }
1801: }
1802: }
1.70 www 1803: return %returnhash;
1804: }
1805:
1806: # ------------------------------------- Find the IDs behind a list of usernames
1807:
1808: sub idrget {
1809: my ($udom,@unames)=@_;
1810: my %returnhash=();
1.800 albertel 1811: foreach my $uname (@unames) {
1812: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1813: }
1.70 www 1814: return %returnhash;
1815: }
1816:
1817: # ------------------------------- Store away a list of names and associated IDs
1818:
1819: sub idput {
1820: my ($udom,%ids)=@_;
1821: my %servers=();
1.800 albertel 1822: foreach my $uname (keys(%ids)) {
1823: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1824: my $uhom=&homeserver($uname,$udom);
1.70 www 1825: if ($uhom ne 'no_host') {
1.800 albertel 1826: my $id=&escape($ids{$uname});
1.70 www 1827: $id=~tr/A-Z/a-z/;
1.800 albertel 1828: my $esc_unam=&escape($uname);
1.70 www 1829: if ($servers{$uhom}) {
1.800 albertel 1830: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1831: } else {
1.800 albertel 1832: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1833: }
1834: }
1.191 harris41 1835: }
1.800 albertel 1836: foreach my $server (keys(%servers)) {
1837: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1838: }
1.344 www 1839: }
1840:
1.1172.2.30 raeburn 1841: # ---------------------------------------- Delete unwanted IDs from ids.db file
1842:
1843: sub iddel {
1844: my ($udom,$idshashref,$uhome)=@_;
1845: my %result=();
1846: unless (ref($idshashref) eq 'HASH') {
1847: return %result;
1848: }
1849: my %servers=();
1850: while (my ($id,$uname) = each(%{$idshashref})) {
1851: my $uhom;
1852: if ($uhome) {
1853: $uhom = $uhome;
1854: } else {
1855: $uhom=&homeserver($uname,$udom);
1856: }
1857: if ($uhom ne 'no_host') {
1858: if ($servers{$uhom}) {
1859: $servers{$uhom}.='&'.&escape($id);
1860: } else {
1861: $servers{$uhom}=&escape($id);
1862: }
1863: }
1864: }
1865: foreach my $server (keys(%servers)) {
1866: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1867: }
1868: return %result;
1869: }
1870:
1.1023 raeburn 1871: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1872: sub dump_dom {
1.1165 droeschl 1873: my ($namespace, $udom, $regexp) = @_;
1874:
1875: $udom ||= $env{'user.domain'};
1876:
1877: return () unless $udom;
1878:
1879: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1880: }
1881:
1.1023 raeburn 1882: # ------------------------------------------ get items from domain db files
1.806 raeburn 1883:
1884: sub get_dom {
1.860 raeburn 1885: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1886: return if ($udom eq 'public');
1.806 raeburn 1887: my $items='';
1888: foreach my $item (@$storearr) {
1889: $items.=&escape($item).'&';
1890: }
1891: $items=~s/\&$//;
1.860 raeburn 1892: if (!$udom) {
1893: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1894: return if ($udom eq 'public');
1.860 raeburn 1895: if (defined(&domain($udom,'primary'))) {
1896: $uhome=&domain($udom,'primary');
1897: } else {
1.874 albertel 1898: undef($uhome);
1.860 raeburn 1899: }
1900: } else {
1901: if (!$uhome) {
1902: if (defined(&domain($udom,'primary'))) {
1903: $uhome=&domain($udom,'primary');
1904: }
1905: }
1906: }
1907: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139 raeburn 1908: my $rep;
1909: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
1910: # domain information is hosted on this machine
1911: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1912: } else {
1913: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1914: }
1.866 raeburn 1915: my %returnhash;
1.875 albertel 1916: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1917: return %returnhash;
1918: }
1.806 raeburn 1919: my @pairs=split(/\&/,$rep);
1920: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1921: return @pairs;
1922: }
1923: my $i=0;
1924: foreach my $item (@$storearr) {
1925: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1926: $i++;
1927: }
1928: return %returnhash;
1929: } else {
1.880 banghart 1930: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1931: }
1932: }
1933:
1934: # -------------------------------------------- put items in domain db files
1935:
1936: sub put_dom {
1.860 raeburn 1937: my ($namespace,$storehash,$udom,$uhome)=@_;
1938: if (!$udom) {
1939: $udom=$env{'user.domain'};
1940: if (defined(&domain($udom,'primary'))) {
1941: $uhome=&domain($udom,'primary');
1942: } else {
1.874 albertel 1943: undef($uhome);
1.860 raeburn 1944: }
1945: } else {
1946: if (!$uhome) {
1947: if (defined(&domain($udom,'primary'))) {
1948: $uhome=&domain($udom,'primary');
1949: }
1950: }
1951: }
1952: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1953: my $items='';
1954: foreach my $item (keys(%$storehash)) {
1955: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1956: }
1957: $items=~s/\&$//;
1958: return &reply("putdom:$udom:$namespace:$items",$uhome);
1959: } else {
1.860 raeburn 1960: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1961: }
1962: }
1963:
1.1023 raeburn 1964: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1965: sub newput_dom {
1.1023 raeburn 1966: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1967: my $result;
1968: if (!$udom) {
1969: $udom=$env{'user.domain'};
1970: }
1.1023 raeburn 1971: if ($udom) {
1972: my $uname = &get_domainconfiguser($udom);
1973: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1974: }
1975: return $result;
1976: }
1977:
1.1023 raeburn 1978: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1979: sub del_dom {
1.1023 raeburn 1980: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1981: if (ref($storearr) eq 'ARRAY') {
1982: if (!$udom) {
1983: $udom=$env{'user.domain'};
1984: }
1.1023 raeburn 1985: if ($udom) {
1986: my $uname = &get_domainconfiguser($udom);
1987: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1988: }
1989: }
1990: }
1991:
1.1023 raeburn 1992: # ----------------------------------construct domainconfig user for a domain
1993: sub get_domainconfiguser {
1994: my ($udom) = @_;
1995: return $udom.'-domainconfig';
1996: }
1997:
1.837 raeburn 1998: sub retrieve_inst_usertypes {
1999: my ($udom) = @_;
2000: my (%returnhash,@order);
1.989 raeburn 2001: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2002: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2003: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 2004: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2005: } else {
2006: if (defined(&domain($udom,'primary'))) {
2007: my $uhome=&domain($udom,'primary');
2008: my $rep=&reply("inst_usertypes:$udom",$uhome);
2009: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 2010: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2011: return (\%returnhash,\@order);
2012: }
2013: my ($hashitems,$orderitems) = split(/:/,$rep);
2014: my @pairs=split(/\&/,$hashitems);
2015: foreach my $item (@pairs) {
2016: my ($key,$value)=split(/=/,$item,2);
2017: $key = &unescape($key);
2018: next if ($key =~ /^error: 2 /);
2019: $returnhash{$key}=&thaw_unescape($value);
2020: }
2021: my @esc_order = split(/\&/,$orderitems);
2022: foreach my $item (@esc_order) {
2023: push(@order,&unescape($item));
2024: }
2025: } else {
1.1172.2.44 raeburn 2026: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2027: }
1.1172.2.44 raeburn 2028: return (\%returnhash,\@order);
1.837 raeburn 2029: }
2030: }
2031:
1.868 raeburn 2032: sub is_domainimage {
2033: my ($url) = @_;
1.1172.2.142 raeburn 2034: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868 raeburn 2035: if (&domain($1) ne '') {
2036: return '1';
2037: }
2038: }
2039: return;
2040: }
2041:
1.899 raeburn 2042: sub inst_directory_query {
2043: my ($srch) = @_;
2044: my $udom = $srch->{'srchdomain'};
2045: my %results;
2046: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2047: my $outcome;
1.899 raeburn 2048: if ($homeserver ne '') {
1.1172.2.116 raeburn 2049: unless ($homeserver eq $perlvar{'lonHostID'}) {
2050: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2051: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116 raeburn 2052: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
2053: if (($major eq '' && $minor eq '') || ($major < 2) ||
2054: (($major == 2) && ($minor < 11)) ||
2055: (($major == 2) && ($minor == 11) && ($subver < 3))) {
2056: return;
2057: }
2058: }
2059: }
1.904 albertel 2060: my $queryid=&reply("querysend:instdirsearch:".
2061: &escape($srch->{'srchby'}).':'.
2062: &escape($srch->{'srchterm'}).':'.
2063: &escape($srch->{'srchtype'}),$homeserver);
2064: my $host=&hostname($homeserver);
2065: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96 raeburn 2066: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2067: return;
2068: }
2069: my $response = &get_query_reply($queryid);
2070: my $maxtries = 5;
2071: my $tries = 1;
2072: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2073: $response = &get_query_reply($queryid);
2074: $tries ++;
2075: }
2076:
2077: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2078: if ($response eq 'unavailable') {
2079: $outcome = $response;
2080: } else {
2081: $outcome = 'ok';
2082: my @matches = split(/\n/,$response);
2083: foreach my $match (@matches) {
2084: my ($key,$value) = split(/=/,$match);
2085: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2086: }
1.899 raeburn 2087: }
2088: }
2089: }
1.909 raeburn 2090: return ($outcome,%results);
1.899 raeburn 2091: }
2092:
2093: sub usersearch {
2094: my ($srch) = @_;
2095: my $dom = $srch->{'srchdomain'};
2096: my %results;
2097: my %libserv = &all_library();
2098: my $query = 'usersearch';
2099: foreach my $tryserver (keys(%libserv)) {
2100: if (&host_domain($tryserver) eq $dom) {
1.1172.2.116 raeburn 2101: unless ($tryserver eq $perlvar{'lonHostID'}) {
2102: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2103: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119 raeburn 2104: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116 raeburn 2105: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2106: (($major == 2) && ($minor < 11)) ||
2107: (($major == 2) && ($minor == 11) && ($subver < 3)));
2108: }
2109: }
1.899 raeburn 2110: my $host=&hostname($tryserver);
2111: my $queryid=
1.911 raeburn 2112: &reply("querysend:".&escape($query).':'.
2113: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2114: &escape($srch->{'srchtype'}).':'.
2115: &escape($srch->{'srchterm'}),$tryserver);
2116: if ($queryid !~/^\Q$host\E\_/) {
2117: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2118: next;
1.899 raeburn 2119: }
2120: my $reply = &get_query_reply($queryid);
2121: my $maxtries = 1;
2122: my $tries = 1;
2123: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2124: $reply = &get_query_reply($queryid);
2125: $tries ++;
2126: }
2127: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2128: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2129: } else {
1.911 raeburn 2130: my @matches;
2131: if ($reply =~ /\n/) {
2132: @matches = split(/\n/,$reply);
2133: } else {
2134: @matches = split(/\&/,$reply);
2135: }
1.899 raeburn 2136: foreach my $match (@matches) {
2137: my ($uname,$udom,%userhash);
1.911 raeburn 2138: foreach my $entry (split(/:/,$match)) {
2139: my ($key,$value) =
2140: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2141: $userhash{$key} = $value;
2142: if ($key eq 'username') {
2143: $uname = $value;
2144: } elsif ($key eq 'domain') {
2145: $udom = $value;
1.911 raeburn 2146: }
1.899 raeburn 2147: }
2148: $results{$uname.':'.$udom} = \%userhash;
2149: }
2150: }
2151: }
2152: }
2153: return %results;
2154: }
2155:
1.912 raeburn 2156: sub get_instuser {
2157: my ($udom,$uname,$id) = @_;
2158: my $homeserver = &domain($udom,'primary');
2159: my ($outcome,%results);
2160: if ($homeserver ne '') {
2161: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2162: &escape($id).':'.&escape($udom),$homeserver);
2163: my $host=&hostname($homeserver);
2164: if ($queryid !~/^\Q$host\E\_/) {
2165: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2166: return;
2167: }
2168: my $response = &get_query_reply($queryid);
2169: my $maxtries = 5;
2170: my $tries = 1;
2171: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2172: $response = &get_query_reply($queryid);
2173: $tries ++;
2174: }
2175: if (!&error($response) && $response ne 'refused') {
2176: if ($response eq 'unavailable') {
2177: $outcome = $response;
2178: } else {
2179: $outcome = 'ok';
2180: my @matches = split(/\n/,$response);
2181: foreach my $match (@matches) {
2182: my ($key,$value) = split(/=/,$match);
2183: $results{&unescape($key)} = &thaw_unescape($value);
2184: }
2185: }
2186: }
2187: }
2188: my %userinfo;
2189: if (ref($results{$uname}) eq 'HASH') {
2190: %userinfo = %{$results{$uname}};
2191: }
2192: return ($outcome,%userinfo);
2193: }
2194:
1.1172.2.69 raeburn 2195: sub get_multiple_instusers {
2196: my ($udom,$users,$caller) = @_;
2197: my ($outcome,$results);
2198: if (ref($users) eq 'HASH') {
2199: my $count = keys(%{$users});
2200: my $requested = &freeze_escape($users);
2201: my $homeserver = &domain($udom,'primary');
2202: if ($homeserver ne '') {
2203: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2204: my $host=&hostname($homeserver);
2205: if ($queryid !~/^\Q$host\E\_/) {
2206: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2207: ' for host: '.$homeserver.'in domain '.$udom);
2208: return ($outcome,$results);
2209: }
2210: my $response = &get_query_reply($queryid);
2211: my $maxtries = 5;
2212: if ($count > 100) {
2213: $maxtries = 1+int($count/20);
2214: }
2215: my $tries = 1;
2216: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2217: $response = &get_query_reply($queryid);
2218: $tries ++;
2219: }
2220: if ($response eq '') {
2221: $results = {};
2222: foreach my $key (keys(%{$users})) {
2223: my ($uname,$id);
2224: if ($caller eq 'id') {
2225: $id = $key;
2226: } else {
2227: $uname = $key;
2228: }
2229: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2230: $outcome = $resp;
2231: if ($resp eq 'ok') {
2232: %{$results} = (%{$results}, %info);
2233: } else {
2234: last;
2235: }
2236: }
2237: } elsif(!&error($response) && ($response ne 'refused')) {
2238: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2239: $outcome = $response;
2240: } else {
2241: ($outcome,my $userdata) = split(/=/,$response,2);
2242: if ($outcome eq 'ok') {
2243: $results = &thaw_unescape($userdata);
2244: }
2245: }
2246: }
2247: }
2248: }
2249: return ($outcome,$results);
2250: }
2251:
1.912 raeburn 2252: sub inst_rulecheck {
1.923 raeburn 2253: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2254: my %returnhash;
2255: if ($udom ne '') {
2256: if (ref($rules) eq 'ARRAY') {
2257: @{$rules} = map {&escape($_);} (@{$rules});
2258: my $rulestr = join(':',@{$rules});
2259: my $homeserver=&domain($udom,'primary');
2260: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2261: my $response;
2262: if ($item eq 'username') {
2263: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2264: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2265: $homeserver));
1.923 raeburn 2266: } elsif ($item eq 'id') {
2267: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2268: ':'.&escape($id).':'.$rulestr,
2269: $homeserver));
1.945 raeburn 2270: } elsif ($item eq 'selfcreate') {
2271: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2272: &escape($udom).':'.&escape($uname).
2273: ':'.$rulestr,$homeserver));
1.1172.2.147 raeburn 2274: } elsif ($item eq 'unamemap') {
2275: $response=&unescape(&reply('instunamemapcheck:'.
2276: &escape($udom).':'.&escape($uname).
2277: ':'.$rulestr,$homeserver));
1.923 raeburn 2278: }
1.912 raeburn 2279: if ($response ne 'refused') {
2280: my @pairs=split(/\&/,$response);
2281: foreach my $item (@pairs) {
2282: my ($key,$value)=split(/=/,$item,2);
2283: $key = &unescape($key);
2284: next if ($key =~ /^error: 2 /);
2285: $returnhash{$key}=&thaw_unescape($value);
2286: }
2287: }
2288: }
2289: }
2290: }
2291: return %returnhash;
2292: }
2293:
2294: sub inst_userrules {
1.923 raeburn 2295: my ($udom,$check) = @_;
1.912 raeburn 2296: my (%ruleshash,@ruleorder);
2297: if ($udom ne '') {
2298: my $homeserver=&domain($udom,'primary');
2299: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2300: my $response;
2301: if ($check eq 'id') {
2302: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2303: $homeserver);
1.943 raeburn 2304: } elsif ($check eq 'email') {
2305: $response=&reply('instemailrules:'.&escape($udom),
2306: $homeserver);
1.1172.2.147 raeburn 2307: } elsif ($check eq 'unamemap') {
2308: $response=&reply('unamemaprules:'.&escape($udom),
2309: $homeserver);
1.923 raeburn 2310: } else {
2311: $response=&reply('instuserrules:'.&escape($udom),
2312: $homeserver);
2313: }
1.912 raeburn 2314: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2315: ($response ne 'unknown_cmd') &&
1.912 raeburn 2316: ($response ne 'no_such_host')) {
2317: my ($hashitems,$orderitems) = split(/:/,$response);
2318: my @pairs=split(/\&/,$hashitems);
2319: foreach my $item (@pairs) {
2320: my ($key,$value)=split(/=/,$item,2);
2321: $key = &unescape($key);
2322: next if ($key =~ /^error: 2 /);
2323: $ruleshash{$key}=&thaw_unescape($value);
2324: }
2325: my @esc_order = split(/\&/,$orderitems);
2326: foreach my $item (@esc_order) {
2327: push(@ruleorder,&unescape($item));
2328: }
2329: }
2330: }
2331: }
2332: return (\%ruleshash,\@ruleorder);
2333: }
2334:
1.976 raeburn 2335: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2336:
2337: sub get_domain_defaults {
1.1172.2.35 raeburn 2338: my ($domain,$ignore_cache) = @_;
2339: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2340: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2341: unless ($ignore_cache) {
2342: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2343: if (defined($cached)) {
2344: if (ref($result) eq 'HASH') {
2345: return %{$result};
2346: }
1.943 raeburn 2347: }
2348: }
2349: my %domdefaults;
2350: my %domconfig =
1.989 raeburn 2351: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2352: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2353: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2354: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2355: 'coursecategories','autoenroll',
1.1172.2.146 raeburn 2356: 'helpsettings','wafproxy'],$domain);
1.1172.2.41 raeburn 2357: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2358: if (ref($domconfig{'defaults'}) eq 'HASH') {
2359: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2360: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2361: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2362: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2363: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2364: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2365: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2366: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2367: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1172.2.147 raeburn 2368: $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943 raeburn 2369: } else {
2370: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2371: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2372: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2373: }
1.976 raeburn 2374: if (ref($domconfig{'quotas'}) eq 'HASH') {
2375: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2376: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2377: } else {
2378: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2379: }
1.1172.2.6 raeburn 2380: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2381: foreach my $item (@usertools) {
2382: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2383: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2384: }
2385: }
1.1172.2.29 raeburn 2386: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2387: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2388: }
1.976 raeburn 2389: }
1.985 raeburn 2390: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2391: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2392: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2393: }
2394: }
1.1172.2.9 raeburn 2395: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2396: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2397: }
1.989 raeburn 2398: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2399: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2400: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2401: }
2402: }
1.1047 raeburn 2403: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2404: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144 raeburn 2405: $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60 raeburn 2406: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2407: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2408: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2409: }
1.1172.2.41 raeburn 2410: foreach my $type (@coursetypes) {
2411: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2412: unless ($type eq 'community') {
2413: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2414: }
2415: }
2416: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2417: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2418: }
1.1172.2.60 raeburn 2419: if ($domdefaults{'postsubmit'} eq 'on') {
2420: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2421: $domdefaults{$type.'postsubtimeout'} =
2422: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2423: }
2424: }
1.1172.2.30 raeburn 2425: }
1.1172.2.67 raeburn 2426: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2427: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2428: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2429: if (@clonecodes) {
2430: $domdefaults{'canclone'} = join('+',@clonecodes);
2431: }
2432: }
2433: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2434: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2435: }
1.1172.2.103 raeburn 2436: if ($domconfig{'coursedefaults'}{'texengine'}) {
2437: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2438: }
1.1047 raeburn 2439: }
1.1073 raeburn 2440: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2441: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2442: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2443: }
2444: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2445: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2446: }
1.1172.2.62 raeburn 2447: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2448: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2449: }
1.1172.2.137 raeburn 2450: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136 raeburn 2451: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2452: }
1.1073 raeburn 2453: }
1.1172.2.41 raeburn 2454: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2455: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2456: my @settings = ('types','registered','enroll_dates','access_dates','section',
2457: 'approval','limit');
2458: foreach my $type (@coursetypes) {
2459: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2460: my @mgrdc = ();
2461: foreach my $item (@settings) {
2462: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2463: push(@mgrdc,$item);
2464: }
2465: }
2466: if (@mgrdc) {
2467: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2468: }
2469: }
2470: }
2471: }
2472: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2473: foreach my $type (@coursetypes) {
2474: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2475: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2476: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2477: }
2478: }
2479: }
2480: }
2481: }
1.1172.2.46 raeburn 2482: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2483: $domdefaults{'catauth'} = 'std';
2484: $domdefaults{'catunauth'} = 'std';
2485: if ($domconfig{'coursecategories'}{'auth'}) {
2486: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2487: }
2488: if ($domconfig{'coursecategories'}{'unauth'}) {
2489: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2490: }
2491: }
1.1172.2.76 raeburn 2492: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2493: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146 raeburn 2494: $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76 raeburn 2495: }
1.1172.2.89 raeburn 2496: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2497: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2498: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2499: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2500: }
2501: }
1.1172.2.142 raeburn 2502: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
2503: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
2504: if ($domconfig{'wafproxy'}{$item}) {
2505: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2506: }
2507: }
2508: }
1.1172.2.23 raeburn 2509: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2510: return %domdefaults;
2511: }
2512:
1.1172.2.106 raeburn 2513: sub get_dom_cats {
2514: my ($dom) = @_;
2515: return unless (&domain($dom));
2516: my ($cats,$cached)=&is_cached_new('cats',$dom);
2517: unless (defined($cached)) {
2518: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2519: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2520: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2521: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2522: } else {
2523: $cats = {};
2524: }
2525: } else {
2526: $cats = {};
2527: }
2528: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2529: }
2530: return $cats;
2531: }
2532:
2533: sub get_dom_instcats {
2534: my ($dom) = @_;
2535: return unless (&domain($dom));
2536: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2537: unless (defined($cached)) {
2538: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2539: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2540: if ($totcodes > 0) {
2541: my $caller = 'global';
2542: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2543: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2544: $instcats = {
2545: codes => \%codes,
2546: codetitles => \@codetitles,
2547: cat_titles => \%cat_titles,
2548: cat_order => \%cat_order,
2549: };
2550: &do_cache_new('instcats',$dom,$instcats,3600);
2551: }
2552: }
2553: }
2554: return $instcats;
2555: }
2556:
2557: sub retrieve_instcodes {
2558: my ($coursecodes,$dom) = @_;
2559: my $totcodes;
2560: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2561: foreach my $course (keys(%courses)) {
2562: if (ref($courses{$course}) eq 'HASH') {
2563: if ($courses{$course}{'inst_code'} ne '') {
2564: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2565: $totcodes ++;
2566: }
2567: }
2568: }
2569: return $totcodes;
2570: }
2571:
1.1172.2.113 raeburn 2572: # --------------------------------------------- Get domain config for passwords
2573:
2574: sub get_passwdconf {
2575: my ($dom) = @_;
2576: my (%passwdconf,$gotconf,$lookup);
2577: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2578: if (defined($cached)) {
2579: if (ref($result) eq 'HASH') {
2580: %passwdconf = %{$result};
2581: $gotconf = 1;
2582: }
2583: }
2584: unless ($gotconf) {
2585: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2586: if (ref($domconfig{'passwords'}) eq 'HASH') {
2587: %passwdconf = %{$domconfig{'passwords'}};
2588: }
2589: my $cachetime = 24*60*60;
2590: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2591: }
2592: return %passwdconf;
2593: }
2594:
1.344 www 2595: # --------------------------------------------------- Assign a key to a student
2596:
2597: sub assign_access_key {
1.364 www 2598: #
2599: # a valid key looks like uname:udom#comments
2600: # comments are being appended
2601: #
1.498 www 2602: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2603: $kdom=
1.620 albertel 2604: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2605: $knum=
1.620 albertel 2606: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2607: $cdom=
1.620 albertel 2608: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2609: $cnum=
1.620 albertel 2610: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2611: $udom=$env{'user.name'} unless (defined($udom));
2612: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2613: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2614: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2615: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2616: # assigned to this person
2617: # - this should not happen,
1.345 www 2618: # unless something went wrong
2619: # the first time around
2620: # ready to assign
1.364 www 2621: $logentry=$1.'; '.$logentry;
1.496 www 2622: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2623: $kdom,$knum) eq 'ok') {
1.345 www 2624: # key now belongs to user
1.346 www 2625: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2626: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2627: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2628: return 'ok';
2629: } else {
2630: return
2631: 'error: Count not permanently assign key, will need to be re-entered later.';
2632: }
2633: } else {
2634: return 'error: Could not assign key, try again later.';
2635: }
1.364 www 2636: } elsif (!$existing{$ckey}) {
1.345 www 2637: # the key does not exist
2638: return 'error: The key does not exist';
2639: } else {
2640: # the key is somebody else's
2641: return 'error: The key is already in use';
2642: }
1.344 www 2643: }
2644:
1.364 www 2645: # ------------------------------------------ put an additional comment on a key
2646:
2647: sub comment_access_key {
2648: #
2649: # a valid key looks like uname:udom#comments
2650: # comments are being appended
2651: #
2652: my ($ckey,$cdom,$cnum,$logentry)=@_;
2653: $cdom=
1.620 albertel 2654: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2655: $cnum=
1.620 albertel 2656: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2657: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2658: if ($existing{$ckey}) {
2659: $existing{$ckey}.='; '.$logentry;
2660: # ready to assign
1.367 www 2661: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2662: $cdom,$cnum) eq 'ok') {
2663: return 'ok';
2664: } else {
2665: return 'error: Count not store comment.';
2666: }
2667: } else {
2668: # the key does not exist
2669: return 'error: The key does not exist';
2670: }
2671: }
2672:
1.344 www 2673: # ------------------------------------------------------ Generate a set of keys
2674:
2675: sub generate_access_keys {
1.364 www 2676: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2677: $cdom=
1.620 albertel 2678: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2679: $cnum=
1.620 albertel 2680: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2681: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2682: unless (($cdom) && ($cnum)) { return 0; }
2683: if ($number>10000) { return 0; }
2684: sleep(2); # make sure don't get same seed twice
2685: srand(time()^($$+($$<<15))); # from "Programming Perl"
2686: my $total=0;
2687: for (my $i=1;$i<=$number;$i++) {
2688: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2689: sprintf("%lx",int(100000*rand)).'-'.
2690: sprintf("%lx",int(100000*rand));
2691: $newkey=~s/1/g/g; # folks mix up 1 and l
2692: $newkey=~s/0/h/g; # and also 0 and O
2693: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2694: if ($existing{$newkey}) {
2695: $i--;
2696: } else {
1.364 www 2697: if (&put('accesskeys',
2698: { $newkey => '# generated '.localtime().
1.620 albertel 2699: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2700: '; '.$logentry },
2701: $cdom,$cnum) eq 'ok') {
1.344 www 2702: $total++;
2703: }
2704: }
2705: }
1.620 albertel 2706: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2707: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2708: return $total;
2709: }
2710:
2711: # ------------------------------------------------------- Validate an accesskey
2712:
2713: sub validate_access_key {
2714: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2715: $cdom=
1.620 albertel 2716: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2717: $cnum=
1.620 albertel 2718: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2719: $udom=$env{'user.domain'} unless (defined($udom));
2720: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2721: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2722: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2723: }
2724:
2725: # ------------------------------------- Find the section of student in a course
1.652 albertel 2726: sub devalidate_getsection_cache {
2727: my ($udom,$unam,$courseid)=@_;
2728: my $hashid="$udom:$unam:$courseid";
2729: &devalidate_cache_new('getsection',$hashid);
2730: }
1.298 matthew 2731:
1.815 albertel 2732: sub courseid_to_courseurl {
2733: my ($courseid) = @_;
2734: #already url style courseid
2735: return $courseid if ($courseid =~ m{^/});
2736:
2737: if (exists($env{'course.'.$courseid.'.num'})) {
2738: my $cnum = $env{'course.'.$courseid.'.num'};
2739: my $cdom = $env{'course.'.$courseid.'.domain'};
2740: return "/$cdom/$cnum";
2741: }
2742:
2743: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2744: if (exists($courseinfo{'num'})) {
2745: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2746: }
2747:
2748: return undef;
2749: }
2750:
1.298 matthew 2751: sub getsection {
2752: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2753: my $cachetime=1800;
1.551 albertel 2754:
2755: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2756: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2757: if (defined($cached)) { return $result; }
2758:
1.298 matthew 2759: my %Pending;
2760: my %Expired;
2761: #
2762: # Each role can either have not started yet (pending), be active,
2763: # or have expired.
2764: #
2765: # If there is an active role, we are done.
2766: #
2767: # If there is more than one role which has not started yet,
2768: # choose the one which will start sooner
2769: # If there is one role which has not started yet, return it.
2770: #
2771: # If there is more than one expired role, choose the one which ended last.
2772: # If there is a role which has expired, return it.
2773: #
1.815 albertel 2774: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2775: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2776: foreach my $key (keys(%roleshash)) {
1.479 albertel 2777: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2778: my $section=$1;
2779: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2780: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2781: my $now=time;
1.548 albertel 2782: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2783: $Expired{$end}=$section;
2784: next;
2785: }
1.548 albertel 2786: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2787: $Pending{$start}=$section;
2788: next;
2789: }
1.599 albertel 2790: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2791: }
2792: #
2793: # Presumedly there will be few matching roles from the above
2794: # loop and the sorting time will be negligible.
2795: if (scalar(keys(%Pending))) {
2796: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2797: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2798: }
2799: if (scalar(keys(%Expired))) {
2800: my @sorted = sort {$a <=> $b} keys(%Expired);
2801: my $time = pop(@sorted);
1.599 albertel 2802: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2803: }
1.599 albertel 2804: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2805: }
1.70 www 2806:
1.599 albertel 2807: sub save_cache {
2808: &purge_remembered();
1.722 albertel 2809: #&Apache::loncommon::validate_page();
1.620 albertel 2810: undef(%env);
1.780 albertel 2811: undef($env_loaded);
1.599 albertel 2812: }
1.452 albertel 2813:
1.599 albertel 2814: my $to_remember=-1;
2815: my %remembered;
2816: my %accessed;
2817: my $kicks=0;
2818: my $hits=0;
1.849 albertel 2819: sub make_key {
2820: my ($name,$id) = @_;
1.872 albertel 2821: if (length($id) > 65
2822: && length(&escape($id)) > 200) {
2823: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2824: }
1.849 albertel 2825: return &escape($name.':'.$id);
2826: }
2827:
1.599 albertel 2828: sub devalidate_cache_new {
2829: my ($name,$id,$debug) = @_;
2830: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2831: my $remembered_id=$name.':'.$id;
1.849 albertel 2832: $id=&make_key($name,$id);
1.599 albertel 2833: $memcache->delete($id);
1.1172.2.81 raeburn 2834: delete($remembered{$remembered_id});
2835: delete($accessed{$remembered_id});
1.599 albertel 2836: }
2837:
2838: sub is_cached_new {
2839: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2840: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2841: # keys in %remembered hash, which persists for
2842: # duration of request (no restriction on key length).
2843: if (exists($remembered{$remembered_id})) {
2844: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2845: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2846: $hits++;
1.1172.2.81 raeburn 2847: return ($remembered{$remembered_id},1);
1.599 albertel 2848: }
1.1172.2.81 raeburn 2849: $id=&make_key($name,$id);
1.599 albertel 2850: my $value = $memcache->get($id);
2851: if (!(defined($value))) {
2852: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2853: return (undef,undef);
1.416 albertel 2854: }
1.599 albertel 2855: if ($value eq '__undef__') {
2856: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2857: $value=undef;
2858: }
1.1172.2.81 raeburn 2859: &make_room($remembered_id,$value,$debug);
1.599 albertel 2860: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2861: return ($value,1);
2862: }
2863:
2864: sub do_cache_new {
2865: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2866: my $remembered_id=$name.':'.$id;
1.849 albertel 2867: $id=&make_key($name,$id);
1.599 albertel 2868: my $setvalue=$value;
2869: if (!defined($setvalue)) {
2870: $setvalue='__undef__';
2871: }
1.623 albertel 2872: if (!defined($time) ) {
2873: $time=600;
2874: }
1.599 albertel 2875: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2876: my $result = $memcache->set($id,$setvalue,$time);
2877: if (! $result) {
1.872 albertel 2878: &logthis("caching of id -> $id failed");
1.910 albertel 2879: $memcache->disconnect_all();
1.872 albertel 2880: }
1.600 albertel 2881: # need to make a copy of $value
1.1172.2.81 raeburn 2882: &make_room($remembered_id,$value,$debug);
1.599 albertel 2883: return $value;
2884: }
2885:
2886: sub make_room {
1.1172.2.81 raeburn 2887: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2888:
1.1172.2.81 raeburn 2889: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2890: : $value;
1.599 albertel 2891: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2892: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2893: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2894: my $to_kick;
2895: my $max_time=0;
2896: foreach my $other (keys(%accessed)) {
2897: if (&tv_interval($accessed{$other}) > $max_time) {
2898: $to_kick=$other;
2899: $max_time=&tv_interval($accessed{$other});
2900: }
2901: }
2902: delete($remembered{$to_kick});
2903: delete($accessed{$to_kick});
2904: $kicks++;
2905: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2906: return;
2907: }
2908:
1.599 albertel 2909: sub purge_remembered {
1.604 albertel 2910: #&logthis("Tossing ".scalar(keys(%remembered)));
2911: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2912: undef(%remembered);
2913: undef(%accessed);
1.428 albertel 2914: }
1.70 www 2915: # ------------------------------------- Read an entry from a user's environment
2916:
2917: sub userenvironment {
2918: my ($udom,$unam,@what)=@_;
1.976 raeburn 2919: my $items;
2920: foreach my $item (@what) {
2921: $items.=&escape($item).'&';
2922: }
2923: $items=~s/\&$//;
1.70 www 2924: my %returnhash=();
1.1009 raeburn 2925: my $uhome = &homeserver($unam,$udom);
2926: unless ($uhome eq 'no_host') {
2927: my @answer=split(/\&/,
2928: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2929: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2930: return %returnhash;
2931: }
1.1009 raeburn 2932: my $i;
2933: for ($i=0;$i<=$#what;$i++) {
2934: $returnhash{$what[$i]}=&unescape($answer[$i]);
2935: }
1.70 www 2936: }
2937: return %returnhash;
1.1 albertel 2938: }
2939:
1.617 albertel 2940: # ---------------------------------------------------------- Get a studentphoto
2941: sub studentphoto {
2942: my ($udom,$unam,$ext) = @_;
2943: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2944: if (defined($env{'request.course.id'})) {
1.708 raeburn 2945: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2946: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2947: return(&retrievestudentphoto($udom,$unam,$ext));
2948: } else {
2949: my ($result,$perm_reqd)=
1.707 albertel 2950: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2951: if ($result eq 'ok') {
2952: if (!($perm_reqd eq 'yes')) {
2953: return(&retrievestudentphoto($udom,$unam,$ext));
2954: }
2955: }
2956: }
2957: }
2958: } else {
2959: my ($result,$perm_reqd) =
1.707 albertel 2960: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2961: if ($result eq 'ok') {
2962: if (!($perm_reqd eq 'yes')) {
2963: return(&retrievestudentphoto($udom,$unam,$ext));
2964: }
2965: }
2966: }
2967: return '/adm/lonKaputt/lonlogo_broken.gif';
2968: }
2969:
2970: sub retrievestudentphoto {
2971: my ($udom,$unam,$ext,$type) = @_;
2972: my $home=&Apache::lonnet::homeserver($unam,$udom);
2973: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2974: if ($ret eq 'ok') {
2975: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2976: if ($type eq 'thumbnail') {
2977: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2978: }
2979: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2980: return $tokenurl;
2981: } else {
2982: if ($type eq 'thumbnail') {
2983: return '/adm/lonKaputt/genericstudent_tn.gif';
2984: } else {
2985: return '/adm/lonKaputt/lonlogo_broken.gif';
2986: }
1.617 albertel 2987: }
2988: }
2989:
1.263 www 2990: # -------------------------------------------------------------------- New chat
2991:
2992: sub chatsend {
1.724 raeburn 2993: my ($newentry,$anon,$group)=@_;
1.620 albertel 2994: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2995: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2996: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2997: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2998: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2999: &escape($newentry)).':'.$group,$chome);
1.292 www 3000: }
3001:
3002: # ------------------------------------------ Find current version of a resource
3003:
3004: sub getversion {
3005: my $fname=&clutter(shift);
1.1172.2.10 raeburn 3006: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3007: return ¤tversion(&filelocation('',$fname));
3008: }
3009:
3010: sub currentversion {
3011: my $fname=shift;
3012: my $author=$fname;
3013: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3014: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3015: my $home=&homeserver($uname,$udom);
1.292 www 3016: if ($home eq 'no_host') {
3017: return -1;
3018: }
1.1112 www 3019: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3020: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3021: return -1;
3022: }
1.1112 www 3023: return $answer;
1.263 www 3024: }
3025:
1.1111 www 3026: #
3027: # Return special version number of resource if set by override, empty otherwise
3028: #
3029: sub usedversion {
3030: my $fname=shift;
3031: unless ($fname) { $fname=$env{'request.uri'}; }
3032: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3033: if ($urlversion) { return $urlversion; }
3034: return '';
3035: }
3036:
1.1 albertel 3037: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3038:
1.1 albertel 3039: sub subscribe {
3040: my $fname=shift;
1.761 raeburn 3041: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3042: $fname=~s/[\n\r]//g;
1.1 albertel 3043: my $author=$fname;
3044: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3045: my ($udom,$uname)=split(/\//,$author);
3046: my $home=homeserver($uname,$udom);
1.335 albertel 3047: if ($home eq 'no_host') {
3048: return 'not_found';
1.1 albertel 3049: }
3050: my $answer=reply("sub:$fname",$home);
1.64 www 3051: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3052: $answer.=' by '.$home;
3053: }
1.1 albertel 3054: return $answer;
3055: }
3056:
1.8 www 3057: # -------------------------------------------------------------- Replicate file
3058:
3059: sub repcopy {
3060: my $filename=shift;
1.23 www 3061: $filename=~s/\/+/\//g;
1.1142 raeburn 3062: my $londocroot = $perlvar{'lonDocRoot'};
3063: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3064: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3065: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3066: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3067: return &repcopy_userfile($filename);
3068: }
1.532 albertel 3069: $filename=~s/[\n\r]//g;
1.8 www 3070: my $transname="$filename.in.transfer";
1.828 www 3071: # FIXME: this should flock
1.607 raeburn 3072: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3073: my $remoteurl=subscribe($filename);
1.64 www 3074: if ($remoteurl =~ /^con_lost by/) {
3075: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3076: return 'unavailable';
1.8 www 3077: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3078: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3079: return 'not_found';
1.64 www 3080: } elsif ($remoteurl =~ /^rejected by/) {
3081: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3082: return 'forbidden';
1.20 www 3083: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3084: return 'ok';
1.8 www 3085: } else {
1.290 www 3086: my $author=$filename;
3087: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3088: my ($udom,$uname)=split(/\//,$author);
3089: my $home=homeserver($uname,$udom);
3090: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3091: my @parts=split(/\//,$filename);
3092: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3093: if ($path ne "$londocroot/res") {
1.8 www 3094: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3095: return 'bad_request';
1.8 www 3096: }
3097: my $count;
3098: for ($count=5;$count<$#parts;$count++) {
3099: $path.="/$parts[$count]";
3100: if ((-e $path)!=1) {
3101: mkdir($path,0777);
3102: }
3103: }
3104: my $ua=new LWP::UserAgent;
3105: my $request=new HTTP::Request('GET',"$remoteurl");
3106: my $response=$ua->request($request,$transname);
3107: if ($response->is_error()) {
3108: unlink($transname);
3109: my $message=$response->status_line;
1.672 albertel 3110: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3111: ." LWP get: $message: $filename</font>");
1.607 raeburn 3112: return 'unavailable';
1.8 www 3113: } else {
1.16 www 3114: if ($remoteurl!~/\.meta$/) {
3115: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3116: my $mresponse=$ua->request($mrequest,$filename.'.meta');
3117: if ($mresponse->is_error()) {
3118: unlink($filename.'.meta');
3119: &logthis(
1.672 albertel 3120: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3121: }
3122: }
1.8 www 3123: rename($transname,$filename);
1.607 raeburn 3124: return 'ok';
1.8 www 3125: }
1.290 www 3126: }
1.8 www 3127: }
1.330 www 3128: }
3129:
1.1172.2.124 raeburn 3130: # ------------------------------------------------- Unsubscribe from a resource
3131:
3132: sub unsubscribe {
3133: my ($fname) = @_;
3134: my $answer;
3135: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3136: $fname=~s/[\n\r]//g;
3137: my $author=$fname;
3138: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3139: my ($udom,$uname)=split(/\//,$author);
3140: my $home=homeserver($uname,$udom);
3141: if ($home eq 'no_host') {
3142: $answer = 'no_host';
3143: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3144: $answer = 'home';
3145: } else {
1.1172.2.125 raeburn 3146: $answer = reply("unsub:$fname",$home);
1.1172.2.124 raeburn 3147: }
3148: return $answer;
3149: }
3150:
1.330 www 3151: # ------------------------------------------------ Get server side include body
3152: sub ssi_body {
1.381 albertel 3153: my ($filelink,%form)=@_;
1.606 matthew 3154: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3155: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3156: }
1.953 www 3157: my $output='';
3158: my $response;
1.980 raeburn 3159: if ($filelink=~/^https?\:/) {
1.954 raeburn 3160: ($output,$response)=&externalssi($filelink);
1.953 www 3161: } else {
1.1004 droeschl 3162: $filelink .= $filelink=~/\?/ ? '&' : '?';
3163: $filelink .= 'inhibitmenu=yes';
1.953 www 3164: ($output,$response)=&ssi($filelink,%form);
3165: }
1.778 albertel 3166: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3167: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3168: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3169: if (wantarray) {
3170: return ($output, $response);
3171: } else {
3172: return $output;
3173: }
1.8 www 3174: }
3175:
1.15 www 3176: # --------------------------------------------------------- Server Side Include
3177:
1.782 albertel 3178: sub absolute_url {
1.1172.2.145 raeburn 3179: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3180: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3181: if ($host_name eq '') {
3182: $host_name = $ENV{'SERVER_NAME'};
3183: }
1.1172.2.145 raeburn 3184: if ($unalias) {
3185: my $alias = &get_proxy_alias();
3186: if ($alias eq $host_name) {
3187: my $lonhost = $perlvar{'lonHostID'};
3188: my $hostname = &hostname($lonhost);
3189: my $lcproto;
3190: if (($keep_proto) || ($hostname eq '')) {
3191: $lcproto = $protocol;
3192: } else {
3193: $lcproto = $protocol{$lonhost};
3194: $lcproto = 'http' if ($lcproto ne 'https');
3195: $lcproto .= '://';
3196: }
3197: unless ($hostname eq '') {
3198: return $lcproto.$hostname;
3199: }
3200: }
3201: }
1.782 albertel 3202: return $protocol.$host_name;
3203: }
3204:
1.942 foxr 3205: #
3206: # Server side include.
3207: # Parameters:
3208: # fn Possibly encrypted resource name/id.
3209: # form Hash that describes how the rendering should be done
3210: # and other things.
1.944 foxr 3211: # Returns:
1.950 raeburn 3212: # Scalar context: The content of the response.
3213: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3214: #
1.15 www 3215: sub ssi {
3216:
1.944 foxr 3217: my ($fn,%form)=@_;
1.1172.2.145 raeburn 3218: my ($host,$request,$response);
3219: $host = &absolute_url('',1);
1.711 albertel 3220:
3221: $form{'no_update_last_known'}=1;
1.895 albertel 3222: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3223: if (%form) {
1.1172.2.145 raeburn 3224: $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58 raeburn 3225: $request->content(join('&',map {
3226: my $name = escape($_);
3227: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3228: ? join("&$name=", map {escape($_) } @{$form{$_}})
3229: : &escape($form{$_}) );
3230: } keys(%form)));
1.23 www 3231: } else {
1.1172.2.145 raeburn 3232: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3233: }
3234:
1.15 www 3235: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100 raeburn 3236:
1.1172.2.101 raeburn 3237: if (($env{'request.course.id'}) &&
3238: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3239: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3240: ($form{'grade_symb'} ne '') &&
3241: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3242: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100 raeburn 3243: if (LWP::UserAgent->VERSION >= 5.834) {
3244: my $ua=new LWP::UserAgent;
3245: $ua->local_address('127.0.0.1');
3246: $response = $ua->request($request);
3247: } else {
3248: {
3249: require LWP::Protocol::http;
3250: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
3251: my $ua=new LWP::UserAgent;
3252: $response = $ua->request($request);
3253: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
3254: }
3255: }
3256: } else {
3257: my $ua=new LWP::UserAgent;
3258: $response = $ua->request($request);
3259: }
1.944 foxr 3260: if (wantarray) {
1.1172.2.3 raeburn 3261: return ($response->content, $response);
1.944 foxr 3262: } else {
1.1172.2.3 raeburn 3263: return $response->content;
1.942 foxr 3264: }
1.324 www 3265: }
3266:
3267: sub externalssi {
3268: my ($url)=@_;
3269: my $ua=new LWP::UserAgent;
3270: my $request=new HTTP::Request('GET',$url);
3271: my $response=$ua->request($request);
1.954 raeburn 3272: if (wantarray) {
3273: return ($response->content, $response);
3274: } else {
3275: return $response->content;
3276: }
1.15 www 3277: }
1.254 www 3278:
1.1172.2.98 raeburn 3279: # If the local copy of a replicated resource is outdated, trigger a
3280: # connection from the homeserver to flush the delayed queue. If no update
3281: # happens, remove local copies of outdated resource (and corresponding
3282: # metadata file).
3283:
3284: sub remove_stale_resfile {
3285: my ($url) = @_;
3286: my $removed;
3287: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3288: my $audom = $1;
3289: my $auname = $2;
3290: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3291: my $homeserver = &homeserver($auname,$audom);
3292: unless (($homeserver eq 'no_host') ||
3293: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3294: my $fname = &filelocation('',$url);
3295: if (-e $fname) {
3296: my $hostname = &hostname($homeserver);
3297: if ($hostname) {
1.1172.2.120 raeburn 3298: my $protocol = $protocol{$homeserver};
3299: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98 raeburn 3300: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120 raeburn 3301: my $ua=new LWP::UserAgent;
3302: $ua->timeout(5);
1.1172.2.98 raeburn 3303: my $request=new HTTP::Request('HEAD',$uri);
3304: my $response=$ua->request($request);
3305: if ($response->is_success()) {
3306: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3307: my $locmodtime = (stat($fname))[9];
3308: if ($locmodtime < $remmodtime) {
3309: my $stale;
3310: my $answer = &reply('pong',$homeserver);
3311: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3312: sleep(0.2);
3313: $locmodtime = (stat($fname))[9];
3314: if ($locmodtime < $remmodtime) {
3315: my $posstransfer = $fname.'.in.transfer';
3316: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3317: $removed = 1;
3318: } else {
3319: $stale = 1;
3320: }
3321: } else {
3322: $removed = 1;
3323: }
3324: } else {
3325: $stale = 1;
3326: }
3327: if ($stale) {
1.1172.2.124 raeburn 3328: if (unlink($fname)) {
3329: if ($uri!~/\.meta$/) {
3330: if (-e $fname.'.meta') {
3331: unlink($fname.'.meta');
3332: }
3333: }
3334: my $unsubresult = &unsubscribe($fname);
3335: unless ($unsubresult eq 'ok') {
3336: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3337: }
3338: $removed = 1;
1.1172.2.98 raeburn 3339: }
3340: }
3341: }
3342: }
3343: }
3344: }
3345: }
3346: }
3347: }
3348: return $removed;
3349: }
3350:
1.492 albertel 3351: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3352:
3353: sub allowuploaded {
3354: my ($srcurl,$url)=@_;
3355: $url=&clutter(&declutter($url));
3356: my $dir=$url;
3357: $dir=~s/\/[^\/]+$//;
3358: my %httpref=();
3359: my $httpurl=&hreflocation('',$url);
3360: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3361: &Apache::lonnet::appenv(\%httpref);
1.254 www 3362: }
1.477 raeburn 3363:
1.1172.2.13 raeburn 3364: #
3365: # Determine if the current user should be able to edit a particular resource,
3366: # when viewing in course context.
3367: # (a) When viewing resource used to determine if "Edit" item is included in
3368: # Functions.
3369: # (b) When displaying folder contents in course editor, used to determine if
3370: # "Edit" link will be displayed alongside resource.
3371: #
3372: # input: six args -- filename (decluttered), course number, course domain,
3373: # url, symb (if registered) and group (if this is a group
3374: # item -- e.g., bulletin board, group page etc.).
3375: # output: array of five scalars --
3376: # $cfile -- url for file editing if editable on current server
3377: # $home -- homeserver of resource (i.e., for author if published,
3378: # or course if uploaded.).
3379: # $switchserver -- 1 if server switch will be needed.
3380: # $forceedit -- 1 if icon/link should be to go to edit mode
3381: # $forceview -- 1 if icon/link should be to go to view mode
3382: #
3383:
3384: sub can_edit_resource {
3385: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3386: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3387: #
3388: # For aboutme pages user can only edit his/her own.
3389: #
3390: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3391: my ($sdom,$sname) = ($1,$2);
3392: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3393: $home = $env{'user.home'};
3394: $cfile = $resurl;
3395: if ($env{'form.forceedit'}) {
3396: $forceview = 1;
3397: } else {
3398: $forceedit = 1;
3399: }
3400: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3401: } else {
3402: return;
3403: }
3404: }
3405:
3406: if ($env{'request.course.id'}) {
3407: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3408: if ($group ne '') {
3409: # if this is a group homepage or group bulletin board, check group privs
3410: my $allowed = 0;
3411: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3412: if ((&allowed('mdg',$env{'request.course.id'}.
3413: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3414: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3415: $allowed = 1;
3416: }
3417: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3418: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3419: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3420: $allowed = 1;
3421: }
3422: }
3423: if ($allowed) {
3424: $home=&homeserver($cnum,$cdom);
3425: if ($env{'form.forceedit'}) {
3426: $forceview = 1;
3427: } else {
3428: $forceedit = 1;
3429: }
3430: $cfile = $resurl;
3431: } else {
3432: return;
3433: }
3434: } else {
1.1172.2.15 raeburn 3435: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3436: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3437: return;
3438: }
3439: } elsif (!$crsedit) {
1.1172.2.148! raeburn 3440: if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
1.1172.2.13 raeburn 3441: #
3442: # No edit allowed where CC has switched to student role.
3443: #
1.1172.2.148! raeburn 3444: return;
! 3445: } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
! 3446: ($resurl =~ m{^/res/lib/templates/})) {
! 3447: return;
! 3448: }
1.1172.2.13 raeburn 3449: }
3450: }
3451: }
3452:
3453: if ($file ne '') {
3454: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3455: if (&is_course_upload($file,$cnum,$cdom)) {
3456: $uploaded = 1;
3457: $incourse = 1;
3458: if ($file =~/\.(htm|html|css|js|txt)$/) {
3459: $cfile = &hreflocation('',$file);
3460: if ($env{'form.forceedit'}) {
3461: $forceview = 1;
3462: } else {
3463: $forceedit = 1;
3464: }
3465: }
3466: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3467: $incourse = 1;
3468: if ($env{'form.forceedit'}) {
3469: $forceview = 1;
3470: } else {
3471: $forceedit = 1;
3472: }
3473: $cfile = $resurl;
3474: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3475: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3476: $incourse = 1;
3477: if ($env{'form.forceedit'}) {
3478: $forceview = 1;
3479: } else {
3480: $forceedit = 1;
3481: }
3482: $cfile = $resurl;
3483: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3484: $incourse = 1;
3485: $cfile = $resurl.'/smpedit';
3486: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3487: $incourse = 1;
3488: if ($env{'form.forceedit'}) {
3489: $forceview = 1;
3490: } else {
3491: $forceedit = 1;
3492: }
3493: $cfile = $resurl;
1.1172.2.122 raeburn 3494: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3495: my ($map,$id,$res) = &decode_symb($symb);
3496: if ($map =~ /\.page$/) {
3497: $incourse = 1;
3498: if ($env{'form.forceedit'}) {
3499: $forceview = 1;
3500: $cfile = $map;
3501: } else {
3502: $forceedit = 1;
3503: $cfile = '/adm/wrapper'.$resurl;
3504: }
3505: }
1.1172.2.15 raeburn 3506: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3507: $incourse = 1;
3508: if ($env{'form.forceedit'}) {
3509: $forceview = 1;
3510: } else {
3511: $forceedit = 1;
3512: }
3513: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3514: }
3515: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3516: my $template = '/res/lib/templates/simpleproblem.problem';
3517: if (&is_on_map($template)) {
3518: $incourse = 1;
3519: $forceview = 1;
3520: $cfile = $template;
3521: }
3522: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118 raeburn 3523: $incourse = 1;
3524: if ($env{'form.forceedit'}) {
3525: $forceview = 1;
3526: } else {
3527: $forceedit = 1;
3528: }
3529: $cfile = $resurl;
1.1172.2.13 raeburn 3530: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3531: $incourse = 1;
3532: $forceview = 1;
3533: if ($symb) {
3534: my ($map,$id,$res)=&decode_symb($symb);
3535: $env{'request.symb'} = $symb;
3536: $cfile = &clutter($res);
3537: } else {
3538: $cfile = $env{'form.suppurl'};
3539: $cfile =~ s{^http://}{};
3540: $cfile = '/adm/wrapper/ext/'.$cfile;
3541: }
1.1172.2.31 raeburn 3542: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3543: if ($env{'form.forceedit'}) {
3544: $forceview = 1;
3545: } else {
3546: $forceedit = 1;
3547: }
3548: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3549: }
3550: }
3551: if ($uploaded || $incourse) {
3552: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3553: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3554: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3555: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3556: # Check that the user has permission to edit this resource
3557: my $setpriv = 1;
3558: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3559: if (defined($cfudom)) {
3560: $home=&homeserver($cfuname,$cfudom);
3561: $cfile=$file;
3562: }
3563: }
3564: if (($cfile ne '') && (!$incourse || $uploaded) &&
3565: (($home ne '') && ($home ne 'no_host'))) {
3566: my @ids=¤t_machine_ids();
3567: unless (grep(/^\Q$home\E$/,@ids)) {
3568: $switchserver=1;
3569: }
3570: }
3571: }
3572: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3573: }
3574:
3575: sub is_course_upload {
3576: my ($file,$cnum,$cdom) = @_;
3577: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3578: $uploadpath =~ s{^\/}{};
3579: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3580: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3581: return 1;
3582: }
3583: return;
3584: }
3585:
3586: sub in_course {
3587: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3588: if ($hideprivileged) {
3589: my $skipuser;
1.1172.2.23 raeburn 3590: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3591: my @possdoms = ($cdom);
3592: if ($coursehash{'checkforpriv'}) {
3593: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3594: }
3595: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3596: $skipuser = 1;
3597: if ($coursehash{'nothideprivileged'}) {
3598: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3599: my $user;
3600: if ($item =~ /:/) {
3601: $user = $item;
3602: } else {
3603: $user = join(':',split(/[\@]/,$item));
3604: }
3605: if ($user eq $uname.':'.$udom) {
3606: undef($skipuser);
3607: last;
3608: }
3609: }
3610: }
3611: if ($skipuser) {
3612: return 0;
3613: }
3614: }
3615: }
3616: $type ||= 'any';
3617: if (!defined($cdom) || !defined($cnum)) {
3618: my $cid = $env{'request.course.id'};
3619: $cdom = $env{'course.'.$cid.'.domain'};
3620: $cnum = $env{'course.'.$cid.'.num'};
3621: }
3622: my $typesref;
3623: if (($type eq 'any') || ($type eq 'all')) {
3624: $typesref = ['active','previous','future'];
3625: } elsif ($type eq 'previous' || $type eq 'future') {
3626: $typesref = [$type];
3627: }
3628: my %roles = &get_my_roles($uname,$udom,'userroles',
3629: $typesref,undef,[$cdom]);
3630: my ($tmp) = keys(%roles);
3631: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3632: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3633: if (@course_roles > 0) {
3634: return 1;
3635: }
3636: return 0;
3637: }
3638:
1.478 albertel 3639: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3640: # input: action, courseID, current domain, intended
1.637 raeburn 3641: # path to file, source of file, instruction to parse file for objects,
3642: # ref to hash for embedded objects,
3643: # ref to hash for codebase of java objects.
1.1095 raeburn 3644: # reference to scalar to accommodate mime type determined
3645: # from File::MMagic if $parser = parse.
1.637 raeburn 3646: #
1.485 raeburn 3647: # output: url to file (if action was uploaddoc),
3648: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3649: #
1.478 albertel 3650: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3651: # course.
1.477 raeburn 3652: #
1.478 albertel 3653: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3654: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3655: # course's home server.
1.477 raeburn 3656: #
1.478 albertel 3657: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3658: # be copied from $source (current location) to
3659: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3660: # and will then be copied to
3661: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3662: # course's home server.
1.485 raeburn 3663: #
1.481 raeburn 3664: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3665: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3666: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3667: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3668: # in course's home server.
1.637 raeburn 3669: #
1.477 raeburn 3670:
3671: sub process_coursefile {
1.1095 raeburn 3672: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3673: $mimetype)=@_;
1.477 raeburn 3674: my $fetchresult;
1.638 albertel 3675: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3676: if ($action eq 'propagate') {
1.638 albertel 3677: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3678: $home);
1.481 raeburn 3679: } else {
1.477 raeburn 3680: my $fpath = '';
3681: my $fname = $file;
1.478 albertel 3682: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3683: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3684: my $filepath = &build_filepath($fpath);
1.481 raeburn 3685: if ($action eq 'copy') {
3686: if ($source eq '') {
3687: $fetchresult = 'no source file';
3688: return $fetchresult;
3689: } else {
3690: my $destination = $filepath.'/'.$fname;
3691: rename($source,$destination);
3692: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3693: $home);
1.481 raeburn 3694: }
3695: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 3696: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3697: print $fh $env{'form.'.$source};
1.481 raeburn 3698: close($fh);
1.637 raeburn 3699: if ($parser eq 'parse') {
1.1024 raeburn 3700: my $mm = new File::MMagic;
1.1095 raeburn 3701: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3702: if ($type eq 'text/html') {
1.1024 raeburn 3703: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3704: unless ($parse_result eq 'ok') {
3705: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3706: }
1.637 raeburn 3707: }
1.1095 raeburn 3708: if (ref($mimetype)) {
3709: $$mimetype = $type;
3710: }
1.637 raeburn 3711: }
1.477 raeburn 3712: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3713: $home);
1.481 raeburn 3714: if ($fetchresult eq 'ok') {
3715: return '/uploaded/'.$fpath.'/'.$fname;
3716: } else {
3717: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3718: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3719: return '/adm/notfound.html';
3720: }
1.477 raeburn 3721: }
3722: }
1.485 raeburn 3723: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3724: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3725: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3726: }
3727: return $fetchresult;
3728: }
3729:
1.637 raeburn 3730: sub build_filepath {
3731: my ($fpath) = @_;
3732: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3733: unless ($fpath eq '') {
3734: my @parts=split('/',$fpath);
3735: foreach my $part (@parts) {
3736: $filepath.= '/'.$part;
3737: if ((-e $filepath)!=1) {
3738: mkdir($filepath,0777);
3739: }
3740: }
3741: }
3742: return $filepath;
3743: }
3744:
3745: sub store_edited_file {
1.638 albertel 3746: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3747: my $file = $primary_url;
3748: $file =~ s#^/uploaded/$docudom/$docuname/##;
3749: my $fpath = '';
3750: my $fname = $file;
3751: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3752: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3753: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 3754: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3755: print $fh $content;
3756: close($fh);
1.638 albertel 3757: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3758: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3759: $home);
1.637 raeburn 3760: if ($$fetchresult eq 'ok') {
3761: return '/uploaded/'.$fpath.'/'.$fname;
3762: } else {
1.638 albertel 3763: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3764: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3765: return '/adm/notfound.html';
3766: }
3767: }
3768:
1.531 albertel 3769: sub clean_filename {
1.831 albertel 3770: my ($fname,$args)=@_;
1.315 www 3771: # Replace Windows backslashes by forward slashes
1.257 www 3772: $fname=~s/\\/\//g;
1.831 albertel 3773: if (!$args->{'keep_path'}) {
3774: # Get rid of everything but the actual filename
3775: $fname=~s/^.*\/([^\/]+)$/$1/;
3776: }
1.315 www 3777: # Replace spaces by underscores
3778: $fname=~s/\s+/\_/g;
1.1172.2.110 raeburn 3779: # Transliterate non-ascii text to ascii
3780: my $lang = &Apache::lonlocal::current_language();
3781: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 3782: # Replace all other weird characters by nothing
1.831 albertel 3783: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3784: # Replace all .\d. sequences with _\d. so they no longer look like version
3785: # numbers
3786: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140 raeburn 3787: # Replace three or more adjacent underscores with one for consistency
3788: # with loncfile::filename_check() so complete url can be extracted by
3789: # lonnet::decode_symb()
3790: $fname=~s/_{3,}/_/g;
1.531 albertel 3791: return $fname;
3792: }
1.1172.2.110 raeburn 3793:
1.1051 raeburn 3794: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3795: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3796: # image with the same aspect ratio as the original, but with dimensions which do
3797: # not exceed $resizewidth and $resizeheight.
3798:
1.984 neumanie 3799: sub resizeImage {
1.1051 raeburn 3800: my ($img_path,$resizewidth,$resizeheight) = @_;
3801: my $ima = Image::Magick->new;
3802: my $resized;
3803: if (-e $img_path) {
3804: $ima->Read($img_path);
3805: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3806: my $width = $ima->Get('width');
3807: my $height = $ima->Get('height');
3808: if ($width > $resizewidth) {
3809: my $factor = $width/$resizewidth;
3810: my $newheight = $height/$factor;
3811: $ima->Scale(width=>$resizewidth,height=>$newheight);
3812: $resized = 1;
3813: }
3814: }
3815: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3816: my $width = $ima->Get('width');
3817: my $height = $ima->Get('height');
3818: if ($height > $resizeheight) {
3819: my $factor = $height/$resizeheight;
3820: my $newwidth = $width/$factor;
3821: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3822: $resized = 1;
3823: }
3824: }
3825: if ($resized) {
3826: $ima->Write($img_path);
3827: }
3828: }
3829: return;
1.977 amueller 3830: }
3831:
1.608 albertel 3832: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3833: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3834: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3835: # $context - possible values: coursedoc, existingfile, overwrite,
1.1172.2.109 raeburn 3836: # canceloverwrite, scantron or ''.
1.1090 raeburn 3837: # if 'coursedoc': upload to the current course
3838: # if 'existingfile': write file to tmp/overwrites directory
3839: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3840: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3841: # $subdir - directory in userfile to store the file into
1.1172.2.109 raeburn 3842: # $parser - instruction to parse file for objects ($parser = parse) or
3843: # if context is 'scantron', $parser is hashref of csv column mapping
3844: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3845: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 3846: # $allfiles - reference to hash for embedded objects
3847: # $codebase - reference to hash for codebase of java objects
3848: # $desuname - username for permanent storage of uploaded file
3849: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3850: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3851: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3852: # $resizewidth - width (pixels) to which to resize uploaded image
3853: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3854: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3855: # from File::MMagic.
1.858 raeburn 3856: #
1.686 albertel 3857: # output: url of file in userspace, or error: <message>
3858: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3859:
1.531 albertel 3860: sub userfileupload {
1.1090 raeburn 3861: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3862: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3863: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3864: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3865: $fname=&clean_filename($fname);
1.1090 raeburn 3866: # See if there is anything left
1.257 www 3867: unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110 raeburn 3868: # If filename now begins with a . prepend unix timestamp _ milliseconds
3869: if ($fname =~ /^\./) {
3870: my ($s,$usec) = &gettimeofday();
3871: while (length($usec) < 6) {
3872: $usec = '0'.$usec;
3873: }
3874: $fname = $s.'_'.substr($usec,0,3).$fname;
3875: }
1.1090 raeburn 3876: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3877: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3878: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3879: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3880: my $now = time;
1.1090 raeburn 3881: my $filepath;
1.1095 raeburn 3882: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3883: $filepath = 'tmp/helprequests/'.$now;
3884: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3885: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3886: '_'.$env{'user.domain'}.'/pending';
3887: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3888: my ($docuname,$docudom);
1.1172.2.96 raeburn 3889: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3890: $docudom = $destudom;
3891: } else {
3892: $docudom = $env{'user.domain'};
3893: }
1.1172.2.96 raeburn 3894: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3895: $docuname = $destuname;
3896: } else {
3897: $docuname = $env{'user.name'};
3898: }
3899: if (exists($env{'form.group'})) {
3900: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3901: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3902: }
3903: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3904: if ($context eq 'canceloverwrite') {
3905: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3906: if (-e $tempfile) {
3907: my @info = stat($tempfile);
3908: if ($info[9] eq $env{'form.timestamp'}) {
3909: unlink($tempfile);
3910: }
3911: }
3912: return;
1.523 raeburn 3913: }
3914: }
1.1090 raeburn 3915: # Create the directory if not present
1.741 raeburn 3916: my @parts=split(/\//,$filepath);
3917: my $fullpath = $perlvar{'lonDaemons'};
3918: for (my $i=0;$i<@parts;$i++) {
3919: $fullpath .= '/'.$parts[$i];
3920: if ((-e $fullpath)!=1) {
3921: mkdir($fullpath,0777);
3922: }
3923: }
1.1172.2.96 raeburn 3924: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3925: print $fh $env{'form.'.$formname};
3926: close($fh);
1.1090 raeburn 3927: if ($context eq 'existingfile') {
3928: my @info = stat($fullpath.'/'.$fname);
3929: return ($fullpath.'/'.$fname,$info[9]);
3930: } else {
3931: return $fullpath.'/'.$fname;
3932: }
1.523 raeburn 3933: }
1.995 raeburn 3934: if ($subdir eq 'scantron') {
3935: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3936: } else {
1.995 raeburn 3937: $fname="$subdir/$fname";
3938: }
1.1090 raeburn 3939: if ($context eq 'coursedoc') {
1.638 albertel 3940: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3941: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3942: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3943: return &finishuserfileupload($docuname,$docudom,
3944: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3945: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3946: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3947: } else {
1.1172.2.21 raeburn 3948: if ($env{'form.folder'}) {
3949: $fname=$env{'form.folder'}.'/'.$fname;
3950: }
1.638 albertel 3951: return &process_coursefile('uploaddoc',$docuname,$docudom,
3952: $fname,$formname,$parser,
1.1095 raeburn 3953: $allfiles,$codebase,$mimetype);
1.481 raeburn 3954: }
1.719 banghart 3955: } elsif (defined($destuname)) {
3956: my $docuname=$destuname;
3957: my $docudom=$destudom;
1.860 raeburn 3958: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3959: $parser,$allfiles,$codebase,
1.1051 raeburn 3960: $thumbwidth,$thumbheight,
1.1095 raeburn 3961: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3962: } else {
1.638 albertel 3963: my $docuname=$env{'user.name'};
3964: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3965: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3966: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3967: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3968: }
1.860 raeburn 3969: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3970: $parser,$allfiles,$codebase,
1.1051 raeburn 3971: $thumbwidth,$thumbheight,
1.1095 raeburn 3972: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3973: }
1.271 www 3974: }
3975:
3976: sub finishuserfileupload {
1.860 raeburn 3977: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3978: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3979: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3980: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3981:
1.860 raeburn 3982: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3983: $file=$fname;
3984: if ($fname=~m|/|) {
3985: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3986: $path.=$fnamepath.'/';
3987: }
1.259 www 3988: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3989: my $count;
3990: for ($count=4;$count<=$#parts;$count++) {
3991: $filepath.="/$parts[$count]";
3992: if ((-e $filepath)!=1) {
3993: mkdir($filepath,0777);
3994: }
3995: }
1.984 neumanie 3996:
1.258 www 3997: # Save the file
3998: {
1.1172.2.96 raeburn 3999: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4000: &logthis('Failed to create '.$filepath.'/'.$file);
4001: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4002: return '/adm/notfound.html';
4003: }
1.1090 raeburn 4004: if ($context eq 'overwrite') {
1.1117 foxr 4005: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4006: my $target = $filepath.'/'.$file;
4007: if (-e $source) {
4008: my @info = stat($source);
4009: if ($info[9] eq $env{'form.timestamp'}) {
4010: unless (&File::Copy::move($source,$target)) {
4011: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4012: return "Moving from $source failed";
4013: }
4014: } else {
4015: return "Temporary file: $source had unexpected date/time for last modification";
4016: }
4017: } else {
4018: return "Temporary file: $source missing";
4019: }
4020: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4021: &logthis('Failed to write to '.$filepath.'/'.$file);
4022: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4023: return '/adm/notfound.html';
4024: }
1.570 albertel 4025: close(FH);
1.1051 raeburn 4026: if ($resizewidth && $resizeheight) {
4027: my $mm = new File::MMagic;
4028: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4029: if ($mime_type =~ m{^image/}) {
4030: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4031: }
1.977 amueller 4032: }
1.258 www 4033: }
1.1152 raeburn 4034: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4035: if (ref($mimetype)) {
4036: if ($$mimetype eq '') {
4037: my $mm = new File::MMagic;
4038: my $type = $mm->checktype_filename($filepath.'/'.$file);
4039: $$mimetype = $type;
4040: }
4041: }
4042: }
1.1172.2.109 raeburn 4043: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4044: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4045: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4046: $allfiles,$codebase);
4047: unless ($parse_result eq 'ok') {
4048: &logthis('Failed to parse '.$filepath.$file.
4049: ' for embedded media: '.$parse_result);
4050: }
1.637 raeburn 4051: }
1.1172.2.109 raeburn 4052: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4053: my $format = $env{'form.scantron_format'};
4054: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4055: }
1.860 raeburn 4056: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4057: my $input = $filepath.'/'.$file;
4058: my $output = $filepath.'/'.'tn-'.$file;
4059: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96 raeburn 4060: my @args = ('convert','-sample',$thumbsize,$input,$output);
4061: system({$args[0]} @args);
1.860 raeburn 4062: if (-e $filepath.'/'.'tn-'.$file) {
4063: $fetchthumb = 1;
4064: }
4065: }
1.858 raeburn 4066:
1.259 www 4067: # Notify homeserver to grep it
4068: #
1.984 neumanie 4069: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4070: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4071: if ($fetchresult eq 'ok') {
1.860 raeburn 4072: if ($fetchthumb) {
4073: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4074: if ($thumbresult ne 'ok') {
4075: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4076: $docuhome.': '.$thumbresult);
4077: }
4078: }
1.259 www 4079: #
1.258 www 4080: # Return the URL to it
1.494 albertel 4081: return '/uploaded/'.$path.$file;
1.263 www 4082: } else {
1.494 albertel 4083: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4084: ': '.$fetchresult);
1.263 www 4085: return '/adm/notfound.html';
1.858 raeburn 4086: }
1.493 albertel 4087: }
4088:
1.637 raeburn 4089: sub extract_embedded_items {
1.961 raeburn 4090: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4091: my @state = ();
1.1164 raeburn 4092: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4093: my %javafiles = (
4094: codebase => '',
4095: code => '',
4096: archive => ''
4097: );
4098: my %mediafiles = (
4099: src => '',
4100: movie => '',
4101: );
1.648 raeburn 4102: my $p;
4103: if ($content) {
4104: $p = HTML::LCParser->new($content);
4105: } else {
1.961 raeburn 4106: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4107: }
1.641 albertel 4108: while (my $t=$p->get_token()) {
1.640 albertel 4109: if ($t->[0] eq 'S') {
4110: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4111: push(@state, $tagname);
1.648 raeburn 4112: if (lc($tagname) eq 'allow') {
4113: &add_filetype($allfiles,$attr->{'src'},'src');
4114: }
1.640 albertel 4115: if (lc($tagname) eq 'img') {
4116: &add_filetype($allfiles,$attr->{'src'},'src');
4117: }
1.886 albertel 4118: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 4119: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4120: &add_filetype($allfiles,$attr->{'href'},'href');
4121: }
1.886 albertel 4122: }
1.645 raeburn 4123: if (lc($tagname) eq 'script') {
1.1164 raeburn 4124: my $src;
1.645 raeburn 4125: if ($attr->{'archive'} =~ /\.jar$/i) {
4126: &add_filetype($allfiles,$attr->{'archive'},'archive');
4127: } else {
1.1164 raeburn 4128: if ($attr->{'src'} ne '') {
4129: $src = $attr->{'src'};
4130: &add_filetype($allfiles,$src,'src');
4131: }
4132: }
4133: my $text = $p->get_trimmed_text();
4134: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4135: my @swfargs = split(/,/,$1);
4136: foreach my $item (@swfargs) {
4137: $item =~ s/["']//g;
4138: $item =~ s/^\s+//;
4139: $item =~ s/\s+$//;
4140: }
4141: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4142: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4143: push(@{$related{$swfargs[0]}},$swfargs[2]);
4144: } else {
4145: $related{$swfargs[0]} = [$swfargs[2]];
4146: }
4147: }
1.645 raeburn 4148: }
4149: }
4150: if (lc($tagname) eq 'link') {
4151: if (lc($attr->{'rel'}) eq 'stylesheet') {
4152: &add_filetype($allfiles,$attr->{'href'},'href');
4153: }
4154: }
1.640 albertel 4155: if (lc($tagname) eq 'object' ||
4156: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4157: foreach my $item (keys(%javafiles)) {
4158: $javafiles{$item} = '';
4159: }
1.1164 raeburn 4160: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4161: $lastids{lc($tagname)} = $attr->{'id'};
4162: }
1.640 albertel 4163: }
4164: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4165: my $name = lc($attr->{'name'});
4166: foreach my $item (keys(%javafiles)) {
4167: if ($name eq $item) {
4168: $javafiles{$item} = $attr->{'value'};
4169: last;
4170: }
4171: }
1.1164 raeburn 4172: my $pathfrom;
1.640 albertel 4173: foreach my $item (keys(%mediafiles)) {
4174: if ($name eq $item) {
1.1164 raeburn 4175: $pathfrom = $attr->{'value'};
4176: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4177: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4178: last;
4179: }
4180: }
1.1164 raeburn 4181: if ($name eq 'flashvars') {
4182: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4183: }
4184: if ($pathfrom ne '') {
4185: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4186: $pathfrom);
4187: }
1.640 albertel 4188: }
4189: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4190: foreach my $item (keys(%javafiles)) {
4191: if ($attr->{$item}) {
4192: $javafiles{$item} = $attr->{$item};
4193: last;
4194: }
4195: }
4196: foreach my $item (keys(%mediafiles)) {
4197: if ($attr->{$item}) {
4198: &add_filetype($allfiles,$attr->{$item},$item);
4199: last;
4200: }
4201: }
1.1164 raeburn 4202: if (lc($tagname) eq 'embed') {
4203: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4204: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4205: $attr->{'src'});
4206: }
4207: }
1.640 albertel 4208: }
1.1172.2.35 raeburn 4209: if (lc($tagname) eq 'iframe') {
4210: my $src = $attr->{'src'} ;
4211: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4212: &add_filetype($allfiles,$src,'src');
4213: } elsif ($src =~ m{^/}) {
4214: if ($env{'request.course.id'}) {
4215: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4216: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4217: my $url = &hreflocation('',$fullpath);
4218: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4219: my $relpath = $1;
4220: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4221: &add_filetype($allfiles,$1,'src');
4222: }
4223: }
4224: }
4225: }
4226: }
1.1164 raeburn 4227: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 4228: pop(@state);
1.1164 raeburn 4229: }
1.640 albertel 4230: } elsif ($t->[0] eq 'E') {
4231: my ($tagname) = ($t->[1]);
4232: if ($javafiles{'codebase'} ne '') {
4233: $javafiles{'codebase'} .= '/';
4234: }
4235: if (lc($tagname) eq 'applet' ||
4236: lc($tagname) eq 'object' ||
4237: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4238: ) {
4239: foreach my $item (keys(%javafiles)) {
4240: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4241: my $file=$javafiles{'codebase'}.$javafiles{$item};
4242: &add_filetype($allfiles,$file,$item);
4243: }
4244: }
4245: }
4246: pop @state;
4247: }
4248: }
1.1164 raeburn 4249: foreach my $id (sort(keys(%flashvars))) {
4250: if ($shockwave{$id} ne '') {
4251: my @pairs = split(/\&/,$flashvars{$id});
4252: foreach my $pair (@pairs) {
4253: my ($key,$value) = split(/\=/,$pair);
4254: if ($key eq 'thumb') {
4255: &add_filetype($allfiles,$value,$key);
4256: } elsif ($key eq 'content') {
4257: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4258: my ($ext) = ($value =~ /\.([^.]+)$/);
4259: if ($ext ne '') {
4260: &add_filetype($allfiles,$path.$value,$ext);
4261: }
4262: }
4263: }
4264: }
4265: }
1.637 raeburn 4266: return 'ok';
4267: }
4268:
1.639 albertel 4269: sub add_filetype {
4270: my ($allfiles,$file,$type)=@_;
4271: if (exists($allfiles->{$file})) {
4272: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4273: push(@{$allfiles->{$file}}, &escape($type));
4274: }
4275: } else {
4276: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4277: }
4278: }
4279:
1.1164 raeburn 4280: sub embedded_dependency {
4281: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4282: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4283: if (($identifier ne '') &&
4284: (ref($related->{$identifier}) eq 'ARRAY') &&
4285: ($pathfrom ne '')) {
4286: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4287: foreach my $dep (@{$related->{$identifier}}) {
4288: &add_filetype($allfiles,$path.$dep,'object');
4289: }
4290: }
4291: }
4292: return;
4293: }
4294:
1.1172.2.109 raeburn 4295: sub bubblesheet_converter {
4296: my ($cdom,$fullpath,$config,$format) = @_;
4297: if ((&domain($cdom) ne '') &&
4298: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4299: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4300: my (%csvcols,%csvoptions);
4301: if (ref($config->{'fields'}) eq 'HASH') {
4302: %csvcols = %{$config->{'fields'}};
4303: }
4304: if (ref($config->{'options'}) eq 'HASH') {
4305: %csvoptions = %{$config->{'options'}};
4306: }
4307: my %csvbynum = reverse(%csvcols);
4308: my %scantronconf = &get_scantron_config($format,$cdom);
4309: if (keys(%scantronconf)) {
4310: my %bynum = (
4311: $scantronconf{CODEstart} => 'CODEstart',
4312: $scantronconf{IDstart} => 'IDstart',
4313: $scantronconf{PaperID} => 'PaperID',
4314: $scantronconf{FirstName} => 'FirstName',
4315: $scantronconf{LastName} => 'LastName',
4316: $scantronconf{Qstart} => 'Qstart',
4317: );
4318: my @ordered;
4319: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4320: push(@ordered,$bynum{$item});
4321: }
4322: my %mapstart = (
4323: CODEstart => 'CODE',
4324: IDstart => 'ID',
4325: PaperID => 'PaperID',
4326: FirstName => 'FirstName',
4327: LastName => 'LastName',
4328: Qstart => 'FirstQuestion',
4329: );
4330: my %maplength = (
4331: CODEstart => 'CODElength',
4332: IDstart => 'IDlength',
4333: PaperID => 'PaperIDlength',
4334: FirstName => 'FirstNamelength',
4335: LastName => 'LastNamelength',
4336: );
4337: if (open(my $fh,'<',$fullpath)) {
4338: my $output;
4339: my %lettdig = &letter_to_digits();
4340: my %diglett = reverse(%lettdig);
4341: my $numletts = scalar(keys(%lettdig));
4342: my $num = 0;
4343: while (my $line=<$fh>) {
4344: $num ++;
4345: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4346: $line =~ s{[\r\n]+$}{};
4347: my %found;
1.1172.2.143 raeburn 4348: my @values = split(/,/,$line,-1);
1.1172.2.109 raeburn 4349: my ($qstart,$record);
4350: for (my $i=0; $i<@values; $i++) {
4351: if ((($qstart ne '') && ($i > $qstart)) ||
4352: ($csvbynum{$i} eq 'FirstQuestion')) {
4353: if ($values[$i] eq '') {
4354: $values[$i] = $scantronconf{'Qoff'};
4355: } elsif ($scantronconf{'Qon'} eq 'number') {
4356: if ($values[$i] =~ /^[A-Ja-j]$/) {
4357: $values[$i] = $lettdig{uc($values[$i])};
4358: }
4359: } elsif ($scantronconf{'Qon'} eq 'letter') {
4360: if ($values[$i] =~ /^[0-9]$/) {
4361: $values[$i] = $diglett{$values[$i]};
4362: }
4363: } else {
4364: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4365: my $digit;
4366: if ($values[$i] =~ /^[A-Ja-j]$/) {
4367: $digit = $lettdig{uc($values[$i])}-1;
4368: if ($values[$i] eq 'J') {
4369: $digit += $numletts;
4370: }
4371: } elsif ($values[$i] =~ /^[0-9]$/) {
4372: $digit = $values[$i]-1;
4373: if ($values[$i] eq '0') {
4374: $digit += $numletts;
4375: }
4376: }
4377: my $qval='';
4378: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4379: if ($j == $digit) {
4380: $qval .= $scantronconf{'Qon'};
4381: } else {
4382: $qval .= $scantronconf{'Qoff'};
4383: }
4384: }
4385: $values[$i] = $qval;
4386: }
4387: }
4388: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4389: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4390: }
4391: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4392: if ($numblank > 0) {
4393: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4394: }
4395: if ($csvbynum{$i} eq 'FirstQuestion') {
4396: $qstart = $i;
4397: $found{$csvbynum{$i}} = $values[$i];
4398: } else {
4399: $found{'FirstQuestion'} .= $values[$i];
4400: }
4401: } elsif (exists($csvbynum{$i})) {
4402: if ($csvoptions{'rem'}) {
4403: $values[$i] =~ s/^\s+//;
4404: }
4405: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4406: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4407: $values[$i] = '0'.$values[$i];
4408: }
4409: }
4410: $found{$csvbynum{$i}} = $values[$i];
4411: }
4412: }
4413: foreach my $item (@ordered) {
4414: my $currlength = 1+length($record);
4415: my $numspaces = $scantronconf{$item} - $currlength;
4416: if ($numspaces > 0) {
4417: $record .= (' ' x $numspaces);
4418: }
4419: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4420: unless ($item eq 'Qstart') {
4421: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4422: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4423: }
4424: }
4425: $record .= $found{$mapstart{$item}};
4426: }
4427: }
4428: $output .= "$record\n";
4429: }
4430: close($fh);
4431: if ($output) {
4432: if (open(my $fh,'>',$fullpath)) {
4433: print $fh $output;
4434: close($fh);
4435: }
4436: }
4437: }
4438: }
4439: return;
4440: }
4441: }
4442:
4443: sub letter_to_digits {
4444: my %lettdig = (
4445: A => 1,
4446: B => 2,
4447: C => 3,
4448: D => 4,
4449: E => 5,
4450: F => 6,
4451: G => 7,
4452: H => 8,
4453: I => 9,
4454: J => 0,
4455: );
4456: return %lettdig;
4457: }
4458:
4459: sub get_scantron_config {
4460: my ($which,$cdom) = @_;
4461: my @lines = &get_scantronformat_file($cdom);
4462: my %config;
4463: #FIXME probably should move to XML it has already gotten a bit much now
4464: foreach my $line (@lines) {
4465: my ($name,$descrip)=split(/:/,$line);
4466: if ($name ne $which ) { next; }
4467: chomp($line);
4468: my @config=split(/:/,$line);
4469: $config{'name'}=$config[0];
4470: $config{'description'}=$config[1];
4471: $config{'CODElocation'}=$config[2];
4472: $config{'CODEstart'}=$config[3];
4473: $config{'CODElength'}=$config[4];
4474: $config{'IDstart'}=$config[5];
4475: $config{'IDlength'}=$config[6];
4476: $config{'Qstart'}=$config[7];
4477: $config{'Qlength'}=$config[8];
4478: $config{'Qoff'}=$config[9];
4479: $config{'Qon'}=$config[10];
4480: $config{'PaperID'}=$config[11];
4481: $config{'PaperIDlength'}=$config[12];
4482: $config{'FirstName'}=$config[13];
4483: $config{'FirstNamelength'}=$config[14];
4484: $config{'LastName'}=$config[15];
4485: $config{'LastNamelength'}=$config[16];
4486: $config{'BubblesPerRow'}=$config[17];
4487: last;
4488: }
4489: return %config;
4490: }
4491:
4492: sub get_scantronformat_file {
4493: my ($cdom) = @_;
4494: if ($cdom eq '') {
4495: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4496: }
4497: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4498: my $gottab = 0;
4499: my @lines;
4500: if (ref($domconfig{'scantron'}) eq 'HASH') {
4501: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4502: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4503: if ($formatfile ne '-1') {
4504: @lines = split("\n",$formatfile,-1);
4505: $gottab = 1;
4506: }
4507: }
4508: }
4509: if (!$gottab) {
4510: my $confname = $cdom.'-domainconfig';
4511: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4512: my $formatfile = &getfile($default);
4513: if ($formatfile ne '-1') {
4514: @lines = split("\n",$formatfile,-1);
4515: $gottab = 1;
4516: }
4517: }
4518: if (!$gottab) {
4519: my @domains = ¤t_machine_domains();
4520: if (grep(/^\Q$cdom\E$/,@domains)) {
4521: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4522: @lines = <$fh>;
4523: close($fh);
4524: }
4525: } else {
4526: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4527: @lines = <$fh>;
4528: close($fh);
4529: }
4530: }
4531: }
4532: return @lines;
4533: }
4534:
1.493 albertel 4535: sub removeuploadedurl {
1.984 neumanie 4536: my ($url)=@_;
4537: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4538: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4539: }
4540:
4541: sub removeuserfile {
4542: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4543: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4544: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4545: if ($result eq 'ok') {
1.798 raeburn 4546: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4547: my $metafile = $fname.'.meta';
4548: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4549: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4550: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4551: my $sqlresult =
1.823 albertel 4552: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4553: 'portfolio_metadata',$group,
4554: 'delete');
1.798 raeburn 4555: }
4556: }
4557: return $result;
1.257 www 4558: }
1.15 www 4559:
1.530 albertel 4560: sub mkdiruserfile {
4561: my ($docuname,$docudom,$dir)=@_;
4562: my $home=&homeserver($docuname,$docudom);
4563: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4564: }
4565:
1.531 albertel 4566: sub renameuserfile {
4567: my ($docuname,$docudom,$old,$new)=@_;
4568: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4569: my $result = &reply("renameuserfile:$docudom:$docuname:".
4570: &escape("$old").':'.&escape("$new"),$home);
4571: if ($result eq 'ok') {
4572: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4573: my $oldmeta = $old.'.meta';
4574: my $newmeta = $new.'.meta';
4575: my $metaresult =
4576: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4577: my $url = "/uploaded/$docudom/$docuname/$old";
4578: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4579: my $sqlresult =
1.823 albertel 4580: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4581: 'portfolio_metadata',$group,
4582: 'delete');
1.798 raeburn 4583: }
4584: }
4585: return $result;
1.531 albertel 4586: }
4587:
1.14 www 4588: # ------------------------------------------------------------------------- Log
4589:
4590: sub log {
4591: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4592: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4593: }
4594:
4595: # ------------------------------------------------------------------ Course Log
1.352 www 4596: #
4597: # This routine flushes several buffers of non-mission-critical nature
4598: #
1.157 www 4599:
4600: sub flushcourselogs {
1.352 www 4601: &logthis('Flushing log buffers');
4602: #
4603: # course logs
4604: # This is a log of all transactions in a course, which can be used
4605: # for data mining purposes
4606: #
4607: # It also collects the courseid database, which lists last transaction
4608: # times and course titles for all courseids
4609: #
4610: my %courseidbuffer=();
1.921 raeburn 4611: foreach my $crsid (keys(%courselogs)) {
1.352 www 4612: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4613: &escape($courselogs{$crsid}),
4614: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4615: delete $courselogs{$crsid};
4616: } else {
4617: &logthis('Failed to flush log buffer for '.$crsid);
4618: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4619: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4620: " exceeded maximum size, deleting.</font>");
4621: delete $courselogs{$crsid};
4622: }
1.352 www 4623: }
1.920 raeburn 4624: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4625: 'description' => $coursedescrbuf{$crsid},
4626: 'inst_code' => $courseinstcodebuf{$crsid},
4627: 'type' => $coursetypebuf{$crsid},
4628: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4629: };
1.191 harris41 4630: }
1.352 www 4631: #
4632: # Write course id database (reverse lookup) to homeserver of courses
4633: # Is used in pickcourse
4634: #
1.840 albertel 4635: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4636: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4637: $courseidbuffer{$crs_home},
4638: $crs_home,'timeonly');
1.352 www 4639: }
4640: #
4641: # File accesses
4642: # Writes to the dynamic metadata of resources to get hit counts, etc.
4643: #
1.449 matthew 4644: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4645: if ($entry =~ /___count$/) {
4646: my ($dom,$name);
1.807 albertel 4647: ($dom,$name,undef)=
1.811 albertel 4648: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4649: if (! defined($dom) || $dom eq '' ||
4650: ! defined($name) || $name eq '') {
1.620 albertel 4651: my $cid = $env{'request.course.id'};
1.1172.2.142 raeburn 4652: #
4653: # FIXME 11/29/2021
4654: # Typo in rev. 1.458 (2003/12/09)??
4655: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
4656: #
4657: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
4658: # $dom and $name will always be null, so the &inc() call will default to storing this data
4659: # in a nohist_accesscount.db file for the user rather than the course.
4660: #
4661: # That said there is a lot of noise in the data being stored.
4662: # So counts for prtspool/ and adm/ etc. are recorded.
4663: #
4664: # A review of which items ending '___count' are written to %accesshash should likely be
4665: # made before deciding whether to set these to 'course.' instead of 'request.'
4666: #
4667: # Under the current scheme each user receives a nohist_accesscount.db file listing
4668: # accesses for things which are not published resources, regardless of course, and
4669: # there is not a nohist_accesscount.db file in a course, which might log accesses from
4670: # anyone in the course for things which are not published resources.
4671: #
4672: # For an author, nohist_accesscount.db ends up having records for other items
4673: # mixed up with the legitimate access counts for the author's published resources.
4674: #
1.620 albertel 4675: $dom = $env{'request.'.$cid.'.domain'};
4676: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4677: }
1.450 matthew 4678: my $value = $accesshash{$entry};
4679: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4680: my %temphash=($url => $value);
1.449 matthew 4681: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4682: if ($result eq 'ok') {
4683: delete $accesshash{$entry};
4684: }
4685: } else {
1.811 albertel 4686: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4687: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4688: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4689: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4690: delete $accesshash{$entry};
4691: }
1.185 www 4692: }
1.191 harris41 4693: }
1.352 www 4694: #
4695: # Roles
4696: # Reverse lookup of user roles for course faculty/staff and co-authorship
4697: #
1.800 albertel 4698: foreach my $entry (keys(%userrolehash)) {
1.351 www 4699: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4700: split(/\:/,$entry);
4701: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4702: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4703: $rudom,$runame) eq 'ok') {
4704: delete $userrolehash{$entry};
4705: }
4706: }
1.662 raeburn 4707: #
1.1172.2.90 raeburn 4708: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4709: #
4710: my %domrolebuffer = ();
1.1000 raeburn 4711: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4712: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4713: if ($domrolebuffer{$rudom}) {
4714: $domrolebuffer{$rudom}.='&'.&escape($entry).
4715: '='.&escape($domainrolehash{$entry});
4716: } else {
4717: $domrolebuffer{$rudom}.=&escape($entry).
4718: '='.&escape($domainrolehash{$entry});
4719: }
4720: delete $domainrolehash{$entry};
4721: }
4722: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4723: my %servers;
4724: if (defined(&domain($dom,'primary'))) {
4725: my $primary=&domain($dom,'primary');
4726: my $hostname=&hostname($primary);
4727: $servers{$primary} = $hostname;
4728: } else {
4729: %servers = &get_servers($dom,'library');
4730: }
1.841 albertel 4731: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4732: if (&reply('domroleput:'.$dom.':'.
4733: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4734: last;
4735: } else {
1.841 albertel 4736: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4737: }
1.662 raeburn 4738: }
4739: }
1.186 www 4740: $dumpcount++;
1.157 www 4741: }
4742:
4743: sub courselog {
4744: my $what=shift;
1.158 www 4745: $what=time.':'.$what;
1.620 albertel 4746: unless ($env{'request.course.id'}) { return ''; }
4747: $coursedombuf{$env{'request.course.id'}}=
4748: $env{'course.'.$env{'request.course.id'}.'.domain'};
4749: $coursenumbuf{$env{'request.course.id'}}=
4750: $env{'course.'.$env{'request.course.id'}.'.num'};
4751: $coursehombuf{$env{'request.course.id'}}=
4752: $env{'course.'.$env{'request.course.id'}.'.home'};
4753: $coursedescrbuf{$env{'request.course.id'}}=
4754: $env{'course.'.$env{'request.course.id'}.'.description'};
4755: $courseinstcodebuf{$env{'request.course.id'}}=
4756: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4757: $courseownerbuf{$env{'request.course.id'}}=
4758: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4759: $coursetypebuf{$env{'request.course.id'}}=
4760: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4761: if (defined $courselogs{$env{'request.course.id'}}) {
4762: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4763: } else {
1.620 albertel 4764: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4765: }
1.620 albertel 4766: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4767: &flushcourselogs();
4768: }
1.158 www 4769: }
4770:
4771: sub courseacclog {
4772: my $fnsymb=shift;
1.620 albertel 4773: unless ($env{'request.course.id'}) { return ''; }
4774: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4775: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4776: $what.=':POST';
1.583 matthew 4777: # FIXME: Probably ought to escape things....
1.800 albertel 4778: foreach my $key (keys(%env)) {
4779: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4780: my $formitem = $1;
4781: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4782: $what.=':'.$formitem.'='.$env{$key};
4783: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131 raeburn 4784: if ($formitem eq 'proctorpassword') {
1.1172.2.132 raeburn 4785: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131 raeburn 4786: } else {
4787: $what.=':'.$formitem.'='.$env{$key};
4788: }
1.975 raeburn 4789: }
1.158 www 4790: }
1.191 harris41 4791: }
1.583 matthew 4792: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4793: # FIXME: We should not be depending on a form parameter that someone
4794: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4795: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4796: $what.= ':POST';
4797: # FIXME: Probably ought to escape things....
4798: foreach my $element ('courseexp','crsfulltext','crsrelated',
4799: 'crsdiscuss') {
1.620 albertel 4800: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4801: }
4802: }
1.158 www 4803: }
4804: &courselog($what);
1.149 www 4805: }
4806:
1.185 www 4807: sub countacc {
4808: my $url=&declutter(shift);
1.458 matthew 4809: return if (! defined($url) || $url eq '');
1.620 albertel 4810: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4811: #
4812: # Mark that this url was used in this course
4813: #
1.620 albertel 4814: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4815: #
4816: # Increase the access count for this resource in this child process
4817: #
1.281 www 4818: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4819: $accesshash{$key}++;
1.185 www 4820: }
1.349 www 4821:
1.361 www 4822: sub linklog {
4823: my ($from,$to)=@_;
4824: $from=&declutter($from);
4825: $to=&declutter($to);
4826: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4827: $accesshash{$to.'___'.$from.'___goto'}=1;
4828: }
1.1160 www 4829:
4830: sub statslog {
4831: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4832: if ($users<2) { return; }
4833: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4834: 'course' => $env{'request.course.id'},
4835: 'sections' => '"all"',
4836: 'num_students' => $users,
4837: 'part' => $part,
4838: 'symb' => $symb,
4839: 'mean_tries' => $av_attempts,
4840: 'deg_of_diff' => $degdiff});
4841: foreach my $key (keys(%dynstore)) {
4842: $accesshash{$key}=$dynstore{$key};
4843: }
4844: }
1.361 www 4845:
1.349 www 4846: sub userrolelog {
4847: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4848: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4849: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4850: $userrolehash
4851: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4852: =$tend.':'.$tstart;
1.662 raeburn 4853: }
1.1169 droeschl 4854: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4855: $userrolehash
4856: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4857: =$tend.':'.$tstart;
4858: }
1.1172.2.90 raeburn 4859: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4860: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4861: $domainrolehash
4862: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4863: = $tend.':'.$tstart;
4864: }
1.351 www 4865: }
4866:
1.957 raeburn 4867: sub courserolelog {
4868: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4869: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4870: my $cdom = $1;
4871: my $cnum = $2;
4872: my $sec = $3;
4873: my $namespace = 'rolelog';
4874: my %storehash = (
4875: role => $trole,
4876: start => $tstart,
4877: end => $tend,
4878: selfenroll => $selfenroll,
4879: context => $context,
4880: );
4881: if ($trole eq 'gr') {
4882: $namespace = 'groupslog';
4883: $storehash{'group'} = $sec;
4884: } else {
4885: $storehash{'section'} = $sec;
4886: }
4887: &write_log('course',$namespace,\%storehash,$delflag,$username,
4888: $domain,$cnum,$cdom);
4889: if (($trole ne 'st') || ($sec ne '')) {
4890: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4891: }
4892: }
4893: return;
4894: }
4895:
1.1172.2.9 raeburn 4896: sub domainrolelog {
4897: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4898: if ($area =~ m{^/($match_domain)/$}) {
4899: my $cdom = $1;
4900: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4901: my $namespace = 'rolelog';
4902: my %storehash = (
4903: role => $trole,
4904: start => $tstart,
4905: end => $tend,
4906: context => $context,
4907: );
4908: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4909: $domain,$domconfiguser,$cdom);
4910: }
4911: return;
4912:
4913: }
4914:
4915: sub coauthorrolelog {
4916: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4917: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4918: my $audom = $1;
4919: my $auname = $2;
4920: my $namespace = 'rolelog';
4921: my %storehash = (
4922: role => $trole,
4923: start => $tstart,
4924: end => $tend,
4925: context => $context,
4926: );
4927: &write_log('author',$namespace,\%storehash,$delflag,$username,
4928: $domain,$auname,$audom);
4929: }
4930: return;
4931: }
4932:
1.351 www 4933: sub get_course_adv_roles {
1.948 raeburn 4934: my ($cid,$codes) = @_;
1.620 albertel 4935: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4936: my %coursehash=&coursedescription($cid);
1.988 raeburn 4937: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4938: my %nothide=();
1.800 albertel 4939: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4940: if ($user !~ /:/) {
4941: $nothide{join(':',split(/[\@]/,$user))}=1;
4942: } else {
4943: $nothide{$user}=1;
4944: }
1.470 www 4945: }
1.1172.2.23 raeburn 4946: my @possdoms = ($coursehash{'domain'});
4947: if ($coursehash{'checkforpriv'}) {
4948: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4949: }
1.351 www 4950: my %returnhash=();
4951: my %dumphash=
4952: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4953: my $now=time;
1.997 raeburn 4954: my %privileged;
1.1000 raeburn 4955: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4956: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4957: if (($tstart) && ($tstart<0)) { next; }
4958: if (($tend) && ($tend<$now)) { next; }
4959: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4960: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4961: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4962: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4963: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4964: if ($role eq 'cr') { next; }
1.948 raeburn 4965: if ($codes) {
4966: if ($section) { $role .= ':'.$section; }
4967: if ($returnhash{$role}) {
4968: $returnhash{$role}.=','.$username.':'.$domain;
4969: } else {
4970: $returnhash{$role}=$username.':'.$domain;
4971: }
1.351 www 4972: } else {
1.988 raeburn 4973: my $key=&plaintext($role,$crstype);
1.973 bisitz 4974: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4975: if ($returnhash{$key}) {
4976: $returnhash{$key}.=','.$username.':'.$domain;
4977: } else {
4978: $returnhash{$key}=$username.':'.$domain;
4979: }
1.351 www 4980: }
1.948 raeburn 4981: }
1.400 www 4982: return %returnhash;
4983: }
4984:
4985: sub get_my_roles {
1.937 raeburn 4986: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4987: unless (defined($uname)) { $uname=$env{'user.name'}; }
4988: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4989: my (%dumphash,%nothide);
1.1086 raeburn 4990: if ($context eq 'userroles') {
1.1166 raeburn 4991: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4992: } else {
1.1172.2.23 raeburn 4993: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4994: if ($hidepriv) {
4995: my %coursehash=&coursedescription($udom.'_'.$uname);
4996: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4997: if ($user !~ /:/) {
4998: $nothide{join(':',split(/[\@]/,$user))} = 1;
4999: } else {
5000: $nothide{$user} = 1;
5001: }
5002: }
5003: }
1.858 raeburn 5004: }
1.400 www 5005: my %returnhash=();
5006: my $now=time;
1.999 raeburn 5007: my %privileged;
1.800 albertel 5008: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5009: my ($role,$tend,$tstart);
5010: if ($context eq 'userroles') {
1.1149 raeburn 5011: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5012: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5013: } else {
5014: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5015: }
1.400 www 5016: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5017: my $status = 'active';
1.939 raeburn 5018: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5019: $status = 'previous';
5020: }
5021: if (($tstart) && ($now<$tstart)) {
5022: $status = 'future';
5023: }
5024: if (ref($types) eq 'ARRAY') {
5025: if (!grep(/^\Q$status\E$/,@{$types})) {
5026: next;
5027: }
5028: } else {
5029: if ($status ne 'active') {
5030: next;
5031: }
5032: }
1.867 raeburn 5033: my ($rolecode,$username,$domain,$section,$area);
5034: if ($context eq 'userroles') {
1.1172.2.9 raeburn 5035: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5036: (undef,$domain,$username,$section) = split(/\//,$area);
5037: } else {
5038: ($role,$username,$domain,$section) = split(/\:/,$entry);
5039: }
1.832 raeburn 5040: if (ref($roledoms) eq 'ARRAY') {
5041: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5042: next;
5043: }
5044: }
5045: if (ref($roles) eq 'ARRAY') {
5046: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5047: if ($role =~ /^cr\//) {
5048: if (!grep(/^cr$/,@{$roles})) {
5049: next;
5050: }
1.1104 raeburn 5051: } elsif ($role =~ /^gr\//) {
5052: if (!grep(/^gr$/,@{$roles})) {
5053: next;
5054: }
1.922 raeburn 5055: } else {
5056: next;
5057: }
1.832 raeburn 5058: }
1.867 raeburn 5059: }
1.937 raeburn 5060: if ($hidepriv) {
1.1172.2.23 raeburn 5061: my @privroles = ('dc','su');
1.999 raeburn 5062: if ($context eq 'userroles') {
1.1172.2.23 raeburn 5063: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5064: } else {
1.1172.2.23 raeburn 5065: my $possdoms = [$domain];
5066: if (ref($roledoms) eq 'ARRAY') {
5067: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5068: }
1.1172.2.23 raeburn 5069: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5070: if (!$nothide{$username.':'.$domain}) {
5071: next;
5072: }
5073: }
1.937 raeburn 5074: }
5075: }
1.933 raeburn 5076: if ($withsec) {
5077: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5078: $tstart.':'.$tend;
5079: } else {
5080: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5081: }
1.832 raeburn 5082: }
1.373 www 5083: return %returnhash;
1.399 www 5084: }
5085:
1.1172.2.89 raeburn 5086: sub get_all_adhocroles {
5087: my ($dom) = @_;
5088: my @roles_by_num = ();
5089: my %domdefaults = &get_domain_defaults($dom);
5090: my (%description,%access_in_dom,%access_info);
5091: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5092: my $count = 0;
5093: my %domcurrent = %{$domdefaults{'adhocroles'}};
5094: my %ordered;
5095: foreach my $role (sort(keys(%domcurrent))) {
5096: my ($order,$desc,$access_in_dom);
5097: if (ref($domcurrent{$role}) eq 'HASH') {
5098: $order = $domcurrent{$role}{'order'};
5099: $desc = $domcurrent{$role}{'desc'};
5100: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5101: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5102: }
5103: if ($order eq '') {
5104: $order = $count;
5105: }
5106: $ordered{$order} = $role;
5107: if ($desc ne '') {
5108: $description{$role} = $desc;
5109: } else {
5110: $description{$role}= $role;
5111: }
5112: $count++;
5113: }
5114: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5115: push(@roles_by_num,$ordered{$item});
5116: }
5117: }
5118: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5119: }
5120:
5121: sub get_my_adhocroles {
5122: my ($cid,$checkreg) = @_;
5123: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5124: if ($env{'request.course.id'} eq $cid) {
5125: $cdom = $env{'course.'.$cid.'.domain'};
5126: $cnum = $env{'course.'.$cid.'.num'};
5127: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5128: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5129: $cdom = $1;
5130: $cnum = $2;
5131: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5132: $cdom,$cnum);
5133: }
5134: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5135: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5136: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5137: if ($rosterhash{$user} ne '') {
5138: my $type = (split(/:/,$rosterhash{$user}))[5];
5139: return ([],{}) if ($type eq 'auto');
5140: }
5141: }
5142: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 5143: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 5144: my $then=$env{'user.login.time'};
5145: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 5146: if (!$update) {
5147: $update = $then;
5148: }
5149: my @liveroles;
5150: foreach my $role ('dh','da') {
5151: if ($env{"user.role.$role./$cdom/"}) {
5152: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5153: my $limit = $update;
5154: if ($env{'request.role'} eq "$role./$cdom/") {
5155: $limit = $then;
5156: }
5157: my $activerole = 1;
5158: if ($tstart && $tstart>$limit) { $activerole = 0; }
5159: if ($tend && $tend <$limit) { $activerole = 0; }
5160: if ($activerole) {
5161: push(@liveroles,$role);
5162: }
5163: }
5164: }
5165: if (@liveroles) {
1.1172.2.89 raeburn 5166: if (&homeserver($cnum,$cdom) ne 'no_host') {
5167: my ($accessref,$accessinfo,%access_in_dom);
5168: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5169: if (ref($roles_by_num) eq 'ARRAY') {
5170: if (@{$roles_by_num}) {
5171: my %settings;
5172: if ($env{'request.course.id'} eq $cid) {
5173: foreach my $envkey (keys(%env)) {
5174: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5175: $settings{$1} = $env{$envkey};
5176: }
5177: }
5178: } else {
5179: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5180: }
5181: my %setincrs;
5182: if ($settings{'internal.adhocaccess'}) {
5183: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5184: }
5185: my @statuses;
5186: if ($env{'environment.inststatus'}) {
5187: @statuses = split(/,/,$env{'environment.inststatus'});
5188: }
5189: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5190: if (ref($accessref) eq 'HASH') {
5191: %access_in_dom = %{$accessref};
5192: }
5193: foreach my $role (@{$roles_by_num}) {
5194: my ($curraccess,@okstatus,@personnel);
5195: if ($setincrs{$role}) {
5196: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5197: if ($curraccess eq 'status') {
5198: @okstatus = split(/\&/,$rest);
5199: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5200: @personnel = split(/\&/,$rest);
5201: }
5202: } else {
5203: $curraccess = $access_in_dom{$role};
5204: if (ref($accessinfo) eq 'HASH') {
5205: if ($curraccess eq 'status') {
5206: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5207: @okstatus = @{$accessinfo->{$role}};
5208: }
5209: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5210: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5211: @personnel = @{$accessinfo->{$role}};
5212: }
5213: }
5214: }
5215: }
5216: if ($curraccess eq 'none') {
5217: next;
5218: } elsif ($curraccess eq 'all') {
5219: push(@possroles,$role);
1.1172.2.90 raeburn 5220: } elsif ($curraccess eq 'dh') {
5221: if (grep(/^dh$/,@liveroles)) {
5222: push(@possroles,$role);
5223: } else {
5224: next;
5225: }
5226: } elsif ($curraccess eq 'da') {
5227: if (grep(/^da$/,@liveroles)) {
5228: push(@possroles,$role);
5229: } else {
5230: next;
5231: }
1.1172.2.89 raeburn 5232: } elsif ($curraccess eq 'status') {
5233: if (@okstatus) {
5234: if (!@statuses) {
5235: if (grep(/^default$/,@okstatus)) {
5236: push(@possroles,$role);
5237: }
5238: } else {
5239: foreach my $status (@okstatus) {
5240: if (grep(/^\Q$status\E$/,@statuses)) {
5241: push(@possroles,$role);
5242: last;
5243: }
5244: }
5245: }
5246: }
5247: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5248: if (grep(/^\Q$user\E$/,@personnel)) {
5249: if ($curraccess eq 'exc') {
5250: push(@possroles,$role);
5251: }
5252: } elsif ($curraccess eq 'inc') {
5253: push(@possroles,$role);
5254: }
5255: }
5256: }
5257: }
5258: }
5259: }
5260: }
5261: }
5262: }
5263: unless (ref($description) eq 'HASH') {
5264: if (ref($roles_by_num) eq 'ARRAY') {
5265: my %desc;
5266: map { $desc{$_} = $_; } (@{$roles_by_num});
5267: $description = \%desc;
5268: } else {
5269: $description = {};
5270: }
5271: }
5272: return (\@possroles,$description);
5273: }
5274:
1.399 www 5275: # ----------------------------------------------------- Frontpage Announcements
5276: #
5277: #
5278:
5279: sub postannounce {
5280: my ($server,$text)=@_;
1.844 albertel 5281: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5282: unless ($text=~/\w/) { $text=''; }
5283: return &reply('setannounce:'.&escape($text),$server);
5284: }
5285:
5286: sub getannounce {
1.448 albertel 5287:
1.1172.2.96 raeburn 5288: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5289: my $announcement='';
1.800 albertel 5290: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5291: close($fh);
1.399 www 5292: if ($announcement=~/\w/) {
5293: return
5294: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5295: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5296: } else {
5297: return '';
5298: }
5299: } else {
5300: return '';
5301: }
1.351 www 5302: }
1.353 www 5303:
5304: # ---------------------------------------------------------- Course ID routines
5305: # Deal with domain's nohist_courseid.db files
5306: #
5307:
5308: sub courseidput {
1.921 raeburn 5309: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5310: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5311: my $outcome;
5312: if ($caller eq 'timeonly') {
5313: my $cids = '';
5314: foreach my $item (keys(%$storehash)) {
5315: $cids.=&escape($item).'&';
5316: }
5317: $cids=~s/\&$//;
5318: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5319: $coursehome);
5320: } else {
5321: my $items = '';
5322: foreach my $item (keys(%$storehash)) {
5323: $items.= &escape($item).'='.
5324: &freeze_escape($$storehash{$item}).'&';
5325: }
5326: $items=~s/\&$//;
5327: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5328: $coursehome);
1.918 raeburn 5329: }
5330: if ($outcome eq 'unknown_cmd') {
5331: my $what;
5332: foreach my $cid (keys(%$storehash)) {
5333: $what .= &escape($cid).'=';
1.921 raeburn 5334: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5335: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5336: }
5337: $what =~ s/\:$/&/;
5338: }
5339: $what =~ s/\&$//;
5340: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5341: } else {
5342: return $outcome;
5343: }
1.353 www 5344: }
5345:
5346: sub courseiddump {
1.921 raeburn 5347: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5348: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5349: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 5350: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 5351: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5352: my $as_hash = 1;
5353: my %returnhash;
5354: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5355: my %libserv = &all_library();
5356: foreach my $tryserver (keys(%libserv)) {
5357: if ( ( $hostidflag == 1
5358: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5359: || (!defined($hostidflag)) ) {
5360:
1.918 raeburn 5361: if (($domfilter eq '') ||
5362: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 5363: my $rep;
5364: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5365: $rep = &LONCAPA::Lond::dump_course_id_handler(
5366: join(":", (&host_domain($tryserver), $sincefilter,
5367: &escape($descfilter), &escape($instcodefilter),
5368: &escape($ownerfilter), &escape($coursefilter),
5369: &escape($typefilter), &escape($regexp_ok),
5370: $as_hash, &escape($selfenrollonly),
5371: &escape($catfilter), $showhidden, $caller,
5372: &escape($cloner), &escape($cc_clone), $cloneonly,
5373: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 5374: &escape($creationcontext),$domcloner,$hasuniquecode,
5375: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 5376: } else {
5377: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5378: $sincefilter.':'.&escape($descfilter).':'.
5379: &escape($instcodefilter).':'.&escape($ownerfilter).
5380: ':'.&escape($coursefilter).':'.&escape($typefilter).
5381: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5382: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5383: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5384: &escape($cc_clone).':'.$cloneonly.':'.
5385: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 5386: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5387: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 5388: }
5389:
1.918 raeburn 5390: my @pairs=split(/\&/,$rep);
5391: foreach my $item (@pairs) {
5392: my ($key,$value)=split(/\=/,$item,2);
5393: $key = &unescape($key);
5394: next if ($key =~ /^error: 2 /);
5395: my $result = &thaw_unescape($value);
5396: if (ref($result) eq 'HASH') {
5397: $returnhash{$key}=$result;
5398: } else {
1.921 raeburn 5399: my @responses = split(/:/,$value);
5400: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5401: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5402: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5403: }
1.1008 raeburn 5404: }
1.353 www 5405: }
5406: }
5407: }
5408: }
5409: return %returnhash;
5410: }
5411:
1.1055 raeburn 5412: sub courselastaccess {
5413: my ($cdom,$cnum,$hostidref) = @_;
5414: my %returnhash;
5415: if ($cdom && $cnum) {
5416: my $chome = &homeserver($cnum,$cdom);
5417: if ($chome ne 'no_host') {
5418: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5419: &extract_lastaccess(\%returnhash,$rep);
5420: }
5421: } else {
5422: if (!$cdom) { $cdom=''; }
5423: my %libserv = &all_library();
5424: foreach my $tryserver (keys(%libserv)) {
5425: if (ref($hostidref) eq 'ARRAY') {
5426: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5427: }
5428: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5429: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5430: &extract_lastaccess(\%returnhash,$rep);
5431: }
5432: }
5433: }
5434: return %returnhash;
5435: }
5436:
5437: sub extract_lastaccess {
5438: my ($returnhash,$rep) = @_;
5439: if (ref($returnhash) eq 'HASH') {
5440: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5441: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5442: $rep eq '') {
5443: my @pairs=split(/\&/,$rep);
5444: foreach my $item (@pairs) {
5445: my ($key,$value)=split(/\=/,$item,2);
5446: $key = &unescape($key);
5447: next if ($key =~ /^error: 2 /);
5448: $returnhash->{$key} = &thaw_unescape($value);
5449: }
5450: }
5451: }
5452: return;
5453: }
5454:
1.658 raeburn 5455: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5456:
5457: sub dcmailput {
1.685 raeburn 5458: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5459: my $status = &Apache::lonnet::critical(
1.740 www 5460: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5461: &escape($message),$server);
1.662 raeburn 5462: return $status;
5463: }
5464:
1.658 raeburn 5465: sub dcmaildump {
5466: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5467: my %returnhash=();
1.846 albertel 5468:
5469: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5470: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5471: &escape($enddate).':';
5472: my @esc_senders=map { &escape($_)} @$senders;
5473: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5474: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5475: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5476: if (($key) && ($value)) {
5477: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5478: }
5479: }
5480: }
5481: return %returnhash;
5482: }
1.662 raeburn 5483: # ---------------------------------------------------------- Domain roles
5484:
5485: sub get_domain_roles {
5486: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5487: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5488: $startdate = '.';
5489: }
1.1018 raeburn 5490: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5491: $enddate = '.';
5492: }
1.922 raeburn 5493: my $rolelist;
5494: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5495: $rolelist = join('&',@{$roles});
1.922 raeburn 5496: }
1.662 raeburn 5497: my %personnel = ();
1.841 albertel 5498:
5499: my %servers = &get_servers($dom,'library');
5500: foreach my $tryserver (keys(%servers)) {
5501: %{$personnel{$tryserver}}=();
5502: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5503: &escape($startdate).':'.
5504: &escape($enddate).':'.
5505: &escape($rolelist), $tryserver))) {
5506: my ($key,$value) = split(/\=/,$line,2);
5507: if (($key) && ($value)) {
5508: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5509: }
5510: }
1.662 raeburn 5511: }
5512: return %personnel;
5513: }
1.658 raeburn 5514:
1.1172.2.89 raeburn 5515: sub get_active_domroles {
5516: my ($dom,$roles) = @_;
5517: return () unless (ref($roles) eq 'ARRAY');
5518: my $now = time;
5519: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5520: my %domroles;
5521: foreach my $server (keys(%dompersonnel)) {
5522: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5523: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5524: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5525: }
5526: }
5527: return %domroles;
5528: }
5529:
1.1057 www 5530: # ----------------------------------------------------------- Interval timing
1.149 www 5531:
1.1153 www 5532: {
5533: # Caches needed for speedup of navmaps
5534: # We don't want to cache this for very long at all (5 seconds at most)
5535: #
5536: # The user for whom we cache
5537: my $cachedkey='';
5538: # The cached times for this user
5539: my %cachedtimes=();
5540: # When this was last done
1.1172.2.66 raeburn 5541: my $cachedtime='';
1.1153 www 5542:
5543: sub load_all_first_access {
1.1154 raeburn 5544: my ($uname,$udom)=@_;
1.1156 www 5545: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 5546: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 5547: return;
5548: }
5549: $cachedtime=time;
5550: $cachedkey=$uname.':'.$udom;
5551: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5552: }
5553:
1.504 albertel 5554: sub get_first_access {
1.1162 raeburn 5555: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 5556: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5557: if ($argsymb) { $symb=$argsymb; }
5558: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5559: if ($argmap) { $map = $argmap; }
1.926 albertel 5560: if ($type eq 'course') {
5561: $res='course';
5562: } elsif ($type eq 'map') {
1.588 albertel 5563: $res=&symbread($map);
5564: } else {
5565: $res=$symb;
5566: }
1.1153 www 5567: &load_all_first_access($uname,$udom);
5568: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5569: }
5570:
5571: sub set_first_access {
1.1162 raeburn 5572: my ($type,$interval)=@_;
1.790 albertel 5573: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5574: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5575: if ($type eq 'course') {
5576: $res='course';
5577: } elsif ($type eq 'map') {
1.588 albertel 5578: $res=&symbread($map);
5579: } else {
5580: $res=$symb;
5581: }
1.1153 www 5582: $cachedkey='';
1.1162 raeburn 5583: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 5584: if ($firstaccess) {
5585: &logthis("First access time already set ($firstaccess) when attempting ".
5586: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5587: "in $courseid");
5588: return 'already_set';
5589: } else {
1.1162 raeburn 5590: my $start = time;
5591: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5592: $udom,$uname);
5593: if ($putres eq 'ok') {
5594: &put('timerinterval',{"$courseid\0$res"=>$interval},
5595: $udom,$uname);
5596: &appenv(
5597: {
5598: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5599: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5600: }
5601: );
1.1172.2.97 raeburn 5602: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5603: $cachedtimes{"$courseid\0$res"} = $start;
5604: }
1.1172.2.102 raeburn 5605: } elsif ($putres ne 'refused') {
5606: &logthis("Result: $putres when attempting to set first access time ".
5607: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5608: }
5609: return $putres;
1.505 albertel 5610: }
5611: return 'already_set';
1.504 albertel 5612: }
1.1153 www 5613: }
1.1172.2.32 raeburn 5614:
5615: sub checkout {
5616: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5617: my $now=time;
5618: my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134 raeburn 5619: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5620: my $infostr=&escape(
5621: 'CHECKOUTTOKEN&'.
5622: $tuname.'&'.
5623: $tudom.'&'.
5624: $tcrsid.'&'.
5625: $symb.'&'.
1.1172.2.134 raeburn 5626: $now.'&'.$ip);
1.1172.2.32 raeburn 5627: my $token=&reply('tmpput:'.$infostr,$lonhost);
5628: if ($token=~/^error\:/) {
5629: &logthis("<font color=\"blue\">WARNING: ".
5630: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5631: "</font>");
5632: return '';
5633: }
5634:
5635: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5636: $token=~tr/a-z/A-Z/;
5637:
5638: my %infohash=('resource.0.outtoken' => $token,
5639: 'resource.0.checkouttime' => $now,
1.1172.2.134 raeburn 5640: 'resource.0.outremote' => $ip);
1.1172.2.32 raeburn 5641:
5642: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5643: return '';
5644: } else {
5645: &logthis("<font color=\"blue\">WARNING: ".
5646: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5647: "</font>");
5648: }
5649:
5650: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5651: &escape('Checkout '.$infostr.' - '.
5652: $token)) ne 'ok') {
5653: return '';
5654: } else {
5655: &logthis("<font color=\"blue\">WARNING: ".
5656: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5657: "</font>");
5658: }
5659: return $token;
5660: }
5661:
5662: # ------------------------------------------------------------ Check in an item
5663:
5664: sub checkin {
5665: my $token=shift;
5666: my $now=time;
5667: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5668: $lonhost=~tr/A-Z/a-z/;
5669: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5670: $dtoken=~s/\W/\_/g;
1.1172.2.134 raeburn 5671: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5672: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5673: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5674:
5675: unless (($tuname) && ($tudom)) {
5676: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5677: return '';
5678: }
5679:
5680: unless (&allowed('mgr',$tcrsid)) {
5681: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5682: $env{'user.name'}.' - '.$env{'user.domain'});
5683: return '';
5684: }
5685:
5686: my %infohash=('resource.0.intoken' => $token,
5687: 'resource.0.checkintime' => $now,
1.1172.2.134 raeburn 5688: 'resource.0.inremote' => $ip);
1.1172.2.32 raeburn 5689:
5690: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5691: return '';
5692: }
5693:
5694: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5695: &escape('Checkin - '.$token)) ne 'ok') {
5696: return '';
5697: }
5698:
5699: return ($symb,$tuname,$tudom,$tcrsid);
5700: }
5701:
1.110 www 5702: # --------------------------------------------- Set Expire Date for Spreadsheet
5703:
5704: sub expirespread {
5705: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5706: my $cid=$env{'request.course.id'};
1.110 www 5707: if ($cid) {
5708: my $now=time;
5709: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5710: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5711: $env{'course.'.$cid.'.num'}.
1.110 www 5712: ':nohist_expirationdates:'.
5713: &escape($key).'='.$now,
1.620 albertel 5714: $env{'course.'.$cid.'.home'})
1.110 www 5715: }
5716: return 'ok';
1.14 www 5717: }
5718:
1.109 www 5719: # ----------------------------------------------------- Devalidate Spreadsheets
5720:
5721: sub devalidate {
1.325 www 5722: my ($symb,$uname,$udom)=@_;
1.620 albertel 5723: my $cid=$env{'request.course.id'};
1.109 www 5724: if ($cid) {
1.391 matthew 5725: # delete the stored spreadsheets for
5726: # - the student level sheet of this user in course's homespace
5727: # - the assessment level sheet for this resource
5728: # for this user in user's homespace
1.553 albertel 5729: # - current conditional state info
1.325 www 5730: my $key=$uname.':'.$udom.':';
1.109 www 5731: my $status=
1.299 matthew 5732: &del('nohist_calculatedsheets',
1.391 matthew 5733: [$key.'studentcalc:'],
1.620 albertel 5734: $env{'course.'.$cid.'.domain'},
5735: $env{'course.'.$cid.'.num'})
1.133 albertel 5736: .' '.
5737: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5738: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5739: unless ($status eq 'ok ok') {
5740: &logthis('Could not devalidate spreadsheet '.
1.325 www 5741: $uname.' at '.$udom.' for '.
1.109 www 5742: $symb.': '.$status);
1.133 albertel 5743: }
1.553 albertel 5744: &delenv('user.state.'.$cid);
1.109 www 5745: }
5746: }
5747:
1.265 albertel 5748: sub get_scalar {
5749: my ($string,$end) = @_;
5750: my $value;
5751: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5752: $value = $1;
5753: } elsif ($$string =~ s/^([^&]*?)&//) {
5754: $value = $1;
5755: }
5756: return &unescape($value);
5757: }
5758:
5759: sub array2str {
5760: my (@array) = @_;
5761: my $result=&arrayref2str(\@array);
5762: $result=~s/^__ARRAY_REF__//;
5763: $result=~s/__END_ARRAY_REF__$//;
5764: return $result;
5765: }
5766:
1.204 albertel 5767: sub arrayref2str {
5768: my ($arrayref) = @_;
1.265 albertel 5769: my $result='__ARRAY_REF__';
1.204 albertel 5770: foreach my $elem (@$arrayref) {
1.265 albertel 5771: if(ref($elem) eq 'ARRAY') {
5772: $result.=&arrayref2str($elem).'&';
5773: } elsif(ref($elem) eq 'HASH') {
5774: $result.=&hashref2str($elem).'&';
5775: } elsif(ref($elem)) {
5776: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5777: } else {
5778: $result.=&escape($elem).'&';
5779: }
5780: }
5781: $result=~s/\&$//;
1.265 albertel 5782: $result .= '__END_ARRAY_REF__';
1.204 albertel 5783: return $result;
5784: }
5785:
1.168 albertel 5786: sub hash2str {
1.204 albertel 5787: my (%hash) = @_;
5788: my $result=&hashref2str(\%hash);
1.265 albertel 5789: $result=~s/^__HASH_REF__//;
5790: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5791: return $result;
5792: }
5793:
5794: sub hashref2str {
5795: my ($hashref)=@_;
1.265 albertel 5796: my $result='__HASH_REF__';
1.800 albertel 5797: foreach my $key (sort(keys(%$hashref))) {
5798: if (ref($key) eq 'ARRAY') {
5799: $result.=&arrayref2str($key).'=';
5800: } elsif (ref($key) eq 'HASH') {
5801: $result.=&hashref2str($key).'=';
5802: } elsif (ref($key)) {
1.265 albertel 5803: $result.='=';
1.800 albertel 5804: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5805: } else {
1.1132 raeburn 5806: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5807: }
5808:
1.800 albertel 5809: if(ref($hashref->{$key}) eq 'ARRAY') {
5810: $result.=&arrayref2str($hashref->{$key}).'&';
5811: } elsif(ref($hashref->{$key}) eq 'HASH') {
5812: $result.=&hashref2str($hashref->{$key}).'&';
5813: } elsif(ref($hashref->{$key})) {
1.265 albertel 5814: $result.='&';
1.800 albertel 5815: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5816: } else {
1.800 albertel 5817: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5818: }
5819: }
1.168 albertel 5820: $result=~s/\&$//;
1.265 albertel 5821: $result .= '__END_HASH_REF__';
1.168 albertel 5822: return $result;
5823: }
5824:
5825: sub str2hash {
1.265 albertel 5826: my ($string)=@_;
5827: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5828: return %$hash;
5829: }
5830:
5831: sub str2hashref {
1.168 albertel 5832: my ($string) = @_;
1.265 albertel 5833:
5834: my %hash;
5835:
5836: if($string !~ /^__HASH_REF__/) {
5837: if (! ($string eq '' || !defined($string))) {
5838: $hash{'error'}='Not hash reference';
5839: }
5840: return (\%hash, $string);
5841: }
5842:
5843: $string =~ s/^__HASH_REF__//;
5844:
5845: while($string !~ /^__END_HASH_REF__/) {
5846: #key
5847: my $key='';
5848: if($string =~ /^__HASH_REF__/) {
5849: ($key, $string)=&str2hashref($string);
5850: if(defined($key->{'error'})) {
5851: $hash{'error'}='Bad data';
5852: return (\%hash, $string);
5853: }
5854: } elsif($string =~ /^__ARRAY_REF__/) {
5855: ($key, $string)=&str2arrayref($string);
5856: if($key->[0] eq 'Array reference error') {
5857: $hash{'error'}='Bad data';
5858: return (\%hash, $string);
5859: }
5860: } else {
5861: $string =~ s/^(.*?)=//;
1.267 albertel 5862: $key=&unescape($1);
1.265 albertel 5863: }
5864: $string =~ s/^=//;
5865:
5866: #value
5867: my $value='';
5868: if($string =~ /^__HASH_REF__/) {
5869: ($value, $string)=&str2hashref($string);
5870: if(defined($value->{'error'})) {
5871: $hash{'error'}='Bad data';
5872: return (\%hash, $string);
5873: }
5874: } elsif($string =~ /^__ARRAY_REF__/) {
5875: ($value, $string)=&str2arrayref($string);
5876: if($value->[0] eq 'Array reference error') {
5877: $hash{'error'}='Bad data';
5878: return (\%hash, $string);
5879: }
5880: } else {
5881: $value=&get_scalar(\$string,'__END_HASH_REF__');
5882: }
5883: $string =~ s/^&//;
5884:
5885: $hash{$key}=$value;
1.204 albertel 5886: }
1.265 albertel 5887:
5888: $string =~ s/^__END_HASH_REF__//;
5889:
5890: return (\%hash, $string);
1.204 albertel 5891: }
5892:
5893: sub str2array {
1.265 albertel 5894: my ($string)=@_;
5895: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5896: return @$array;
5897: }
5898:
5899: sub str2arrayref {
1.204 albertel 5900: my ($string) = @_;
1.265 albertel 5901: my @array;
5902:
5903: if($string !~ /^__ARRAY_REF__/) {
5904: if (! ($string eq '' || !defined($string))) {
5905: $array[0]='Array reference error';
5906: }
5907: return (\@array, $string);
5908: }
5909:
5910: $string =~ s/^__ARRAY_REF__//;
5911:
5912: while($string !~ /^__END_ARRAY_REF__/) {
5913: my $value='';
5914: if($string =~ /^__HASH_REF__/) {
5915: ($value, $string)=&str2hashref($string);
5916: if(defined($value->{'error'})) {
5917: $array[0] ='Array reference error';
5918: return (\@array, $string);
5919: }
5920: } elsif($string =~ /^__ARRAY_REF__/) {
5921: ($value, $string)=&str2arrayref($string);
5922: if($value->[0] eq 'Array reference error') {
5923: $array[0] ='Array reference error';
5924: return (\@array, $string);
5925: }
5926: } else {
5927: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5928: }
5929: $string =~ s/^&//;
5930:
5931: push(@array, $value);
1.191 harris41 5932: }
1.265 albertel 5933:
5934: $string =~ s/^__END_ARRAY_REF__//;
5935:
5936: return (\@array, $string);
1.168 albertel 5937: }
5938:
1.167 albertel 5939: # -------------------------------------------------------------------Temp Store
5940:
1.168 albertel 5941: sub tmpreset {
5942: my ($symb,$namespace,$domain,$stuname) = @_;
5943: if (!$symb) {
5944: $symb=&symbread();
1.620 albertel 5945: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5946: }
5947: $symb=escape($symb);
5948:
1.620 albertel 5949: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5950: $namespace=~s/\//\_/g;
5951: $namespace=~s/\W//g;
5952:
1.620 albertel 5953: if (!$domain) { $domain=$env{'user.domain'}; }
5954: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5955: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 5956: $stuname=&get_requestor_ip();
1.591 albertel 5957: }
1.1117 foxr 5958: my $path=LONCAPA::tempdir();
1.168 albertel 5959: my %hash;
5960: if (tie(%hash,'GDBM_File',
5961: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5962: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5963: foreach my $key (keys(%hash)) {
1.180 albertel 5964: if ($key=~ /:$symb/) {
1.168 albertel 5965: delete($hash{$key});
5966: }
5967: }
5968: }
5969: }
5970:
1.167 albertel 5971: sub tmpstore {
1.168 albertel 5972: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5973:
5974: if (!$symb) {
5975: $symb=&symbread();
1.620 albertel 5976: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5977: }
5978: $symb=escape($symb);
5979:
5980: if (!$namespace) {
5981: # I don't think we would ever want to store this for a course.
5982: # it seems this will only be used if we don't have a course.
1.620 albertel 5983: #$namespace=$env{'request.course.id'};
1.168 albertel 5984: #if (!$namespace) {
1.620 albertel 5985: $namespace=$env{'request.state'};
1.168 albertel 5986: #}
5987: }
5988: $namespace=~s/\//\_/g;
5989: $namespace=~s/\W//g;
1.620 albertel 5990: if (!$domain) { $domain=$env{'user.domain'}; }
5991: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5992: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 5993: $stuname=&get_requestor_ip();
1.591 albertel 5994: }
1.168 albertel 5995: my $now=time;
5996: my %hash;
1.1117 foxr 5997: my $path=LONCAPA::tempdir();
1.168 albertel 5998: if (tie(%hash,'GDBM_File',
5999: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6000: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6001: $hash{"version:$symb"}++;
6002: my $version=$hash{"version:$symb"};
6003: my $allkeys='';
6004: foreach my $key (keys(%$storehash)) {
6005: $allkeys.=$key.':';
1.591 albertel 6006: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6007: }
6008: $hash{"$version:$symb:timestamp"}=$now;
6009: $allkeys.='timestamp';
6010: $hash{"$version:keys:$symb"}=$allkeys;
6011: if (untie(%hash)) {
6012: return 'ok';
6013: } else {
6014: return "error:$!";
6015: }
6016: } else {
6017: return "error:$!";
6018: }
6019: }
1.167 albertel 6020:
1.168 albertel 6021: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6022:
1.168 albertel 6023: sub tmprestore {
6024: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6025:
1.168 albertel 6026: if (!$symb) {
6027: $symb=&symbread();
1.620 albertel 6028: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6029: }
6030: $symb=escape($symb);
6031:
1.620 albertel 6032: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6033:
1.620 albertel 6034: if (!$domain) { $domain=$env{'user.domain'}; }
6035: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6036: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6037: $stuname=&get_requestor_ip();
1.591 albertel 6038: }
1.168 albertel 6039: my %returnhash;
6040: $namespace=~s/\//\_/g;
6041: $namespace=~s/\W//g;
6042: my %hash;
1.1117 foxr 6043: my $path=LONCAPA::tempdir();
1.168 albertel 6044: if (tie(%hash,'GDBM_File',
6045: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6046: &GDBM_READER(),0640)) {
1.168 albertel 6047: my $version=$hash{"version:$symb"};
6048: $returnhash{'version'}=$version;
6049: my $scope;
6050: for ($scope=1;$scope<=$version;$scope++) {
6051: my $vkeys=$hash{"$scope:keys:$symb"};
6052: my @keys=split(/:/,$vkeys);
6053: my $key;
6054: $returnhash{"$scope:keys"}=$vkeys;
6055: foreach $key (@keys) {
1.591 albertel 6056: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6057: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6058: }
6059: }
1.168 albertel 6060: if (!(untie(%hash))) {
6061: return "error:$!";
6062: }
6063: } else {
6064: return "error:$!";
6065: }
6066: return %returnhash;
1.167 albertel 6067: }
6068:
1.9 www 6069: # ----------------------------------------------------------------------- Store
6070:
6071: sub store {
1.1172.2.64 raeburn 6072: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6073: my $home='';
6074:
1.168 albertel 6075: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6076:
1.213 www 6077: $symb=&symbclean($symb);
1.122 albertel 6078: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6079:
1.620 albertel 6080: if (!$domain) { $domain=$env{'user.domain'}; }
6081: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6082:
6083: &devalidate($symb,$stuname,$domain);
1.109 www 6084:
6085: $symb=escape($symb);
1.187 www 6086: if (!$namespace) {
1.620 albertel 6087: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6088: return '';
6089: }
6090: }
1.620 albertel 6091: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6092:
1.1172.2.138 raeburn 6093: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6094: $$storehash{'host'}=$perlvar{'lonHostID'};
6095:
1.12 www 6096: my $namevalue='';
1.800 albertel 6097: foreach my $key (keys(%$storehash)) {
6098: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6099: }
1.12 www 6100: $namevalue=~s/\&$//;
1.187 www 6101: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 6102: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6103: }
6104:
1.47 www 6105: # -------------------------------------------------------------- Critical Store
6106:
6107: sub cstore {
1.1172.2.64 raeburn 6108: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6109: my $home='';
6110:
1.168 albertel 6111: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6112:
1.213 www 6113: $symb=&symbclean($symb);
1.122 albertel 6114: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6115:
1.620 albertel 6116: if (!$domain) { $domain=$env{'user.domain'}; }
6117: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6118:
6119: &devalidate($symb,$stuname,$domain);
1.109 www 6120:
6121: $symb=escape($symb);
1.187 www 6122: if (!$namespace) {
1.620 albertel 6123: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6124: return '';
6125: }
6126: }
1.620 albertel 6127: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6128:
1.1172.2.138 raeburn 6129: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6130: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6131:
1.47 www 6132: my $namevalue='';
1.800 albertel 6133: foreach my $key (keys(%$storehash)) {
6134: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6135: }
1.47 www 6136: $namevalue=~s/\&$//;
1.187 www 6137: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6138: return critical
1.1172.2.64 raeburn 6139: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6140: }
6141:
1.9 www 6142: # --------------------------------------------------------------------- Restore
6143:
6144: sub restore {
1.124 www 6145: my ($symb,$namespace,$domain,$stuname) = @_;
6146: my $home='';
6147:
1.168 albertel 6148: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6149:
1.122 albertel 6150: if (!$symb) {
1.1172.2.26 raeburn 6151: return if ($namespace eq 'courserequests');
6152: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6153: } else {
1.1172.2.26 raeburn 6154: unless ($namespace eq 'courserequests') {
6155: $symb=&escape(&symbclean($symb));
6156: }
1.122 albertel 6157: }
1.188 www 6158: if (!$namespace) {
1.620 albertel 6159: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6160: return '';
6161: }
6162: }
1.620 albertel 6163: if (!$domain) { $domain=$env{'user.domain'}; }
6164: if (!$stuname) { $stuname=$env{'user.name'}; }
6165: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6166: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6167:
1.12 www 6168: my %returnhash=();
1.800 albertel 6169: foreach my $line (split(/\&/,$answer)) {
6170: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6171: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6172: }
1.75 www 6173: my $version;
6174: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6175: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6176: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6177: }
1.75 www 6178: }
1.13 www 6179: return %returnhash;
1.34 www 6180: }
6181:
6182: # ---------------------------------------------------------- Course Description
1.1118 foxr 6183: #
6184: #
1.34 www 6185:
6186: sub coursedescription {
1.731 albertel 6187: my ($courseid,$args)=@_;
1.34 www 6188: $courseid=~s/^\///;
1.49 www 6189: $courseid=~s/\_/\//g;
1.34 www 6190: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6191: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6192: my $normalid=$cdomain.'_'.$cnum;
6193: # need to always cache even if we get errors otherwise we keep
6194: # trying and trying and trying to get the course description.
6195: my %envhash=();
6196: my %returnhash=();
1.731 albertel 6197:
6198: my $expiretime=600;
6199: if ($env{'request.course.id'} eq $normalid) {
6200: $expiretime=120;
6201: }
6202:
6203: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6204: if (!$args->{'freshen_cache'}
6205: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6206: foreach my $key (keys(%env)) {
6207: next if ($key !~ /^\Q$prefix\E(.*)/);
6208: my ($setting) = $1;
6209: $returnhash{$setting} = $env{$key};
6210: }
6211: return %returnhash;
6212: }
6213:
1.1118 foxr 6214: # get the data again
6215:
1.731 albertel 6216: if (!$args->{'one_time'}) {
6217: $envhash{'course.'.$normalid.'.last_cache'}=time;
6218: }
1.811 albertel 6219:
1.34 www 6220: if ($chome ne 'no_host') {
1.302 albertel 6221: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6222: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6223: my $username = $env{'user.name'}; # Defult username
6224: if(defined $args->{'user'}) {
6225: $username = $args->{'user'};
6226: }
1.129 albertel 6227: $returnhash{'home'}= $chome;
6228: $returnhash{'domain'} = $cdomain;
6229: $returnhash{'num'} = $cnum;
1.741 raeburn 6230: if (!defined($returnhash{'type'})) {
6231: $returnhash{'type'} = 'Course';
6232: }
1.130 albertel 6233: while (my ($name,$value) = each %returnhash) {
1.53 www 6234: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6235: }
1.270 www 6236: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6237: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6238: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6239: $envhash{'course.'.$normalid.'.home'}=$chome;
6240: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6241: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6242: }
6243: }
1.731 albertel 6244: if (!$args->{'one_time'}) {
1.949 raeburn 6245: &appenv(\%envhash);
1.731 albertel 6246: }
1.302 albertel 6247: return %returnhash;
1.461 www 6248: }
6249:
1.1080 raeburn 6250: sub update_released_required {
6251: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6252: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6253: $cid = $env{'request.course.id'};
6254: $cdom = $env{'course.'.$cid.'.domain'};
6255: $cnum = $env{'course.'.$cid.'.num'};
6256: $chome = $env{'course.'.$cid.'.home'};
6257: }
6258: if ($needsrelease) {
6259: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6260: my $needsupdate;
6261: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6262: $needsupdate = 1;
6263: } else {
6264: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6265: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6266: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6267: $needsupdate = 1;
6268: }
6269: }
6270: if ($needsupdate) {
6271: my %needshash = (
6272: 'internal.releaserequired' => $needsrelease,
6273: );
6274: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6275: if ($putresult eq 'ok') {
6276: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6277: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6278: if (ref($crsinfo{$cid}) eq 'HASH') {
6279: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6280: &courseidput($cdom,\%crsinfo,$chome,'notime');
6281: }
6282: }
6283: }
6284: }
6285: return;
6286: }
6287:
1.461 www 6288: # -------------------------------------------------See if a user is privileged
6289:
6290: sub privileged {
1.1172.2.23 raeburn 6291: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6292: my $now = time;
1.1172.2.23 raeburn 6293: my $roles;
6294: if (ref($possroles) eq 'ARRAY') {
6295: $roles = $possroles;
6296: } else {
6297: $roles = ['dc','su'];
6298: }
6299: if (ref($possdomains) eq 'ARRAY') {
6300: my %privileged = &privileged_by_domain($possdomains,$roles);
6301: foreach my $dom (@{$possdomains}) {
6302: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6303: (ref($privileged{$dom}) eq 'HASH')) {
6304: foreach my $role (@{$roles}) {
6305: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6306: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6307: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6308: return 1 unless (($end && $end < $now) ||
6309: ($start && $start > $now));
6310: }
6311: }
6312: }
6313: }
6314: }
6315: } else {
6316: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6317: my $now = time;
1.1170 droeschl 6318:
1.1172.2.58 raeburn 6319: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6320: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 6321: if (grep(/^\Q$trole\E$/,@{$roles})) {
6322: return 1 unless ($tend && $tend < $now)
6323: or ($tstart && $tstart > $now);
1.1170 droeschl 6324: }
1.1172.2.23 raeburn 6325: }
6326: }
1.461 www 6327: return 0;
1.9 www 6328: }
1.1 albertel 6329:
1.1172.2.23 raeburn 6330: sub privileged_by_domain {
6331: my ($domains,$roles) = @_;
6332: my %privileged = ();
6333: my $cachetime = 60*60*24;
6334: my $now = time;
6335: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6336: return %privileged;
6337: }
6338: foreach my $dom (@{$domains}) {
6339: next if (ref($privileged{$dom}) eq 'HASH');
6340: my $needroles;
6341: foreach my $role (@{$roles}) {
6342: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6343: if (defined($cached)) {
6344: if (ref($result) eq 'HASH') {
6345: $privileged{$dom}{$role} = $result;
6346: }
6347: } else {
6348: $needroles = 1;
6349: }
6350: }
6351: if ($needroles) {
6352: my %dompersonnel = &get_domain_roles($dom,$roles);
6353: $privileged{$dom} = {};
6354: foreach my $server (keys(%dompersonnel)) {
6355: if (ref($dompersonnel{$server}) eq 'HASH') {
6356: foreach my $item (keys(%{$dompersonnel{$server}})) {
6357: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6358: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6359: next if ($end && $end < $now);
6360: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6361: $dompersonnel{$server}{$item};
6362: }
6363: }
6364: }
6365: if (ref($privileged{$dom}) eq 'HASH') {
6366: foreach my $role (@{$roles}) {
6367: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6368: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6369: } else {
6370: my %hash = ();
6371: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6372: }
6373: }
6374: }
6375: }
6376: }
6377: return %privileged;
6378: }
6379:
1.103 harris41 6380: # -------------------------------------------------------- Get user privileges
1.11 www 6381:
6382: sub rolesinit {
1.1169 droeschl 6383: my ($domain, $username) = @_;
6384: my %userroles = ('user.login.time' => time);
6385: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6386:
6387: # firstaccess and timerinterval are related to timed maps/resources.
6388: # also, blocking can be triggered by an activating timer
6389: # it's saved in the user's %env.
6390: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6391: my %timerinterval = &dump('timerinterval', $domain, $username);
6392: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6393: %timerintchk, %timerintenv);
6394:
1.1162 raeburn 6395: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6396: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6397: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6398: }
1.1169 droeschl 6399:
1.1162 raeburn 6400: foreach my $key (keys(%timerinterval)) {
6401: my ($cid,$rest) = split(/\0/,$key);
6402: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6403: }
1.1169 droeschl 6404:
1.11 www 6405: my %allroles=();
1.1162 raeburn 6406: my %allgroups=();
1.11 www 6407:
1.1172.2.58 raeburn 6408: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6409: my $role = $rolesdump{$area};
6410: $area =~ s/\_\w\w$//;
6411:
6412: my ($trole, $tend, $tstart, $group_privs);
6413:
6414: if ($role =~ /^cr/) {
6415: # Custom role, defined by a user
6416: # e.g., user.role.cr/msu/smith/mynewrole
6417: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6418: $trole = $1;
6419: ($tend, $tstart) = split('_', $2);
6420: } else {
6421: $trole = $role;
6422: }
6423: } elsif ($role =~ m|^gr/|) {
6424: # Role of member in a group, defined within a course/community
6425: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6426: ($trole, $tend, $tstart) = split(/_/, $role);
6427: next if $tstart eq '-1';
6428: ($trole, $group_privs) = split(/\//, $trole);
6429: $group_privs = &unescape($group_privs);
6430: } else {
6431: # Just a normal role, defined in roles.tab
6432: ($trole, $tend, $tstart) = split(/_/,$role);
6433: }
6434:
6435: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6436: $username);
6437: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6438:
6439: # role expired or not available yet?
6440: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6441: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6442:
6443: next if $area eq '' or $trole eq '';
6444:
6445: my $spec = "$trole.$area";
6446: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6447:
6448: if ($trole =~ /^cr\//) {
6449: # Custom role, defined by a user
6450: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6451: } elsif ($trole eq 'gr') {
6452: # Role of a member in a group, defined within a course/community
6453: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6454: next;
6455: } else {
6456: # Normal role, defined in roles.tab
6457: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6458: }
6459:
6460: my $cid = $tdomain.'_'.$trest;
6461: unless ($firstaccchk{$cid}) {
6462: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6463: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6464: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6465: $coursetimerstarts{$cid}{$item};
6466: }
6467: }
6468: $firstaccchk{$cid} = 1;
6469: }
6470: unless ($timerintchk{$cid}) {
6471: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6472: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6473: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6474: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6475: }
1.12 www 6476: }
1.1169 droeschl 6477: $timerintchk{$cid} = 1;
1.191 harris41 6478: }
1.11 www 6479: }
1.1169 droeschl 6480:
1.1172.2.91 raeburn 6481: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6482: \%allroles, \%allgroups);
1.1169 droeschl 6483: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6484: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6485:
1.1162 raeburn 6486: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6487: }
6488:
1.567 raeburn 6489: sub set_arearole {
1.1172.2.19 raeburn 6490: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6491: unless ($nolog) {
1.567 raeburn 6492: # log the associated role with the area
1.1172.2.19 raeburn 6493: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6494: }
1.743 albertel 6495: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6496: }
6497:
6498: sub custom_roleprivs {
6499: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6500: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6501: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6502: if (&hostname($homsvr) ne '') {
1.567 raeburn 6503: my ($rdummy,$roledef)=
6504: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6505: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6506: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6507: if (defined($syspriv)) {
1.1043 raeburn 6508: if ($trest =~ /^$match_community$/) {
6509: $syspriv =~ s/bre\&S//;
6510: }
1.567 raeburn 6511: $$allroles{'cm./'}.=':'.$syspriv;
6512: $$allroles{$spec.'./'}.=':'.$syspriv;
6513: }
6514: if ($tdomain ne '') {
6515: if (defined($dompriv)) {
6516: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6517: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6518: }
6519: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6520: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6521: my $rolename = $1;
6522: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6523: }
1.567 raeburn 6524: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6525: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6526: }
6527: }
6528: }
6529: }
6530: }
6531:
1.1172.2.89 raeburn 6532: sub course_adhocrole_privs {
6533: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6534: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6535: if ($overrides{"internal.adhocpriv.$rolename"}) {
6536: my (%currprivs,%storeprivs);
6537: foreach my $item (split(/:/,$coursepriv)) {
6538: my ($priv,$restrict) = split(/\&/,$item);
6539: $currprivs{$priv} = $restrict;
6540: }
6541: my (%possadd,%possremove,%full);
6542: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6543: my ($priv,$restrict)=split(/\&/,$item);
6544: $full{$priv} = $restrict;
6545: }
6546: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6547: next if ($item eq '');
6548: my ($rule,$rest) = split(/=/,$item);
6549: next unless (($rule eq 'off') || ($rule eq 'on'));
6550: foreach my $priv (split(/:/,$rest)) {
6551: if ($priv ne '') {
6552: if ($rule eq 'off') {
6553: $possremove{$priv} = 1;
6554: } else {
6555: $possadd{$priv} = 1;
6556: }
6557: }
6558: }
6559: }
6560: foreach my $priv (sort(keys(%full))) {
6561: if (exists($currprivs{$priv})) {
6562: unless (exists($possremove{$priv})) {
6563: $storeprivs{$priv} = $currprivs{$priv};
6564: }
6565: } elsif (exists($possadd{$priv})) {
6566: $storeprivs{$priv} = $full{$priv};
6567: }
6568: }
6569: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6570: }
6571: return $coursepriv;
6572: }
6573:
1.678 raeburn 6574: sub group_roleprivs {
6575: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6576: my $access = 1;
6577: my $now = time;
6578: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6579: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6580: if ($access) {
1.811 albertel 6581: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6582: $$allgroups{$course}{$group} .=':'.$group_privs;
6583: }
6584: }
1.567 raeburn 6585:
6586: sub standard_roleprivs {
6587: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6588: if (defined($pr{$trole.':s'})) {
6589: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6590: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6591: }
6592: if ($tdomain ne '') {
6593: if (defined($pr{$trole.':d'})) {
6594: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6595: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6596: }
6597: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6598: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6599: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6600: }
6601: }
6602: }
6603:
6604: sub set_userprivs {
1.1064 raeburn 6605: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6606: my $author=0;
6607: my $adv=0;
1.1172.2.91 raeburn 6608: my $rar=0;
1.678 raeburn 6609: my %grouproles = ();
6610: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6611: my @groupkeys;
1.1000 raeburn 6612: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6613: push(@groupkeys,$role);
6614: }
6615: if (ref($groups_roles) eq 'HASH') {
6616: foreach my $key (keys(%{$groups_roles})) {
6617: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6618: push(@groupkeys,$key);
6619: }
6620: }
6621: }
6622: if (@groupkeys > 0) {
6623: foreach my $role (@groupkeys) {
6624: my ($trole,$area,$sec,$extendedarea);
6625: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6626: $trole = $1;
6627: $area = $2;
6628: $sec = $3;
6629: $extendedarea = $area.$sec;
6630: if (exists($$allgroups{$area})) {
6631: foreach my $group (keys(%{$$allgroups{$area}})) {
6632: my $spec = $trole.'.'.$extendedarea;
6633: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6634: $$allgroups{$area}{$group};
1.1064 raeburn 6635: }
1.678 raeburn 6636: }
6637: }
6638: }
6639: }
6640: }
1.800 albertel 6641: foreach my $group (keys(%grouproles)) {
6642: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6643: }
1.800 albertel 6644: foreach my $role (keys(%{$allroles})) {
6645: my %thesepriv;
1.941 raeburn 6646: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6647: foreach my $item (split(/:/,$$allroles{$role})) {
6648: if ($item ne '') {
6649: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6650: if ($restrictions eq '') {
6651: $thesepriv{$privilege}='F';
6652: } elsif ($thesepriv{$privilege} ne 'F') {
6653: $thesepriv{$privilege}.=$restrictions;
6654: }
6655: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 6656: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6657: }
6658: }
6659: my $thesestr='';
1.1104 raeburn 6660: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6661: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6662: }
6663: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6664: }
1.1172.2.91 raeburn 6665: return ($author,$adv,$rar);
1.567 raeburn 6666: }
6667:
1.994 raeburn 6668: sub role_status {
1.1104 raeburn 6669: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6670: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 6671: my ($one,$two) = split(m{\./},$rolekey,2);
6672: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6673: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 6674: $$where = '/'.$two;
1.994 raeburn 6675: $$trolecode=$$role.'.'.$$where;
6676: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6677: $$tstatus='is';
1.1104 raeburn 6678: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6679: $$tstatus='future';
1.1034 raeburn 6680: if ($$tstart<$now) {
6681: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6682: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6683: my (%allroles,%allgroups,$group_privs,
6684: %groups_roles,@rolecodes);
1.1002 raeburn 6685: my %userroles = (
6686: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6687: );
1.1064 raeburn 6688: @rolecodes = ('cm');
1.1002 raeburn 6689: my $spec=$$role.'.'.$$where;
6690: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6691: if ($$role =~ /^cr\//) {
6692: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6693: push(@rolecodes,'cr');
1.1002 raeburn 6694: } elsif ($$role eq 'gr') {
1.1064 raeburn 6695: push(@rolecodes,$$role);
1.1002 raeburn 6696: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6697: $env{'user.name'});
1.1064 raeburn 6698: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6699: (undef,my $group_privs) = split(/\//,$trole);
6700: $group_privs = &unescape($group_privs);
6701: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6702: 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 6703: &get_groups_roles($tdomain,$trest,
6704: \%course_roles,\@rolecodes,
6705: \%groups_roles);
1.1002 raeburn 6706: } else {
1.1064 raeburn 6707: push(@rolecodes,$$role);
1.1002 raeburn 6708: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6709: }
1.1172.2.91 raeburn 6710: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6711: \%groups_roles);
1.1064 raeburn 6712: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 6713: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6714: }
6715: }
1.1034 raeburn 6716: $$tstatus = 'is';
1.1002 raeburn 6717: }
1.994 raeburn 6718: }
6719: if ($$tend) {
1.1104 raeburn 6720: if ($$tend<$update) {
1.994 raeburn 6721: $$tstatus='expired';
6722: } elsif ($$tend<$now) {
6723: $$tstatus='will_not';
6724: }
6725: }
6726: }
6727: }
6728: }
6729:
1.1104 raeburn 6730: sub get_groups_roles {
6731: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6732: return unless((ref($cdom_courseroles) eq 'HASH') &&
6733: (ref($rolecodes) eq 'ARRAY') &&
6734: (ref($groups_roles) eq 'HASH'));
6735: if (keys(%{$cdom_courseroles}) > 0) {
6736: my ($cnum) = ($rest =~ /^($match_courseid)/);
6737: if ($cdom ne '' && $cnum ne '') {
6738: foreach my $key (keys(%{$cdom_courseroles})) {
6739: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6740: my $crsrole = $1;
6741: my $crssec = $2;
6742: if ($crsrole =~ /^cr/) {
6743: unless (grep(/^cr$/,@{$rolecodes})) {
6744: push(@{$rolecodes},'cr');
6745: }
6746: } else {
6747: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6748: push(@{$rolecodes},$crsrole);
6749: }
6750: }
6751: my $rolekey = "$crsrole./$cdom/$cnum";
6752: if ($crssec ne '') {
6753: $rolekey .= "/$crssec";
6754: }
6755: $rolekey .= './';
6756: $groups_roles->{$rolekey} = $rolecodes;
6757: }
6758: }
6759: }
6760: }
6761: return;
6762: }
6763:
6764: sub delete_env_groupprivs {
6765: my ($where,$courseroles,$possroles) = @_;
6766: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6767: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6768: unless (ref($courseroles->{$udom}) eq 'HASH') {
6769: %{$courseroles->{$udom}} =
6770: &get_my_roles('','','userroles',['active'],
6771: $possroles,[$udom],1);
6772: }
6773: if (ref($courseroles->{$udom}) eq 'HASH') {
6774: foreach my $item (keys(%{$courseroles->{$udom}})) {
6775: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6776: my $area = '/'.$cdom.'/'.$cnum;
6777: my $privkey = "user.priv.$crsrole.$area";
6778: if ($crssec ne '') {
6779: $privkey .= '/'.$crssec;
6780: }
6781: $privkey .= ".$area/$group";
6782: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6783: }
6784: }
6785: return;
6786: }
6787:
1.994 raeburn 6788: sub check_adhoc_privs {
1.1172.2.86 raeburn 6789: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6790: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6791: if ($sec) {
6792: $cckey .= '/'.$sec;
6793: }
1.1172.2.9 raeburn 6794: my $setprivs;
1.994 raeburn 6795: if ($env{$cckey}) {
6796: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6797: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6798: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6799: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6800: $setprivs = 1;
1.994 raeburn 6801: }
6802: } else {
1.1172.2.87 raeburn 6803: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6804: $setprivs = 1;
1.994 raeburn 6805: }
1.1172.2.9 raeburn 6806: return $setprivs;
1.994 raeburn 6807: }
6808:
6809: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6810: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6811: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6812: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6813: if ($sec ne '') {
6814: $area .= '/'.$sec;
6815: }
1.994 raeburn 6816: my $spec = $role.'.'.$area;
6817: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6818: $env{'user.name'},1);
1.1172.2.84 raeburn 6819: my %rolehash = ();
1.1172.2.89 raeburn 6820: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6821: my $rolename = $1;
1.1172.2.84 raeburn 6822: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6823: my %domdef = &get_domain_defaults($dcdom);
6824: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6825: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6826: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6827: }
6828: }
1.1172.2.84 raeburn 6829: } else {
6830: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6831: }
1.1172.2.91 raeburn 6832: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6833: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6834: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6835: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6836: &appenv( {'request.role' => $spec,
6837: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6838: 'request.course.sec' => $sec,
1.1088 raeburn 6839: }
6840: );
6841: my $tadv=0;
6842: if (&allowed('adv') eq 'F') { $tadv=1; }
6843: &appenv({'request.role.adv' => $tadv});
6844: }
1.994 raeburn 6845: }
6846:
1.12 www 6847: # --------------------------------------------------------------- get interface
6848:
6849: sub get {
1.131 albertel 6850: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6851: my $items='';
1.800 albertel 6852: foreach my $item (@$storearr) {
6853: $items.=&escape($item).'&';
1.191 harris41 6854: }
1.12 www 6855: $items=~s/\&$//;
1.620 albertel 6856: if (!$udomain) { $udomain=$env{'user.domain'}; }
6857: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6858: my $uhome=&homeserver($uname,$udomain);
6859:
1.133 albertel 6860: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6861: my @pairs=split(/\&/,$rep);
1.273 albertel 6862: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6863: return @pairs;
6864: }
1.15 www 6865: my %returnhash=();
1.42 www 6866: my $i=0;
1.800 albertel 6867: foreach my $item (@$storearr) {
6868: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6869: $i++;
1.191 harris41 6870: }
1.15 www 6871: return %returnhash;
1.27 www 6872: }
6873:
6874: # --------------------------------------------------------------- del interface
6875:
6876: sub del {
1.133 albertel 6877: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6878: my $items='';
1.800 albertel 6879: foreach my $item (@$storearr) {
6880: $items.=&escape($item).'&';
1.191 harris41 6881: }
1.984 neumanie 6882:
1.27 www 6883: $items=~s/\&$//;
1.620 albertel 6884: if (!$udomain) { $udomain=$env{'user.domain'}; }
6885: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6886: my $uhome=&homeserver($uname,$udomain);
6887: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6888: }
6889:
6890: # -------------------------------------------------------------- dump interface
6891:
1.1172.2.22 raeburn 6892: sub unserialize {
6893: my ($rep, $escapedkeys) = @_;
6894:
6895: return {} if $rep =~ /^error/;
6896:
6897: my %returnhash=();
6898: foreach my $item (split(/\&/,$rep)) {
6899: my ($key, $value) = split(/=/, $item, 2);
6900: $key = unescape($key) unless $escapedkeys;
6901: next if $key =~ /^error: 2 /;
6902: $returnhash{$key} = &thaw_unescape($value);
6903: }
6904: return \%returnhash;
6905: }
6906:
6907: # see Lond::dump_with_regexp
6908: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6909: sub dump {
1.1172.2.22 raeburn 6910: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6911: if (!$udomain) { $udomain=$env{'user.domain'}; }
6912: if (!$uname) { $uname=$env{'user.name'}; }
6913: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6914:
1.1172.2.55 raeburn 6915: if ($regexp) {
6916: $regexp=&escape($regexp);
6917: } else {
6918: $regexp='.';
6919: }
1.1172.2.22 raeburn 6920: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6921: # user is hosted on this machine
1.1172.2.55 raeburn 6922: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6923: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6924: return %{&unserialize($reply, $escapedkeys)};
6925: }
1.1166 raeburn 6926: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6927: my @pairs=split(/\&/,$rep);
6928: my %returnhash=();
1.1098 foxr 6929: if (!($rep =~ /^error/ )) {
6930: foreach my $item (@pairs) {
6931: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6932: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6933: next if ($key =~ /^error: 2 /);
6934: $returnhash{$key}=&thaw_unescape($value);
6935: }
1.755 albertel 6936: }
6937: return %returnhash;
1.407 www 6938: }
6939:
1.1098 foxr 6940:
1.717 albertel 6941: # --------------------------------------------------------- dumpstore interface
6942:
6943: sub dumpstore {
6944: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6945: # same as dump but keys must be escaped. They may contain colon separated
6946: # lists of values that may themself contain colons (e.g. symbs).
6947: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6948: }
6949:
1.407 www 6950: # -------------------------------------------------------------- keys interface
6951:
6952: sub getkeys {
6953: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6954: if (!$udomain) { $udomain=$env{'user.domain'}; }
6955: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6956: my $uhome=&homeserver($uname,$udomain);
6957: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6958: my @keyarray=();
1.800 albertel 6959: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6960: next if ($key =~ /^error: 2 /);
1.800 albertel 6961: push(@keyarray,&unescape($key));
1.407 www 6962: }
6963: return @keyarray;
1.318 matthew 6964: }
6965:
1.319 matthew 6966: # --------------------------------------------------------------- currentdump
6967: sub currentdump {
1.328 matthew 6968: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6969: $courseid = $env{'request.course.id'} if (! defined($courseid));
6970: $sdom = $env{'user.domain'} if (! defined($sdom));
6971: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6972: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6973: my $rep;
6974:
6975: if (grep { $_ eq $uhome } current_machine_ids()) {
6976: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6977: $courseid)));
6978: } else {
6979: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6980: }
6981:
1.318 matthew 6982: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6983: #
1.318 matthew 6984: my %returnhash=();
1.319 matthew 6985: #
6986: if ($rep eq "unknown_cmd") {
6987: # an old lond will not know currentdump
6988: # Do a dump and make it look like a currentdump
1.822 albertel 6989: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6990: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6991: my %hash = @tmp;
6992: @tmp=();
1.424 matthew 6993: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6994: } else {
6995: my @pairs=split(/\&/,$rep);
1.800 albertel 6996: foreach my $pair (@pairs) {
6997: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6998: my ($symb,$param) = split(/:/,$key);
6999: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7000: &thaw_unescape($value);
1.319 matthew 7001: }
1.191 harris41 7002: }
1.12 www 7003: return %returnhash;
1.424 matthew 7004: }
7005:
7006: sub convert_dump_to_currentdump{
7007: my %hash = %{shift()};
7008: my %returnhash;
7009: # Code ripped from lond, essentially. The only difference
7010: # here is the unescaping done by lonnet::dump(). Conceivably
7011: # we might run in to problems with parameter names =~ /^v\./
7012: while (my ($key,$value) = each(%hash)) {
7013: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7014: $symb = &unescape($symb);
7015: $param = &unescape($param);
1.424 matthew 7016: next if ($v eq 'version' || $symb eq 'keys');
7017: next if (exists($returnhash{$symb}) &&
7018: exists($returnhash{$symb}->{$param}) &&
7019: $returnhash{$symb}->{'v.'.$param} > $v);
7020: $returnhash{$symb}->{$param}=$value;
7021: $returnhash{$symb}->{'v.'.$param}=$v;
7022: }
7023: #
7024: # Remove all of the keys in the hashes which keep track of
7025: # the version of the parameter.
7026: while (my ($symb,$param_hash) = each(%returnhash)) {
7027: # use a foreach because we are going to delete from the hash.
7028: foreach my $key (keys(%$param_hash)) {
7029: delete($param_hash->{$key}) if ($key =~ /^v\./);
7030: }
7031: }
7032: return \%returnhash;
1.12 www 7033: }
7034:
1.627 albertel 7035: # ------------------------------------------------------ critical inc interface
7036:
7037: sub cinc {
7038: return &inc(@_,'critical');
7039: }
7040:
1.449 matthew 7041: # --------------------------------------------------------------- inc interface
7042:
7043: sub inc {
1.627 albertel 7044: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7045: if (!$udomain) { $udomain=$env{'user.domain'}; }
7046: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7047: my $uhome=&homeserver($uname,$udomain);
7048: my $items='';
7049: if (! ref($store)) {
7050: # got a single value, so use that instead
7051: $items = &escape($store).'=&';
7052: } elsif (ref($store) eq 'SCALAR') {
7053: $items = &escape($$store).'=&';
7054: } elsif (ref($store) eq 'ARRAY') {
7055: $items = join('=&',map {&escape($_);} @{$store});
7056: } elsif (ref($store) eq 'HASH') {
7057: while (my($key,$value) = each(%{$store})) {
7058: $items.= &escape($key).'='.&escape($value).'&';
7059: }
7060: }
7061: $items=~s/\&$//;
1.627 albertel 7062: if ($critical) {
7063: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7064: } else {
7065: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7066: }
1.449 matthew 7067: }
7068:
1.12 www 7069: # --------------------------------------------------------------- put interface
7070:
7071: sub put {
1.134 albertel 7072: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7073: if (!$udomain) { $udomain=$env{'user.domain'}; }
7074: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7075: my $uhome=&homeserver($uname,$udomain);
1.12 www 7076: my $items='';
1.800 albertel 7077: foreach my $item (keys(%$storehash)) {
7078: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7079: }
1.12 www 7080: $items=~s/\&$//;
1.134 albertel 7081: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7082: }
7083:
1.631 albertel 7084: # ------------------------------------------------------------ newput interface
7085:
7086: sub newput {
7087: my ($namespace,$storehash,$udomain,$uname)=@_;
7088: if (!$udomain) { $udomain=$env{'user.domain'}; }
7089: if (!$uname) { $uname=$env{'user.name'}; }
7090: my $uhome=&homeserver($uname,$udomain);
7091: my $items='';
7092: foreach my $key (keys(%$storehash)) {
7093: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7094: }
7095: $items=~s/\&$//;
7096: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7097: }
7098:
7099: # --------------------------------------------------------- putstore interface
7100:
1.524 raeburn 7101: sub putstore {
1.1172.2.59 raeburn 7102: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7103: if (!$udomain) { $udomain=$env{'user.domain'}; }
7104: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7105: my $uhome=&homeserver($uname,$udomain);
7106: my $items='';
1.715 albertel 7107: foreach my $key (keys(%$storehash)) {
7108: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7109: }
1.715 albertel 7110: $items=~s/\&$//;
1.716 albertel 7111: my $esc_symb=&escape($symb);
7112: my $esc_v=&escape($version);
1.715 albertel 7113: my $reply =
1.716 albertel 7114: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7115: $uhome);
1.1172.2.59 raeburn 7116: if (($tolog) && ($reply eq 'ok')) {
7117: my $namevalue='';
7118: foreach my $key (keys(%{$storehash})) {
7119: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7120: }
1.1172.2.134 raeburn 7121: my $ip = &get_requestor_ip();
1.1172.2.135 raeburn 7122: $namevalue .= 'ip='.&escape($ip).
1.1172.2.59 raeburn 7123: '&host='.&escape($perlvar{'lonHostID'}).
7124: '&version='.$esc_v.
7125: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7126: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7127: }
1.715 albertel 7128: if ($reply eq 'unknown_cmd') {
1.716 albertel 7129: # gfall back to way things use to be done
1.715 albertel 7130: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7131: $uname);
1.524 raeburn 7132: }
1.715 albertel 7133: return $reply;
7134: }
7135:
7136: sub old_putstore {
1.716 albertel 7137: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7138: if (!$udomain) { $udomain=$env{'user.domain'}; }
7139: if (!$uname) { $uname=$env{'user.name'}; }
7140: my $uhome=&homeserver($uname,$udomain);
7141: my %newstorehash;
1.800 albertel 7142: foreach my $item (keys(%$storehash)) {
7143: my $key = $version.':'.&escape($symb).':'.$item;
7144: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7145: }
7146: my $items='';
7147: my %allitems = ();
1.800 albertel 7148: foreach my $item (keys(%newstorehash)) {
7149: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7150: my $key = $1.':keys:'.$2;
7151: $allitems{$key} .= $3.':';
7152: }
1.800 albertel 7153: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7154: }
1.800 albertel 7155: foreach my $item (keys(%allitems)) {
7156: $allitems{$item} =~ s/\:$//;
7157: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7158: }
7159: $items=~s/\&$//;
7160: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7161: }
7162:
1.47 www 7163: # ------------------------------------------------------ critical put interface
7164:
7165: sub cput {
1.134 albertel 7166: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7167: if (!$udomain) { $udomain=$env{'user.domain'}; }
7168: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7169: my $uhome=&homeserver($uname,$udomain);
1.47 www 7170: my $items='';
1.800 albertel 7171: foreach my $item (keys(%$storehash)) {
7172: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7173: }
1.47 www 7174: $items=~s/\&$//;
1.134 albertel 7175: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7176: }
7177:
7178: # -------------------------------------------------------------- eget interface
7179:
7180: sub eget {
1.133 albertel 7181: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7182: my $items='';
1.800 albertel 7183: foreach my $item (@$storearr) {
7184: $items.=&escape($item).'&';
1.191 harris41 7185: }
1.12 www 7186: $items=~s/\&$//;
1.620 albertel 7187: if (!$udomain) { $udomain=$env{'user.domain'}; }
7188: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7189: my $uhome=&homeserver($uname,$udomain);
7190: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7191: my @pairs=split(/\&/,$rep);
7192: my %returnhash=();
1.42 www 7193: my $i=0;
1.800 albertel 7194: foreach my $item (@$storearr) {
7195: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7196: $i++;
1.191 harris41 7197: }
1.12 www 7198: return %returnhash;
7199: }
7200:
1.667 albertel 7201: # ------------------------------------------------------------ tmpput interface
7202: sub tmpput {
1.802 raeburn 7203: my ($storehash,$server,$context)=@_;
1.667 albertel 7204: my $items='';
1.800 albertel 7205: foreach my $item (keys(%$storehash)) {
7206: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7207: }
7208: $items=~s/\&$//;
1.802 raeburn 7209: if (defined($context)) {
7210: $items .= ':'.&escape($context);
7211: }
1.667 albertel 7212: return &reply("tmpput:$items",$server);
7213: }
7214:
7215: # ------------------------------------------------------------ tmpget interface
7216: sub tmpget {
1.688 albertel 7217: my ($token,$server)=@_;
7218: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7219: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7220: my %returnhash;
1.1172.2.85 raeburn 7221: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7222: return %returnhash;
7223: }
1.667 albertel 7224: foreach my $item (split(/\&/,$rep)) {
7225: my ($key,$value)=split(/=/,$item);
7226: $returnhash{&unescape($key)}=&thaw_unescape($value);
7227: }
7228: return %returnhash;
7229: }
7230:
1.1113 raeburn 7231: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7232: sub tmpdel {
7233: my ($token,$server)=@_;
7234: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7235: return &reply("tmpdel:$token",$server);
7236: }
7237:
1.1172.2.13 raeburn 7238: # ------------------------------------------------------------ get_timebased_id
7239:
7240: sub get_timebased_id {
7241: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7242: $maxtries) = @_;
7243: my ($newid,$error,$dellock);
7244: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7245: return ('','ok','invalid call to get suffix');
7246: }
7247:
7248: # set defaults for any optional args for which values were not supplied
7249: if ($who eq '') {
7250: $who = $env{'user.name'}.':'.$env{'user.domain'};
7251: }
7252: if (!$locktries) {
7253: $locktries = 3;
7254: }
7255: if (!$maxtries) {
7256: $maxtries = 10;
7257: }
7258:
7259: if (($cdom eq '') || ($cnum eq '')) {
7260: if ($env{'request.course.id'}) {
7261: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7262: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7263: }
7264: if (($cdom eq '') || ($cnum eq '')) {
7265: return ('','ok','call to get suffix not in course context');
7266: }
7267: }
7268:
7269: # construct locking item
7270: my $lockhash = {
7271: $prefix."\0".'locked_'.$keyid => $who,
7272: };
7273: my $tries = 0;
7274:
7275: # attempt to get lock on nohist_$namespace file
7276: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7277: while (($gotlock ne 'ok') && $tries <$locktries) {
7278: $tries ++;
7279: sleep 1;
7280: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7281: }
7282:
7283: # attempt to get unique identifier, based on current timestamp
7284: if ($gotlock eq 'ok') {
7285: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7286: my $id = time;
7287: $newid = $id;
1.1172.2.56 raeburn 7288: if ($idtype eq 'addcode') {
7289: $newid .= &sixnum_code();
7290: }
1.1172.2.13 raeburn 7291: my $idtries = 0;
7292: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7293: if ($idtype eq 'concat') {
7294: $newid = $id.$idtries;
1.1172.2.56 raeburn 7295: } elsif ($idtype eq 'addcode') {
7296: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 7297: } else {
7298: $newid ++;
7299: }
7300: $idtries ++;
7301: }
7302: if (!exists($inuse{$prefix."\0".$newid})) {
7303: my %new_item = (
7304: $prefix."\0".$newid => $who,
7305: );
7306: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7307: $cdom,$cnum);
7308: if ($putresult ne 'ok') {
7309: undef($newid);
7310: $error = 'error saving new item: '.$putresult;
7311: }
7312: } else {
1.1172.2.56 raeburn 7313: undef($newid);
1.1172.2.13 raeburn 7314: $error = ('error: no unique suffix available for the new item ');
7315: }
7316: # remove lock
7317: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7318: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7319: } else {
7320: $error = "error: could not obtain lockfile\n";
7321: $dellock = 'ok';
1.1172.2.58 raeburn 7322: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7323: $dellock = 'nolock';
7324: }
1.1172.2.13 raeburn 7325: }
7326: return ($newid,$dellock,$error);
7327: }
7328:
1.1172.2.56 raeburn 7329: sub sixnum_code {
7330: my $code;
7331: for (0..6) {
7332: $code .= int( rand(9) );
7333: }
7334: return $code;
7335: }
7336:
1.765 albertel 7337: # -------------------------------------------------- portfolio access checking
7338:
7339: sub portfolio_access {
1.1172.2.77 raeburn 7340: my ($requrl,$clientip) = @_;
1.765 albertel 7341: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 7342: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7343: if ($result) {
7344: my %setters;
7345: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142 raeburn 7346: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7347: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7348: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7349: return 'B';
7350: }
7351: } else {
1.1172.2.142 raeburn 7352: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
7353: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7354: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7355: return 'B';
7356: }
7357: }
7358: }
1.765 albertel 7359: if ($result eq 'ok') {
1.766 albertel 7360: return 'F';
1.765 albertel 7361: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7362: return 'A';
1.765 albertel 7363: }
1.766 albertel 7364: return '';
1.765 albertel 7365: }
7366:
7367: sub get_portfolio_access {
1.1172.2.77 raeburn 7368: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7369:
7370: if (!ref($access_hash)) {
7371: my $current_perms = &get_portfile_permissions($udom,$unum);
7372: my %access_controls = &get_access_controls($current_perms,$group,
7373: $file_name);
7374: $access_hash = $access_controls{$file_name};
7375: }
7376:
1.1172.2.77 raeburn 7377: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7378: my $now = time;
7379: if (ref($access_hash) eq 'HASH') {
7380: foreach my $key (keys(%{$access_hash})) {
7381: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7382: if ($start > $now) {
7383: next;
7384: }
7385: if ($end && $end<$now) {
7386: next;
7387: }
7388: if ($scope eq 'public') {
7389: $public = $key;
7390: last;
7391: } elsif ($scope eq 'guest') {
7392: $guest = $key;
7393: } elsif ($scope eq 'domains') {
7394: push(@domains,$key);
7395: } elsif ($scope eq 'users') {
7396: push(@users,$key);
7397: } elsif ($scope eq 'course') {
7398: push(@courses,$key);
7399: } elsif ($scope eq 'group') {
7400: push(@groups,$key);
1.1172.2.77 raeburn 7401: } elsif ($scope eq 'ip') {
7402: push(@ips,$key);
1.765 albertel 7403: }
7404: }
7405: if ($public) {
7406: return 'ok';
1.1172.2.77 raeburn 7407: } elsif (@ips > 0) {
7408: my $allowed;
7409: foreach my $ipkey (@ips) {
7410: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7411: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7412: $allowed = 1;
7413: last;
7414: }
7415: }
7416: }
7417: if ($allowed) {
7418: return 'ok';
7419: }
1.765 albertel 7420: }
7421: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7422: if ($guest) {
7423: return $guest;
7424: }
7425: } else {
7426: if (@domains > 0) {
7427: foreach my $domkey (@domains) {
7428: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7429: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7430: return 'ok';
7431: }
7432: }
7433: }
7434: }
7435: if (@users > 0) {
7436: foreach my $userkey (@users) {
1.865 raeburn 7437: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7438: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7439: if (ref($item) eq 'HASH') {
7440: if (($item->{'uname'} eq $env{'user.name'}) &&
7441: ($item->{'udom'} eq $env{'user.domain'})) {
7442: return 'ok';
7443: }
7444: }
7445: }
7446: }
1.765 albertel 7447: }
7448: }
7449: my %roleshash;
7450: my @courses_and_groups = @courses;
7451: push(@courses_and_groups,@groups);
7452: if (@courses_and_groups > 0) {
7453: my (%allgroups,%allroles);
7454: my ($start,$end,$role,$sec,$group);
7455: foreach my $envkey (%env) {
1.1060 raeburn 7456: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7457: my $cid = $2.'_'.$3;
7458: if ($1 eq 'gr') {
7459: $group = $4;
7460: $allgroups{$cid}{$group} = $env{$envkey};
7461: } else {
7462: if ($4 eq '') {
7463: $sec = 'none';
7464: } else {
7465: $sec = $4;
7466: }
7467: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7468: }
1.811 albertel 7469: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7470: my $cid = $2.'_'.$3;
7471: if ($4 eq '') {
7472: $sec = 'none';
7473: } else {
7474: $sec = $4;
7475: }
7476: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7477: }
7478: }
7479: if (keys(%allroles) == 0) {
7480: return;
7481: }
7482: foreach my $key (@courses_and_groups) {
7483: my %content = %{$$access_hash{$key}};
7484: my $cnum = $content{'number'};
7485: my $cdom = $content{'domain'};
7486: my $cid = $cdom.'_'.$cnum;
7487: if (!exists($allroles{$cid})) {
7488: next;
7489: }
7490: foreach my $role_id (keys(%{$content{'roles'}})) {
7491: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7492: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7493: my @status = @{$content{'roles'}{$role_id}{'access'}};
7494: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7495: foreach my $role (keys(%{$allroles{$cid}})) {
7496: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7497: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7498: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7499: if (grep/^all$/,@sections) {
7500: return 'ok';
7501: } else {
7502: if (grep/^$sec$/,@sections) {
7503: return 'ok';
7504: }
7505: }
7506: }
7507: }
7508: if (keys(%{$allgroups{$cid}}) == 0) {
7509: if (grep/^none$/,@groups) {
7510: return 'ok';
7511: }
7512: } else {
7513: if (grep/^all$/,@groups) {
7514: return 'ok';
7515: }
7516: foreach my $group (keys(%{$allgroups{$cid}})) {
7517: if (grep/^$group$/,@groups) {
7518: return 'ok';
7519: }
7520: }
7521: }
7522: }
7523: }
7524: }
7525: }
7526: }
7527: if ($guest) {
7528: return $guest;
7529: }
7530: }
7531: }
7532: return;
7533: }
7534:
7535: sub course_group_datechecker {
7536: my ($dates,$now,$status) = @_;
7537: my ($start,$end) = split(/\./,$dates);
7538: if (!$start && !$end) {
7539: return 'ok';
7540: }
7541: if (grep/^active$/,@{$status}) {
7542: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7543: return 'ok';
7544: }
7545: }
7546: if (grep/^previous$/,@{$status}) {
7547: if ($end > $now ) {
7548: return 'ok';
7549: }
7550: }
7551: if (grep/^future$/,@{$status}) {
7552: if ($start > $now) {
7553: return 'ok';
7554: }
7555: }
7556: return;
7557: }
7558:
7559: sub parse_portfolio_url {
7560: my ($url) = @_;
7561:
7562: my ($type,$udom,$unum,$group,$file_name);
7563:
1.823 albertel 7564: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7565: $type = 1;
7566: $udom = $1;
7567: $unum = $2;
7568: $file_name = $3;
1.823 albertel 7569: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7570: $type = 2;
7571: $udom = $1;
7572: $unum = $2;
7573: $group = $3;
7574: $file_name = $3.'/'.$4;
7575: }
7576: if (wantarray) {
7577: return ($type,$udom,$unum,$file_name,$group);
7578: }
7579: return $type;
7580: }
7581:
7582: sub is_portfolio_url {
7583: my ($url) = @_;
7584: return scalar(&parse_portfolio_url($url));
7585: }
7586:
1.798 raeburn 7587: sub is_portfolio_file {
7588: my ($file) = @_;
1.820 raeburn 7589: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7590: return 1;
7591: }
7592: return;
7593: }
7594:
1.976 raeburn 7595: sub usertools_access {
1.1084 raeburn 7596: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7597: my ($access,%tools);
7598: if ($context eq '') {
7599: $context = 'tools';
7600: }
7601: if ($context eq 'requestcourses') {
7602: %tools = (
7603: official => 1,
7604: unofficial => 1,
1.1006 raeburn 7605: community => 1,
1.1172.2.37 raeburn 7606: textbook => 1,
1.985 raeburn 7607: );
1.1172.2.9 raeburn 7608: } elsif ($context eq 'requestauthor') {
7609: %tools = (
7610: requestauthor => 1,
7611: );
1.985 raeburn 7612: } else {
7613: %tools = (
7614: aboutme => 1,
7615: blog => 1,
1.1172.2.6 raeburn 7616: webdav => 1,
1.985 raeburn 7617: portfolio => 1,
7618: );
7619: }
1.976 raeburn 7620: return if (!defined($tools{$tool}));
7621:
1.1172.2.35 raeburn 7622: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7623: $udom = $env{'user.domain'};
7624: $uname = $env{'user.name'};
7625: }
7626:
1.978 raeburn 7627: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7628: if ($action ne 'reload') {
1.985 raeburn 7629: if ($context eq 'requestcourses') {
7630: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 7631: } elsif ($context eq 'requestauthor') {
7632: return $env{'environment.canrequest.author'};
1.985 raeburn 7633: } else {
7634: return $env{'environment.availabletools.'.$tool};
7635: }
7636: }
1.976 raeburn 7637: }
7638:
1.1172.2.9 raeburn 7639: my ($toolstatus,$inststatus,$envkey);
7640: if ($context eq 'requestauthor') {
7641: $envkey = $context;
7642: } else {
7643: $envkey = $context.'.'.$tool;
7644: }
1.976 raeburn 7645:
1.985 raeburn 7646: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7647: ($action ne 'reload')) {
1.1172.2.9 raeburn 7648: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7649: $inststatus = $env{'environment.inststatus'};
7650: } else {
1.1084 raeburn 7651: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 7652: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7653: $inststatus = $userenvref->{'inststatus'};
7654: } else {
1.1172.2.9 raeburn 7655: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7656: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7657: $inststatus = $userenv{'inststatus'};
7658: }
1.976 raeburn 7659: }
7660:
7661: if ($toolstatus ne '') {
7662: if ($toolstatus) {
7663: $access = 1;
7664: } else {
7665: $access = 0;
7666: }
7667: return $access;
7668: }
7669:
1.1084 raeburn 7670: my ($is_adv,%domdef);
7671: if (ref($is_advref) eq 'HASH') {
7672: $is_adv = $is_advref->{'is_adv'};
7673: } else {
7674: $is_adv = &is_advanced_user($udom,$uname);
7675: }
7676: if (ref($domdefref) eq 'HASH') {
7677: %domdef = %{$domdefref};
7678: } else {
7679: %domdef = &get_domain_defaults($udom);
7680: }
1.976 raeburn 7681: if (ref($domdef{$tool}) eq 'HASH') {
7682: if ($is_adv) {
7683: if ($domdef{$tool}{'_LC_adv'} ne '') {
7684: if ($domdef{$tool}{'_LC_adv'}) {
7685: $access = 1;
7686: } else {
7687: $access = 0;
7688: }
7689: return $access;
7690: }
7691: }
7692: if ($inststatus ne '') {
7693: my ($hasaccess,$hasnoaccess);
7694: foreach my $affiliation (split(/:/,$inststatus)) {
7695: if ($domdef{$tool}{$affiliation} ne '') {
7696: if ($domdef{$tool}{$affiliation}) {
7697: $hasaccess = 1;
7698: } else {
7699: $hasnoaccess = 1;
7700: }
7701: }
7702: }
7703: if ($hasaccess || $hasnoaccess) {
7704: if ($hasaccess) {
7705: $access = 1;
7706: } elsif ($hasnoaccess) {
7707: $access = 0;
7708: }
7709: return $access;
7710: }
7711: } else {
7712: if ($domdef{$tool}{'default'} ne '') {
7713: if ($domdef{$tool}{'default'}) {
7714: $access = 1;
7715: } elsif ($domdef{$tool}{'default'} == 0) {
7716: $access = 0;
7717: }
7718: return $access;
7719: }
7720: }
7721: } else {
1.1172.2.6 raeburn 7722: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7723: $access = 1;
7724: } else {
7725: $access = 0;
7726: }
1.976 raeburn 7727: return $access;
7728: }
7729: }
7730:
1.1050 raeburn 7731: sub is_course_owner {
7732: my ($cdom,$cnum,$udom,$uname) = @_;
7733: if (($udom eq '') || ($uname eq '')) {
7734: $udom = $env{'user.domain'};
7735: $uname = $env{'user.name'};
7736: }
7737: unless (($udom eq '') || ($uname eq '')) {
7738: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7739: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7740: return 1;
7741: } else {
7742: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7743: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7744: return 1;
7745: }
7746: }
7747: }
7748: }
7749: return;
7750: }
7751:
1.976 raeburn 7752: sub is_advanced_user {
7753: my ($udom,$uname) = @_;
1.1085 raeburn 7754: if ($udom ne '' && $uname ne '') {
7755: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7756: if (wantarray) {
7757: return ($env{'user.adv'},$env{'user.author'});
7758: } else {
7759: return $env{'user.adv'};
7760: }
1.1085 raeburn 7761: }
7762: }
1.976 raeburn 7763: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7764: my %allroles;
1.1128 raeburn 7765: my ($is_adv,$is_author);
1.976 raeburn 7766: foreach my $role (keys(%roleshash)) {
7767: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7768: my $area = '/'.$tdomain.'/'.$trest;
7769: if ($sec ne '') {
7770: $area .= '/'.$sec;
7771: }
7772: if (($area ne '') && ($trole ne '')) {
7773: my $spec=$trole.'.'.$area;
7774: if ($trole =~ /^cr\//) {
7775: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7776: } elsif ($trole ne 'gr') {
7777: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7778: }
1.1128 raeburn 7779: if ($trole eq 'au') {
7780: $is_author = 1;
7781: }
1.976 raeburn 7782: }
7783: }
7784: foreach my $role (keys(%allroles)) {
7785: last if ($is_adv);
7786: foreach my $item (split(/:/,$allroles{$role})) {
7787: if ($item ne '') {
7788: my ($privilege,$restrictions)=split(/&/,$item);
7789: if ($privilege eq 'adv') {
7790: $is_adv = 1;
7791: last;
7792: }
7793: }
7794: }
7795: }
1.1128 raeburn 7796: if (wantarray) {
7797: return ($is_adv,$is_author);
7798: }
1.976 raeburn 7799: return $is_adv;
7800: }
1.798 raeburn 7801:
1.1035 raeburn 7802: sub check_can_request {
1.1036 raeburn 7803: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7804: my $canreq = 0;
7805: my ($types,$typename) = &Apache::loncommon::course_types();
7806: my @options = ('approval','validate','autolimit');
7807: my $optregex = join('|',@options);
7808: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7809: foreach my $type (@{$types}) {
7810: if (&usertools_access($env{'user.name'},
7811: $env{'user.domain'},
7812: $type,undef,'requestcourses')) {
7813: $canreq ++;
1.1036 raeburn 7814: if (ref($request_domains) eq 'HASH') {
7815: push(@{$request_domains->{$type}},$env{'user.domain'});
7816: }
1.1035 raeburn 7817: if ($dom eq $env{'user.domain'}) {
7818: $can_request->{$type} = 1;
7819: }
7820: }
7821: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7822: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7823: if (@curr > 0) {
1.1036 raeburn 7824: foreach my $item (@curr) {
7825: if (ref($request_domains) eq 'HASH') {
7826: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7827: if ($otherdom ne '') {
7828: if (ref($request_domains->{$type}) eq 'ARRAY') {
7829: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7830: push(@{$request_domains->{$type}},$otherdom);
7831: }
7832: } else {
7833: push(@{$request_domains->{$type}},$otherdom);
7834: }
7835: }
7836: }
7837: }
7838: unless($dom eq $env{'user.domain'}) {
7839: $canreq ++;
1.1035 raeburn 7840: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7841: $can_request->{$type} = 1;
7842: }
7843: }
7844: }
7845: }
7846: }
7847: }
7848: return $canreq;
7849: }
7850:
1.341 www 7851: # ---------------------------------------------- Custom access rule evaluation
7852:
7853: sub customaccess {
7854: my ($priv,$uri)=@_;
1.807 albertel 7855: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7856: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7857: $udom = &LONCAPA::clean_domain($udom);
7858: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7859: my $access=0;
1.800 albertel 7860: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7861: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7862: if ($type eq 'user') {
7863: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7864: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7865: if ($tdom) {
7866: if ($tdom ne $env{'user.domain'}) { next; }
7867: }
1.896 albertel 7868: if ($tuname) {
7869: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7870: }
7871: $access=($effect eq 'allow');
7872: last;
7873: }
7874: } else {
7875: if ($role) {
7876: if ($role ne $urole) { next; }
7877: }
7878: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7879: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7880: if ($tdom) {
7881: if ($tdom ne $udom) { next; }
7882: }
7883: if ($tcrs) {
7884: if ($tcrs ne $ucrs) { next; }
7885: }
7886: if ($tsec) {
7887: if ($tsec ne $usec) { next; }
7888: }
7889: $access=($effect eq 'allow');
7890: last;
7891: }
7892: if ($realm eq '' && $role eq '') {
7893: $access=($effect eq 'allow');
7894: }
1.402 bowersj2 7895: }
1.341 www 7896: }
7897: return $access;
7898: }
7899:
1.103 harris41 7900: # ------------------------------------------------- Check for a user privilege
1.12 www 7901:
7902: sub allowed {
1.1172.2.126 raeburn 7903: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705 albertel 7904: my $ver_orguri=$uri;
1.439 www 7905: $uri=&deversion($uri);
1.152 www 7906: my $orguri=$uri;
1.52 www 7907: $uri=&declutter($uri);
1.809 raeburn 7908:
1.810 raeburn 7909: if ($priv eq 'evb') {
7910: # Evade communication block restrictions for specified role in a course
7911: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7912: return $1;
7913: } else {
7914: return;
7915: }
7916: }
7917:
1.620 albertel 7918: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7919: # Free bre access to adm and meta resources
1.1172.2.133 raeburn 7920: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$}))
1.769 albertel 7921: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7922: && ($priv eq 'bre')) {
1.14 www 7923: return 'F';
1.159 www 7924: }
7925:
1.545 banghart 7926: # Free bre access to user's own portfolio contents
1.714 raeburn 7927: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7928: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7929: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7930: my %setters;
1.1172.2.142 raeburn 7931: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7932: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7933: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7934: return 'B';
7935: } else {
7936: return 'F';
7937: }
1.545 banghart 7938: }
7939:
1.762 raeburn 7940: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7941: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7942: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7943: if (exists($env{'request.course.id'})) {
7944: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7945: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7946: if (($domain eq $cdom) && ($name eq $cnum)) {
7947: my $courseprivid=$env{'request.course.id'};
7948: $courseprivid=~s/\_/\//;
7949: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7950: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7951: return $1;
1.762 raeburn 7952: } else {
7953: if ($env{'request.course.sec'}) {
7954: $courseprivid.='/'.$env{'request.course.sec'};
7955: }
7956: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7957: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7958: return $2;
7959: }
1.714 raeburn 7960: }
7961: }
7962: }
7963: }
7964:
1.159 www 7965: # Free bre to public access
7966:
7967: if ($priv eq 'bre') {
1.238 www 7968: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7969: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7970: return 'F';
7971: }
1.238 www 7972: if ($copyright eq 'priv') {
7973: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7974: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7975: return '';
7976: }
7977: }
7978: if ($copyright eq 'domain') {
7979: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7980: unless (($env{'user.domain'} eq $1) ||
7981: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7982: return '';
7983: }
1.262 matthew 7984: }
1.620 albertel 7985: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7986: # Library role, so allow browsing of resources in this domain.
7987: return 'F';
1.238 www 7988: }
1.341 www 7989: if ($copyright eq 'custom') {
7990: unless (&customaccess($priv,$uri)) { return ''; }
7991: }
1.14 www 7992: }
1.264 matthew 7993: # Domain coordinator is trying to create a course
1.620 albertel 7994: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7995: # uri is the requested domain in this case.
7996: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7997: # a role of dc for the domain in question.
1.620 albertel 7998: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7999: }
1.29 www 8000:
1.52 www 8001: my $thisallowed='';
8002: my $statecond=0;
8003: my $courseprivid='';
8004:
1.1039 raeburn 8005: my $ownaccess;
1.1043 raeburn 8006: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8007: if (($priv eq 'bro') && ($env{'user.author'})) {
8008: if ($uri eq '') {
8009: $ownaccess = 1;
8010: } else {
8011: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8012: my $udom = $env{'user.domain'};
8013: my $uname = $env{'user.name'};
8014: if ($uri =~ m{^\Q$udom\E/?$}) {
8015: $ownaccess = 1;
1.1040 raeburn 8016: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8017: unless ($uri =~ m{\.\./}) {
8018: $ownaccess = 1;
8019: }
8020: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8021: my $now = time;
8022: if ($uri =~ m{^([^/]+)/?$}) {
8023: my $adom = $1;
8024: foreach my $key (keys(%env)) {
1.1042 raeburn 8025: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142 raeburn 8026: my ($start,$end) = split(/\./,$env{$key});
8027: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8028: $ownaccess = 1;
8029: last;
8030: }
8031: }
8032: }
8033: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8034: my $adom = $1;
8035: my $aname = $2;
1.1042 raeburn 8036: foreach my $role ('ca','aa') {
8037: if ($env{"user.role.$role./$adom/$aname"}) {
8038: my ($start,$end) =
1.1172.2.142 raeburn 8039: split(/\./,$env{"user.role.$role./$adom/$aname"});
8040: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8041: $ownaccess = 1;
8042: last;
8043: }
1.1039 raeburn 8044: }
8045: }
8046: }
8047: }
8048: }
8049: }
8050: }
8051:
1.52 www 8052: # Course
8053:
1.620 albertel 8054: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8055: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8056: $thisallowed.=$1;
8057: }
1.52 www 8058: }
1.29 www 8059:
1.52 www 8060: # Domain
8061:
1.620 albertel 8062: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8063: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8064: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8065: $thisallowed.=$1;
8066: }
1.12 www 8067: }
1.52 www 8068:
1.1141 raeburn 8069: # User who is not author or co-author might still be able to edit
8070: # resource of an author in the domain (e.g., if Domain Coordinator).
8071: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8072: (&allowed('mdc',$env{'request.course.id'}))) {
8073: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8074: $thisallowed.=$1;
8075: }
8076: }
8077:
1.52 www 8078: # Course: uri itself is a course
1.66 www 8079: my $courseuri=$uri;
8080: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8081: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8082:
1.620 albertel 8083: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8084: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115 raeburn 8085: if ($priv eq 'mip') {
8086: my $rem = $1;
8087: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8088: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8089: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8090: if ($cdom ne '') {
8091: my %passwdconf = &get_passwdconf($cdom);
8092: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8093: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8094: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8095: my @inststatuses = split(':',$env{'environment.inststatus'});
8096: unless (@inststatuses) {
8097: @inststatuses = ('default');
8098: }
8099: foreach my $status (@inststatuses) {
8100: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8101: $thisallowed.=$rem;
8102: }
8103: }
8104: }
8105: }
8106: }
8107: }
8108: }
8109: } else {
8110: unless (($priv eq 'bro') && (!$ownaccess)) {
8111: $thisallowed.=$1;
8112: }
1.1039 raeburn 8113: }
1.12 www 8114: }
1.29 www 8115:
1.665 albertel 8116: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8117: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8118: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8119: $thisallowed='';
1.671 raeburn 8120: my ($match)=&is_on_map($uri);
8121: if ($match) {
8122: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8123: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 8124: my $value = $1;
8125: if ($noblockcheck) {
8126: $thisallowed.=$value;
1.1162 raeburn 8127: } else {
1.1172.2.126 raeburn 8128: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8129: if (@blockers > 0) {
8130: $thisallowed = 'B';
8131: } else {
8132: $thisallowed.=$value;
8133: }
1.1162 raeburn 8134: }
1.671 raeburn 8135: }
8136: } else {
1.705 albertel 8137: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8138: if ($refuri) {
8139: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8140: $thisallowed='F';
1.671 raeburn 8141: } else {
8142: $refuri=&declutter($refuri);
8143: my ($match) = &is_on_map($refuri);
8144: if ($match) {
1.1172.2.65 raeburn 8145: if ($noblockcheck) {
1.1162 raeburn 8146: $thisallowed='F';
1.1172.2.65 raeburn 8147: } else {
1.1172.2.127 raeburn 8148: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8149: if (@blockers > 0) {
8150: $thisallowed = 'B';
8151: } else {
8152: $thisallowed='F';
8153: }
1.1162 raeburn 8154: }
1.671 raeburn 8155: }
1.669 raeburn 8156: }
1.671 raeburn 8157: }
8158: }
1.314 www 8159: }
1.492 albertel 8160:
1.766 albertel 8161: if ($priv eq 'bre'
8162: && $thisallowed ne 'F'
8163: && $thisallowed ne '2'
8164: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 8165: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8166: }
8167:
1.52 www 8168: # Full access at system, domain or course-wide level? Exit.
1.29 www 8169: if ($thisallowed=~/F/) {
8170: return 'F';
8171: }
8172:
1.52 www 8173: # If this is generating or modifying users, exit with special codes
1.29 www 8174:
1.643 www 8175: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8176: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8177: my ($audom,$auname)=split('/',$uri);
1.643 www 8178: # no author name given, so this just checks on the general right to make a co-author in this domain
8179: unless ($auname) { return $thisallowed; }
8180: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8181: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8182: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8183: ($audom ne $env{'request.role.domain'}))) { return ''; }
8184: }
1.52 www 8185: return $thisallowed;
8186: }
8187: #
1.103 harris41 8188: # Gathered so far: system, domain and course wide privileges
1.52 www 8189: #
8190: # Course: See if uri or referer is an individual resource that is part of
8191: # the course
8192:
1.620 albertel 8193: if ($env{'request.course.id'}) {
1.232 www 8194:
1.1172.2.115 raeburn 8195: # If this is modifying password (internal auth) domains must match for user and user's role.
8196:
8197: if ($priv eq 'mip') {
8198: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8199: return $thisallowed;
8200: } else {
8201: return '';
8202: }
8203: }
8204:
1.620 albertel 8205: $courseprivid=$env{'request.course.id'};
8206: if ($env{'request.course.sec'}) {
8207: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8208: }
8209: $courseprivid=~s/\_/\//;
8210: my $checkreferer=1;
1.232 www 8211: my ($match,$cond)=&is_on_map($uri);
8212: if ($match) {
8213: $statecond=$cond;
1.620 albertel 8214: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8215: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8216: my $value = $1;
8217: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8218: if ($noblockcheck) {
1.1162 raeburn 8219: $thisallowed.=$value;
1.1172.2.65 raeburn 8220: } else {
1.1172.2.126 raeburn 8221: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8222: if (@blockers > 0) {
8223: $thisallowed = 'B';
8224: } else {
8225: $thisallowed.=$value;
8226: }
1.1162 raeburn 8227: }
8228: } else {
8229: $thisallowed.=$value;
8230: }
1.52 www 8231: $checkreferer=0;
8232: }
1.29 www 8233: }
1.1172.2.126 raeburn 8234:
1.148 www 8235: if ($checkreferer) {
1.620 albertel 8236: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8237: unless ($refuri) {
1.800 albertel 8238: foreach my $key (keys(%env)) {
8239: if ($key=~/^httpref\..*\*/) {
8240: my $pattern=$key;
1.156 www 8241: $pattern=~s/^httpref\.\/res\///;
1.148 www 8242: $pattern=~s/\*/\[\^\/\]\+/g;
8243: $pattern=~s/\//\\\//g;
1.152 www 8244: if ($orguri=~/$pattern/) {
1.800 albertel 8245: $refuri=$env{$key};
1.148 www 8246: }
8247: }
1.191 harris41 8248: }
1.148 www 8249: }
1.232 www 8250:
1.148 www 8251: if ($refuri) {
1.152 www 8252: $refuri=&declutter($refuri);
1.232 www 8253: my ($match,$cond)=&is_on_map($refuri);
8254: if ($match) {
8255: my $refstatecond=$cond;
1.620 albertel 8256: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8257: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8258: my $value = $1;
8259: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8260: if ($noblockcheck) {
1.1162 raeburn 8261: $thisallowed.=$value;
1.1172.2.65 raeburn 8262: } else {
1.1172.2.127 raeburn 8263: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8264: if (@blockers > 0) {
8265: $thisallowed = 'B';
8266: } else {
8267: $thisallowed.=$value;
8268: }
1.1162 raeburn 8269: }
8270: } else {
8271: $thisallowed.=$value;
8272: }
1.53 www 8273: $uri=$refuri;
8274: $statecond=$refstatecond;
1.52 www 8275: }
8276: }
1.148 www 8277: }
1.29 www 8278: }
1.52 www 8279: }
1.29 www 8280:
1.52 www 8281: #
1.103 harris41 8282: # Gathered now: all privileges that could apply, and condition number
1.52 www 8283: #
8284: #
8285: # Full or no access?
8286: #
1.29 www 8287:
1.52 www 8288: if ($thisallowed=~/F/) {
8289: return 'F';
8290: }
1.29 www 8291:
1.52 www 8292: unless ($thisallowed) {
8293: return '';
8294: }
1.29 www 8295:
1.52 www 8296: # Restrictions exist, deal with them
8297: #
8298: # C:according to course preferences
8299: # R:according to resource settings
8300: # L:unless locked
8301: # X:according to user session state
8302: #
8303:
8304: # Possibly locked functionality, check all courses
1.1172.2.142 raeburn 8305: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8306: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142 raeburn 8307: # courses, and 2 minutes for current course, in which user has st or ta role
8308: # which is neither expired nor a future role (unless current course).
1.52 www 8309:
1.1172.2.142 raeburn 8310: my ($needlockcheck,$now,$crsonly);
1.52 www 8311: if ($thisallowed=~/L/) {
1.1172.2.142 raeburn 8312: $now = time;
8313: if ($priv eq 'bre') {
8314: if ($uri ne '') {
8315: if ($orguri =~ m{^/+res/}) {
8316: if ($uri =~ m{^lib/templates/}) {
8317: if ($env{'request.course.id'}) {
8318: $crsonly = 1;
8319: $needlockcheck = 1;
8320: }
8321: } else {
8322: $needlockcheck = 1;
8323: }
8324: } elsif ($env{'request.course.id'}) {
8325: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8326: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8327: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8328: $crsonly = 1;
8329: }
8330: $needlockcheck = 1;
8331: }
8332: }
8333: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8334: $needlockcheck = 1;
8335: }
8336: }
8337: if ($needlockcheck) {
8338: foreach my $envkey (keys(%env)) {
1.54 www 8339: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8340: my $courseid=$2;
8341: my $roleid=$1.'.'.$2;
1.92 www 8342: $courseid=~s/^\///;
1.1172.2.142 raeburn 8343: unless ($env{'request.role'} eq $roleid) {
8344: my ($start,$end) = split(/\./,$env{$envkey});
8345: next unless (($now >= $start) && (!$end || $end > $now));
8346: }
1.54 www 8347: my $expiretime=600;
1.620 albertel 8348: if ($env{'request.role'} eq $roleid) {
1.54 www 8349: $expiretime=120;
8350: }
8351: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8352: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8353: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8354: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8355: }
1.620 albertel 8356: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8357: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8358: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8359: &log($env{'user.domain'},$env{'user.name'},
8360: $env{'user.home'},
1.57 www 8361: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8362: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8363: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8364: return '';
8365: }
8366: }
1.620 albertel 8367: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8368: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142 raeburn 8369: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8370: &log($env{'user.domain'},$env{'user.name'},
8371: $env{'user.home'},
1.57 www 8372: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8373: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8374: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8375: return '';
8376: }
8377: }
8378: }
1.29 www 8379: }
1.52 www 8380: }
1.1172.2.126 raeburn 8381:
1.52 www 8382: #
8383: # Rest of the restrictions depend on selected course
8384: #
8385:
1.620 albertel 8386: unless ($env{'request.course.id'}) {
1.766 albertel 8387: if ($thisallowed eq 'A') {
8388: return 'A';
1.814 raeburn 8389: } elsif ($thisallowed eq 'B') {
8390: return 'B';
1.766 albertel 8391: } else {
8392: return '1';
8393: }
1.52 www 8394: }
1.29 www 8395:
1.52 www 8396: #
8397: # Now user is definitely in a course
8398: #
1.53 www 8399:
8400:
8401: # Course preferences
8402:
8403: if ($thisallowed=~/C/) {
1.620 albertel 8404: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8405: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8406: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8407: =~/\Q$rolecode\E/) {
1.1103 raeburn 8408: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8409: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8410: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8411: $env{'request.course.id'});
8412: }
1.237 www 8413: return '';
8414: }
8415:
1.620 albertel 8416: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8417: =~/\Q$unamedom\E/) {
1.1103 raeburn 8418: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8419: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8420: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8421: $env{'request.course.id'});
8422: }
1.54 www 8423: return '';
8424: }
1.53 www 8425: }
8426:
8427: # Resource preferences
8428:
8429: if ($thisallowed=~/R/) {
1.620 albertel 8430: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8431: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8432: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8433: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8434: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8435: }
8436: return '';
1.54 www 8437: }
1.53 www 8438: }
1.30 www 8439:
1.246 www 8440: # Restricted by state or randomout?
1.30 www 8441:
1.52 www 8442: if ($thisallowed=~/X/) {
1.620 albertel 8443: if ($env{'acc.randomout'}) {
1.579 albertel 8444: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8445: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8446: return '';
8447: }
1.247 www 8448: }
8449: if (&condval($statecond)) {
1.52 www 8450: return '2';
8451: } else {
8452: return '';
8453: }
8454: }
1.30 www 8455:
1.766 albertel 8456: if ($thisallowed eq 'A') {
8457: return 'A';
1.814 raeburn 8458: } elsif ($thisallowed eq 'B') {
8459: return 'B';
1.766 albertel 8460: }
1.52 www 8461: return 'F';
1.232 www 8462: }
1.1162 raeburn 8463:
1.1172.2.13 raeburn 8464: # ------------------------------------------- Check construction space access
8465:
8466: sub constructaccess {
8467: my ($url,$setpriv)=@_;
8468:
8469: # We do not allow editing of previous versions of files
8470: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8471:
8472: # Get username and domain from URL
8473: my ($ownername,$ownerdomain,$ownerhome);
8474:
8475: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 8476: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 8477:
8478: # The URL does not really point to any authorspace, forget it
8479: unless (($ownername) && ($ownerdomain)) { return ''; }
8480:
8481: # Now we need to see if the user has access to the authorspace of
8482: # $ownername at $ownerdomain
8483:
8484: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8485: # Real author for this?
8486: $ownerhome = $env{'user.home'};
8487: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8488: return ($ownername,$ownerdomain,$ownerhome);
8489: }
8490: } else {
8491: # Co-author for this?
8492: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8493: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8494: $ownerhome = &homeserver($ownername,$ownerdomain);
8495: return ($ownername,$ownerdomain,$ownerhome);
8496: }
8497: }
8498:
8499: # We don't have any access right now. If we are not possibly going to do anything about this,
8500: # we might as well leave
8501: unless ($setpriv) { return ''; }
8502:
8503: # Backdoor access?
8504: my $allowed=&allowed('eco',$ownerdomain);
8505: # Nope
8506: unless ($allowed) { return ''; }
8507: # Looks like we may have access, but could be locked by the owner of the construction space
8508: if ($allowed eq 'U') {
8509: my %blocked=&get('environment',['domcoord.author'],
8510: $ownerdomain,$ownername);
8511: # Is blocked by owner
8512: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8513: }
8514: if (($allowed eq 'F') || ($allowed eq 'U')) {
8515: # Grant temporary access
8516: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 8517: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 8518: if (!$update) { $update = $then; }
8519: my $refresh=$env{'user.refresh.time'};
8520: if (!$refresh) { $refresh = $update; }
8521: my $now = time;
8522: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8523: $now,'ca','constructaccess');
8524: $ownerhome = &homeserver($ownername,$ownerdomain);
8525: return($ownername,$ownerdomain,$ownerhome);
8526: }
8527: # No business here
8528: return '';
8529: }
8530:
1.1172.2.66 raeburn 8531: # ----------------------------------------------------------- Content Blocking
8532:
8533: {
8534: # Caches for faster Course Contents display where content blocking
8535: # is in operation (i.e., interval param set) for timed quiz.
8536: #
8537: # User for whom data are being temporarily cached.
8538: my $cacheduser='';
1.1172.2.126 raeburn 8539: # Course for which data are being temporarily cached.
8540: my $cachedcid='';
1.1172.2.66 raeburn 8541: # Cached blockers for this user (a hash of blocking items).
8542: my %cachedblockers=();
8543: # When the data were last cached.
8544: my $cachedlast='';
8545:
8546: sub load_all_blockers {
1.1172.2.128 raeburn 8547: my ($uname,$udom)=@_;
1.1172.2.66 raeburn 8548: if (($uname ne '') && ($udom ne '')) {
8549: if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126 raeburn 8550: ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128 raeburn 8551: (abs($cachedlast-time)<5)) {
1.1172.2.66 raeburn 8552: return;
8553: }
8554: }
8555: $cachedlast=time;
8556: $cacheduser=$uname.':'.$udom;
1.1172.2.126 raeburn 8557: $cachedcid=$env{'request.course.id'};
1.1172.2.128 raeburn 8558: %cachedblockers = &get_commblock_resources();
1.1172.2.126 raeburn 8559: return;
1.1172.2.66 raeburn 8560: }
8561:
1.1162 raeburn 8562: sub get_comm_blocks {
8563: my ($cdom,$cnum) = @_;
8564: if ($cdom eq '' || $cnum eq '') {
8565: return unless ($env{'request.course.id'});
8566: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8567: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8568: }
8569: my %commblocks;
8570: my $hashid=$cdom.'_'.$cnum;
8571: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8572: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8573: %commblocks = %{$blocksref};
8574: } else {
8575: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8576: my $cachetime = 600;
8577: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8578: }
8579: return %commblocks;
8580: }
8581:
1.1172.2.66 raeburn 8582: sub get_commblock_resources {
8583: my ($blocks) = @_;
8584: my %blockers = ();
8585: return %blockers unless ($env{'request.course.id'});
1.1172.2.142 raeburn 8586: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8587: if ($env{'request.course.sec'}) {
8588: $courseurl .= '/'.$env{'request.course.sec'};
8589: }
8590: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 8591: my %commblocks;
8592: if (ref($blocks) eq 'HASH') {
8593: %commblocks = %{$blocks};
8594: } else {
8595: %commblocks = &get_comm_blocks();
8596: }
1.1172.2.66 raeburn 8597: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 8598: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 8599: return %blockers unless (ref($navmap));
8600: my $now = time;
1.1162 raeburn 8601: foreach my $block (keys(%commblocks)) {
8602: if ($block =~ /^(\d+)____(\d+)$/) {
8603: my ($start,$end) = ($1,$2);
8604: if ($start <= $now && $end >= $now) {
8605: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8606: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8607: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 8608: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8609: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8610: }
8611: }
8612: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 8613: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8614: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8615: }
8616: }
8617: }
8618: }
8619: }
8620: } elsif ($block =~ /^firstaccess____(.+)$/) {
8621: my $item = $1;
8622: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8623: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142 raeburn 8624: my (@interval,$mapname);
1.1172.2.66 raeburn 8625: my $type = 'map';
8626: if ($item eq 'course') {
8627: $type = 'course';
8628: @interval=&EXT("resource.0.interval");
8629: } else {
8630: if ($item =~ /___\d+___/) {
8631: $type = 'resource';
8632: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 8633: } else {
1.1172.2.142 raeburn 8634: $mapname = &deversion($item);
8635: if (ref($navmap)) {
8636: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
8637: @interval = ($timelimit,'map');
1.1162 raeburn 8638: }
8639: }
1.1172.2.66 raeburn 8640: }
8641: if ($interval[0] =~ /^\d+$/) {
8642: my $first_access;
8643: if ($type eq 'resource') {
8644: $first_access=&get_first_access($interval[1],$item);
8645: } elsif ($type eq 'map') {
8646: $first_access=&get_first_access($interval[1],undef,$item);
8647: } else {
8648: $first_access=&get_first_access($interval[1]);
8649: }
8650: if ($first_access) {
8651: my $timesup = $first_access+$interval[0];
8652: if ($timesup > $now) {
8653: my $activeblock;
1.1172.2.142 raeburn 8654: if ($type eq 'resource') {
8655: if (ref($navmap)) {
8656: my $res = $navmap->getBySymb($item);
8657: if ($res->answerable()) {
8658: $activeblock = 1;
8659: }
8660: }
8661: } elsif ($type eq 'map') {
8662: my $mapsymb = &symbread($mapname,1);
8663: if (($mapsymb) && (ref($navmap))) {
8664: my $mapres = $navmap->getBySymb($mapsymb);
8665: if (ref($mapres)) {
8666: my $first = $mapres->map_start();
8667: my $finish = $mapres->map_finish();
8668: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8669: if (ref($it)) {
8670: my $res;
8671: while ($res = $it->next(undef,1)) {
8672: next unless (ref($res));
8673: my $symb = $res->symb();
8674: next if (($symb eq $mapsymb) || ($symb eq ''));
8675: @interval=&EXT("resource.0.interval",$symb);
8676: if ($interval[1] eq 'map') {
8677: if ($res->answerable()) {
8678: $activeblock = 1;
8679: last;
8680: }
8681: }
8682: }
8683: }
8684: }
1.1172.2.66 raeburn 8685: }
8686: }
8687: if ($activeblock) {
8688: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8689: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8690: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8691: }
8692: }
8693: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8694: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8695: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8696: }
1.1162 raeburn 8697: }
8698: }
8699: }
8700: }
8701: }
8702: }
8703: }
8704: }
8705: }
1.1172.2.66 raeburn 8706: return %blockers;
1.1162 raeburn 8707: }
8708:
1.1172.2.66 raeburn 8709: sub has_comm_blocking {
1.1172.2.128 raeburn 8710: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66 raeburn 8711: my @blockers;
8712: return unless ($env{'request.course.id'});
8713: return unless ($priv eq 'bre');
8714: return if ($env{'request.state'} eq 'construct');
1.1172.2.142 raeburn 8715: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8716: if ($env{'request.course.sec'}) {
8717: $courseurl .= '/'.$env{'request.course.sec'};
8718: }
8719: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128 raeburn 8720: my %blockinfo;
8721: if (ref($blocks) eq 'HASH') {
8722: %blockinfo = &get_commblock_resources($blocks);
8723: } else {
8724: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8725: %blockinfo = %cachedblockers;
8726: }
8727: return unless (keys(%blockinfo) > 0);
1.1172.2.66 raeburn 8728: my (%possibles,@symbs);
8729: if (!$symb) {
1.1172.2.128 raeburn 8730: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 8731: }
1.1172.2.66 raeburn 8732: if ($symb) {
8733: @symbs = ($symb);
8734: } elsif (keys(%possibles)) {
8735: @symbs = keys(%possibles);
8736: }
8737: my $noblock;
8738: foreach my $symb (@symbs) {
8739: last if ($noblock);
8740: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128 raeburn 8741: foreach my $block (keys(%blockinfo)) {
1.1172.2.66 raeburn 8742: if ($block =~ /^firstaccess____(.+)$/) {
8743: my $item = $1;
1.1172.2.126 raeburn 8744: unless ($blocked) {
8745: if (($item eq $map) || ($item eq $symb)) {
8746: $noblock = 1;
8747: last;
8748: }
1.1172.2.66 raeburn 8749: }
1.1162 raeburn 8750: }
1.1172.2.128 raeburn 8751: if (ref($blockinfo{$block}) eq 'HASH') {
8752: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8753: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66 raeburn 8754: unless (grep(/^\Q$block\E$/,@blockers)) {
8755: push(@blockers,$block);
8756: }
8757: }
8758: }
1.1172.2.128 raeburn 8759: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8760: if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126 raeburn 8761: unless (grep(/^\Q$block\E$/,@blockers)) {
8762: push(@blockers,$block);
8763: }
1.1172.2.66 raeburn 8764: }
8765: }
1.1162 raeburn 8766: }
8767: }
8768: }
1.1172.2.126 raeburn 8769: unless ($noblock) {
8770: return @blockers;
8771: }
8772: return;
1.1172.2.66 raeburn 8773: }
1.1162 raeburn 8774: }
8775:
1.1172.2.66 raeburn 8776: # -------------------------------- Deversion and split uri into path an filename
8777:
1.1133 foxr 8778: #
1.1172.2.66 raeburn 8779: # Removes the version from a URI and
1.1133 foxr 8780: # splits it in to its filename and path to the filename.
8781: # Seems like File::Basename could have done this more clearly.
8782: # Parameters:
8783: # $uri - input URI
8784: # Returns:
8785: # Two element list consisting of
8786: # $pathname - the URI up to and excluding the trailing /
8787: # $filename - The part of the URI following the last /
8788: # NOTE:
8789: # Another realization of this is simply:
8790: # use File::Basename;
8791: # ...
8792: # $uri = shift;
8793: # $filename = basename($uri);
8794: # $path = dirname($uri);
8795: # return ($filename, $path);
8796: #
8797: # The implementation below is probably faster however.
8798: #
1.710 albertel 8799: sub split_uri_for_cond {
8800: my $uri=&deversion(&declutter(shift));
8801: my @uriparts=split(/\//,$uri);
8802: my $filename=pop(@uriparts);
8803: my $pathname=join('/',@uriparts);
8804: return ($pathname,$filename);
8805: }
1.232 www 8806: # --------------------------------------------------- Is a resource on the map?
8807:
8808: sub is_on_map {
1.710 albertel 8809: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8810: #Trying to find the conditional for the file
1.620 albertel 8811: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8812: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8813: if ($match) {
1.289 bowersj2 8814: return (1,$1);
8815: } else {
1.434 www 8816: return (0,0);
1.289 bowersj2 8817: }
1.12 www 8818: }
8819:
1.427 www 8820: # --------------------------------------------------------- Get symb from alias
8821:
8822: sub get_symb_from_alias {
8823: my $symb=shift;
8824: my ($map,$resid,$url)=&decode_symb($symb);
8825: # Already is a symb
8826: if ($url) { return $symb; }
8827: # Must be an alias
8828: my $aliassymb='';
8829: my %bighash;
1.620 albertel 8830: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8831: &GDBM_READER(),0640)) {
8832: my $rid=$bighash{'mapalias_'.$symb};
8833: if ($rid) {
8834: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8835: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8836: $resid,$bighash{'src_'.$rid});
1.427 www 8837: }
8838: untie %bighash;
8839: }
8840: return $aliassymb;
8841: }
8842:
1.12 www 8843: # ----------------------------------------------------------------- Define Role
8844:
8845: sub definerole {
8846: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8847: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8848: foreach my $role (split(':',$sysrole)) {
8849: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8850: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8851: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8852: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8853: return "refused:s:$crole&$cqual";
8854: }
8855: }
1.191 harris41 8856: }
1.800 albertel 8857: foreach my $role (split(':',$domrole)) {
8858: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8859: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8860: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8861: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8862: return "refused:d:$crole&$cqual";
8863: }
8864: }
1.191 harris41 8865: }
1.800 albertel 8866: foreach my $role (split(':',$courole)) {
8867: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8868: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8869: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8870: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8871: return "refused:c:$crole&$cqual";
8872: }
8873: }
1.191 harris41 8874: }
1.1172.2.84 raeburn 8875: my $uhome;
8876: if (($uname ne '') && ($udom ne '')) {
8877: $uhome = &homeserver($uname,$udom);
8878: return $uhome if ($uhome eq 'no_host');
8879: } else {
8880: $uname = $env{'user.name'};
8881: $udom = $env{'user.domain'};
8882: $uhome = $env{'user.home'};
8883: }
1.620 albertel 8884: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8885: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8886: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8887: return reply($command,$uhome);
1.12 www 8888: } else {
8889: return 'refused';
8890: }
1.105 harris41 8891: }
8892:
8893: # ---------------- Make a metadata query against the network of library servers
8894:
8895: sub metadata_query {
1.1172.2.33 raeburn 8896: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8897: my %rhash;
1.845 albertel 8898: my %libserv = &all_library();
1.244 matthew 8899: my @server_list = (defined($server_array) ? @$server_array
8900: : keys(%libserv) );
8901: for my $server (@server_list) {
1.1172.2.33 raeburn 8902: my $domains = '';
8903: if (ref($domains_hash) eq 'HASH') {
8904: $domains = $domains_hash->{$server};
8905: }
1.118 harris41 8906: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8907: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8908: $rhash{$server}=$reply;
8909: }
8910: else {
8911: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8912: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8913: $server);
8914: $rhash{$server}=$reply;
8915: }
1.112 harris41 8916: }
1.118 harris41 8917: return \%rhash;
1.240 www 8918: }
8919:
8920: # ----------------------------------------- Send log queries and wait for reply
8921:
8922: sub log_query {
8923: my ($uname,$udom,$query,%filters)=@_;
8924: my $uhome=&homeserver($uname,$udom);
8925: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8926: my $uhost=&hostname($uhome);
1.800 albertel 8927: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8928: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8929: $uhome);
1.479 albertel 8930: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8931: return get_query_reply($queryid);
8932: }
8933:
1.818 raeburn 8934: # -------------------------- Update MySQL table for portfolio file
8935:
8936: sub update_portfolio_table {
1.821 raeburn 8937: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8938: if ($group ne '') {
8939: $file_name =~s /^\Q$group\E//;
8940: }
1.818 raeburn 8941: my $homeserver = &homeserver($uname,$udom);
8942: my $queryid=
1.821 raeburn 8943: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8944: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8945: my $reply = &get_query_reply($queryid);
8946: return $reply;
8947: }
8948:
1.899 raeburn 8949: # -------------------------- Update MySQL allusers table
8950:
8951: sub update_allusers_table {
8952: my ($uname,$udom,$names) = @_;
8953: my $homeserver = &homeserver($uname,$udom);
8954: my $queryid=
8955: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8956: 'lastname='.&escape($names->{'lastname'}).'%%'.
8957: 'firstname='.&escape($names->{'firstname'}).'%%'.
8958: 'middlename='.&escape($names->{'middlename'}).'%%'.
8959: 'generation='.&escape($names->{'generation'}).'%%'.
8960: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8961: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8962: return;
1.899 raeburn 8963: }
8964:
1.508 raeburn 8965: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8966:
8967: sub fetch_enrollment_query {
1.511 raeburn 8968: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8969: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8970: my $maxtries = 1;
1.508 raeburn 8971: if ($context eq 'automated') {
8972: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8973: $sleep = 2;
8974: $loopmax = 100;
1.547 raeburn 8975: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8976: } else {
8977: $homeserver = &homeserver($cnum,$dom);
8978: }
1.838 albertel 8979: my $host=&hostname($homeserver);
1.506 raeburn 8980: my $cmd = '';
1.1000 raeburn 8981: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8982: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8983: }
8984: $cmd =~ s/%%$//;
8985: $cmd = &escape($cmd);
8986: my $query = 'fetchenrollment';
1.620 albertel 8987: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8988: unless ($queryid=~/^\Q$host\E\_/) {
8989: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8990: return 'error: '.$queryid;
8991: }
1.1172.2.93 raeburn 8992: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8993: my $tries = 1;
8994: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8995: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8996: $tries ++;
8997: }
1.526 raeburn 8998: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8999: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9000: } else {
1.901 albertel 9001: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 9002: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9003: foreach my $line (@responses) {
9004: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9005: $$replyref{$key} = $value;
9006: }
9007: } else {
1.1117 foxr 9008: my $pathname = LONCAPA::tempdir();
1.800 albertel 9009: foreach my $line (@responses) {
9010: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9011: $$replyref{$key} = $value;
9012: if ($value > 0) {
1.800 albertel 9013: foreach my $item (@{$$affiliatesref{$key}}) {
9014: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9015: my $destname = $pathname.'/'.$filename;
9016: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9017: if ($xml_classlist =~ /^error/) {
9018: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9019: } else {
1.1172.2.96 raeburn 9020: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9021: print FILE &unescape($xml_classlist);
9022: close(FILE);
1.526 raeburn 9023: } else {
9024: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9025: }
9026: }
9027: }
9028: }
9029: }
9030: }
9031: return 'ok';
9032: }
9033: return 'error';
9034: }
9035:
1.242 www 9036: sub get_query_reply {
1.1172.2.79 raeburn 9037: my ($queryid,$sleep,$loopmax) = @_;
9038: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9039: $sleep = 0.2;
9040: }
9041: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9042: $loopmax = 100;
9043: }
1.1117 foxr 9044: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9045: my $reply='';
1.1172.2.79 raeburn 9046: for (1..$loopmax) {
9047: sleep($sleep);
1.240 www 9048: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 9049: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9050: $reply = join('',<$fh>);
9051: close($fh);
1.240 www 9052: } else { return 'error: reply_file_error'; }
1.242 www 9053: return &unescape($reply);
9054: }
1.240 www 9055: }
1.242 www 9056: return 'timeout:'.$queryid;
1.240 www 9057: }
9058:
9059: sub courselog_query {
1.241 www 9060: #
9061: # possible filters:
9062: # url: url or symb
9063: # username
9064: # domain
9065: # action: view, submit, grade
9066: # start: timestamp
9067: # end: timestamp
9068: #
1.240 www 9069: my (%filters)=@_;
1.620 albertel 9070: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9071: if ($filters{'url'}) {
9072: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9073: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9074: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9075: }
1.620 albertel 9076: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9077: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9078: return &log_query($cname,$cdom,'courselog',%filters);
9079: }
9080:
9081: sub userlog_query {
1.858 raeburn 9082: #
9083: # possible filters:
9084: # action: log check role
9085: # start: timestamp
9086: # end: timestamp
9087: #
1.240 www 9088: my ($uname,$udom,%filters)=@_;
9089: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9090: }
9091:
1.506 raeburn 9092: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9093:
9094: sub auto_run {
1.508 raeburn 9095: my ($cnum,$cdom) = @_;
1.876 raeburn 9096: my $response = 0;
9097: my $settings;
9098: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9099: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9100: $settings = $domconfig{'autoenroll'};
9101: if ($settings->{'run'} eq '1') {
9102: $response = 1;
9103: }
9104: } else {
1.934 raeburn 9105: my $homeserver;
9106: if (&is_course($cdom,$cnum)) {
9107: $homeserver = &homeserver($cnum,$cdom);
9108: } else {
9109: $homeserver = &domain($cdom,'primary');
9110: }
9111: if ($homeserver ne 'no_host') {
9112: $response = &reply('autorun:'.$cdom,$homeserver);
9113: }
1.876 raeburn 9114: }
1.506 raeburn 9115: return $response;
9116: }
1.776 albertel 9117:
1.506 raeburn 9118: sub auto_get_sections {
1.508 raeburn 9119: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9120: my $homeserver;
9121: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9122: $homeserver = &homeserver($cnum,$cdom);
9123: }
9124: if (!defined($homeserver)) {
9125: if ($cdom =~ /^$match_domain$/) {
9126: $homeserver = &domain($cdom,'primary');
9127: }
9128: }
9129: my @secs;
9130: if (defined($homeserver)) {
9131: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9132: unless ($response eq 'refused') {
9133: @secs = split(/:/,$response);
9134: }
1.506 raeburn 9135: }
9136: return @secs;
9137: }
1.776 albertel 9138:
1.506 raeburn 9139: sub auto_new_course {
1.1099 raeburn 9140: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9141: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9142: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9143: return $response;
9144: }
1.776 albertel 9145:
1.506 raeburn 9146: sub auto_validate_courseID {
1.508 raeburn 9147: my ($cnum,$cdom,$inst_course_id) = @_;
9148: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9149: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9150: return $response;
9151: }
1.776 albertel 9152:
1.1007 raeburn 9153: sub auto_validate_instcode {
1.1020 raeburn 9154: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9155: my ($homeserver,$response);
9156: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9157: $homeserver = &homeserver($cnum,$cdom);
9158: }
9159: if (!defined($homeserver)) {
9160: if ($cdom =~ /^$match_domain$/) {
9161: $homeserver = &domain($cdom,'primary');
9162: }
9163: }
1.1065 raeburn 9164: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9165: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 9166: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9167: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9168: }
9169:
1.1172.2.141 raeburn 9170: sub auto_validate_inst_crosslist {
9171: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9172: my ($homeserver,$response);
9173: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9174: $homeserver = &homeserver($cnum,$cdom);
9175: }
9176: if (!defined($homeserver)) {
9177: if ($cdom =~ /^$match_domain$/) {
9178: $homeserver = &domain($cdom,'primary');
9179: }
9180: }
9181: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9182: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9183: &escape($instcode).':'.&escape($inst_xlist).':'.
9184: &escape($coowner),$homeserver);
9185: }
9186: return $response;
9187: }
9188:
1.506 raeburn 9189: sub auto_create_password {
1.873 raeburn 9190: my ($cnum,$cdom,$authparam,$udom) = @_;
9191: my ($homeserver,$response);
1.506 raeburn 9192: my $create_passwd = 0;
9193: my $authchk = '';
1.873 raeburn 9194: if ($udom =~ /^$match_domain$/) {
9195: $homeserver = &domain($udom,'primary');
9196: }
9197: if ($homeserver eq '') {
9198: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9199: $homeserver = &homeserver($cnum,$cdom);
9200: }
9201: }
9202: if ($homeserver eq '') {
9203: $authchk = 'nodomain';
1.506 raeburn 9204: } else {
1.873 raeburn 9205: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9206: if ($response eq 'refused') {
9207: $authchk = 'refused';
9208: } else {
1.901 albertel 9209: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9210: }
1.506 raeburn 9211: }
9212: return ($authparam,$create_passwd,$authchk);
9213: }
9214:
1.706 raeburn 9215: sub auto_photo_permission {
9216: my ($cnum,$cdom,$students) = @_;
9217: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9218: my ($outcome,$perm_reqd,$conditions) =
9219: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9220: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9221: return (undef,undef);
9222: }
1.706 raeburn 9223: return ($outcome,$perm_reqd,$conditions);
9224: }
9225:
9226: sub auto_checkphotos {
9227: my ($uname,$udom,$pid) = @_;
9228: my $homeserver = &homeserver($uname,$udom);
9229: my ($result,$resulttype);
9230: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9231: &escape($uname).':'.&escape($pid),
9232: $homeserver));
1.709 albertel 9233: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9234: return (undef,undef);
9235: }
1.706 raeburn 9236: if ($outcome) {
9237: ($result,$resulttype) = split(/:/,$outcome);
9238: }
9239: return ($result,$resulttype);
9240: }
9241:
9242: sub auto_photochoice {
9243: my ($cnum,$cdom) = @_;
9244: my $homeserver = &homeserver($cnum,$cdom);
9245: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9246: &escape($cdom),
9247: $homeserver)));
1.709 albertel 9248: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9249: return (undef,undef);
9250: }
1.706 raeburn 9251: return ($update,$comment);
9252: }
9253:
9254: sub auto_photoupdate {
9255: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9256: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9257: my $host=&hostname($homeserver);
1.706 raeburn 9258: my $cmd = '';
9259: my $maxtries = 1;
1.800 albertel 9260: foreach my $affiliate (keys(%{$affiliatesref})) {
9261: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9262: }
9263: $cmd =~ s/%%$//;
9264: $cmd = &escape($cmd);
9265: my $query = 'institutionalphotos';
9266: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9267: unless ($queryid=~/^\Q$host\E\_/) {
9268: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9269: return 'error: '.$queryid;
9270: }
9271: my $reply = &get_query_reply($queryid);
9272: my $tries = 1;
9273: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9274: $reply = &get_query_reply($queryid);
9275: $tries ++;
9276: }
9277: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9278: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9279: } else {
9280: my @responses = split(/:/,$reply);
9281: my $outcome = shift(@responses);
9282: foreach my $item (@responses) {
9283: my ($key,$value) = split(/=/,$item);
9284: $$photo{$key} = $value;
9285: }
9286: return $outcome;
9287: }
9288: return 'error';
9289: }
9290:
1.521 raeburn 9291: sub auto_instcode_format {
1.793 albertel 9292: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9293: $cat_order) = @_;
1.521 raeburn 9294: my $courses = '';
1.772 raeburn 9295: my @homeservers;
1.521 raeburn 9296: if ($caller eq 'global') {
1.841 albertel 9297: my %servers = &get_servers($codedom,'library');
9298: foreach my $tryserver (keys(%servers)) {
9299: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9300: push(@homeservers,$tryserver);
9301: }
1.584 raeburn 9302: }
1.1022 raeburn 9303: } elsif ($caller eq 'requests') {
9304: if ($codedom =~ /^$match_domain$/) {
9305: my $chome = &domain($codedom,'primary');
9306: unless ($chome eq 'no_host') {
9307: push(@homeservers,$chome);
9308: }
9309: }
1.521 raeburn 9310: } else {
1.772 raeburn 9311: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9312: }
1.793 albertel 9313: foreach my $code (keys(%{$instcodes})) {
9314: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9315: }
9316: chop($courses);
1.772 raeburn 9317: my $ok_response = 0;
9318: my $response;
9319: while (@homeservers > 0 && $ok_response == 0) {
9320: my $server = shift(@homeservers);
9321: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9322: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9323: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9324: split(/:/,$response);
1.772 raeburn 9325: %{$codes} = (%{$codes},&str2hash($codes_str));
9326: push(@{$codetitles},&str2array($codetitles_str));
9327: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9328: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9329: $ok_response = 1;
9330: }
9331: }
9332: if ($ok_response) {
1.521 raeburn 9333: return 'ok';
1.772 raeburn 9334: } else {
9335: return $response;
1.521 raeburn 9336: }
9337: }
9338:
1.792 raeburn 9339: sub auto_instcode_defaults {
9340: my ($domain,$returnhash,$code_order) = @_;
9341: my @homeservers;
1.841 albertel 9342:
9343: my %servers = &get_servers($domain,'library');
9344: foreach my $tryserver (keys(%servers)) {
9345: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9346: push(@homeservers,$tryserver);
9347: }
1.792 raeburn 9348: }
1.841 albertel 9349:
1.792 raeburn 9350: my $response;
1.841 albertel 9351: foreach my $server (@homeservers) {
1.792 raeburn 9352: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9353: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9354:
9355: foreach my $pair (split(/\&/,$response)) {
9356: my ($name,$value)=split(/\=/,$pair);
9357: if ($name eq 'code_order') {
9358: @{$code_order} = split(/\&/,&unescape($value));
9359: } else {
9360: $returnhash->{&unescape($name)}=&unescape($value);
9361: }
9362: }
9363: return 'ok';
1.792 raeburn 9364: }
1.841 albertel 9365:
9366: return $response;
1.1003 raeburn 9367: }
9368:
9369: sub auto_possible_instcodes {
1.1007 raeburn 9370: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9371: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9372: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9373: return;
9374: }
1.1003 raeburn 9375: my (@homeservers,$uhome);
9376: if (defined(&domain($domain,'primary'))) {
9377: $uhome=&domain($domain,'primary');
9378: push(@homeservers,&domain($domain,'primary'));
9379: } else {
9380: my %servers = &get_servers($domain,'library');
9381: foreach my $tryserver (keys(%servers)) {
9382: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9383: push(@homeservers,$tryserver);
9384: }
9385: }
9386: }
9387: my $response;
9388: foreach my $server (@homeservers) {
9389: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9390: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9391: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9392: split(':',$response);
9393: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9394: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9395: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9396: my ($name,$value)=split('=',$item);
9397: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9398: }
9399: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9400: my ($name,$value)=split('=',$item);
9401: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9402: }
9403: return 'ok';
9404: }
9405: return $response;
9406: }
1.792 raeburn 9407:
1.1010 raeburn 9408: sub auto_courserequest_checks {
9409: my ($dom) = @_;
1.1020 raeburn 9410: my ($homeserver,%validations);
9411: if ($dom =~ /^$match_domain$/) {
9412: $homeserver = &domain($dom,'primary');
9413: }
9414: unless ($homeserver eq 'no_host') {
9415: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9416: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9417: my @items = split(/&/,$response);
9418: foreach my $item (@items) {
9419: my ($key,$value) = split('=',$item);
9420: $validations{&unescape($key)} = &thaw_unescape($value);
9421: }
9422: }
9423: }
1.1010 raeburn 9424: return %validations;
9425: }
9426:
1.1020 raeburn 9427: sub auto_courserequest_validation {
1.1172.2.43 raeburn 9428: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9429: my ($homeserver,$response);
9430: if ($dom =~ /^$match_domain$/) {
9431: $homeserver = &domain($dom,'primary');
9432: }
1.1172.2.43 raeburn 9433: unless ($homeserver eq 'no_host') {
9434: my $customdata;
9435: if (ref($custominfo) eq 'HASH') {
9436: $customdata = &freeze_escape($custominfo);
9437: }
1.1020 raeburn 9438: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9439: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 9440: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9441: $customdata,$homeserver));
1.1020 raeburn 9442: }
9443: return $response;
9444: }
9445:
1.777 albertel 9446: sub auto_validate_class_sec {
1.918 raeburn 9447: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9448: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9449: my $ownerlist;
9450: if (ref($owners) eq 'ARRAY') {
9451: $ownerlist = join(',',@{$owners});
9452: } else {
9453: $ownerlist = $owners;
9454: }
1.773 raeburn 9455: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9456: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9457: return $response;
9458: }
9459:
1.1172.2.141 raeburn 9460: sub auto_instsec_reformat {
9461: my ($cdom,$action,$instsecref) = @_;
9462: return unless(($action eq 'clutter') || ($action eq 'declutter'));
9463: my @homeservers;
9464: if (defined(&domain($cdom,'primary'))) {
9465: push(@homeservers,&domain($cdom,'primary'));
9466: } else {
9467: my %servers = &get_servers($cdom,'library');
9468: foreach my $tryserver (keys(%servers)) {
9469: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9470: push(@homeservers,$tryserver);
9471: }
9472: }
9473: }
9474: my $response;
9475: my %reformatted = %{$instsecref};
9476: foreach my $server (@homeservers) {
9477: if (ref($instsecref) eq 'HASH') {
9478: my $info = &freeze_escape($instsecref);
9479: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
9480: $action.':'.$info,$server);
9481: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
9482: my @items = split(/&/,$response);
9483: foreach my $item (@items) {
9484: my ($key,$value) = split(/=/,$item);
9485: $reformatted{&unescape($key)} = &thaw_unescape($value);
9486: }
9487: }
9488: }
9489: return %reformatted;
9490: }
9491:
1.1172.2.94 raeburn 9492: sub auto_validate_instclasses {
9493: my ($cdom,$cnum,$owners,$classesref) = @_;
9494: my ($homeserver,%validations);
9495: $homeserver = &homeserver($cnum,$cdom);
9496: unless ($homeserver eq 'no_host') {
9497: my $ownerlist;
9498: if (ref($owners) eq 'ARRAY') {
9499: $ownerlist = join(',',@{$owners});
9500: } else {
9501: $ownerlist = $owners;
9502: }
9503: if (ref($classesref) eq 'HASH') {
9504: my $classes = &freeze_escape($classesref);
9505: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9506: ':'.$cdom.':'.$classes,$homeserver);
9507: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9508: my @items = split(/&/,$response);
9509: foreach my $item (@items) {
9510: my ($key,$value) = split('=',$item);
9511: $validations{&unescape($key)} = &thaw_unescape($value);
9512: }
9513: }
9514: }
9515: }
9516: return %validations;
9517: }
9518:
1.1172.2.38 raeburn 9519: sub auto_crsreq_update {
9520: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 9521: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 9522: my ($homeserver,%crsreqresponse);
9523: if ($cdom =~ /^$match_domain$/) {
9524: $homeserver = &domain($cdom,'primary');
9525: }
9526: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9527: my $info;
9528: if (ref($inbound) eq 'HASH') {
9529: $info = &freeze_escape($inbound);
9530: }
9531: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9532: ':'.&escape($action).':'.&escape($ownername).':'.
9533: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 9534: &escape($title).':'.&escape($code).':'.
9535: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 9536: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9537: my @items = split(/&/,$response);
9538: foreach my $item (@items) {
9539: my ($key,$value) = split('=',$item);
9540: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9541: }
9542: }
9543: }
9544: return \%crsreqresponse;
9545: }
9546:
1.1172.2.78 raeburn 9547: sub auto_export_grades {
9548: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9549: my ($homeserver,%exportresponse);
9550: if ($cdom =~ /^$match_domain$/) {
9551: $homeserver = &domain($cdom,'primary');
9552: }
9553: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9554: my $info;
9555: if (ref($inforef) eq 'HASH') {
9556: $info = &freeze_escape($inforef);
9557: }
9558: if (ref($gradesref) eq 'HASH') {
9559: my $grades = &freeze_escape($gradesref);
9560: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9561: $info.':'.$grades,$homeserver);
9562: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9563: my @items = split(/&/,$response);
9564: foreach my $item (@items) {
9565: my ($key,$value) = split('=',$item);
9566: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9567: }
9568: }
9569: }
9570: }
9571: return \%exportresponse;
9572: }
9573:
1.1172.2.68 raeburn 9574: sub check_instcode_cloning {
9575: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9576: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9577: return;
9578: }
9579: my $canclone;
9580: if (@{$code_order} > 0) {
9581: my $instcoderegexp ='^';
9582: my @clonecodes = split(/\&/,$cloner);
9583: foreach my $item (@{$code_order}) {
9584: if (grep(/^\Q$item\E=/,@clonecodes)) {
9585: foreach my $pair (@clonecodes) {
9586: my ($key,$val) = split(/\=/,$pair,2);
9587: $val = &unescape($val);
9588: if ($key eq $item) {
9589: $instcoderegexp .= '('.$val.')';
9590: last;
9591: }
9592: }
9593: } else {
9594: $instcoderegexp .= $codedefaults->{$item};
9595: }
9596: }
9597: $instcoderegexp .= '$';
9598: my (@from,@to);
9599: eval {
9600: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9601: (@to) = ($clonetocode =~ /$instcoderegexp/);
9602: };
9603: if ((@from > 0) && (@to > 0)) {
9604: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9605: if (!@diffs) {
9606: $canclone = 1;
9607: }
9608: }
9609: }
9610: return $canclone;
9611: }
9612:
9613: sub default_instcode_cloning {
9614: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9615: my (%codedefaults,@code_order,$canclone);
9616: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9617: %codedefaults = %{$codedefaultsref};
9618: @code_order = @{$codeorderref};
9619: } elsif ($clonedom) {
9620: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9621: }
9622: if (($domdefclone) && (@code_order)) {
9623: my @clonecodes = split(/\+/,$domdefclone);
9624: my $instcoderegexp ='^';
9625: foreach my $item (@code_order) {
9626: if (grep(/^\Q$item\E$/,@clonecodes)) {
9627: $instcoderegexp .= '('.$codedefaults{$item}.')';
9628: } else {
9629: $instcoderegexp .= $codedefaults{$item};
9630: }
9631: }
9632: $instcoderegexp .= '$';
9633: my (@from,@to);
9634: eval {
9635: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9636: (@to) = ($clonetocode =~ /$instcoderegexp/);
9637: };
9638: if ((@from > 0) && (@to > 0)) {
9639: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9640: if (!@diffs) {
9641: $canclone = 1;
9642: }
9643: }
9644: }
9645: return $canclone;
9646: }
9647:
1.679 raeburn 9648: # ------------------------------------------------------- Course Group routines
9649:
9650: sub get_coursegroups {
1.809 raeburn 9651: my ($cdom,$cnum,$group,$namespace) = @_;
9652: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9653: }
9654:
1.679 raeburn 9655: sub modify_coursegroup {
9656: my ($cdom,$cnum,$groupsettings) = @_;
9657: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9658: }
9659:
1.809 raeburn 9660: sub toggle_coursegroup_status {
9661: my ($cdom,$cnum,$group,$action) = @_;
9662: my ($from_namespace,$to_namespace);
9663: if ($action eq 'delete') {
9664: $from_namespace = 'coursegroups';
9665: $to_namespace = 'deleted_groups';
9666: } else {
9667: $from_namespace = 'deleted_groups';
9668: $to_namespace = 'coursegroups';
9669: }
9670: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9671: if (my $tmp = &error(%curr_group)) {
9672: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9673: return ('read error',$tmp);
9674: } else {
9675: my %savedsettings = %curr_group;
1.809 raeburn 9676: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9677: my $deloutcome;
9678: if ($result eq 'ok') {
1.809 raeburn 9679: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9680: } else {
9681: return ('write error',$result);
9682: }
9683: if ($deloutcome eq 'ok') {
9684: return 'ok';
9685: } else {
9686: return ('delete error',$deloutcome);
9687: }
9688: }
9689: }
9690:
1.679 raeburn 9691: sub modify_group_roles {
1.957 raeburn 9692: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9693: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9694: my $role = 'gr/'.&escape($userprivs);
9695: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9696: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9697: if ($result eq 'ok') {
9698: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9699: }
1.679 raeburn 9700: return $result;
9701: }
9702:
9703: sub modify_coursegroup_membership {
9704: my ($cdom,$cnum,$membership) = @_;
9705: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9706: return $result;
9707: }
9708:
1.682 raeburn 9709: sub get_active_groups {
9710: my ($udom,$uname,$cdom,$cnum) = @_;
9711: my $now = time;
9712: my %groups = ();
9713: foreach my $key (keys(%env)) {
1.811 albertel 9714: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9715: my ($start,$end) = split(/\./,$env{$key});
9716: if (($end!=0) && ($end<$now)) { next; }
9717: if (($start!=0) && ($start>$now)) { next; }
9718: if ($1 eq $cdom && $2 eq $cnum) {
9719: $groups{$3} = $env{$key} ;
9720: }
9721: }
9722: }
9723: return %groups;
9724: }
9725:
1.683 raeburn 9726: sub get_group_membership {
9727: my ($cdom,$cnum,$group) = @_;
9728: return(&dump('groupmembership',$cdom,$cnum,$group));
9729: }
9730:
9731: sub get_users_groups {
9732: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9733: my @usersgroups;
1.683 raeburn 9734: my $cachetime=1800;
9735:
9736: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9737: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9738: if (defined($cached)) {
1.734 albertel 9739: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9740: } else {
9741: $grouplist = '';
1.816 raeburn 9742: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9743: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9744: my $access_end = $env{'course.'.$courseid.
9745: '.default_enrollment_end_date'};
9746: my $now = time;
9747: foreach my $key (keys(%roleshash)) {
9748: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9749: my $group = $1;
9750: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9751: my $start = $2;
9752: my $end = $1;
9753: if ($start == -1) { next; } # deleted from group
9754: if (($start!=0) && ($start>$now)) { next; }
9755: if (($end!=0) && ($end<$now)) {
9756: if ($access_end && $access_end < $now) {
9757: if ($access_end - $end < 86400) {
9758: push(@usersgroups,$group);
1.733 raeburn 9759: }
9760: }
1.817 raeburn 9761: next;
1.733 raeburn 9762: }
1.817 raeburn 9763: push(@usersgroups,$group);
1.683 raeburn 9764: }
9765: }
9766: }
1.817 raeburn 9767: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9768: $grouplist = join(':',@usersgroups);
9769: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9770: }
1.733 raeburn 9771: return @usersgroups;
1.683 raeburn 9772: }
9773:
9774: sub devalidate_getgroups_cache {
9775: my ($udom,$uname,$cdom,$cnum)=@_;
9776: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9777:
1.683 raeburn 9778: my $hashid="$udom:$uname:$courseid";
9779: &devalidate_cache_new('getgroups',$hashid);
9780: }
9781:
1.12 www 9782: # ------------------------------------------------------------------ Plain Text
9783:
9784: sub plaintext {
1.988 raeburn 9785: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9786: if ($short =~ m{^cr/}) {
1.758 albertel 9787: return (split('/',$short))[-1];
9788: }
1.742 raeburn 9789: if (!defined($cid)) {
9790: $cid = $env{'request.course.id'};
9791: }
9792: my %rolenames = (
1.1008 raeburn 9793: Course => 'std',
9794: Community => 'alt1',
1.742 raeburn 9795: );
1.1037 raeburn 9796: if ($cid ne '') {
9797: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9798: unless ($forcedefault) {
9799: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9800: &Apache::lonlocal::mt_escape(\$roletext);
9801: return &Apache::lonlocal::mt($roletext);
9802: }
9803: }
9804: }
9805: if ((defined($type)) && (defined($rolenames{$type})) &&
9806: (defined($rolenames{$type})) &&
9807: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9808: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9809: } elsif ($cid ne '') {
9810: my $crstype = $env{'course.'.$cid.'.type'};
9811: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9812: (defined($prp{$short}{$rolenames{$crstype}}))) {
9813: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9814: }
1.742 raeburn 9815: }
1.1037 raeburn 9816: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9817: }
9818:
9819: # ----------------------------------------------------------------- Assign Role
9820:
9821: sub assignrole {
1.957 raeburn 9822: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9823: $context)=@_;
1.21 www 9824: my $mrole;
9825: if ($role =~ /^cr\//) {
1.393 www 9826: my $cwosec=$url;
1.811 albertel 9827: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9828: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9829: my $refused = 1;
9830: if ($context eq 'requestcourses') {
9831: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9832: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9833: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9834: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9835: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9836: if ($crsenv{'internal.courseowner'} eq
9837: $env{'user.name'}.':'.$env{'user.domain'}) {
9838: $refused = '';
9839: }
9840: }
9841: }
9842: }
9843: }
9844: if ($refused) {
9845: &logthis('Refused custom assignrole: '.
9846: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9847: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9848: return 'refused';
9849: }
1.104 www 9850: }
1.21 www 9851: $mrole='cr';
1.678 raeburn 9852: } elsif ($role =~ /^gr\//) {
9853: my $cwogrp=$url;
1.811 albertel 9854: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9855: unless (&allowed('mdg',$cwogrp)) {
9856: &logthis('Refused group assignrole: '.
9857: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9858: $env{'user.name'}.' at '.$env{'user.domain'});
9859: return 'refused';
9860: }
9861: $mrole='gr';
1.21 www 9862: } else {
1.82 www 9863: my $cwosec=$url;
1.811 albertel 9864: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9865: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9866: my $refused;
9867: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9868: if (!(&allowed('c'.$role,$url))) {
9869: $refused = 1;
9870: }
9871: } else {
9872: $refused = 1;
9873: }
1.947 raeburn 9874: if ($refused) {
1.1045 raeburn 9875: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9876: if (!$selfenroll && $context eq 'course') {
9877: my %crsenv;
9878: if ($role eq 'cc' || $role eq 'co') {
9879: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9880: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9881: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9882: if ($crsenv{'internal.courseowner'} eq
9883: $env{'user.name'}.':'.$env{'user.domain'}) {
9884: $refused = '';
9885: }
9886: }
9887: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9888: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9889: if ($crsenv{'internal.courseowner'} eq
9890: $env{'user.name'}.':'.$env{'user.domain'}) {
9891: $refused = '';
9892: }
9893: }
9894: }
9895: }
9896: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9897: $refused = '';
1.1017 raeburn 9898: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9899: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9900: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9901: my $wrongcc;
9902: if ($cnum =~ /^$match_community$/) {
9903: $wrongcc = 1 if ($role eq 'cc');
9904: } else {
9905: $wrongcc = 1 if ($role eq 'co');
9906: }
9907: unless ($wrongcc) {
9908: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9909: if ($crsenv{'internal.courseowner'} eq
9910: $env{'user.name'}.':'.$env{'user.domain'}) {
9911: $refused = '';
9912: }
1.1017 raeburn 9913: }
9914: }
1.1172.2.9 raeburn 9915: } elsif ($context eq 'requestauthor') {
9916: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9917: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9918: if ($env{'environment.requestauthor'} eq 'automatic') {
9919: $refused = '';
9920: } else {
9921: my %domdefaults = &get_domain_defaults($udom);
9922: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9923: my $checkbystatus;
9924: if ($env{'user.adv'}) {
9925: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9926: if ($disposition eq 'automatic') {
9927: $refused = '';
9928: } elsif ($disposition eq '') {
9929: $checkbystatus = 1;
9930: }
9931: } else {
9932: $checkbystatus = 1;
9933: }
9934: if ($checkbystatus) {
9935: if ($env{'environment.inststatus'}) {
9936: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9937: foreach my $type (@inststatuses) {
9938: if (($type ne '') &&
9939: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9940: $refused = '';
9941: }
9942: }
9943: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9944: $refused = '';
9945: }
9946: }
9947: }
9948: }
9949: }
1.1017 raeburn 9950: }
9951: if ($refused) {
1.947 raeburn 9952: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9953: ' '.$role.' '.$end.' '.$start.' by '.
9954: $env{'user.name'}.' at '.$env{'user.domain'});
9955: return 'refused';
9956: }
1.932 raeburn 9957: }
1.1131 raeburn 9958: } elsif ($role eq 'au') {
9959: if ($url ne '/'.$udom.'/') {
9960: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9961: ' to assign author role for '.$uname.':'.$udom.
9962: ' in domain: '.$url.' refused (wrong domain).');
9963: return 'refused';
9964: }
1.104 www 9965: }
1.21 www 9966: $mrole=$role;
9967: }
1.620 albertel 9968: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9969: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9970: if ($end) { $command.='_'.$end; }
1.21 www 9971: if ($start) {
9972: if ($end) {
1.81 www 9973: $command.='_'.$start;
1.21 www 9974: } else {
1.81 www 9975: $command.='_0_'.$start;
1.21 www 9976: }
9977: }
1.739 raeburn 9978: my $origstart = $start;
9979: my $origend = $end;
1.957 raeburn 9980: my $delflag;
1.357 www 9981: # actually delete
9982: if ($deleteflag) {
1.373 www 9983: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9984: # modify command to delete the role
1.620 albertel 9985: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9986: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9987: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9988: # set start and finish to negative values for userrolelog
9989: $start=-1;
9990: $end=-1;
1.957 raeburn 9991: $delflag = 1;
1.357 www 9992: }
9993: }
9994: # send command
1.349 www 9995: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9996: # log new user role if status is ok
1.349 www 9997: if ($answer eq 'ok') {
1.663 raeburn 9998: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9999: if (($role eq 'cc') || ($role eq 'in') ||
10000: ($role eq 'ep') || ($role eq 'ad') ||
10001: ($role eq 'ta') || ($role eq 'st') ||
10002: ($role=~/^cr/) || ($role eq 'gr') ||
10003: ($role eq 'co')) {
1.1172.2.13 raeburn 10004: # for course roles, perform group memberships changes triggered by role change.
10005: unless ($role =~ /^gr/) {
10006: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10007: $origstart,$selfenroll,$context);
10008: }
1.1172.2.9 raeburn 10009: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10010: $selfenroll,$context);
10011: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 10012: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10013: ($role eq 'da')) {
1.1172.2.9 raeburn 10014: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10015: $context);
10016: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10017: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10018: $context);
10019: }
1.1053 raeburn 10020: if ($role eq 'cc') {
10021: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10022: }
1.349 www 10023: }
10024: return $answer;
1.169 harris41 10025: }
10026:
1.1053 raeburn 10027: sub autoupdate_coowners {
10028: my ($url,$end,$start,$uname,$udom) = @_;
10029: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10030: if (($cdom ne '') && ($cnum ne '')) {
10031: my $now = time;
10032: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10033: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10034: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10035: my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141 raeburn 10036: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10037: if ($instcode ne '') {
1.1056 raeburn 10038: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10039: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10040: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10041: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141 raeburn 10042: unless ($result eq 'valid') {
10043: if ($xlists ne '') {
10044: foreach my $xlist (split(',',$xlists)) {
10045: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10046: $result =
10047: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10048: $inst_crosslist,$uname.':'.$udom);
10049: last if ($result eq 'valid');
10050: }
10051: }
10052: }
1.1056 raeburn 10053: if ($result eq 'valid') {
10054: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10055: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10056: push(@newcoowners,$coowner);
10057: }
10058: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10059: push(@newcoowners,$uname.':'.$udom);
10060: }
10061: @newcoowners = sort(@newcoowners);
10062: } else {
10063: push(@newcoowners,$uname.':'.$udom);
10064: }
1.1172.2.141 raeburn 10065: } elsif ($coursehash{'internal.co-owners'}) {
10066: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10067: unless ($coowner eq $uname.':'.$udom) {
10068: push(@newcoowners,$coowner);
1.1053 raeburn 10069: }
10070: }
1.1172.2.141 raeburn 10071: unless (@newcoowners > 0) {
10072: $delcoowners = 1;
10073: $coowners = '';
10074: }
1.1053 raeburn 10075: }
10076: if (@newcoowners || $delcoowners) {
10077: &store_coowners($cdom,$cnum,$coursehash{'home'},
10078: $delcoowners,@newcoowners);
10079: }
10080: }
10081: }
10082: }
10083: }
10084: }
10085: }
10086:
10087: sub store_coowners {
10088: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10089: my $cid = $cdom.'_'.$cnum;
10090: my ($coowners,$delresult,$putresult);
10091: if (@newcoowners) {
10092: $coowners = join(',',@newcoowners);
10093: my %coownershash = (
10094: 'internal.co-owners' => $coowners,
10095: );
10096: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10097: if ($putresult eq 'ok') {
10098: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10099: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10100: }
10101: }
10102: }
10103: if ($delcoowners) {
10104: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10105: if ($delresult eq 'ok') {
10106: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10107: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10108: }
10109: }
10110: }
10111: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10112: my %crsinfo =
10113: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10114: if (ref($crsinfo{$cid}) eq 'HASH') {
10115: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10116: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10117: }
10118: }
10119: }
10120:
1.169 harris41 10121: # -------------------------------------------------- Modify user authentication
1.197 www 10122: # Overrides without validation
10123:
1.169 harris41 10124: sub modifyuserauth {
10125: my ($udom,$uname,$umode,$upass)=@_;
10126: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 10127: my $allowed;
10128: if (&allowed('mau',$udom)) {
10129: $allowed = 1;
10130: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10131: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10132: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10133: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10134: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10135: if (($cdom ne '') && ($cnum ne '')) {
10136: my $is_owner = &is_course_owner($cdom,$cnum);
10137: if ($is_owner) {
10138: $allowed = 1;
10139: }
10140: }
10141: }
10142: unless ($allowed) { return 'refused'; }
1.197 www 10143: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10144: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10145: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10146: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10147: &escape($upass),$uhome);
1.1172.2.134 raeburn 10148: my $ip = &get_requestor_ip();
1.620 albertel 10149: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10150: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134 raeburn 10151: '(Remote '.$ip.'): '.$reply);
1.197 www 10152: &log($udom,,$uname,$uhome,
1.620 albertel 10153: 'Authentication changed by '.$env{'user.domain'}.', '.
10154: $env{'user.name'}.', '.$umode.
1.1172.2.134 raeburn 10155: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10156: unless ($reply eq 'ok') {
1.197 www 10157: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10158: return 'error: '.$reply;
10159: }
1.170 harris41 10160: return 'ok';
1.80 www 10161: }
10162:
1.81 www 10163: # --------------------------------------------------------------- Modify a user
1.80 www 10164:
1.81 www 10165: sub modifyuser {
1.206 matthew 10166: my ($udom, $uname, $uid,
10167: $umode, $upass, $first,
10168: $middle, $last, $gene,
1.1058 raeburn 10169: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10170: $udom= &LONCAPA::clean_domain($udom);
10171: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10172: my $showcandelete = 'none';
10173: if (ref($candelete) eq 'ARRAY') {
10174: if (@{$candelete} > 0) {
10175: $showcandelete = join(', ',@{$candelete});
10176: }
10177: }
1.81 www 10178: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10179: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10180: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10181: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10182: ' desiredhome not specified').
1.620 albertel 10183: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10184: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10185: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10186: my $newuser;
10187: if ($uhome eq 'no_host') {
10188: $newuser = 1;
10189: }
1.80 www 10190: # ----------------------------------------------------------------- Create User
1.406 albertel 10191: if (($uhome eq 'no_host') &&
10192: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 10193: my $unhome='';
1.844 albertel 10194: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10195: $unhome = $desiredhome;
1.620 albertel 10196: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10197: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10198: } else { # load balancing routine for determining $unhome
1.81 www 10199: my $loadm=10000000;
1.841 albertel 10200: my %servers = &get_servers($udom,'library');
10201: foreach my $tryserver (keys(%servers)) {
10202: my $answer=reply('load',$tryserver);
10203: if (($answer=~/\d+/) && ($answer<$loadm)) {
10204: $loadm=$answer;
10205: $unhome=$tryserver;
10206: }
1.80 www 10207: }
10208: }
10209: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10210: return 'error: unable to find a home server for '.$uname.
10211: ' in domain '.$udom;
1.80 www 10212: }
10213: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10214: &escape($upass),$unhome);
10215: unless ($reply eq 'ok') {
10216: return 'error: '.$reply;
10217: }
1.230 stredwic 10218: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10219: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10220: return 'error: unable verify users home machine.';
1.80 www 10221: }
1.209 matthew 10222: } # End of creation of new user
1.80 www 10223: # ---------------------------------------------------------------------- Add ID
10224: if ($uid) {
10225: $uid=~tr/A-Z/a-z/;
10226: my %uidhash=&idrget($udom,$uname);
1.196 www 10227: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10228: && (!$forceid)) {
1.80 www 10229: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10230: return 'error: user id "'.$uid.'" does not match '.
10231: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10232: }
10233: } else {
10234: &idput($udom,($uname => $uid));
10235: }
10236: }
10237: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10238: my @tmp=&get('environment',
1.899 raeburn 10239: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10240: 'permanentemail','inststatus'],
1.134 albertel 10241: $udom,$uname);
1.1075 raeburn 10242: my (%names,%oldnames);
1.313 matthew 10243: if ($tmp[0] =~ m/^error:.*/) {
10244: %names=();
10245: } else {
10246: %names = @tmp;
1.1075 raeburn 10247: %oldnames = %names;
1.313 matthew 10248: }
1.388 www 10249: #
1.1058 raeburn 10250: # If name, email and/or uid are blank (e.g., because an uploaded file
10251: # of users did not contain them), do not overwrite existing values
10252: # unless field is in $candelete array ref.
10253: #
10254:
10255: my @fields = ('firstname','middlename','lastname','generation',
10256: 'permanentemail','id');
10257: my %newvalues;
10258: if (ref($candelete) eq 'ARRAY') {
10259: foreach my $field (@fields) {
10260: if (grep(/^\Q$field\E$/,@{$candelete})) {
10261: if ($field eq 'firstname') {
10262: $names{$field} = $first;
10263: } elsif ($field eq 'middlename') {
10264: $names{$field} = $middle;
10265: } elsif ($field eq 'lastname') {
10266: $names{$field} = $last;
10267: } elsif ($field eq 'generation') {
10268: $names{$field} = $gene;
10269: } elsif ($field eq 'permanentemail') {
10270: $names{$field} = $email;
10271: } elsif ($field eq 'id') {
10272: $names{$field} = $uid;
10273: }
10274: }
10275: }
10276: }
1.388 www 10277: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10278: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10279: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10280: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10281: if ($email) {
10282: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10283: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10284: }
1.899 raeburn 10285: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10286: if (defined($inststatus)) {
10287: $names{'inststatus'} = '';
10288: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10289: if (ref($usertypes) eq 'HASH') {
10290: my @okstatuses;
10291: foreach my $item (split(/:/,$inststatus)) {
10292: if (defined($usertypes->{$item})) {
10293: push(@okstatuses,$item);
10294: }
10295: }
10296: if (@okstatuses) {
10297: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10298: }
10299: }
10300: }
1.1075 raeburn 10301: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10302: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10303: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10304: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10305: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10306: } else {
10307: $logmsg .= ' during self creation';
10308: }
1.1075 raeburn 10309: my $changed;
10310: if ($newuser) {
10311: $changed = 1;
10312: } else {
10313: foreach my $field (@fields) {
10314: if ($names{$field} ne $oldnames{$field}) {
10315: $changed = 1;
10316: last;
10317: }
10318: }
10319: }
10320: unless ($changed) {
10321: $logmsg = 'No changes in user information needed for: '.$logmsg;
10322: &logthis($logmsg);
10323: return 'ok';
10324: }
10325: my $reply = &put('environment', \%names, $udom,$uname);
10326: if ($reply ne 'ok') {
10327: return 'error: '.$reply;
10328: }
1.1087 raeburn 10329: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10330: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10331: }
1.1075 raeburn 10332: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10333: &devalidate_cache_new('namescache',$uname.':'.$udom);
10334: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10335: &logthis($logmsg);
1.134 albertel 10336: return 'ok';
1.80 www 10337: }
10338:
1.81 www 10339: # -------------------------------------------------------------- Modify student
1.80 www 10340:
1.81 www 10341: sub modifystudent {
10342: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10343: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10344: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10345: if (!$cid) {
1.620 albertel 10346: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10347: return 'not_in_class';
10348: }
1.80 www 10349: }
10350: # --------------------------------------------------------------- Make the user
1.81 www 10351: my $reply=&modifyuser
1.209 matthew 10352: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10353: $desiredhome,$email,$inststatus);
1.80 www 10354: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10355: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10356: # student's environment
1.297 matthew 10357: $uid = undef if (!$forceid);
1.455 albertel 10358: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10359: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10360: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10361: return $reply;
10362: }
10363:
10364: sub modify_student_enrollment {
1.1172.2.23 raeburn 10365: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10366: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10367: my ($cdom,$cnum,$chome);
10368: if (!$cid) {
1.620 albertel 10369: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10370: return 'not_in_class';
10371: }
1.620 albertel 10372: $cdom=$env{'course.'.$cid.'.domain'};
10373: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10374: } else {
10375: ($cdom,$cnum)=split(/_/,$cid);
10376: }
1.620 albertel 10377: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10378: if (!$chome) {
1.457 raeburn 10379: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10380: }
1.455 albertel 10381: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10382: # Make sure the user exists
1.81 www 10383: my $uhome=&homeserver($uname,$udom);
10384: if (($uhome eq '') || ($uhome eq 'no_host')) {
10385: return 'error: no such user';
10386: }
1.297 matthew 10387: # Get student data if we were not given enough information
10388: if (!defined($first) || $first eq '' ||
10389: !defined($last) || $last eq '' ||
10390: !defined($uid) || $uid eq '' ||
10391: !defined($middle) || $middle eq '' ||
10392: !defined($gene) || $gene eq '') {
1.294 matthew 10393: # They did not supply us with enough data to enroll the student, so
10394: # we need to pick up more information.
1.297 matthew 10395: my %tmp = &get('environment',
1.294 matthew 10396: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10397: ,$udom,$uname);
10398:
1.800 albertel 10399: #foreach my $key (keys(%tmp)) {
10400: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10401: #}
1.294 matthew 10402: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10403: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10404: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10405: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10406: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10407: }
1.556 albertel 10408: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10409: my $user = "$uname:$udom";
10410: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10411: my $reply=cput('classlist',
1.1148 raeburn 10412: {$user =>
1.1172.2.76 raeburn 10413: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10414: $cdom,$cnum);
1.1148 raeburn 10415: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10416: &devalidate_getsection_cache($udom,$uname,$cid);
10417: } else {
1.81 www 10418: return 'error: '.$reply;
10419: }
1.297 matthew 10420: # Add student role to user
1.83 www 10421: my $uurl='/'.$cid;
1.81 www 10422: $uurl=~s/\_/\//g;
10423: if ($usec) {
10424: $uurl.='/'.$usec;
10425: }
1.1148 raeburn 10426: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10427: $selfenroll,$context);
10428: if ($result ne 'ok') {
10429: if ($old_entry{$user} ne '') {
10430: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10431: } else {
10432: $reply = &del('classlist',[$user],$cdom,$cnum);
10433: }
10434: }
10435: return $result;
1.21 www 10436: }
10437:
1.556 albertel 10438: sub format_name {
10439: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10440: my $name;
10441: if ($first ne 'lastname') {
10442: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10443: } else {
10444: if ($lastname=~/\S/) {
10445: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10446: $name=~s/\s+,/,/;
10447: } else {
10448: $name.= $firstname.' '.$middlename.' '.$generation;
10449: }
10450: }
10451: $name=~s/^\s+//;
10452: $name=~s/\s+$//;
10453: $name=~s/\s+/ /g;
10454: return $name;
10455: }
10456:
1.84 www 10457: # ------------------------------------------------- Write to course preferences
10458:
10459: sub writecoursepref {
10460: my ($courseid,%prefs)=@_;
10461: $courseid=~s/^\///;
10462: $courseid=~s/\_/\//g;
10463: my ($cdomain,$cnum)=split(/\//,$courseid);
10464: my $chome=homeserver($cnum,$cdomain);
10465: if (($chome eq '') || ($chome eq 'no_host')) {
10466: return 'error: no such course';
10467: }
10468: my $cstring='';
1.800 albertel 10469: foreach my $pref (keys(%prefs)) {
10470: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10471: }
1.84 www 10472: $cstring=~s/\&$//;
10473: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10474: }
10475:
10476: # ---------------------------------------------------------- Make/modify course
10477:
10478: sub createcourse {
1.741 raeburn 10479: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10480: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10481: $url=&declutter($url);
10482: my $cid='';
1.1028 raeburn 10483: if ($context eq 'requestcourses') {
10484: my $can_create = 0;
10485: my ($ownername,$ownerdom) = split(':',$course_owner);
10486: if ($udom eq $ownerdom) {
10487: if (&usertools_access($ownername,$ownerdom,$category,undef,
10488: $context)) {
10489: $can_create = 1;
10490: }
10491: } else {
10492: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10493: $category);
10494: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10495: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10496: if (@curr > 0) {
10497: my @options = qw(approval validate autolimit);
10498: my $optregex = join('|',@options);
10499: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10500: $can_create = 1;
10501: }
10502: }
10503: }
10504: }
10505: if ($can_create) {
10506: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10507: unless (&allowed('ccc',$udom)) {
10508: return 'refused';
10509: }
1.1017 raeburn 10510: }
10511: } else {
10512: return 'refused';
10513: }
1.1028 raeburn 10514: } elsif (!&allowed('ccc',$udom)) {
10515: return 'refused';
1.84 www 10516: }
1.1011 raeburn 10517: # --------------------------------------------------------------- Get Unique ID
10518: my $uname;
10519: if ($cnum =~ /^$match_courseid$/) {
10520: my $chome=&homeserver($cnum,$udom,'true');
10521: if (($chome eq '') || ($chome eq 'no_host')) {
10522: $uname = $cnum;
10523: } else {
1.1038 raeburn 10524: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10525: }
10526: } else {
1.1038 raeburn 10527: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10528: }
10529: return $uname if ($uname =~ /^error/);
10530: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10531: if (!defined($course_server)) {
10532: if (defined(&domain($udom,'primary'))) {
10533: $course_server = &domain($udom,'primary');
10534: } else {
10535: $course_server = $env{'user.home'};
10536: }
10537: }
10538: my %host_servers =
10539: &Apache::lonnet::get_servers($udom,'library');
10540: unless ($host_servers{$course_server}) {
10541: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10542: }
1.84 www 10543: # ------------------------------------------------------------- Make the course
10544: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10545: $course_server);
1.84 www 10546: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10547: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10548: if (($uhome eq '') || ($uhome eq 'no_host')) {
10549: return 'error: no such course';
10550: }
1.271 www 10551: # ----------------------------------------------------------------- Course made
1.516 raeburn 10552: # log existence
1.1029 raeburn 10553: my $now = time;
1.918 raeburn 10554: my $newcourse = {
10555: $udom.'_'.$uname => {
1.921 raeburn 10556: description => $description,
10557: inst_code => $inst_code,
10558: owner => $course_owner,
10559: type => $crstype,
1.1029 raeburn 10560: creator => $env{'user.name'}.':'.
10561: $env{'user.domain'},
10562: created => $now,
10563: context => $context,
1.918 raeburn 10564: },
10565: };
1.921 raeburn 10566: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10567: # set toplevel url
1.271 www 10568: my $topurl=$url;
10569: unless ($nonstandard) {
10570: # ------------------------------------------ For standard courses, make top url
10571: my $mapurl=&clutter($url);
1.278 www 10572: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10573: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10574: <map>
10575: <resource id="1" type="start"></resource>
10576: <resource id="2" src="$mapurl"></resource>
10577: <resource id="3" type="finish"></resource>
10578: <link index="1" from="1" to="2"></link>
10579: <link index="2" from="2" to="3"></link>
10580: </map>
10581: ENDINITMAP
10582: $topurl=&declutter(
1.638 albertel 10583: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10584: );
10585: }
10586: # ----------------------------------------------------------- Write preferences
1.84 www 10587: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10588: ('description' => $description,
10589: 'url' => $topurl,
10590: 'internal.creator' => $env{'user.name'}.':'.
10591: $env{'user.domain'},
10592: 'internal.created' => $now,
10593: 'internal.creationcontext' => $context)
10594: );
1.84 www 10595: return '/'.$udom.'/'.$uname;
10596: }
10597:
1.1011 raeburn 10598: # ------------------------------------------------------------------- Create ID
10599: sub generate_coursenum {
1.1038 raeburn 10600: my ($udom,$crstype) = @_;
1.1011 raeburn 10601: my $domdesc = &domain($udom);
10602: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10603: my $first;
10604: if ($crstype eq 'Community') {
10605: $first = '0';
10606: } else {
10607: $first = int(1+rand(9));
10608: }
10609: my $uname=$first.
1.1011 raeburn 10610: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10611: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10612: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10613: # ----------------------------------------------- Make sure that does not exist
10614: my $uhome=&homeserver($uname,$udom,'true');
10615: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10616: if ($crstype eq 'Community') {
10617: $first = '0';
10618: } else {
10619: $first = int(1+rand(9));
10620: }
10621: $uname=$first.
1.1011 raeburn 10622: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10623: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10624: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10625: $uhome=&homeserver($uname,$udom,'true');
10626: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10627: return 'error: unable to generate unique course-ID';
10628: }
10629: }
10630: return $uname;
10631: }
10632:
1.813 albertel 10633: sub is_course {
1.1167 droeschl 10634: my ($cdom, $cnum) = scalar(@_) == 1 ?
10635: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 10636: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10637: my $uhome=&homeserver($cnum,$cdom);
10638: my $iscourse;
10639: if (grep { $_ eq $uhome } current_machine_ids()) {
10640: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10641: } else {
10642: my $hashid = $cdom.':'.$cnum;
10643: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10644: unless (defined($cached)) {
10645: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10646: $cnum,undef,undef,'.');
10647: $iscourse = 0;
10648: if (exists($courses{$cdom.'_'.$cnum})) {
10649: $iscourse = 1;
10650: }
10651: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10652: }
10653: }
10654: return unless($iscourse);
1.1167 droeschl 10655: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10656: }
10657:
1.1015 raeburn 10658: sub store_userdata {
10659: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10660: my $result;
1.1016 raeburn 10661: if ($datakey ne '') {
1.1013 raeburn 10662: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10663: if ($udom eq '' || $uname eq '') {
10664: $udom = $env{'user.domain'};
10665: $uname = $env{'user.name'};
10666: }
10667: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10668: if (($uhome eq '') || ($uhome eq 'no_host')) {
10669: $result = 'error: no_host';
10670: } else {
1.1172.2.138 raeburn 10671: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 10672: $storehash->{'host'} = $perlvar{'lonHostID'};
10673:
10674: my $namevalue='';
10675: foreach my $key (keys(%{$storehash})) {
10676: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10677: }
10678: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 10679: unless ($namespace eq 'courserequests') {
10680: $datakey = &escape($datakey);
10681: }
1.1105 raeburn 10682: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10683: $namevalue,$uhome);
1.1013 raeburn 10684: }
10685: } else {
10686: $result = 'error: data to store was not a hash reference';
10687: }
10688: } else {
10689: $result= 'error: invalid requestkey';
10690: }
10691: return $result;
10692: }
10693:
1.21 www 10694: # ---------------------------------------------------------- Assign Custom Role
10695:
10696: sub assigncustomrole {
1.957 raeburn 10697: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10698: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10699: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10700: }
10701:
10702: # ----------------------------------------------------------------- Revoke Role
10703:
10704: sub revokerole {
1.957 raeburn 10705: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10706: my $now=time;
1.965 raeburn 10707: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10708: }
10709:
10710: # ---------------------------------------------------------- Revoke Custom Role
10711:
10712: sub revokecustomrole {
1.957 raeburn 10713: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10714: my $now=time;
1.357 www 10715: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10716: $deleteflag,$selfenroll,$context);
1.17 www 10717: }
10718:
1.533 banghart 10719: # ------------------------------------------------------------ Disk usage
1.535 albertel 10720: sub diskusage {
1.955 raeburn 10721: my ($udom,$uname,$directorypath,$getpropath)=@_;
10722: $directorypath =~ s/\/$//;
10723: my $listing=&reply('du2:'.&escape($directorypath).':'
10724: .&escape($getpropath).':'.&escape($uname).':'
10725: .&escape($udom),homeserver($uname,$udom));
10726: if ($listing eq 'unknown_cmd') {
10727: if ($getpropath) {
10728: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10729: }
10730: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10731: }
1.514 albertel 10732: return $listing;
1.512 banghart 10733: }
10734:
1.566 banghart 10735: sub is_locked {
1.1096 raeburn 10736: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10737: my @check;
10738: my $is_locked;
1.1093 raeburn 10739: push (@check,$file_name);
1.613 albertel 10740: my %locked = &get('file_permissions',\@check,
1.620 albertel 10741: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10742: my ($tmp)=keys(%locked);
10743: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10744:
1.566 banghart 10745: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10746: $is_locked = 'false';
10747: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10748: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10749: $is_locked = 'true';
1.1096 raeburn 10750: if (ref($which) eq 'ARRAY') {
10751: push(@{$which},$entry);
10752: } else {
10753: last;
10754: }
1.745 raeburn 10755: }
10756: }
1.566 banghart 10757: } else {
10758: $is_locked = 'false';
10759: }
1.1093 raeburn 10760: return $is_locked;
1.566 banghart 10761: }
10762:
1.759 albertel 10763: sub declutter_portfile {
10764: my ($file) = @_;
1.833 albertel 10765: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10766: return $file;
10767: }
10768:
1.559 banghart 10769: # ------------------------------------------------------------- Mark as Read Only
10770:
10771: sub mark_as_readonly {
10772: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10773: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10774: my ($tmp)=keys(%current_permissions);
10775: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10776: foreach my $file (@{$files}) {
1.759 albertel 10777: $file = &declutter_portfile($file);
1.561 banghart 10778: push(@{$current_permissions{$file}},$what);
1.559 banghart 10779: }
1.613 albertel 10780: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10781: return;
10782: }
10783:
1.572 banghart 10784: # ------------------------------------------------------------Save Selected Files
10785:
10786: sub save_selected_files {
10787: my ($user, $path, @files) = @_;
10788: my $filename = $user."savedfiles";
1.573 banghart 10789: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 10790: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10791: foreach my $file (@files) {
1.620 albertel 10792: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10793: }
10794: foreach my $file (@other_files) {
1.574 banghart 10795: print (OUT $file."\n");
1.572 banghart 10796: }
1.574 banghart 10797: close (OUT);
1.572 banghart 10798: return 'ok';
10799: }
10800:
1.574 banghart 10801: sub clear_selected_files {
10802: my ($user) = @_;
10803: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 10804: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10805: print (OUT undef);
10806: close (OUT);
10807: return ("ok");
10808: }
10809:
1.572 banghart 10810: sub files_in_path {
10811: my ($user, $path) = @_;
10812: my $filename = $user."savedfiles";
10813: my %return_files;
1.1172.2.96 raeburn 10814: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10815: while (my $line_in = <IN>) {
1.574 banghart 10816: chomp ($line_in);
10817: my @paths_and_file = split (m!/!, $line_in);
10818: my $file_part = pop (@paths_and_file);
10819: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10820: $path_part.='/';
10821: my $path_and_file = $path_part.$file_part;
10822: if ($path_part eq $path) {
10823: $return_files{$file_part}= 'selected';
10824: }
10825: }
1.574 banghart 10826: close (IN);
10827: return (\%return_files);
1.572 banghart 10828: }
10829:
10830: # called in portfolio select mode, to show files selected NOT in current directory
10831: sub files_not_in_path {
10832: my ($user, $path) = @_;
10833: my $filename = $user."savedfiles";
10834: my @return_files;
10835: my $path_part;
1.1172.2.96 raeburn 10836: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10837: while (my $line = <IN>) {
1.572 banghart 10838: #ok, I know it's clunky, but I want it to work
1.800 albertel 10839: my @paths_and_file = split(m|/|, $line);
10840: my $file_part = pop(@paths_and_file);
10841: chomp($file_part);
10842: my $path_part = join('/', @paths_and_file);
1.572 banghart 10843: $path_part .= '/';
10844: my $path_and_file = $path_part.$file_part;
10845: if ($path_part ne $path) {
1.800 albertel 10846: push(@return_files, ($path_and_file));
1.572 banghart 10847: }
10848: }
1.800 albertel 10849: close(OUT);
1.574 banghart 10850: return (@return_files);
1.572 banghart 10851: }
10852:
1.745 raeburn 10853: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10854:
1.745 raeburn 10855: sub get_portfile_permissions {
10856: my ($domain,$user) = @_;
1.613 albertel 10857: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10858: my ($tmp)=keys(%current_permissions);
10859: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10860: return \%current_permissions;
10861: }
10862:
10863: #---------------------------------------------Get portfolio file access controls
10864:
1.749 raeburn 10865: sub get_access_controls {
1.745 raeburn 10866: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10867: my %access;
10868: my $real_file = $file;
10869: $file =~ s/\.meta$//;
1.745 raeburn 10870: if (defined($file)) {
1.749 raeburn 10871: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10872: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10873: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10874: }
10875: }
1.745 raeburn 10876: } else {
1.749 raeburn 10877: foreach my $key (keys(%{$current_permissions})) {
10878: if ($key =~ /\0accesscontrol$/) {
10879: if (defined($group)) {
10880: if ($key !~ m-^\Q$group\E/-) {
10881: next;
10882: }
10883: }
10884: my ($fullpath) = split(/\0/,$key);
10885: if (ref($$current_permissions{$key}) eq 'HASH') {
10886: foreach my $control (keys(%{$$current_permissions{$key}})) {
10887: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10888: }
10889: }
10890: }
10891: }
10892: }
10893: return %access;
10894: }
10895:
10896: sub modify_access_controls {
10897: my ($file_name,$changes,$domain,$user)=@_;
10898: my ($outcome,$deloutcome);
10899: my %store_permissions;
10900: my %new_values;
10901: my %new_control;
10902: my %translation;
10903: my @deletions = ();
10904: my $now = time;
10905: if (exists($$changes{'activate'})) {
10906: if (ref($$changes{'activate'}) eq 'HASH') {
10907: my @newitems = sort(keys(%{$$changes{'activate'}}));
10908: my $numnew = scalar(@newitems);
10909: for (my $i=0; $i<$numnew; $i++) {
10910: my $newkey = $newitems[$i];
10911: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10912: if ($newkey =~ /^\d+:/) {
10913: $newkey =~ s/^(\d+)/$newid/;
10914: $translation{$1} = $newid;
10915: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10916: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10917: $translation{$1} = $newid;
10918: }
1.749 raeburn 10919: $new_values{$file_name."\0".$newkey} =
10920: $$changes{'activate'}{$newitems[$i]};
10921: $new_control{$newkey} = $now;
10922: }
10923: }
10924: }
10925: my %todelete;
10926: my %changed_items;
10927: foreach my $action ('delete','update') {
10928: if (exists($$changes{$action})) {
10929: if (ref($$changes{$action}) eq 'HASH') {
10930: foreach my $key (keys(%{$$changes{$action}})) {
10931: my ($itemnum) = ($key =~ /^([^:]+):/);
10932: if ($action eq 'delete') {
10933: $todelete{$itemnum} = 1;
10934: } else {
10935: $changed_items{$itemnum} = $key;
10936: }
10937: }
1.745 raeburn 10938: }
10939: }
1.749 raeburn 10940: }
10941: # get lock on access controls for file.
10942: my $lockhash = {
10943: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10944: ':'.$env{'user.domain'},
10945: };
10946: my $tries = 0;
10947: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10948:
1.1172.2.79 raeburn 10949: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10950: $tries ++;
1.1172.2.79 raeburn 10951: sleep(0.1);
1.749 raeburn 10952: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10953: }
10954: if ($gotlock eq 'ok') {
10955: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10956: my ($tmp)=keys(%curr_permissions);
10957: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10958: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10959: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10960: if (ref($curr_controls) eq 'HASH') {
10961: foreach my $control_item (keys(%{$curr_controls})) {
10962: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10963: if (defined($todelete{$itemnum})) {
10964: push(@deletions,$file_name."\0".$control_item);
10965: } else {
10966: if (defined($changed_items{$itemnum})) {
10967: $new_control{$changed_items{$itemnum}} = $now;
10968: push(@deletions,$file_name."\0".$control_item);
10969: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10970: } else {
10971: $new_control{$control_item} = $$curr_controls{$control_item};
10972: }
10973: }
1.745 raeburn 10974: }
10975: }
10976: }
1.970 raeburn 10977: my ($group);
10978: if (&is_course($domain,$user)) {
10979: ($group,my $file) = split(/\//,$file_name,2);
10980: }
1.749 raeburn 10981: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10982: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10983: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10984: # remove lock
10985: my @del_lock = ($file_name."\0".'locked_access_records');
10986: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10987: my $sqlresult =
1.970 raeburn 10988: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10989: $group);
1.749 raeburn 10990: } else {
10991: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10992: }
1.749 raeburn 10993: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10994: }
10995:
1.827 raeburn 10996: sub make_public_indefinitely {
10997: my ($requrl) = @_;
10998: my $now = time;
10999: my $action = 'activate';
11000: my $aclnum = 0;
11001: if (&is_portfolio_url($requrl)) {
11002: my (undef,$udom,$unum,$file_name,$group) =
11003: &parse_portfolio_url($requrl);
11004: my $current_perms = &get_portfile_permissions($udom,$unum);
11005: my %access_controls = &get_access_controls($current_perms,
11006: $group,$file_name);
11007: foreach my $key (keys(%{$access_controls{$file_name}})) {
11008: my ($num,$scope,$end,$start) =
11009: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11010: if ($scope eq 'public') {
11011: if ($start <= $now && $end == 0) {
11012: $action = 'none';
11013: } else {
11014: $action = 'update';
11015: $aclnum = $num;
11016: }
11017: last;
11018: }
11019: }
11020: if ($action eq 'none') {
11021: return 'ok';
11022: } else {
11023: my %changes;
11024: my $newend = 0;
11025: my $newstart = $now;
11026: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
11027: $changes{$action}{$newkey} = {
11028: type => 'public',
11029: time => {
11030: start => $newstart,
11031: end => $newend,
11032: },
11033: };
11034: my ($outcome,$deloutcome,$new_values,$translation) =
11035: &modify_access_controls($file_name,\%changes,$udom,$unum);
11036: return $outcome;
11037: }
11038: } else {
11039: return 'invalid';
11040: }
11041: }
11042:
1.745 raeburn 11043: #------------------------------------------------------Get Marked as Read Only
11044:
11045: sub get_marked_as_readonly {
11046: my ($domain,$user,$what,$group) = @_;
11047: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11048: my @readonly_files;
1.629 banghart 11049: my $cmp1=$what;
11050: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11051: while (my ($file_name,$value) = each(%{$current_permissions})) {
11052: if (defined($group)) {
11053: if ($file_name !~ m-^\Q$group\E/-) {
11054: next;
11055: }
11056: }
1.561 banghart 11057: if (ref($value) eq "ARRAY"){
11058: foreach my $stored_what (@{$value}) {
1.629 banghart 11059: my $cmp2=$stored_what;
1.759 albertel 11060: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11061: $cmp2=join('',@{$stored_what});
1.745 raeburn 11062: }
1.629 banghart 11063: if ($cmp1 eq $cmp2) {
1.561 banghart 11064: push(@readonly_files, $file_name);
1.745 raeburn 11065: last;
1.563 banghart 11066: } elsif (!defined($what)) {
11067: push(@readonly_files, $file_name);
1.745 raeburn 11068: last;
1.561 banghart 11069: }
11070: }
1.745 raeburn 11071: }
1.561 banghart 11072: }
11073: return @readonly_files;
11074: }
1.577 banghart 11075: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11076:
1.577 banghart 11077: sub get_marked_as_readonly_hash {
1.745 raeburn 11078: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11079: my %readonly_files;
1.745 raeburn 11080: while (my ($file_name,$value) = each(%{$current_permissions})) {
11081: if (defined($group)) {
11082: if ($file_name !~ m-^\Q$group\E/-) {
11083: next;
11084: }
11085: }
1.577 banghart 11086: if (ref($value) eq "ARRAY"){
11087: foreach my $stored_what (@{$value}) {
1.745 raeburn 11088: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11089: foreach my $lock_descriptor(@{$stored_what}) {
11090: if ($lock_descriptor eq 'graded') {
11091: $readonly_files{$file_name} = 'graded';
11092: } elsif ($lock_descriptor eq 'handback') {
11093: $readonly_files{$file_name} = 'handback';
11094: } else {
11095: if (!exists($readonly_files{$file_name})) {
11096: $readonly_files{$file_name} = 'locked';
11097: }
11098: }
1.745 raeburn 11099: }
1.750 banghart 11100: }
1.577 banghart 11101: }
11102: }
11103: }
11104: return %readonly_files;
11105: }
1.559 banghart 11106: # ------------------------------------------------------------ Unmark as Read Only
11107:
11108: sub unmark_as_readonly {
1.629 banghart 11109: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11110: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11111: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11112: $file_name = &declutter_portfile($file_name);
1.634 albertel 11113: my $symb_crs = $what;
11114: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11115: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11116: my ($tmp)=keys(%current_permissions);
11117: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11118: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11119: foreach my $file (@readonly_files) {
1.759 albertel 11120: my $clean_file = &declutter_portfile($file);
11121: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11122: my $current_locks = $current_permissions{$file};
1.563 banghart 11123: my @new_locks;
11124: my @del_keys;
11125: if (ref($current_locks) eq "ARRAY"){
11126: foreach my $locker (@{$current_locks}) {
1.632 albertel 11127: my $compare=$locker;
1.749 raeburn 11128: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11129: $compare=join('',@{$locker});
1.746 raeburn 11130: if ($compare ne $symb_crs) {
11131: push(@new_locks, $locker);
11132: }
1.563 banghart 11133: }
11134: }
1.650 albertel 11135: if (scalar(@new_locks) > 0) {
1.563 banghart 11136: $current_permissions{$file} = \@new_locks;
11137: } else {
11138: push(@del_keys, $file);
1.613 albertel 11139: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11140: delete($current_permissions{$file});
1.563 banghart 11141: }
11142: }
1.561 banghart 11143: }
1.613 albertel 11144: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11145: return;
11146: }
1.512 banghart 11147:
1.17 www 11148: # ------------------------------------------------------------ Directory lister
11149:
11150: sub dirlist {
1.955 raeburn 11151: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11152: $uri=~s/^\///;
11153: $uri=~s/\/$//;
1.253 stredwic 11154: my ($udom, $uname);
1.955 raeburn 11155: if ($getuserdir) {
1.253 stredwic 11156: $udom = $userdomain;
11157: $uname = $username;
1.955 raeburn 11158: } else {
11159: (undef,$udom,$uname)=split(/\//,$uri);
11160: if(defined($userdomain)) {
11161: $udom = $userdomain;
11162: }
11163: if(defined($username)) {
11164: $uname = $username;
11165: }
1.253 stredwic 11166: }
1.955 raeburn 11167: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11168:
1.955 raeburn 11169: $dirRoot = $perlvar{'lonDocRoot'};
11170: if (defined($getpropath)) {
11171: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11172: $dirRoot =~ s/\/$//;
1.955 raeburn 11173: } elsif (defined($getuserdir)) {
11174: my $subdir=$uname.'__';
11175: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11176: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11177: ."/$udom/$subdir/$uname";
11178: } elsif (defined($alternateRoot)) {
11179: $dirRoot = $alternateRoot;
1.751 banghart 11180: }
1.253 stredwic 11181:
11182: if($udom) {
11183: if($uname) {
1.1135 raeburn 11184: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11185: if ($uhome eq 'no_host') {
11186: return ([],'no_host');
11187: }
1.955 raeburn 11188: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11189: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11190: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11191: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11192: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11193: } else {
11194: @listing_results = map { &unescape($_); } split(/:/,$listing);
11195: }
1.605 matthew 11196: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11197: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11198: @listing_results = split(/:/,$listing);
11199: } else {
11200: @listing_results = map { &unescape($_); } split(/:/,$listing);
11201: }
1.1135 raeburn 11202: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11203: ($listing eq 'rejected') || ($listing eq 'refused') ||
11204: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11205: return ([],$listing);
11206: } else {
11207: return (\@listing_results);
1.1135 raeburn 11208: }
1.955 raeburn 11209: } elsif(!$alternateRoot) {
1.1136 raeburn 11210: my (%allusers,%listerror);
1.841 albertel 11211: my %servers = &get_servers($udom,'library');
1.955 raeburn 11212: foreach my $tryserver (keys(%servers)) {
11213: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11214: &escape($udom),$tryserver);
11215: if ($listing eq 'unknown_cmd') {
11216: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11217: $udom, $tryserver);
11218: } else {
11219: @listing_results = map { &unescape($_); } split(/:/,$listing);
11220: }
1.841 albertel 11221: if ($listing eq 'unknown_cmd') {
11222: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11223: $udom, $tryserver);
11224: @listing_results = split(/:/,$listing);
11225: } else {
11226: @listing_results =
11227: map { &unescape($_); } split(/:/,$listing);
11228: }
1.1136 raeburn 11229: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11230: ($listing eq 'rejected') || ($listing eq 'refused') ||
11231: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11232: $listerror{$tryserver} = $listing;
11233: } else {
1.841 albertel 11234: foreach my $line (@listing_results) {
11235: my ($entry) = split(/&/,$line,2);
11236: $allusers{$entry} = 1;
11237: }
11238: }
1.253 stredwic 11239: }
1.1136 raeburn 11240: my @alluserslist=();
1.800 albertel 11241: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11242: push(@alluserslist,$user.'&user');
1.253 stredwic 11243: }
1.1172.2.80 raeburn 11244: if (!%listerror) {
11245: # no errors
11246: return (\@alluserslist);
11247: } elsif (scalar(keys(%servers)) == 1) {
11248: # one library server, one error
11249: my ($key) = keys(%listerror);
11250: return (\@alluserslist, $listerror{$key});
11251: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11252: # con_lost indicates that we might miss data from at least one
11253: # library server
11254: return (\@alluserslist, 'con_lost');
11255: } else {
11256: # multiple library servers and no con_lost -> data should be
11257: # complete.
11258: return (\@alluserslist);
11259: }
11260:
1.253 stredwic 11261: } else {
1.1136 raeburn 11262: return ([],'missing username');
1.253 stredwic 11263: }
1.955 raeburn 11264: } elsif(!defined($getpropath)) {
1.1136 raeburn 11265: my $path = $perlvar{'lonDocRoot'}.'/res/';
11266: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11267: return (\@all_domains);
1.955 raeburn 11268: } else {
1.1136 raeburn 11269: return ([],'missing domain');
1.275 stredwic 11270: }
11271: }
11272:
11273: # --------------------------------------------- GetFileTimestamp
11274: # This function utilizes dirlist and returns the date stamp for
11275: # when it was last modified. It will also return an error of -1
11276: # if an error occurs
11277:
11278: sub GetFileTimestamp {
1.955 raeburn 11279: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11280: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11281: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11282: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11283: undef,$getuserdir);
11284: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11285: return -1;
11286: }
11287: if (ref($fileref) eq 'ARRAY') {
11288: my @stats = split('&',$fileref->[0]);
1.375 matthew 11289: # @stats contains first the filename, then the stat output
11290: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11291: } else {
11292: return -1;
1.253 stredwic 11293: }
1.26 www 11294: }
11295:
1.712 albertel 11296: sub stat_file {
11297: my ($uri) = @_;
1.787 albertel 11298: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11299:
1.955 raeburn 11300: my ($udom,$uname,$file);
1.712 albertel 11301: if ($uri =~ m-^/(uploaded|editupload)/-) {
11302: ($udom,$uname,$file) =
1.811 albertel 11303: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11304: $file = 'userfiles/'.$file;
11305: }
11306: if ($uri =~ m-^/res/-) {
11307: ($udom,$uname) =
1.807 albertel 11308: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11309: $file = $uri;
11310: }
11311:
11312: if (!$udom || !$uname || !$file) {
11313: # unable to handle the uri
11314: return ();
11315: }
1.956 raeburn 11316: my $getpropath;
11317: if ($file =~ /^userfiles\//) {
11318: $getpropath = 1;
11319: }
1.1136 raeburn 11320: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11321: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11322: return ();
11323: } else {
11324: if (ref($listref) eq 'ARRAY') {
11325: my @stats = split('&',$listref->[0]);
11326: shift(@stats); #filename is first
11327: return @stats;
11328: }
1.712 albertel 11329: }
11330: return ();
11331: }
11332:
1.26 www 11333: # -------------------------------------------------------- Value of a Condition
11334:
1.713 albertel 11335: # gets the value of a specific preevaluated condition
11336: # stored in the string $env{user.state.<cid>}
11337: # or looks up a condition reference in the bighash and if if hasn't
11338: # already been evaluated recurses into docondval to get the value of
11339: # the condition, then memoizing it to
11340: # $env{user.state.<cid>.<condition>}
1.40 www 11341: sub directcondval {
11342: my $number=shift;
1.620 albertel 11343: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11344: &Apache::lonuserstate::evalstate();
11345: }
1.713 albertel 11346: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11347: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11348: } elsif ($number =~ /^_/) {
11349: my $sub_condition;
11350: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11351: &GDBM_READER(),0640)) {
11352: $sub_condition=$bighash{'conditions'.$number};
11353: untie(%bighash);
11354: }
11355: my $value = &docondval($sub_condition);
1.949 raeburn 11356: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11357: return $value;
11358: }
1.620 albertel 11359: if ($env{'user.state.'.$env{'request.course.id'}}) {
11360: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11361: } else {
11362: return 2;
11363: }
11364: }
11365:
1.713 albertel 11366: # get the collection of conditions for this resource
1.26 www 11367: sub condval {
11368: my $condidx=shift;
1.54 www 11369: my $allpathcond='';
1.713 albertel 11370: foreach my $cond (split(/\|/,$condidx)) {
11371: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11372: $allpathcond.=
11373: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11374: }
1.191 harris41 11375: }
1.54 www 11376: $allpathcond=~s/\|$//;
1.713 albertel 11377: return &docondval($allpathcond);
11378: }
11379:
11380: #evaluates an expression of conditions
11381: sub docondval {
11382: my ($allpathcond) = @_;
11383: my $result=0;
11384: if ($env{'request.course.id'}
11385: && defined($allpathcond)) {
11386: my $operand='|';
11387: my @stack;
11388: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11389: if ($chunk eq '(') {
11390: push @stack,($operand,$result);
11391: } elsif ($chunk eq ')') {
11392: my $before=pop @stack;
11393: if (pop @stack eq '&') {
11394: $result=$result>$before?$before:$result;
11395: } else {
11396: $result=$result>$before?$result:$before;
11397: }
11398: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11399: $operand=$chunk;
11400: } else {
11401: my $new=directcondval($chunk);
11402: if ($operand eq '&') {
11403: $result=$result>$new?$new:$result;
11404: } else {
11405: $result=$result>$new?$result:$new;
11406: }
11407: }
11408: }
1.26 www 11409: }
11410: return $result;
1.421 albertel 11411: }
11412:
11413: # ---------------------------------------------------- Devalidate courseresdata
11414:
11415: sub devalidatecourseresdata {
11416: my ($coursenum,$coursedomain)=@_;
11417: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11418: &devalidate_cache_new('courseres',$hashid);
1.28 www 11419: }
11420:
1.763 www 11421:
1.200 www 11422: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11423: #
11424: # Parameters:
11425: # $coursenum - Number of the course.
11426: # $coursedomain - Domain at which the course was created.
11427: # Returns:
11428: # A hash of the course parameters along (I think) with timestamps
11429: # and version info.
1.877 foxr 11430:
1.624 albertel 11431: sub get_courseresdata {
11432: my ($coursenum,$coursedomain)=@_;
1.200 www 11433: my $coursehom=&homeserver($coursenum,$coursedomain);
11434: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11435: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11436: my %dumpreply;
1.417 albertel 11437: unless (defined($cached)) {
1.624 albertel 11438: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11439: $result=\%dumpreply;
1.251 albertel 11440: my ($tmp) = keys(%dumpreply);
11441: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11442: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11443: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11444: return $tmp;
1.416 albertel 11445: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11446: $result=undef;
1.599 albertel 11447: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11448: }
11449: }
1.624 albertel 11450: return $result;
11451: }
11452:
1.633 albertel 11453: sub devalidateuserresdata {
11454: my ($uname,$udom)=@_;
11455: my $hashid="$udom:$uname";
11456: &devalidate_cache_new('userres',$hashid);
11457: }
11458:
1.624 albertel 11459: sub get_userresdata {
11460: my ($uname,$udom)=@_;
11461: #most student don\'t have any data set, check if there is some data
11462: if (&EXT_cache_status($udom,$uname)) { return undef; }
11463:
11464: my $hashid="$udom:$uname";
11465: my ($result,$cached)=&is_cached_new('userres',$hashid);
11466: if (!defined($cached)) {
11467: my %resourcedata=&dump('resourcedata',$udom,$uname);
11468: $result=\%resourcedata;
11469: &do_cache_new('userres',$hashid,$result,600);
11470: }
11471: my ($tmp)=keys(%$result);
11472: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11473: return $result;
11474: }
11475: #error 2 occurs when the .db doesn't exist
11476: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 11477: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11478: &logthis("<font color=\"blue\">WARNING:".
11479: " Trying to get resource data for ".
11480: $uname." at ".$udom.": ".
11481: $tmp."</font>");
11482: }
1.624 albertel 11483: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11484: #&EXT_cache_set($udom,$uname);
11485: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11486: undef($tmp); # not really an error so don't send it back
1.624 albertel 11487: }
11488: return $tmp;
11489: }
1.879 foxr 11490: #----------------------------------------------- resdata - return resource data
11491: # Purpose:
11492: # Return resource data for either users or for a course.
11493: # Parameters:
11494: # $name - Course/user name.
11495: # $domain - Name of the domain the user/course is registered on.
11496: # $type - Type of thing $name is (must be 'course' or 'user'
11497: # @which - Array of names of resources desired.
11498: # Returns:
11499: # The value of the first reasource in @which that is found in the
11500: # resource hash.
11501: # Exceptional Conditions:
11502: # If the $type passed in is not valid (not the string 'course' or
11503: # 'user', an undefined reference is returned.
11504: # If none of the resources are found, an undef is returned
1.624 albertel 11505: sub resdata {
11506: my ($name,$domain,$type,@which)=@_;
11507: my $result;
11508: if ($type eq 'course') {
11509: $result=&get_courseresdata($name,$domain);
11510: } elsif ($type eq 'user') {
11511: $result=&get_userresdata($name,$domain);
11512: }
11513: if (!ref($result)) { return $result; }
1.251 albertel 11514: foreach my $item (@which) {
1.927 albertel 11515: if (defined($result->{$item->[0]})) {
11516: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11517: }
1.250 albertel 11518: }
1.291 albertel 11519: return undef;
1.200 www 11520: }
11521:
1.1172.2.31 raeburn 11522: sub get_numsuppfiles {
11523: my ($cnum,$cdom,$ignorecache)=@_;
11524: my $hashid=$cnum.':'.$cdom;
11525: my ($suppcount,$cached);
11526: unless ($ignorecache) {
11527: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11528: }
11529: unless (defined($cached)) {
11530: my $chome=&homeserver($cnum,$cdom);
11531: unless ($chome eq 'no_host') {
11532: ($suppcount,my $errors) = (0,0);
11533: my $suppmap = 'supplemental.sequence';
11534: ($suppcount,$errors) =
11535: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11536: }
11537: &do_cache_new('suppcount',$hashid,$suppcount,600);
11538: }
11539: return $suppcount;
11540: }
11541:
1.379 matthew 11542: #
11543: # EXT resource caching routines
11544: #
11545:
11546: sub clear_EXT_cache_status {
1.383 albertel 11547: &delenv('cache.EXT.');
1.379 matthew 11548: }
11549:
11550: sub EXT_cache_status {
11551: my ($target_domain,$target_user) = @_;
1.383 albertel 11552: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11553: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11554: # We know already the user has no data
11555: return 1;
11556: } else {
11557: return 0;
11558: }
11559: }
11560:
11561: sub EXT_cache_set {
11562: my ($target_domain,$target_user) = @_;
1.383 albertel 11563: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11564: #&appenv({$cachename => time});
1.379 matthew 11565: }
11566:
1.28 www 11567: # --------------------------------------------------------- Value of a Variable
1.58 www 11568: sub EXT {
1.715 albertel 11569:
1.1172.2.28 raeburn 11570: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11571: unless ($varname) { return ''; }
1.218 albertel 11572: #get real user name/domain, courseid and symb
11573: my $courseid;
1.359 albertel 11574: my $publicuser;
1.427 www 11575: if ($symbparm) {
11576: $symbparm=&get_symb_from_alias($symbparm);
11577: }
1.218 albertel 11578: if (!($uname && $udom)) {
1.790 albertel 11579: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11580: if (!$symbparm) { $symbparm=$cursymb; }
11581: } else {
1.620 albertel 11582: $courseid=$env{'request.course.id'};
1.218 albertel 11583: }
1.48 www 11584: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11585: my $rest;
1.320 albertel 11586: if (defined($therest[0])) {
1.48 www 11587: $rest=join('.',@therest);
11588: } else {
11589: $rest='';
11590: }
1.320 albertel 11591:
1.57 www 11592: my $qualifierrest=$qualifier;
11593: if ($rest) { $qualifierrest.='.'.$rest; }
11594: my $spacequalifierrest=$space;
11595: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11596: if ($realm eq 'user') {
1.48 www 11597: # --------------------------------------------------------------- user.resource
11598: if ($space eq 'resource') {
1.651 albertel 11599: if ( (defined($Apache::lonhomework::parsing_a_problem)
11600: || defined($Apache::lonhomework::parsing_a_task))
11601: &&
1.1172.2.142 raeburn 11602: ($symbparm eq &symbread()) ) {
1.744 albertel 11603: # if we are in the middle of processing the resource the
11604: # get the value we are planning on committing
11605: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11606: return $Apache::lonhomework::results{$qualifierrest};
11607: } else {
11608: return $Apache::lonhomework::history{$qualifierrest};
11609: }
1.335 albertel 11610: } else {
1.359 albertel 11611: my %restored;
1.620 albertel 11612: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11613: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11614: } else {
11615: %restored=&restore($symbparm,$courseid,$udom,$uname);
11616: }
1.335 albertel 11617: return $restored{$qualifierrest};
11618: }
1.48 www 11619: # ----------------------------------------------------------------- user.access
11620: } elsif ($space eq 'access') {
1.218 albertel 11621: # FIXME - not supporting calls for a specific user
1.48 www 11622: return &allowed($qualifier,$rest);
11623: # ------------------------------------------ user.preferences, user.environment
11624: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11625: if (($uname eq $env{'user.name'}) &&
11626: ($udom eq $env{'user.domain'})) {
11627: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11628: } else {
1.359 albertel 11629: my %returnhash;
11630: if (!$publicuser) {
11631: %returnhash=&userenvironment($udom,$uname,
11632: $qualifierrest);
11633: }
1.218 albertel 11634: return $returnhash{$qualifierrest};
11635: }
1.48 www 11636: # ----------------------------------------------------------------- user.course
11637: } elsif ($space eq 'course') {
1.218 albertel 11638: # FIXME - not supporting calls for a specific user
1.620 albertel 11639: return $env{join('.',('request.course',$qualifier))};
1.48 www 11640: # ------------------------------------------------------------------- user.role
11641: } elsif ($space eq 'role') {
1.218 albertel 11642: # FIXME - not supporting calls for a specific user
1.620 albertel 11643: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11644: if ($qualifier eq 'value') {
11645: return $role;
11646: } elsif ($qualifier eq 'extent') {
11647: return $where;
11648: }
11649: # ----------------------------------------------------------------- user.domain
11650: } elsif ($space eq 'domain') {
1.218 albertel 11651: return $udom;
1.48 www 11652: # ------------------------------------------------------------------- user.name
11653: } elsif ($space eq 'name') {
1.218 albertel 11654: return $uname;
1.48 www 11655: # ---------------------------------------------------- Any other user namespace
1.29 www 11656: } else {
1.359 albertel 11657: my %reply;
11658: if (!$publicuser) {
11659: %reply=&get($space,[$qualifierrest],$udom,$uname);
11660: }
11661: return $reply{$qualifierrest};
1.48 www 11662: }
1.236 www 11663: } elsif ($realm eq 'query') {
11664: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11665: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11666: [$spacequalifierrest]);
1.620 albertel 11667: return $env{'form.'.$spacequalifierrest};
1.236 www 11668: } elsif ($realm eq 'request') {
1.48 www 11669: # ------------------------------------------------------------- request.browser
11670: if ($space eq 'browser') {
1.1145 bisitz 11671: return $env{'browser.'.$qualifier};
1.57 www 11672: # ------------------------------------------------------------ request.filename
11673: } else {
1.620 albertel 11674: return $env{'request.'.$spacequalifierrest};
1.29 www 11675: }
1.28 www 11676: } elsif ($realm eq 'course') {
1.48 www 11677: # ---------------------------------------------------------- course.description
1.620 albertel 11678: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11679: } elsif ($realm eq 'resource') {
1.165 www 11680:
1.620 albertel 11681: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11682: if (!$symbparm) { $symbparm=&symbread(); }
11683: }
1.693 albertel 11684:
1.1172.2.30 raeburn 11685: if ($qualifier eq '') {
11686: if ($space eq 'title') {
11687: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11688: return &gettitle($symbparm);
11689: }
1.693 albertel 11690:
1.1172.2.30 raeburn 11691: if ($space eq 'map') {
11692: my ($map) = &decode_symb($symbparm);
11693: return &symbread($map);
11694: }
11695: if ($space eq 'maptitle') {
11696: my ($map) = &decode_symb($symbparm);
11697: return &gettitle($map);
11698: }
11699: if ($space eq 'filename') {
11700: if ($symbparm) {
11701: return &clutter((&decode_symb($symbparm))[2]);
11702: }
11703: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11704: }
1.1172.2.30 raeburn 11705:
11706: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11707: if ($space eq 'visibleparts') {
11708: my $navmap = Apache::lonnavmaps::navmap->new();
11709: my $item;
11710: if (ref($navmap)) {
11711: my $res = $navmap->getBySymb($symbparm);
11712: my $parts = $res->parts();
11713: if (ref($parts) eq 'ARRAY') {
11714: $item = join(',',@{$parts});
11715: }
11716: undef($navmap);
11717: }
11718: return $item;
11719: }
11720: }
11721: }
1.693 albertel 11722:
11723: my ($section, $group, @groups);
1.593 albertel 11724: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 11725: if (($courseid eq '') && ($cid)) {
11726: $courseid = $cid;
11727: }
11728: if (($symbparm && $courseid) &&
11729: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11730:
1.218 albertel 11731: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11732:
1.60 www 11733: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11734: my $symbp=$symbparm;
1.735 albertel 11735: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11736:
11737: my $symbparm=$symbp.'.'.$spacequalifierrest;
11738: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11739:
1.620 albertel 11740: if (($env{'user.name'} eq $uname) &&
11741: ($env{'user.domain'} eq $udom)) {
11742: $section=$env{'request.course.sec'};
1.733 raeburn 11743: @groups = split(/:/,$env{'request.course.groups'});
11744: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11745: } else {
1.539 albertel 11746: if (! defined($usection)) {
1.551 albertel 11747: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11748: } else {
11749: $section = $usection;
11750: }
1.733 raeburn 11751: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11752: }
11753:
11754: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11755: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11756: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11757:
1.593 albertel 11758: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11759: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 11760: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11761:
1.60 www 11762: # ----------------------------------------------------------- first, check user
1.624 albertel 11763:
11764: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 11765: ([$courselevelr,'resource'],
11766: [$courselevelm,'map' ],
11767: [$courselevel, 'course' ]));
1.931 albertel 11768: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11769:
1.594 albertel 11770: # ------------------------------------------------ second, check some of course
1.684 raeburn 11771: my $coursereply;
1.691 raeburn 11772: if (@groups > 0) {
11773: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11774: $mapparm,$spacequalifierrest);
1.927 albertel 11775: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11776: }
1.96 www 11777:
1.684 raeburn 11778: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11779: $env{'course.'.$courseid.'.domain'},
11780: 'course',
11781: ([$seclevelr, 'resource'],
11782: [$seclevelm, 'map' ],
11783: [$seclevel, 'course' ],
11784: [$courselevelr,'resource']));
11785: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11786:
1.60 www 11787: # ------------------------------------------------------ third, check map parms
1.218 albertel 11788: my %parmhash=();
11789: my $thisparm='';
11790: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11791: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11792: &GDBM_READER(),0640)) {
1.218 albertel 11793: $thisparm=$parmhash{$symbparm};
11794: untie(%parmhash);
11795: }
1.927 albertel 11796: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11797: }
1.594 albertel 11798: # ------------------------------------------ fourth, look in resource metadata
1.71 www 11799:
1.218 albertel 11800: $spacequalifierrest=~s/\./\_/;
1.282 albertel 11801: my $filename;
11802: if (!$symbparm) { $symbparm=&symbread(); }
11803: if ($symbparm) {
1.409 www 11804: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11805: } else {
1.620 albertel 11806: $filename=$env{'request.filename'};
1.282 albertel 11807: }
11808: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 11809: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 11810: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 11811: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11812:
1.927 albertel 11813: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 11814: if ($symbparm && defined($courseid) &&
1.620 albertel 11815: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11816: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11817: $env{'course.'.$courseid.'.domain'},
11818: 'course',
1.927 albertel 11819: ([$courselevelm,'map' ],
11820: [$courselevel, 'course']));
11821: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11822: }
1.145 www 11823: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11824: unless ($space eq '0') {
1.336 albertel 11825: my @parts=split(/_/,$space);
11826: my $id=pop(@parts);
11827: my $part=join('_',@parts);
11828: if ($part eq '') { $part='0'; }
1.927 albertel 11829: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11830: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11831: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11832: }
1.395 albertel 11833: if ($recurse) { return undef; }
11834: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11835: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11836: # ---------------------------------------------------- Any other user namespace
11837: } elsif ($realm eq 'environment') {
11838: # ----------------------------------------------------------------- environment
1.620 albertel 11839: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11840: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11841: } else {
1.770 albertel 11842: if ($uname eq 'anonymous' && $udom eq '') {
11843: return '';
11844: }
1.219 albertel 11845: my %returnhash=&userenvironment($udom,$uname,
11846: $spacequalifierrest);
11847: return $returnhash{$spacequalifierrest};
11848: }
1.28 www 11849: } elsif ($realm eq 'system') {
1.48 www 11850: # ----------------------------------------------------------------- system.time
11851: if ($space eq 'time') {
11852: return time;
11853: }
1.696 albertel 11854: } elsif ($realm eq 'server') {
11855: # ----------------------------------------------------------------- system.time
11856: if ($space eq 'name') {
11857: return $ENV{'SERVER_NAME'};
11858: }
1.28 www 11859: }
1.48 www 11860: return '';
1.61 www 11861: }
11862:
1.927 albertel 11863: sub get_reply {
11864: my ($reply_value) = @_;
1.940 raeburn 11865: if (ref($reply_value) eq 'ARRAY') {
11866: if (wantarray) {
11867: return @$reply_value;
11868: }
11869: return $reply_value->[0];
11870: } else {
11871: return $reply_value;
1.927 albertel 11872: }
11873: }
11874:
1.691 raeburn 11875: sub check_group_parms {
11876: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11877: my @groupitems = ();
11878: my $resultitem;
1.927 albertel 11879: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11880: foreach my $group (@{$groups}) {
11881: foreach my $level (@levels) {
1.927 albertel 11882: my $item = $courseid.'.['.$group.'].'.$level->[0];
11883: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11884: }
11885: }
11886: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11887: $env{'course.'.$courseid.'.domain'},
11888: 'course',@groupitems);
11889: return $coursereply;
11890: }
11891:
11892: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11893: my ($courseid,@groups) = @_;
11894: @groups = sort(@groups);
1.691 raeburn 11895: return @groups;
11896: }
11897:
1.395 albertel 11898: sub packages_tab_default {
11899: my ($uri,$varname)=@_;
11900: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11901:
11902: my (@extension,@specifics,$do_default);
11903: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11904: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11905: if ($pack_type eq 'default') {
11906: $do_default=1;
11907: } elsif ($pack_type eq 'extension') {
11908: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11909: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11910: # only look at packages defaults for packages that this id is
1.738 albertel 11911: push(@specifics,[$package,$pack_type,$pack_part]);
11912: }
11913: }
11914: # first look for a package that matches the requested part id
11915: foreach my $package (@specifics) {
11916: my (undef,$pack_type,$pack_part)=@{$package};
11917: next if ($pack_part ne $part);
11918: if (defined($packagetab{"$pack_type&$name&default"})) {
11919: return $packagetab{"$pack_type&$name&default"};
11920: }
11921: }
11922: # look for any possible matching non extension_ package
11923: foreach my $package (@specifics) {
11924: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11925: if (defined($packagetab{"$pack_type&$name&default"})) {
11926: return $packagetab{"$pack_type&$name&default"};
11927: }
1.585 albertel 11928: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11929: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11930: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11931: }
11932: }
1.738 albertel 11933: # look for any posible extension_ match
11934: foreach my $package (@extension) {
11935: my ($package,$pack_type)=@{$package};
11936: if (defined($packagetab{"$pack_type&$name&default"})) {
11937: return $packagetab{"$pack_type&$name&default"};
11938: }
11939: if (defined($packagetab{$package."&$name&default"})) {
11940: return $packagetab{$package."&$name&default"};
11941: }
11942: }
11943: # look for a global default setting
11944: if ($do_default && defined($packagetab{"default&$name&default"})) {
11945: return $packagetab{"default&$name&default"};
11946: }
1.395 albertel 11947: return undef;
11948: }
11949:
1.334 albertel 11950: sub add_prefix_and_part {
11951: my ($prefix,$part)=@_;
11952: my $keyroot;
11953: if (defined($prefix) && $prefix !~ /^__/) {
11954: # prefix that has a part already
11955: $keyroot=$prefix;
11956: } elsif (defined($prefix)) {
11957: # prefix that is missing a part
11958: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11959: } else {
11960: # no prefix at all
11961: if (defined($part)) { $keyroot='_'.$part; }
11962: }
11963: return $keyroot;
11964: }
11965:
1.71 www 11966: # ---------------------------------------------------------------- Get metadata
11967:
1.599 albertel 11968: my %metaentry;
1.1070 www 11969: my %importedpartids;
1.1172.2.99 raeburn 11970: my %importedrespids;
1.71 www 11971: sub metadata {
1.176 www 11972: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11973: $uri=&declutter($uri);
1.288 albertel 11974: # if it is a non metadata possible uri return quickly
1.529 albertel 11975: if (($uri eq '') ||
11976: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 11977: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 11978: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11979: return undef;
11980: }
1.1172.2.49 raeburn 11981: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11982: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11983: return undef;
1.288 albertel 11984: }
1.73 www 11985: my $filename=$uri;
11986: $uri=~s/\.meta$//;
1.172 www 11987: #
11988: # Is the metadata already cached?
1.177 www 11989: # Look at timestamp of caching
1.172 www 11990: # Everything is cached by the main uri, libraries are never directly cached
11991: #
1.428 albertel 11992: if (!defined($liburi)) {
1.599 albertel 11993: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11994: if (defined($cached)) { return $result->{':'.$what}; }
11995: }
11996: {
1.1069 www 11997: # Imported parts would go here
1.1172.2.99 raeburn 11998: my @origfiletagids=();
1.1069 www 11999: my $importedparts=0;
1.1172.2.99 raeburn 12000:
12001: # Imported responseids would go here
12002: my $importedresponses=0;
1.172 www 12003: #
12004: # Is this a recursive call for a library?
12005: #
1.599 albertel 12006: # if (! exists($metacache{$uri})) {
12007: # $metacache{$uri}={};
12008: # }
1.924 albertel 12009: my $cachetime = 60*60;
1.171 www 12010: if ($liburi) {
12011: $liburi=&declutter($liburi);
12012: $filename=$liburi;
1.401 bowersj2 12013: } else {
1.599 albertel 12014: &devalidate_cache_new('meta',$uri);
12015: undef(%metaentry);
1.401 bowersj2 12016: }
1.140 www 12017: my %metathesekeys=();
1.73 www 12018: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12019: my $metastring;
1.1140 www 12020: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12021: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12022: $metastring =
1.929 albertel 12023: &Apache::lonnet::ssi_body($which,
1.924 albertel 12024: ('grade_target' => 'meta'));
12025: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12026: } elsif (($uri !~ m -^(editupload)/-) &&
12027: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12028: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12029: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12030: $metastring=&getfile($file);
1.489 albertel 12031: }
1.208 albertel 12032: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12033: my $token;
1.140 www 12034: undef %metathesekeys;
1.71 www 12035: while ($token=$parser->get_token) {
1.339 albertel 12036: if ($token->[0] eq 'S') {
12037: if (defined($token->[2]->{'package'})) {
1.172 www 12038: #
12039: # This is a package - get package info
12040: #
1.339 albertel 12041: my $package=$token->[2]->{'package'};
12042: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12043: if (defined($token->[2]->{'id'})) {
12044: $keyroot.='_'.$token->[2]->{'id'};
12045: }
1.599 albertel 12046: if ($metaentry{':packages'}) {
12047: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12048: } else {
1.599 albertel 12049: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12050: }
1.736 albertel 12051: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12052: my $part=$keyroot;
12053: $part=~s/^\_//;
1.736 albertel 12054: if ($pack_entry=~/^\Q$package\E\&/ ||
12055: $pack_entry=~/^\Q$package\E_0\&/) {
12056: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12057: # ignore package.tab specified default values
12058: # here &package_tab_default() will fetch those
12059: if ($subp eq 'default') { next; }
1.736 albertel 12060: my $value=$packagetab{$pack_entry};
1.432 albertel 12061: my $unikey;
12062: if ($pack =~ /_0$/) {
12063: $unikey='parameter_0_'.$name;
12064: $part=0;
12065: } else {
12066: $unikey='parameter'.$keyroot.'_'.$name;
12067: }
1.339 albertel 12068: if ($subp eq 'display') {
12069: $value.=' [Part: '.$part.']';
12070: }
1.599 albertel 12071: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12072: $metathesekeys{$unikey}=1;
1.599 albertel 12073: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12074: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12075: }
1.599 albertel 12076: if (defined($metaentry{':'.$unikey.'.default'})) {
12077: $metaentry{':'.$unikey}=
12078: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12079: }
1.339 albertel 12080: }
12081: }
12082: } else {
1.172 www 12083: #
12084: # This is not a package - some other kind of start tag
1.339 albertel 12085: #
12086: my $entry=$token->[1];
1.1068 www 12087: my $unikey='';
1.175 www 12088:
1.339 albertel 12089: if ($entry eq 'import') {
1.175 www 12090: #
12091: # Importing a library here
1.339 albertel 12092: #
1.1067 www 12093: my $location=$parser->get_text('/import');
12094: my $dir=$filename;
12095: $dir=~s|[^/]*$||;
12096: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 12097:
12098: my $importid=$token->[2]->{'id'};
1.1068 www 12099: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 12100: #
12101: # Check metadata for imported file to
12102: # see if it contained response items
12103: #
12104: my %currmetaentry = %metaentry;
12105: my $libresponseorder = &metadata($location,'responseorder');
12106: my $origfile;
12107: if ($libresponseorder ne '') {
12108: if ($#origfiletagids<0) {
12109: undef(%importedrespids);
12110: undef(%importedpartids);
12111: }
12112: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
12113: if (@{$importedrespids{$importid}} > 0) {
12114: $importedresponses = 1;
12115: # We need to get the original file and the imported file to get the response order correct
12116: # Load and inspect original file
12117: if ($#origfiletagids<0) {
12118: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12119: $origfile=&getfile($origfilelocation);
12120: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12121: }
12122: }
12123: }
12124: # Do not overwrite contents of %metaentry hash for resource itself with
12125: # hash populated for imported library file
12126: %metaentry = %currmetaentry;
12127: undef(%currmetaentry);
1.1068 www 12128: if ($importmode eq 'problem') {
1.1069 www 12129: # Import as problem/response
1.1068 www 12130: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12131: } elsif ($importmode eq 'part') {
12132: # Import as part(s)
1.1069 www 12133: $importedparts=1;
12134: # We need to get the original file and the imported file to get the part order correct
12135: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 12136: # Load and inspect original file if we didn't do that already
12137: if ($#origfiletagids<0) {
12138: undef(%importedrespids);
12139: undef(%importedpartids);
12140: if ($origfile eq '') {
12141: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12142: $origfile=&getfile($origfilelocation);
12143: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12144: }
1.1070 www 12145: }
12146:
1.1069 www 12147: # Load and inspect imported file
12148: my $impfile=&getfile($location);
12149: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12150: if ($#impfilepartids>=0) {
12151: # This problem had parts
1.1070 www 12152: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12153: } else {
12154: # Importing by turning a single problem into a problem part
12155: # It gets the import-tags ID as part-ID
12156: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12157: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12158: }
1.1068 www 12159: } else {
12160: # Normal import
12161: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12162: if (defined($token->[2]->{'id'})) {
12163: $unikey.='_'.$token->[2]->{'id'};
12164: }
1.1067 www 12165: }
12166:
1.339 albertel 12167: if ($depthcount<20) {
1.736 albertel 12168: my $metadata =
12169: &metadata($uri,'keys', $location,$unikey,
12170: $depthcount+1);
12171: foreach my $meta (split(',',$metadata)) {
12172: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12173: $metathesekeys{$meta}=1;
1.339 albertel 12174: }
1.1068 www 12175:
12176: }
1.1067 www 12177: } else {
12178: #
12179: # Not importing, some other kind of non-package, non-library start tag
12180: #
12181: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12182: if (defined($token->[2]->{'id'})) {
12183: $unikey.='_'.$token->[2]->{'id'};
12184: }
1.339 albertel 12185: if (defined($token->[2]->{'name'})) {
12186: $unikey.='_'.$token->[2]->{'name'};
12187: }
12188: $metathesekeys{$unikey}=1;
1.736 albertel 12189: foreach my $param (@{$token->[3]}) {
12190: $metaentry{':'.$unikey.'.'.$param} =
12191: $token->[2]->{$param};
1.339 albertel 12192: }
12193: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12194: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12195: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12196: # only ws inside the tag, and not in default, so use default
12197: # as value
1.599 albertel 12198: $metaentry{':'.$unikey}=$default;
1.908 albertel 12199: } elsif ( $internaltext =~ /\S/ ) {
12200: # something interesting inside the tag
12201: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12202: } else {
1.908 albertel 12203: # no interesting values, don't set a default
1.339 albertel 12204: }
1.172 www 12205: # end of not-a-package not-a-library import
1.339 albertel 12206: }
1.172 www 12207: # end of not-a-package start tag
1.339 albertel 12208: }
1.172 www 12209: # the next is the end of "start tag"
1.339 albertel 12210: }
12211: }
1.483 albertel 12212: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12213: $extension = lc($extension);
12214: if ($extension eq 'htm') { $extension='html'; }
12215:
1.737 albertel 12216: foreach my $key (keys(%packagetab)) {
1.483 albertel 12217: #no specific packages #how's our extension
12218: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12219: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12220: \%metathesekeys);
12221: }
1.883 albertel 12222:
12223: if (!exists($metaentry{':packages'})
12224: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12225: foreach my $key (keys(%packagetab)) {
1.483 albertel 12226: #no specific packages well let's get default then
12227: if ($key!~/^default&/) { next; }
1.488 albertel 12228: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12229: \%metathesekeys);
12230: }
12231: }
1.338 www 12232: # are there custom rights to evaluate
1.599 albertel 12233: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12234:
1.338 www 12235: #
12236: # Importing a rights file here
1.339 albertel 12237: #
12238: unless ($depthcount) {
1.599 albertel 12239: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12240: my $dir=$filename;
12241: $dir=~s|[^/]*$||;
12242: $location=&filelocation($dir,$location);
1.736 albertel 12243: my $rights_metadata =
12244: &metadata($uri,'keys',$location,'_rights',
12245: $depthcount+1);
12246: foreach my $rights (split(',',$rights_metadata)) {
12247: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12248: $metathesekeys{$rights}=1;
1.339 albertel 12249: }
12250: }
12251: }
1.737 albertel 12252: # uniqifiy package listing
12253: my %seen;
12254: my @uniq_packages =
12255: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12256: $metaentry{':packages'} = join(',',@uniq_packages);
12257:
1.1172.2.99 raeburn 12258: if (($importedresponses) || ($importedparts)) {
12259: if ($importedparts) {
1.1070 www 12260: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 12261: $metaentry{':partorder'}='';
12262: $metathesekeys{'partorder'}=1;
12263: }
12264: if ($importedresponses) {
12265: # We had imported responses and need to rebuild responseorder
12266: $metaentry{':responseorder'}='';
12267: $metathesekeys{'responseorder'}=1;
12268: }
12269: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12270: my $origid = $origfiletagids[$index+1];
12271: if ($origfiletagids[$index] eq 'part') {
12272: # Original part, part of the problem
12273: if ($importedparts) {
12274: $metaentry{':partorder'}.=','.$origid;
12275: }
12276: } elsif ($origfiletagids[$index] eq 'import') {
12277: if ($importedparts) {
12278: # We have imported parts at this position
12279: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12280: }
12281: if ($importedresponses) {
12282: # We have imported responses at this position
12283: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12284: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12285: }
12286: }
12287: } else {
12288: # Original response item, part of the problem
12289: if ($importedresponses) {
12290: $metaentry{':responseorder'}.=','.$origid;
12291: }
12292: }
12293: }
12294: if ($importedparts) {
12295: $metaentry{':partorder'}=~s/^\,//;
12296: }
12297: if ($importedresponses) {
12298: $metaentry{':responseorder'}=~s/^\,//;
12299: }
1.1070 www 12300: }
12301:
1.737 albertel 12302: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12303: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 12304: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 12305: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 12306: # this is the end of "was not already recently cached
1.71 www 12307: }
1.599 albertel 12308: return $metaentry{':'.$what};
1.261 albertel 12309: }
12310:
1.488 albertel 12311: sub metadata_create_package_def {
1.483 albertel 12312: my ($uri,$key,$package,$metathesekeys)=@_;
12313: my ($pack,$name,$subp)=split(/\&/,$key);
12314: if ($subp eq 'default') { next; }
12315:
1.599 albertel 12316: if (defined($metaentry{':packages'})) {
12317: $metaentry{':packages'}.=','.$package;
1.483 albertel 12318: } else {
1.599 albertel 12319: $metaentry{':packages'}=$package;
1.483 albertel 12320: }
12321: my $value=$packagetab{$key};
12322: my $unikey;
12323: $unikey='parameter_0_'.$name;
1.599 albertel 12324: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12325: $$metathesekeys{$unikey}=1;
1.599 albertel 12326: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12327: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12328: }
1.599 albertel 12329: if (defined($metaentry{':'.$unikey.'.default'})) {
12330: $metaentry{':'.$unikey}=
12331: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12332: }
12333: }
12334:
1.261 albertel 12335: sub metadata_generate_part0 {
12336: my ($metadata,$metacache,$uri) = @_;
12337: my %allnames;
1.737 albertel 12338: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12339: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12340: my $part=$$metacache{':'.$metakey.'.part'};
12341: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12342: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12343: $allnames{$name}=$part;
12344: }
12345: }
12346: }
12347: foreach my $name (keys(%allnames)) {
12348: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12349: my $key=":parameter_0_$name";
1.261 albertel 12350: $$metacache{"$key.part"}='0';
12351: $$metacache{"$key.name"}=$name;
1.428 albertel 12352: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12353: $allnames{$name}.'_'.$name.
12354: '.type'};
1.428 albertel 12355: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12356: '.display'};
1.644 www 12357: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12358: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12359: $$metacache{"$key.display"}=$olddis;
12360: }
1.71 www 12361: }
12362:
1.764 albertel 12363: # ------------------------------------------------------ Devalidate title cache
12364:
12365: sub devalidate_title_cache {
12366: my ($url)=@_;
12367: if (!$env{'request.course.id'}) { return; }
12368: my $symb=&symbread($url);
12369: if (!$symb) { return; }
12370: my $key=$env{'request.course.id'}."\0".$symb;
12371: &devalidate_cache_new('title',$key);
12372: }
12373:
1.1014 droeschl 12374: # ------------------------------------------------- Get the title of a course
12375:
12376: sub current_course_title {
12377: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12378: }
1.301 www 12379: # ------------------------------------------------- Get the title of a resource
12380:
12381: sub gettitle {
12382: my $urlsymb=shift;
12383: my $symb=&symbread($urlsymb);
1.534 albertel 12384: if ($symb) {
1.620 albertel 12385: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12386: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12387: if (defined($cached)) {
12388: return $result;
12389: }
1.534 albertel 12390: my ($map,$resid,$url)=&decode_symb($symb);
12391: my $title='';
1.907 albertel 12392: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12393: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12394: } else {
12395: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12396: &GDBM_READER(),0640)) {
12397: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12398: $title=$bighash{'title_'.$mapid.'.'.$resid};
12399: untie(%bighash);
12400: }
1.534 albertel 12401: }
12402: $title=~s/\&colon\;/\:/gs;
12403: if ($title) {
1.1159 www 12404: # Remember both $symb and $title for dynamic metadata
12405: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12406: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12407: # Cache this title and then return it
1.599 albertel 12408: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12409: }
12410: $urlsymb=$url;
12411: }
12412: my $title=&metadata($urlsymb,'title');
12413: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12414: return $title;
1.301 www 12415: }
1.613 albertel 12416:
1.614 albertel 12417: sub get_slot {
12418: my ($which,$cnum,$cdom)=@_;
12419: if (!$cnum || !$cdom) {
1.790 albertel 12420: (undef,my $courseid)=&whichuser();
1.620 albertel 12421: $cdom=$env{'course.'.$courseid.'.domain'};
12422: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12423: }
1.703 albertel 12424: my $key=join("\0",'slots',$cdom,$cnum,$which);
12425: my %slotinfo;
12426: if (exists($remembered{$key})) {
12427: $slotinfo{$which} = $remembered{$key};
12428: } else {
12429: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12430: &Apache::lonhomework::showhash(%slotinfo);
12431: my ($tmp)=keys(%slotinfo);
12432: if ($tmp=~/^error:/) { return (); }
12433: $remembered{$key} = $slotinfo{$which};
12434: }
1.616 albertel 12435: if (ref($slotinfo{$which}) eq 'HASH') {
12436: return %{$slotinfo{$which}};
12437: }
12438: return $slotinfo{$which};
1.614 albertel 12439: }
1.1150 raeburn 12440:
12441: sub get_reservable_slots {
12442: my ($cnum,$cdom,$uname,$udom) = @_;
12443: my $now = time;
12444: my $reservable_info;
12445: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12446: if (exists($remembered{$key})) {
12447: $reservable_info = $remembered{$key};
12448: } else {
12449: my %resv;
12450: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12451: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12452: $reservable_info = \%resv;
12453: $remembered{$key} = $reservable_info;
12454: }
12455: return $reservable_info;
12456: }
12457:
12458: sub get_course_slots {
12459: my ($cnum,$cdom) = @_;
12460: my $hashid=$cnum.':'.$cdom;
12461: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12462: if (defined($cached)) {
12463: if (ref($result) eq 'HASH') {
12464: return %{$result};
12465: }
12466: } else {
12467: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12468: my ($tmp) = keys(%slots);
12469: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 12470: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12471: return %slots;
12472: }
12473: }
12474: return;
12475: }
12476:
12477: sub devalidate_slots_cache {
12478: my ($cnum,$cdom)=@_;
12479: my $hashid=$cnum.':'.$cdom;
12480: &devalidate_cache_new('allslots',$hashid);
12481: }
12482:
1.1172.2.8 raeburn 12483: sub get_coursechange {
12484: my ($cdom,$cnum) = @_;
12485: if ($cdom eq '' || $cnum eq '') {
12486: return unless ($env{'request.course.id'});
12487: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12488: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12489: }
12490: my $hashid=$cdom.'_'.$cnum;
12491: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12492: if ((defined($cached)) && ($change ne '')) {
12493: return $change;
12494: } else {
12495: my %crshash;
12496: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12497: if ($crshash{'internal.contentchange'} eq '') {
12498: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12499: if ($change eq '') {
12500: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12501: $change = $crshash{'internal.created'};
12502: }
12503: } else {
12504: $change = $crshash{'internal.contentchange'};
12505: }
12506: my $cachetime = 600;
12507: &do_cache_new('crschange',$hashid,$change,$cachetime);
12508: }
12509: return $change;
12510: }
12511:
12512: sub devalidate_coursechange_cache {
12513: my ($cnum,$cdom)=@_;
12514: my $hashid=$cnum.':'.$cdom;
12515: &devalidate_cache_new('crschange',$hashid);
12516: }
12517:
1.31 www 12518: # ------------------------------------------------- Update symbolic store links
12519:
12520: sub symblist {
12521: my ($mapname,%newhash)=@_;
1.438 www 12522: $mapname=&deversion(&declutter($mapname));
1.31 www 12523: my %hash;
1.620 albertel 12524: if (($env{'request.course.fn'}) && (%newhash)) {
12525: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12526: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12527: foreach my $url (keys(%newhash)) {
1.711 albertel 12528: next if ($url eq 'last_known'
12529: && $env{'form.no_update_last_known'});
12530: $hash{declutter($url)}=&encode_symb($mapname,
12531: $newhash{$url}->[1],
12532: $newhash{$url}->[0]);
1.191 harris41 12533: }
1.31 www 12534: if (untie(%hash)) {
12535: return 'ok';
12536: }
12537: }
12538: }
12539: return 'error';
1.212 www 12540: }
12541:
12542: # --------------------------------------------------------------- Verify a symb
12543:
12544: sub symbverify {
1.1172.2.11 raeburn 12545: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12546: my $thisfn=$thisurl;
1.439 www 12547: $thisfn=&declutter($thisfn);
1.215 www 12548: # direct jump to resource in page or to a sequence - will construct own symbs
12549: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12550: # check URL part
1.409 www 12551: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12552:
1.431 www 12553: unless ($url eq $thisfn) { return 0; }
1.213 www 12554:
1.216 www 12555: $symb=&symbclean($symb);
1.510 www 12556: $thisurl=&deversion($thisurl);
1.439 www 12557: $thisfn=&deversion($thisfn);
1.213 www 12558:
12559: my %bighash;
12560: my $okay=0;
1.431 www 12561:
1.620 albertel 12562: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12563: &GDBM_READER(),0640)) {
1.1032 raeburn 12564: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12565: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 12566: if ($map =~ m{^uploaded/.+\.page$}) {
12567: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12568: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12569: }
12570: }
12571: my $ids;
1.1172.2.122 raeburn 12572: if ($map =~ m{^uploaded/.+\.page$}) {
12573: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 12574: } else {
12575: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12576: }
1.1102 raeburn 12577: unless ($ids) {
1.1172.2.13 raeburn 12578: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 12579: $ids=$bighash{$idkey};
1.216 www 12580: }
12581: if ($ids) {
12582: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 12583: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12584: $symb =~ s/\?.+$//;
12585: }
1.800 albertel 12586: foreach my $id (split(/\,/,$ids)) {
12587: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12588: if (
12589: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 12590: eq $symb) {
1.1172.2.11 raeburn 12591: if (ref($encstate)) {
12592: $$encstate = $bighash{'encrypted_'.$id};
12593: }
1.1172.2.13 raeburn 12594: if (($env{'request.role.adv'}) ||
12595: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 12596: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 12597: $okay=1;
12598: last;
12599: }
12600: }
12601: }
1.216 www 12602: }
1.213 www 12603: untie(%bighash);
12604: }
12605: return $okay;
1.31 www 12606: }
12607:
1.210 www 12608: # --------------------------------------------------------------- Clean-up symb
12609:
12610: sub symbclean {
12611: my $symb=shift;
1.568 albertel 12612: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12613: # remove version from map
12614: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12615:
1.210 www 12616: # remove version from URL
12617: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12618:
1.507 www 12619: # remove wrapper
12620:
1.510 www 12621: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12622: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12623: return $symb;
1.409 www 12624: }
12625:
12626: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12627:
12628: sub encode_symb {
12629: my ($map,$resid,$url)=@_;
12630: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12631: }
1.409 www 12632:
12633: sub decode_symb {
1.568 albertel 12634: my $symb=shift;
12635: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12636: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12637: return (&fixversion($map),$resid,&fixversion($url));
12638: }
12639:
12640: sub fixversion {
12641: my $fn=shift;
1.609 banghart 12642: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12643: my %bighash;
12644: my $uri=&clutter($fn);
1.620 albertel 12645: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12646: # is this cached?
1.599 albertel 12647: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12648: if (defined($cached)) { return $result; }
12649: # unfortunately not cached, or expired
1.620 albertel 12650: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12651: &GDBM_READER(),0640)) {
12652: if ($bighash{'version_'.$uri}) {
12653: my $version=$bighash{'version_'.$uri};
1.444 www 12654: unless (($version eq 'mostrecent') ||
12655: ($version==&getversion($uri))) {
1.440 www 12656: $uri=~s/\.(\w+)$/\.$version\.$1/;
12657: }
12658: }
12659: untie %bighash;
1.413 www 12660: }
1.599 albertel 12661: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12662: }
12663:
12664: sub deversion {
12665: my $url=shift;
12666: $url=~s/\.\d+\.(\w+)$/\.$1/;
12667: return $url;
1.210 www 12668: }
12669:
1.31 www 12670: # ------------------------------------------------------ Return symb list entry
12671:
12672: sub symbread {
1.1172.2.126 raeburn 12673: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128 raeburn 12674: $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54 raeburn 12675: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128 raeburn 12676: if (defined($env{$cache_str})) {
1.1172.2.126 raeburn 12677: unless (ref($possibles) eq 'HASH') {
12678: if ($ignorecachednull) {
12679: return $env{$cache_str} unless ($env{$cache_str} eq '');
12680: } else {
12681: return $env{$cache_str};
12682: }
1.1172.2.66 raeburn 12683: }
12684: }
1.242 www 12685: # no filename provided? try from environment
1.1172.2.54 raeburn 12686: unless ($thisfn) {
1.620 albertel 12687: if ($env{'request.symb'}) {
1.1172.2.128 raeburn 12688: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13 raeburn 12689: }
12690: $thisfn=$env{'request.filename'};
1.44 www 12691: }
1.569 albertel 12692: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12693: # is that filename actually a symb? Verify, clean, and return
12694: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12695: if (&symbverify($thisfn,$1)) {
1.1172.2.128 raeburn 12696: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12697: }
1.242 www 12698: }
1.44 www 12699: $thisfn=declutter($thisfn);
1.31 www 12700: my %hash;
1.37 www 12701: my %bighash;
12702: my $syval='';
1.620 albertel 12703: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12704: my $targetfn = $thisfn;
1.609 banghart 12705: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12706: $targetfn = 'adm/wrapper/'.$thisfn;
12707: }
1.687 albertel 12708: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12709: $targetfn=$1;
12710: }
1.1172.2.128 raeburn 12711: unless ($ignoresymbdb) {
1.1172.2.126 raeburn 12712: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12713: &GDBM_READER(),0640)) {
12714: $syval=$hash{$targetfn};
12715: untie(%hash);
12716: }
1.1172.2.128 raeburn 12717: if ($syval && $checkforblock) {
12718: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126 raeburn 12719: if (@blockers) {
12720: $syval='';
12721: }
12722: }
1.37 www 12723: }
12724: # ---------------------------------------------------------- There was an entry
12725: if ($syval) {
1.601 albertel 12726: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12727: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12728: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12729: #return $env{$cache_str}='';
1.601 albertel 12730: #}
12731: #$syval.=$1;
12732: #}
1.37 www 12733: } else {
12734: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12735: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12736: &GDBM_READER(),0640)) {
1.37 www 12737: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12738: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12739: unless ($ids) {
12740: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12741: }
12742: unless ($ids) {
12743: # alias?
12744: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12745: }
1.37 www 12746: if ($ids) {
12747: # ------------------------------------------------------------------- Has ID(s)
12748: my @possibilities=split(/\,/,$ids);
1.39 www 12749: if ($#possibilities==0) {
12750: # ----------------------------------------------- There is only one possibility
1.37 www 12751: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12752: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12753: $resid,$thisfn);
1.1172.2.66 raeburn 12754: if (ref($possibles) eq 'HASH') {
1.1172.2.126 raeburn 12755: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12756: $possibles->{$syval} = 1;
12757: }
1.1172.2.66 raeburn 12758: }
12759: if ($checkforblock) {
1.1172.2.126 raeburn 12760: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127 raeburn 12761: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126 raeburn 12762: if (@blockers) {
12763: $syval = '';
12764: untie(%bighash);
12765: return $env{$cache_str}='';
12766: }
1.1172.2.66 raeburn 12767: }
12768: }
12769: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12770: # ------------------------------------------ There is more than one possibility
12771: my $realpossible=0;
1.800 albertel 12772: foreach my $id (@possibilities) {
12773: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 12774: my $canaccess;
12775: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12776: $canaccess = 1;
12777: } else {
12778: $canaccess = &allowed('bre',$file);
12779: }
12780: if ($canaccess) {
12781: my ($mapid,$resid)=split(/\./,$id);
12782: if ($bighash{'map_type_'.$mapid} ne 'page') {
12783: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12784: $resid,$thisfn);
1.1172.2.126 raeburn 12785: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127 raeburn 12786: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66 raeburn 12787: if ($checkforblock) {
1.1172.2.127 raeburn 12788: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126 raeburn 12789: if (@blockers > 0) {
12790: $syval = '';
12791: } else {
1.1172.2.66 raeburn 12792: $syval = $poss_syval;
12793: $realpossible++;
12794: }
12795: } else {
12796: $syval = $poss_syval;
12797: $realpossible++;
12798: }
1.1172.2.126 raeburn 12799: if ($syval) {
12800: if (ref($possibles) eq 'HASH') {
12801: $possibles->{$syval} = 1;
12802: }
12803: }
1.1172.2.66 raeburn 12804: }
1.39 www 12805: }
1.191 harris41 12806: }
1.39 www 12807: if ($realpossible!=1) { $syval=''; }
1.249 www 12808: } else {
12809: $syval='';
1.37 www 12810: }
12811: }
1.1172.2.66 raeburn 12812: untie(%bighash);
1.481 raeburn 12813: }
1.31 www 12814: }
1.62 www 12815: if ($syval) {
1.1172.2.128 raeburn 12816: return $env{$cache_str}=$syval;
1.62 www 12817: }
1.31 www 12818: }
1.949 raeburn 12819: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12820: return $env{$cache_str}='';
1.31 www 12821: }
12822:
12823: # ---------------------------------------------------------- Return random seed
12824:
1.32 www 12825: sub numval {
12826: my $txt=shift;
12827: $txt=~tr/A-J/0-9/;
12828: $txt=~tr/a-j/0-9/;
12829: $txt=~tr/K-T/0-9/;
12830: $txt=~tr/k-t/0-9/;
12831: $txt=~tr/U-Z/0-5/;
12832: $txt=~tr/u-z/0-5/;
12833: $txt=~s/\D//g;
1.564 albertel 12834: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12835: return int($txt);
1.368 albertel 12836: }
12837:
1.484 albertel 12838: sub numval2 {
12839: my $txt=shift;
12840: $txt=~tr/A-J/0-9/;
12841: $txt=~tr/a-j/0-9/;
12842: $txt=~tr/K-T/0-9/;
12843: $txt=~tr/k-t/0-9/;
12844: $txt=~tr/U-Z/0-5/;
12845: $txt=~tr/u-z/0-5/;
12846: $txt=~s/\D//g;
12847: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12848: my $total;
12849: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12850: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12851: return int($total);
12852: }
12853:
1.575 albertel 12854: sub numval3 {
12855: use integer;
12856: my $txt=shift;
12857: $txt=~tr/A-J/0-9/;
12858: $txt=~tr/a-j/0-9/;
12859: $txt=~tr/K-T/0-9/;
12860: $txt=~tr/k-t/0-9/;
12861: $txt=~tr/U-Z/0-5/;
12862: $txt=~tr/u-z/0-5/;
12863: $txt=~s/\D//g;
12864: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12865: my $total;
12866: foreach my $val (@txts) { $total+=$val; }
12867: if ($_64bit) { $total=(($total<<32)>>32); }
12868: return $total;
12869: }
12870:
1.675 albertel 12871: sub digest {
12872: my ($data)=@_;
12873: my $digest=&Digest::MD5::md5($data);
12874: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12875: my ($e,$f);
12876: {
12877: use integer;
12878: $e=($a+$b);
12879: $f=($c+$d);
12880: if ($_64bit) {
12881: $e=(($e<<32)>>32);
12882: $f=(($f<<32)>>32);
12883: }
12884: }
12885: if (wantarray) {
12886: return ($e,$f);
12887: } else {
12888: my $g;
12889: {
12890: use integer;
12891: $g=($e+$f);
12892: if ($_64bit) {
12893: $g=(($g<<32)>>32);
12894: }
12895: }
12896: return $g;
12897: }
12898: }
12899:
1.368 albertel 12900: sub latest_rnd_algorithm_id {
1.675 albertel 12901: return '64bit5';
1.366 albertel 12902: }
1.32 www 12903:
1.503 albertel 12904: sub get_rand_alg {
12905: my ($courseid)=@_;
1.790 albertel 12906: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12907: if ($courseid) {
1.620 albertel 12908: return $env{"course.$courseid.rndseed"};
1.503 albertel 12909: }
12910: return &latest_rnd_algorithm_id();
12911: }
12912:
1.562 albertel 12913: sub validCODE {
12914: my ($CODE)=@_;
12915: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12916: return 0;
12917: }
12918:
1.491 albertel 12919: sub getCODE {
1.620 albertel 12920: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12921: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12922: defined($Apache::lonhomework::parsing_a_task) ) &&
12923: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12924: return $Apache::lonhomework::history{'resource.CODE'};
12925: }
12926: return undef;
12927: }
1.1133 foxr 12928: #
12929: # Determines the random seed for a specific context:
12930: #
12931: # parameters:
12932: # symb - in course context the symb for the seed.
12933: # course_id - The course id of the form domain_coursenum.
12934: # domain - Domain for the user.
12935: # course - Course for the user.
12936: # cenv - environment of the course.
12937: #
12938: # NOTE:
12939: # All parameters are picked out of the environment if missing
12940: # or not defined.
12941: # If a symb cannot be determined the current time is used instead.
12942: #
12943: # For a given well defined symb, courside, domain, username,
12944: # and course environment, the seed is reproducible.
12945: #
1.31 www 12946: sub rndseed {
1.1133 foxr 12947: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12948: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12949: if (!defined($symb)) {
1.366 albertel 12950: unless ($symb=$wsymb) { return time; }
12951: }
1.1146 foxr 12952: if (!defined $courseid) {
12953: $courseid=$wcourseid;
12954: }
12955: if (!defined $domain) { $domain=$wdomain; }
12956: if (!defined $username) { $username=$wusername }
1.1133 foxr 12957:
12958: my $which;
12959: if (defined($cenv->{'rndseed'})) {
12960: $which = $cenv->{'rndseed'};
12961: } else {
12962: $which =&get_rand_alg($courseid);
12963: }
1.491 albertel 12964: if (defined(&getCODE())) {
1.675 albertel 12965: if ($which eq '64bit5') {
12966: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12967: } elsif ($which eq '64bit4') {
1.575 albertel 12968: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12969: } else {
12970: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12971: }
1.675 albertel 12972: } elsif ($which eq '64bit5') {
12973: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12974: } elsif ($which eq '64bit4') {
12975: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12976: } elsif ($which eq '64bit3') {
12977: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12978: } elsif ($which eq '64bit2') {
12979: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12980: } elsif ($which eq '64bit') {
12981: return &rndseed_64bit($symb,$courseid,$domain,$username);
12982: }
12983: return &rndseed_32bit($symb,$courseid,$domain,$username);
12984: }
12985:
12986: sub rndseed_32bit {
12987: my ($symb,$courseid,$domain,$username)=@_;
12988: {
12989: use integer;
12990: my $symbchck=unpack("%32C*",$symb) << 27;
12991: my $symbseed=numval($symb) << 22;
12992: my $namechck=unpack("%32C*",$username) << 17;
12993: my $nameseed=numval($username) << 12;
12994: my $domainseed=unpack("%32C*",$domain) << 7;
12995: my $courseseed=unpack("%32C*",$courseid);
12996: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12997: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12998: #&logthis("rndseed :$num:$symb");
1.564 albertel 12999: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 13000: return $num;
13001: }
13002: }
13003:
13004: sub rndseed_64bit {
13005: my ($symb,$courseid,$domain,$username)=@_;
13006: {
13007: use integer;
13008: my $symbchck=unpack("%32S*",$symb) << 21;
13009: my $symbseed=numval($symb) << 10;
13010: my $namechck=unpack("%32S*",$username);
13011:
13012: my $nameseed=numval($username) << 21;
13013: my $domainseed=unpack("%32S*",$domain) << 10;
13014: my $courseseed=unpack("%32S*",$courseid);
13015:
13016: my $num1=$symbchck+$symbseed+$namechck;
13017: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13018: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13019: #&logthis("rndseed :$num:$symb");
1.564 albertel 13020: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13021: return "$num1,$num2";
1.155 albertel 13022: }
1.366 albertel 13023: }
13024:
1.443 albertel 13025: sub rndseed_64bit2 {
13026: my ($symb,$courseid,$domain,$username)=@_;
13027: {
13028: use integer;
13029: # strings need to be an even # of cahracters long, it it is odd the
13030: # last characters gets thrown away
13031: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13032: my $symbseed=numval($symb) << 10;
13033: my $namechck=unpack("%32S*",$username.' ');
13034:
13035: my $nameseed=numval($username) << 21;
1.501 albertel 13036: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13037: my $courseseed=unpack("%32S*",$courseid.' ');
13038:
13039: my $num1=$symbchck+$symbseed+$namechck;
13040: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13041: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13042: #&logthis("rndseed :$num:$symb");
1.803 albertel 13043: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13044: return "$num1,$num2";
13045: }
13046: }
13047:
13048: sub rndseed_64bit3 {
13049: my ($symb,$courseid,$domain,$username)=@_;
13050: {
13051: use integer;
13052: # strings need to be an even # of cahracters long, it it is odd the
13053: # last characters gets thrown away
13054: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13055: my $symbseed=numval2($symb) << 10;
13056: my $namechck=unpack("%32S*",$username.' ');
13057:
13058: my $nameseed=numval2($username) << 21;
1.443 albertel 13059: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13060: my $courseseed=unpack("%32S*",$courseid.' ');
13061:
13062: my $num1=$symbchck+$symbseed+$namechck;
13063: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13064: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13065: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 13066: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13067:
1.503 albertel 13068: return "$num1:$num2";
1.443 albertel 13069: }
13070: }
13071:
1.575 albertel 13072: sub rndseed_64bit4 {
13073: my ($symb,$courseid,$domain,$username)=@_;
13074: {
13075: use integer;
13076: # strings need to be an even # of cahracters long, it it is odd the
13077: # last characters gets thrown away
13078: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13079: my $symbseed=numval3($symb) << 10;
13080: my $namechck=unpack("%32S*",$username.' ');
13081:
13082: my $nameseed=numval3($username) << 21;
13083: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13084: my $courseseed=unpack("%32S*",$courseid.' ');
13085:
13086: my $num1=$symbchck+$symbseed+$namechck;
13087: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13088: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13089: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 13090: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13091:
1.575 albertel 13092: return "$num1:$num2";
13093: }
13094: }
13095:
1.675 albertel 13096: sub rndseed_64bit5 {
13097: my ($symb,$courseid,$domain,$username)=@_;
13098: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13099: return "$num1:$num2";
13100: }
13101:
1.366 albertel 13102: sub rndseed_CODE_64bit {
13103: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 13104: {
1.366 albertel 13105: use integer;
1.443 albertel 13106: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 13107: my $symbseed=numval2($symb);
1.491 albertel 13108: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13109: my $CODEseed=numval(&getCODE());
1.443 albertel 13110: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 13111: my $num1=$symbseed+$CODEchck;
13112: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13113: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13114: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13115: if ($_64bit) { $num1=(($num1<<32)>>32); }
13116: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13117: return "$num1:$num2";
1.366 albertel 13118: }
13119: }
13120:
1.575 albertel 13121: sub rndseed_CODE_64bit4 {
13122: my ($symb,$courseid,$domain,$username)=@_;
13123: {
13124: use integer;
13125: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13126: my $symbseed=numval3($symb);
13127: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13128: my $CODEseed=numval3(&getCODE());
13129: my $courseseed=unpack("%32S*",$courseid.' ');
13130: my $num1=$symbseed+$CODEchck;
13131: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13132: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13133: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13134: if ($_64bit) { $num1=(($num1<<32)>>32); }
13135: if ($_64bit) { $num2=(($num2<<32)>>32); }
13136: return "$num1:$num2";
13137: }
13138: }
13139:
1.675 albertel 13140: sub rndseed_CODE_64bit5 {
13141: my ($symb,$courseid,$domain,$username)=@_;
13142: my $code = &getCODE();
13143: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13144: return "$num1:$num2";
13145: }
13146:
1.366 albertel 13147: sub setup_random_from_rndseed {
13148: my ($rndseed)=@_;
1.503 albertel 13149: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 13150: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13151: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13152: &Math::Random::random_set_seed_from_phrase($rndseed);
13153: } else {
13154: &Math::Random::random_set_seed($num1,$num2);
13155: }
1.366 albertel 13156: } else {
13157: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13158: }
1.36 albertel 13159: }
13160:
1.474 albertel 13161: sub latest_receipt_algorithm_id {
1.835 albertel 13162: return 'receipt3';
1.474 albertel 13163: }
13164:
1.480 www 13165: sub recunique {
13166: my $fucourseid=shift;
13167: my $unique;
1.835 albertel 13168: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13169: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13170: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 13171: } else {
13172: $unique=$perlvar{'lonReceipt'};
13173: }
13174: return unpack("%32C*",$unique);
13175: }
13176:
13177: sub recprefix {
13178: my $fucourseid=shift;
13179: my $prefix;
1.835 albertel 13180: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13181: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13182: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13183: } else {
13184: $prefix=$perlvar{'lonHostID'};
13185: }
13186: return unpack("%32C*",$prefix);
13187: }
13188:
1.76 www 13189: sub ireceipt {
1.474 albertel 13190: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13191:
13192: my $return =&recprefix($fucourseid).'-';
13193:
13194: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13195: $env{'request.state'} eq 'construct') {
13196: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13197: return $return;
13198: }
13199:
1.76 www 13200: my $cuname=unpack("%32C*",$funame);
13201: my $cudom=unpack("%32C*",$fudom);
13202: my $cucourseid=unpack("%32C*",$fucourseid);
13203: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13204: my $cunique=&recunique($fucourseid);
1.474 albertel 13205: my $cpart=unpack("%32S*",$part);
1.835 albertel 13206: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13207:
1.790 albertel 13208: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13209:
13210: $return.= ($cunique%$cuname+
13211: $cunique%$cudom+
13212: $cusymb%$cuname+
13213: $cusymb%$cudom+
13214: $cucourseid%$cuname+
13215: $cucourseid%$cudom+
13216: $cpart%$cuname+
13217: $cpart%$cudom);
13218: } else {
13219: $return.= ($cunique%$cuname+
13220: $cunique%$cudom+
13221: $cusymb%$cuname+
13222: $cusymb%$cudom+
13223: $cucourseid%$cuname+
13224: $cucourseid%$cudom);
13225: }
13226: return $return;
1.76 www 13227: }
13228:
13229: sub receipt {
1.474 albertel 13230: my ($part)=@_;
1.790 albertel 13231: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13232: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13233: }
1.260 ng 13234:
1.790 albertel 13235: sub whichuser {
13236: my ($passedsymb)=@_;
13237: my ($symb,$courseid,$domain,$name,$publicuser);
13238: if (defined($env{'form.grade_symb'})) {
13239: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13240: my $allowed=&allowed('vgr',$tmp_courseid);
13241: if (!$allowed &&
13242: exists($env{'request.course.sec'}) &&
13243: $env{'request.course.sec'} !~ /^\s*$/) {
13244: $allowed=&allowed('vgr',$tmp_courseid.
13245: '/'.$env{'request.course.sec'});
13246: }
13247: if ($allowed) {
13248: ($symb)=&get_env_multiple('form.grade_symb');
13249: $courseid=$tmp_courseid;
13250: ($domain)=&get_env_multiple('form.grade_domain');
13251: ($name)=&get_env_multiple('form.grade_username');
13252: return ($symb,$courseid,$domain,$name,$publicuser);
13253: }
13254: }
13255: if (!$passedsymb) {
13256: $symb=&symbread();
13257: } else {
13258: $symb=$passedsymb;
13259: }
13260: $courseid=$env{'request.course.id'};
13261: $domain=$env{'user.domain'};
13262: $name=$env{'user.name'};
13263: if ($name eq 'public' && $domain eq 'public') {
13264: if (!defined($env{'form.username'})) {
13265: $env{'form.username'}.=time.rand(10000000);
13266: }
13267: $name.=$env{'form.username'};
13268: }
13269: return ($symb,$courseid,$domain,$name,$publicuser);
13270:
13271: }
13272:
1.36 albertel 13273: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13274: # returns either the contents of the file or
13275: # -1 if the file doesn't exist
1.481 raeburn 13276: #
13277: # if the target is a file that was uploaded via DOCS,
13278: # a check will be made to see if a current copy exists on the local server,
13279: # if it does this will be served, otherwise a copy will be retrieved from
13280: # the home server for the course and stored in /home/httpd/html/userfiles on
13281: # the local server.
1.472 albertel 13282:
1.36 albertel 13283: sub getfile {
1.538 albertel 13284: my ($file) = @_;
1.609 banghart 13285: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13286: &repcopy($file);
13287: return &readfile($file);
13288: }
13289:
13290: sub repcopy_userfile {
13291: my ($file)=@_;
1.1142 raeburn 13292: my $londocroot = $perlvar{'lonDocRoot'};
13293: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13294: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13295: my ($cdom,$cnum,$filename) =
1.811 albertel 13296: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13297: my $uri="/uploaded/$cdom/$cnum/$filename";
13298: if (-e "$file") {
1.828 www 13299: # we already have a local copy, check it out
1.538 albertel 13300: my @fileinfo = stat($file);
1.828 www 13301: my $rtncode;
13302: my $info;
1.538 albertel 13303: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13304: if ($lwpresp ne 'ok') {
1.828 www 13305: # there is no such file anymore, even though we had a local copy
1.482 albertel 13306: if ($rtncode eq '404') {
1.538 albertel 13307: unlink($file);
1.482 albertel 13308: }
13309: return -1;
13310: }
13311: if ($info < $fileinfo[9]) {
1.828 www 13312: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13313: return 'ok';
1.828 www 13314: } else {
13315: # the file is outdated, get rid of it
13316: unlink($file);
1.482 albertel 13317: }
1.828 www 13318: }
13319: # one way or the other, at this point, we don't have the file
13320: # construct the correct path for the file
13321: my @parts = ($cdom,$cnum);
13322: if ($filename =~ m|^(.+)/[^/]+$|) {
13323: push @parts, split(/\//,$1);
13324: }
13325: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13326: foreach my $part (@parts) {
13327: $path .= '/'.$part;
13328: if (!-e $path) {
13329: mkdir($path,0770);
1.482 albertel 13330: }
13331: }
1.828 www 13332: # now the path exists for sure
13333: # get a user agent
13334: my $ua=new LWP::UserAgent;
13335: my $transferfile=$file.'.in.transfer';
13336: # FIXME: this should flock
13337: if (-e $transferfile) { return 'ok'; }
13338: my $request;
13339: $uri=~s/^\///;
1.980 raeburn 13340: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13341: my $hostname = &hostname($homeserver);
1.980 raeburn 13342: my $protocol = $protocol{$homeserver};
13343: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13344: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 13345: my $response=$ua->request($request,$transferfile);
13346: # did it work?
13347: if ($response->is_error()) {
13348: unlink($transferfile);
13349: &logthis("Userfile repcopy failed for $uri");
13350: return -1;
13351: }
13352: # worked, rename the transfer file
13353: rename($transferfile,$file);
1.607 raeburn 13354: return 'ok';
1.481 raeburn 13355: }
13356:
1.517 albertel 13357: sub tokenwrapper {
13358: my $uri=shift;
1.980 raeburn 13359: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13360: $uri=~s|^/||;
1.620 albertel 13361: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13362: my $token=$1;
1.552 albertel 13363: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13364: if ($udom && $uname && $file) {
13365: $file=~s|(\?\.*)*$||;
1.949 raeburn 13366: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13367: my $homeserver = &homeserver($uname,$udom);
1.1172.2.120 raeburn 13368: my $hostname = &hostname($homeserver);
1.980 raeburn 13369: my $protocol = $protocol{$homeserver};
13370: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13371: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13372: (($uri=~/\?/)?'&':'?').'token='.$token.
13373: '&tokenissued='.$perlvar{'lonHostID'};
13374: } else {
13375: return '/adm/notfound.html';
13376: }
13377: }
13378:
1.828 www 13379: # call with reqtype HEAD: get last modification time
13380: # call with reqtype GET: get the file contents
13381: # Do not call this with reqtype GET for large files! It loads everything into memory
13382: #
1.481 raeburn 13383: sub getuploaded {
13384: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13385: $uri=~s/^\///;
1.980 raeburn 13386: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13387: my $hostname = &hostname($homeserver);
1.980 raeburn 13388: my $protocol = $protocol{$homeserver};
13389: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13390: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13391: my $ua=new LWP::UserAgent;
13392: my $request=new HTTP::Request($reqtype,$uri);
13393: my $response=$ua->request($request);
13394: $$rtncode = $response->code;
1.482 albertel 13395: if (! $response->is_success()) {
13396: return 'failed';
13397: }
13398: if ($reqtype eq 'HEAD') {
1.486 www 13399: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13400: } elsif ($reqtype eq 'GET') {
13401: $$info = $response->content;
1.472 albertel 13402: }
1.482 albertel 13403: return 'ok';
1.36 albertel 13404: }
13405:
1.481 raeburn 13406: sub readfile {
13407: my $file = shift;
13408: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13409: my $fh;
1.1172.2.96 raeburn 13410: open($fh,"<",$file);
1.481 raeburn 13411: my $a='';
1.800 albertel 13412: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13413: return $a;
13414: }
13415:
1.36 albertel 13416: sub filelocation {
1.590 banghart 13417: my ($dir,$file) = @_;
13418: my $location;
13419: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13420:
13421: if ($file =~ m-^/adm/-) {
13422: $file=~s-^/adm/wrapper/-/-;
13423: $file=~s-^/adm/coursedocs/showdoc/-/-;
13424: }
1.882 albertel 13425:
1.1139 www 13426: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13427: $location = $file;
1.609 banghart 13428: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13429: my ($udom,$uname,$filename)=
1.811 albertel 13430: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13431: my $home=&homeserver($uname,$udom);
13432: my $is_me=0;
13433: my @ids=¤t_machine_ids();
13434: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13435: if ($is_me) {
1.1117 foxr 13436: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13437: } else {
13438: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13439: $udom.'/'.$uname.'/'.$filename;
13440: }
1.882 albertel 13441: } elsif ($file =~ m-^/adm/-) {
13442: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13443: } else {
13444: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13445: $file=~s:^/(res|priv)/:/:;
13446: my $space=$1;
1.590 banghart 13447: if ( !( $file =~ m:^/:) ) {
13448: $location = $dir. '/'.$file;
13449: } else {
1.1142 raeburn 13450: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13451: }
1.59 albertel 13452: }
1.590 banghart 13453: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13454: while ($location=~m{/\.\./}) {
13455: if ($location =~ m{/[^/]+/\.\./}) {
13456: $location=~ s{/[^/]+/\.\./}{/}g;
13457: } else {
13458: $location=~ s{/\.\./}{/}g;
13459: }
13460: } #remove dir/..
1.590 banghart 13461: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13462: return $location;
1.46 www 13463: }
1.36 albertel 13464:
1.46 www 13465: sub hreflocation {
13466: my ($dir,$file)=@_;
1.980 raeburn 13467: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13468: $file=filelocation($dir,$file);
1.700 albertel 13469: } elsif ($file=~m-^/adm/-) {
13470: $file=~s-^/adm/wrapper/-/-;
13471: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13472: }
13473: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13474: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13475: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13476: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13477: {/uploaded/$1/$2/}x;
1.46 www 13478: }
1.913 albertel 13479: if ($file=~ m{^/userfiles/}) {
13480: $file =~ s{^/userfiles/}{/uploaded/};
13481: }
1.462 albertel 13482: return $file;
1.465 albertel 13483: }
13484:
1.1139 www 13485:
13486:
13487:
13488:
1.465 albertel 13489: sub current_machine_domains {
1.853 albertel 13490: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13491: }
13492:
13493: sub machine_domains {
13494: my ($hostname) = @_;
1.465 albertel 13495: my @domains;
1.838 albertel 13496: my %hostname = &all_hostnames();
1.465 albertel 13497: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13498: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13499: if ($hostname eq $name) {
1.844 albertel 13500: push(@domains,&host_domain($id));
1.465 albertel 13501: }
13502: }
13503: return @domains;
13504: }
13505:
13506: sub current_machine_ids {
1.853 albertel 13507: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13508: }
13509:
13510: sub machine_ids {
13511: my ($hostname) = @_;
13512: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13513: my @ids;
1.888 albertel 13514: my %name_to_host = &all_names();
1.889 albertel 13515: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13516: return @{ $name_to_host{$hostname} };
13517: }
13518: return;
1.31 www 13519: }
13520:
1.824 raeburn 13521: sub additional_machine_domains {
13522: my @domains;
1.1172.2.142 raeburn 13523: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
13524: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
13525: while( my $line = <$fh>) {
13526: chomp($line);
13527: $line =~ s/\s//g;
13528: push(@domains,$line);
13529: }
13530: close($fh);
13531: }
1.824 raeburn 13532: }
13533: return @domains;
13534: }
13535:
13536: sub default_login_domain {
13537: my $domain = $perlvar{'lonDefDomain'};
13538: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13539: foreach my $posdom (¤t_machine_domains(),
13540: &additional_machine_domains()) {
13541: if (lc($posdom) eq lc($testdomain)) {
13542: $domain=$posdom;
13543: last;
13544: }
13545: }
13546: return $domain;
13547: }
13548:
1.1172.2.106 raeburn 13549: sub shared_institution {
1.1172.2.136 raeburn 13550: my ($dom,$lonhost) = @_;
13551: if ($lonhost eq '') {
13552: $lonhost = $perlvar{'lonHostID'};
13553: }
1.1172.2.106 raeburn 13554: my $same_intdom;
1.1172.2.136 raeburn 13555: my $hostintdom = &internet_dom($lonhost);
1.1172.2.106 raeburn 13556: if ($hostintdom ne '') {
13557: my %iphost = &get_iphost();
13558: my $primary_id = &domain($dom,'primary');
13559: my $primary_ip = &get_host_ip($primary_id);
13560: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13561: foreach my $id (@{$iphost{$primary_ip}}) {
13562: my $intdom = &internet_dom($id);
13563: if ($intdom eq $hostintdom) {
13564: $same_intdom = 1;
13565: last;
13566: }
13567: }
13568: }
13569: }
13570: return $same_intdom;
13571: }
13572:
1.1172.2.120 raeburn 13573: sub uses_sts {
13574: my ($ignore_cache) = @_;
13575: my $lonhost = $perlvar{'lonHostID'};
13576: my $hostname = &hostname($lonhost);
13577: my $sts_on;
13578: if ($protocol{$lonhost} eq 'https') {
13579: my $cachetime = 12*3600;
13580: if (!$ignore_cache) {
13581: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13582: if (defined($cached)) {
13583: return $sts_on;
13584: }
13585: }
1.1172.2.121 raeburn 13586: my $ua=new LWP::UserAgent;
1.1172.2.120 raeburn 13587: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13588: my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121 raeburn 13589: my $response=$ua->request($request);
1.1172.2.120 raeburn 13590: if ($response->is_success) {
13591: my $has_sts = $response->header('Strict-Transport-Security');
13592: if ($has_sts eq '') {
13593: $sts_on = 0;
13594: } else {
13595: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13596: my $maxage = $1;
13597: if ($maxage) {
13598: $sts_on = 1;
13599: } else {
13600: $sts_on = 0;
13601: }
13602: } else {
13603: $sts_on = 0;
13604: }
13605: }
13606: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13607: }
13608: }
13609: return;
13610: }
13611:
1.1172.2.142 raeburn 13612: sub waf_allssl {
13613: my ($host_name) = @_;
13614: my $alias = &get_proxy_alias();
13615: if ($host_name eq '') {
13616: $host_name = $ENV{'SERVER_NAME'};
13617: }
13618: if (($host_name ne '') && ($alias eq $host_name)) {
13619: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
13620: my %defdomdefaults = &get_domain_defaults($serverhomedom);
13621: if ($defdomdefaults{'waf_sslopt'}) {
13622: return $defdomdefaults{'waf_sslopt'};
13623: }
13624: }
13625: return;
13626: }
13627:
1.1172.2.134 raeburn 13628: sub get_requestor_ip {
13629: my ($r,$nolookup,$noproxy) = @_;
13630: my $from_ip;
13631: if (ref($r)) {
1.1172.2.142 raeburn 13632: if ($r->can('useragent_ip')) {
13633: if ($noproxy && $r->can('client_ip')) {
13634: $from_ip = $r->client_ip();
13635: } else {
13636: $from_ip = $r->useragent_ip();
13637: }
13638: } elsif ($r->connection->can('remote_ip')) {
13639: $from_ip = $r->connection->remote_ip();
13640: } else {
13641: $from_ip = $r->get_remote_host($nolookup);
13642: }
1.1172.2.134 raeburn 13643: } else {
13644: $from_ip = $ENV{'REMOTE_ADDR'};
13645: }
1.1172.2.142 raeburn 13646: return $from_ip if ($noproxy);
13647: # Who controls proxy settings for server
13648: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
13649: my $proxyinfo = &get_proxy_settings($dom_in_use);
13650: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
13651: if ($proxyinfo->{'vpnint'}) {
13652: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
13653: return $from_ip;
13654: }
13655: }
13656: if ($proxyinfo->{'trusted'}) {
13657: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
13658: my $ipheader = $proxyinfo->{'ipheader'};
13659: my ($ip,$xfor);
13660: if (ref($r)) {
13661: if ($ipheader) {
13662: $ip = $r->headers_in->{$ipheader};
13663: }
13664: $xfor = $r->headers_in->{'X-Forwarded-For'};
13665: } else {
13666: if ($ipheader) {
13667: $ip = $ENV{'HTTP_'.uc($ipheader)};
13668: }
13669: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
13670: }
13671: if (($ip eq '') && ($xfor ne '')) {
13672: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
13673: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
13674: $ip = $poss_ip;
13675: last;
13676: }
13677: }
13678: }
13679: if ($ip ne '') {
13680: return $ip;
13681: }
13682: }
13683: }
13684: }
1.1172.2.134 raeburn 13685: return $from_ip;
13686: }
13687:
1.1172.2.142 raeburn 13688: sub get_proxy_settings {
13689: my ($dom_in_use) = @_;
13690: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
13691: my $proxyinfo = {
13692: ipheader => $domdefaults{'waf_ipheader'},
13693: trusted => $domdefaults{'waf_trusted'},
13694: vpnint => $domdefaults{'waf_vpnint'},
13695: vpnext => $domdefaults{'waf_vpnext'},
13696: sslopt => $domdefaults{'waf_sslopt'},
13697: };
13698: return $proxyinfo;
13699: }
13700:
13701: sub ip_match {
13702: my ($ip,$pattern_str) = @_;
13703: $ip=Net::CIDR::cidrvalidate($ip);
13704: if ($ip) {
13705: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
13706: }
13707: return;
13708: }
13709:
13710: sub get_proxy_alias {
13711: my ($lonid) = @_;
13712: if ($lonid eq '') {
13713: $lonid = $perlvar{'lonHostID'};
13714: }
13715: if (!defined(&hostname($lonid))) {
13716: return;
13717: }
13718: if ($lonid ne '') {
13719: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
13720: if ($cached) {
13721: return $alias;
13722: }
13723: my $dom = &Apache::lonnet::host_domain($lonid);
13724: if ($dom ne '') {
13725: my $cachetime = 60*60*24;
13726: my %domconfig =
13727: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
13728: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
13729: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
13730: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
13731: }
13732: }
13733: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
13734: }
13735: }
13736: return;
13737: }
13738:
13739: sub use_proxy_alias {
13740: my ($r,$lonid) = @_;
13741: my $alias = &get_proxy_alias($lonid);
13742: if ($alias) {
13743: my $dom = &host_domain($lonid);
13744: if ($dom ne '') {
13745: my $proxyinfo = &get_proxy_settings($dom);
13746: my ($vpnint,$remote_ip);
13747: if (ref($proxyinfo) eq 'HASH') {
13748: $vpnint = $proxyinfo->{'vpnint'};
13749: if ($vpnint) {
13750: $remote_ip = &get_requestor_ip($r,1,1);
13751: }
13752: }
13753: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
13754: return $alias;
13755: }
13756: }
13757: }
13758: return;
13759: }
13760:
13761: sub alias_sso {
13762: my ($lonid) = @_;
13763: if ($lonid eq '') {
13764: $lonid = $perlvar{'lonHostID'};
13765: }
13766: if (!defined(&hostname($lonid))) {
13767: return;
13768: }
13769: if ($lonid ne '') {
13770: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
13771: if ($cached) {
13772: return $use_alias;
13773: }
13774: my $dom = &Apache::lonnet::host_domain($lonid);
13775: if ($dom ne '') {
13776: my $cachetime = 60*60*24;
13777: my %domconfig =
13778: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
13779: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
13780: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
13781: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
13782: }
13783: }
13784: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
13785: }
13786: }
13787: return;
13788: }
13789:
13790: sub get_saml_landing {
13791: my ($lonid) = @_;
13792: if ($lonid eq '') {
13793: my $defdom = &default_login_domain();
13794: my @hosts = ¤t_machine_ids();
13795: if (@hosts > 1) {
13796: foreach my $hostid (@hosts) {
13797: if (&host_domain($hostid) eq $defdom) {
13798: $lonid = $hostid;
13799: last;
13800: }
13801: }
13802: } else {
13803: $lonid = $perlvar{'lonHostID'};
13804: }
13805: if ($lonid) {
13806: unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
13807: return;
13808: }
13809: } else {
13810: return;
13811: }
13812: } elsif (!defined(&hostname($lonid))) {
13813: return;
13814: }
13815: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
13816: if ($cached) {
13817: return $landing;
13818: }
13819: my $dom = &Apache::lonnet::host_domain($lonid);
13820: if ($dom ne '') {
13821: my $cachetime = 60*60*24;
13822: my %domconfig =
13823: &Apache::lonnet::get_dom('configuration',['login'],$dom);
13824: if (ref($domconfig{'login'}) eq 'HASH') {
13825: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
13826: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
13827: $landing = 1;
13828: }
13829: }
13830: }
13831: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
13832: }
13833: return;
13834: }
13835:
1.31 www 13836: # ------------------------------------------------------------- Declutters URLs
13837:
13838: sub declutter {
13839: my $thisfn=shift;
1.569 albertel 13840: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 13841: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13842: $thisfn=~s{^/home/httpd/html}{};
13843: }
1.31 www 13844: $thisfn=~s/^\///;
1.697 albertel 13845: $thisfn=~s|^adm/wrapper/||;
13846: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13847: $thisfn=~s/^res\///;
1.1172 bisitz 13848: $thisfn=~s/^priv\///;
1.1032 raeburn 13849: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13850: $thisfn=~s/\?.+$//;
13851: }
1.268 www 13852: return $thisfn;
13853: }
13854:
13855: # ------------------------------------------------------------- Clutter up URLs
13856:
13857: sub clutter {
13858: my $thisfn='/'.&declutter(shift);
1.887 albertel 13859: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13860: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13861: $thisfn='/res'.$thisfn;
13862: }
1.1031 raeburn 13863: if ($thisfn !~m|^/adm|) {
13864: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13865: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13866: } else {
13867: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13868: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13869: if ($embstyle eq 'ssi'
13870: || ($embstyle eq 'hdn')
13871: || ($embstyle eq 'rat')
13872: || ($embstyle eq 'prv')
13873: || ($embstyle eq 'ign')) {
13874: #do nothing with these
13875: } elsif (($embstyle eq 'img')
1.695 albertel 13876: || ($embstyle eq 'emb')
13877: || ($embstyle eq 'wrp')) {
13878: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13879: } elsif ($embstyle eq 'unk'
13880: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13881: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13882: } else {
1.718 www 13883: # &logthis("Got a blank emb style");
1.695 albertel 13884: }
1.694 albertel 13885: }
13886: }
1.31 www 13887: return $thisfn;
1.12 www 13888: }
13889:
1.787 albertel 13890: sub clutter_with_no_wrapper {
13891: my $uri = &clutter(shift);
13892: if ($uri =~ m-^/adm/-) {
13893: $uri =~ s-^/adm/wrapper/-/-;
13894: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13895: }
13896: return $uri;
13897: }
13898:
1.557 albertel 13899: sub freeze_escape {
13900: my ($value)=@_;
13901: if (ref($value)) {
13902: $value=&nfreeze($value);
13903: return '__FROZEN__'.&escape($value);
13904: }
13905: return &escape($value);
13906: }
13907:
1.11 www 13908:
1.557 albertel 13909: sub thaw_unescape {
13910: my ($value)=@_;
13911: if ($value =~ /^__FROZEN__/) {
13912: substr($value,0,10,undef);
13913: $value=&unescape($value);
13914: return &thaw($value);
13915: }
13916: return &unescape($value);
13917: }
13918:
1.436 albertel 13919: sub correct_line_ends {
13920: my ($result)=@_;
13921: $$result =~s/\r\n/\n/mg;
13922: $$result =~s/\r/\n/mg;
1.415 albertel 13923: }
1.1 albertel 13924: # ================================================================ Main Program
13925:
1.184 www 13926: sub goodbye {
1.204 albertel 13927: &logthis("Starting Shut down");
1.443 albertel 13928: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13929: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13930: #converted
1.599 albertel 13931: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13932: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13933: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13934: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13935: #1.1 only
1.870 albertel 13936: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13937: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13938: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13939: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13940: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13941: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13942: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13943: &flushcourselogs();
13944: &logthis("Shutting down");
13945: }
13946:
1.852 albertel 13947: sub get_dns {
1.1172.2.17 raeburn 13948: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13949: if (!$ignore_cache) {
13950: my ($content,$cached)=
13951: &Apache::lonnet::is_cached_new('dns',$url);
13952: if ($cached) {
1.1172.2.17 raeburn 13953: &$func($content,$hashref);
1.869 albertel 13954: return;
13955: }
13956: }
13957:
13958: my %alldns;
1.1172.2.96 raeburn 13959: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13960: foreach my $dns (<$config>) {
13961: next if ($dns !~ /^\^(\S*)/x);
13962: my $line = $1;
13963: my ($host,$protocol) = split(/:/,$line);
13964: if ($protocol ne 'https') {
13965: $protocol = 'http';
13966: }
13967: $alldns{$host} = $protocol;
1.979 raeburn 13968: }
1.1172.2.96 raeburn 13969: close($config);
1.869 albertel 13970: }
13971: while (%alldns) {
1.1172.2.52 raeburn 13972: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142 raeburn 13973: my @content;
13974: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
13975: my $command = (split('/',$url))[3];
13976: my ($dir,$file) = &parse_getdns_url($command,$url);
13977: delete($alldns{$dns});
13978: next if (($dir eq '') || ($file eq ''));
13979: if (open(my $config,'<',"$dir/$file")) {
13980: @content = <$config>;
13981: close($config);
13982: }
13983: } else {
13984: my $ua=new LWP::UserAgent;
13985: $ua->timeout(30);
13986: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13987: my $response=$ua->request($request);
13988: delete($alldns{$dns});
13989: next if ($response->is_error());
13990: @content = split("\n",$response->content);
13991: }
1.1172.2.17 raeburn 13992: unless ($nocache) {
1.1172.2.23 raeburn 13993: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 13994: }
13995: &$func(\@content,$hashref);
1.869 albertel 13996: return;
1.852 albertel 13997: }
1.871 albertel 13998: my $which = (split('/',$url))[3];
13999: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 14000: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14001: my @content = <$config>;
14002: &$func(\@content,$hashref);
14003: }
1.1172.2.17 raeburn 14004: return;
14005: }
14006:
14007: # ------------------------------------------------------Get DNS checksums file
14008: sub parse_dns_checksums_tab {
14009: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 14010: my $lonhost = $perlvar{'lonHostID'};
14011: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 14012: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 14013: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14014: my $webconfdir = '/etc/httpd/conf';
14015: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14016: $webconfdir = '/etc/apache2';
14017: } elsif ($distro =~ /^sles(\d+)$/) {
14018: if ($1 >= 10) {
14019: $webconfdir = '/etc/apache2';
14020: }
14021: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14022: if ($1 >= 10.0) {
14023: $webconfdir = '/etc/apache2';
14024: }
14025: }
1.1172.2.17 raeburn 14026: my ($release,$timestamp) = split(/\-/,$loncaparev);
14027: my (%chksum,%revnum);
14028: if (ref($lines) eq 'ARRAY') {
14029: chomp(@{$lines});
1.1172.2.34 raeburn 14030: my $version = shift(@{$lines});
14031: if ($version eq $release) {
1.1172.2.17 raeburn 14032: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 14033: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 14034: if ($file =~ m{^/etc/httpd/conf}) {
14035: if ($webconfdir eq '/etc/apache2') {
14036: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14037: }
14038: }
1.1172.2.34 raeburn 14039: $chksum{$file} = $shasum;
14040: $revnum{$file} = $version;
1.1172.2.17 raeburn 14041: }
14042: if (ref($hashref) eq 'HASH') {
14043: %{$hashref} = (
14044: sums => \%chksum,
14045: versions => \%revnum,
14046: );
14047: }
14048: }
14049: }
1.869 albertel 14050: return;
1.852 albertel 14051: }
1.1172.2.17 raeburn 14052:
14053: sub fetch_dns_checksums {
14054: my %checksums;
1.1172.2.34 raeburn 14055: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 14056: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 14057: my ($release,$timestamp) = split(/\-/,$loncaparev);
14058: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 14059: \%checksums);
14060: return \%checksums;
14061: }
14062:
1.1172.2.142 raeburn 14063: sub parse_getdns_url {
14064: my ($command,$url) = @_;
14065: my $dir = $perlvar{'lonTabDir'};
14066: my $file;
14067: if ($command eq 'hosts') {
14068: $file = 'dns_hosts.tab';
14069: } elsif ($command eq 'domain') {
14070: $file = 'dns_domain.tab';
14071: } elsif ($command eq 'checksums') {
14072: my $version = (split('/',$url))[4];
14073: $file = "dns_checksums/$version.tab",
14074: }
14075: return ($dir,$file);
14076: }
14077:
1.327 albertel 14078: # ------------------------------------------------------------ Read domain file
14079: {
1.852 albertel 14080: my $loaded;
1.846 albertel 14081: my %domain;
14082:
1.852 albertel 14083: sub parse_domain_tab {
14084: my ($lines) = @_;
14085: foreach my $line (@$lines) {
14086: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 14087:
1.846 albertel 14088: chomp($line);
1.852 albertel 14089: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 14090: my %this_domain;
14091: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14092: 'lang_def', 'city', 'longi', 'lati',
14093: 'primary') {
14094: $this_domain{$field} = shift(@elements);
14095: }
14096: $domain{$name} = \%this_domain;
1.852 albertel 14097: }
14098: }
1.864 albertel 14099:
14100: sub reset_domain_info {
14101: undef($loaded);
14102: undef(%domain);
14103: }
14104:
1.852 albertel 14105: sub load_domain_tab {
1.1172.2.70 raeburn 14106: my ($ignore_cache,$nocache) = @_;
14107: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 14108: my $fh;
1.1172.2.96 raeburn 14109: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 14110: my @lines = <$fh>;
14111: &parse_domain_tab(\@lines);
1.448 albertel 14112: }
1.852 albertel 14113: close($fh);
14114: $loaded = 1;
1.327 albertel 14115: }
1.846 albertel 14116:
14117: sub domain {
1.852 albertel 14118: &load_domain_tab() if (!$loaded);
14119:
1.846 albertel 14120: my ($name,$what) = @_;
14121: return if ( !exists($domain{$name}) );
14122:
14123: if (!$what) {
14124: return $domain{$name}{'description'};
14125: }
14126: return $domain{$name}{$what};
14127: }
1.974 raeburn 14128:
14129: sub domain_info {
14130: &load_domain_tab() if (!$loaded);
14131: return %domain;
14132: }
14133:
1.327 albertel 14134: }
14135:
14136:
1.1 albertel 14137: # ------------------------------------------------------------- Read hosts file
14138: {
1.838 albertel 14139: my %hostname;
1.844 albertel 14140: my %hostdom;
1.845 albertel 14141: my %libserv;
1.852 albertel 14142: my $loaded;
1.888 albertel 14143: my %name_to_host;
1.1074 raeburn 14144: my %internetdom;
1.1107 raeburn 14145: my %LC_dns_serv;
1.852 albertel 14146:
14147: sub parse_hosts_tab {
14148: my ($file) = @_;
14149: foreach my $configline (@$file) {
14150: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 14151: chomp($configline);
14152: if ($configline =~ /^\^/) {
14153: if ($configline =~ /^\^([\w.\-]+)/) {
14154: $LC_dns_serv{$1} = 1;
14155: }
14156: next;
14157: }
1.1074 raeburn 14158: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 14159: $name=~s/\s//g;
14160: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 14161: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14162: my $curr = $hostname{$id};
14163: my $skip;
14164: if (ref($name_to_host{$curr}) eq 'ARRAY') {
14165: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14166: $skip = 1;
14167: } else {
14168: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14169: }
14170: }
14171: unless ($skip) {
14172: push(@{$name_to_host{$name}},$id);
14173: }
14174: } else {
14175: push(@{$name_to_host{$name}},$id);
14176: }
1.852 albertel 14177: $hostname{$id}=$name;
14178: $hostdom{$id}=$domain;
14179: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 14180: if (defined($protocol)) {
14181: if ($protocol eq 'https') {
14182: $protocol{$id} = $protocol;
14183: } else {
14184: $protocol{$id} = 'http';
14185: }
1.968 raeburn 14186: } else {
1.969 raeburn 14187: $protocol{$id} = 'http';
1.968 raeburn 14188: }
1.1074 raeburn 14189: if (defined($intdom)) {
14190: $internetdom{$id} = $intdom;
14191: }
1.852 albertel 14192: }
14193: }
14194: }
1.864 albertel 14195:
14196: sub reset_hosts_info {
1.897 albertel 14197: &purge_remembered();
1.864 albertel 14198: &reset_domain_info();
14199: &reset_hosts_ip_info();
1.892 albertel 14200: undef(%name_to_host);
1.864 albertel 14201: undef(%hostname);
14202: undef(%hostdom);
14203: undef(%libserv);
14204: undef($loaded);
14205: }
1.1 albertel 14206:
1.852 albertel 14207: sub load_hosts_tab {
1.1172.2.70 raeburn 14208: my ($ignore_cache,$nocache) = @_;
14209: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 14210: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 14211: my @config = <$config>;
14212: &parse_hosts_tab(\@config);
14213: close($config);
14214: $loaded=1;
1.1 albertel 14215: }
1.852 albertel 14216:
1.838 albertel 14217: sub hostname {
1.852 albertel 14218: &load_hosts_tab() if (!$loaded);
14219:
1.838 albertel 14220: my ($lonid) = @_;
14221: return $hostname{$lonid};
14222: }
1.845 albertel 14223:
1.838 albertel 14224: sub all_hostnames {
1.852 albertel 14225: &load_hosts_tab() if (!$loaded);
14226:
1.838 albertel 14227: return %hostname;
14228: }
1.845 albertel 14229:
1.888 albertel 14230: sub all_names {
1.1172.2.70 raeburn 14231: my ($ignore_cache,$nocache) = @_;
14232: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 14233:
14234: return %name_to_host;
14235: }
14236:
1.974 raeburn 14237: sub all_host_domain {
14238: &load_hosts_tab() if (!$loaded);
14239: return %hostdom;
14240: }
14241:
1.845 albertel 14242: sub is_library {
1.852 albertel 14243: &load_hosts_tab() if (!$loaded);
14244:
1.845 albertel 14245: return exists($libserv{$_[0]});
14246: }
14247:
14248: sub all_library {
1.852 albertel 14249: &load_hosts_tab() if (!$loaded);
14250:
1.845 albertel 14251: return %libserv;
14252: }
14253:
1.1062 droeschl 14254: sub unique_library {
14255: #2x reverse removes all hostnames that appear more than once
14256: my %unique = reverse &all_library();
14257: return reverse %unique;
14258: }
14259:
1.841 albertel 14260: sub get_servers {
1.852 albertel 14261: &load_hosts_tab() if (!$loaded);
14262:
1.841 albertel 14263: my ($domain,$type) = @_;
14264: my %possible_hosts = ($type eq 'library') ? %libserv
14265: : %hostname;
14266: my %result;
1.842 albertel 14267: if (ref($domain) eq 'ARRAY') {
14268: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 14269: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 14270: $result{$host} = $hostname;
14271: }
14272: }
14273: } else {
14274: while ( my ($host,$hostname) = each(%possible_hosts)) {
14275: if ($hostdom{$host} eq $domain) {
14276: $result{$host} = $hostname;
14277: }
1.841 albertel 14278: }
14279: }
14280: return %result;
14281: }
1.845 albertel 14282:
1.1062 droeschl 14283: sub get_unique_servers {
14284: my %unique = reverse &get_servers(@_);
14285: return reverse %unique;
14286: }
14287:
1.844 albertel 14288: sub host_domain {
1.852 albertel 14289: &load_hosts_tab() if (!$loaded);
14290:
1.844 albertel 14291: my ($lonid) = @_;
14292: return $hostdom{$lonid};
14293: }
14294:
1.841 albertel 14295: sub all_domains {
1.852 albertel 14296: &load_hosts_tab() if (!$loaded);
14297:
1.841 albertel 14298: my %seen;
14299: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14300: return @uniq;
14301: }
1.1074 raeburn 14302:
14303: sub internet_dom {
14304: &load_hosts_tab() if (!$loaded);
14305:
14306: my ($lonid) = @_;
14307: return $internetdom{$lonid};
14308: }
1.1107 raeburn 14309:
14310: sub is_LC_dns {
14311: &load_hosts_tab() if (!$loaded);
14312:
14313: my ($hostname) = @_;
14314: return exists($LC_dns_serv{$hostname});
14315: }
14316:
1.1 albertel 14317: }
14318:
1.847 albertel 14319: {
14320: my %iphost;
1.856 albertel 14321: my %name_to_ip;
14322: my %lonid_to_ip;
1.869 albertel 14323:
1.847 albertel 14324: sub get_hosts_from_ip {
14325: my ($ip) = @_;
14326: my %iphosts = &get_iphost();
14327: if (ref($iphosts{$ip})) {
14328: return @{$iphosts{$ip}};
14329: }
14330: return;
1.839 albertel 14331: }
1.864 albertel 14332:
14333: sub reset_hosts_ip_info {
14334: undef(%iphost);
14335: undef(%name_to_ip);
14336: undef(%lonid_to_ip);
14337: }
1.856 albertel 14338:
14339: sub get_host_ip {
14340: my ($lonid) = @_;
14341: if (exists($lonid_to_ip{$lonid})) {
14342: return $lonid_to_ip{$lonid};
14343: }
14344: my $name=&hostname($lonid);
14345: my $ip = gethostbyname($name);
14346: return if (!$ip || length($ip) ne 4);
14347: $ip=inet_ntoa($ip);
14348: $name_to_ip{$name} = $ip;
14349: $lonid_to_ip{$lonid} = $ip;
14350: return $ip;
14351: }
1.847 albertel 14352:
14353: sub get_iphost {
1.1172.2.70 raeburn 14354: my ($ignore_cache,$nocache) = @_;
1.894 albertel 14355:
1.869 albertel 14356: if (!$ignore_cache) {
14357: if (%iphost) {
14358: return %iphost;
14359: }
14360: my ($ip_info,$cached)=
14361: &Apache::lonnet::is_cached_new('iphost','iphost');
14362: if ($cached) {
14363: %iphost = %{$ip_info->[0]};
14364: %name_to_ip = %{$ip_info->[1]};
14365: %lonid_to_ip = %{$ip_info->[2]};
14366: return %iphost;
14367: }
14368: }
1.894 albertel 14369:
14370: # get yesterday's info for fallback
14371: my %old_name_to_ip;
14372: my ($ip_info,$cached)=
14373: &Apache::lonnet::is_cached_new('iphost','iphost');
14374: if ($cached) {
14375: %old_name_to_ip = %{$ip_info->[1]};
14376: }
14377:
1.1172.2.70 raeburn 14378: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 14379: foreach my $name (keys(%name_to_host)) {
1.847 albertel 14380: my $ip;
14381: if (!exists($name_to_ip{$name})) {
14382: $ip = gethostbyname($name);
14383: if (!$ip || length($ip) ne 4) {
1.894 albertel 14384: if (defined($old_name_to_ip{$name})) {
14385: $ip = $old_name_to_ip{$name};
14386: &logthis("Can't find $name defaulting to old $ip");
14387: } else {
14388: &logthis("Name $name no IP found");
14389: next;
14390: }
14391: } else {
14392: $ip=inet_ntoa($ip);
1.847 albertel 14393: }
14394: $name_to_ip{$name} = $ip;
14395: } else {
14396: $ip = $name_to_ip{$name};
1.653 albertel 14397: }
1.888 albertel 14398: foreach my $id (@{ $name_to_host{$name} }) {
14399: $lonid_to_ip{$id} = $ip;
14400: }
14401: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 14402: }
1.1172.2.70 raeburn 14403: unless ($nocache) {
14404: &do_cache_new('iphost','iphost',
14405: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14406: 48*60*60);
14407: }
1.869 albertel 14408:
1.847 albertel 14409: return %iphost;
1.598 albertel 14410: }
14411:
1.992 raeburn 14412: #
14413: # Given a DNS returns the loncapa host name for that DNS
14414: #
14415: sub host_from_dns {
14416: my ($dns) = @_;
14417: my @hosts;
14418: my $ip;
14419:
1.993 raeburn 14420: if (exists($name_to_ip{$dns})) {
1.992 raeburn 14421: $ip = $name_to_ip{$dns};
14422: }
14423: if (!$ip) {
14424: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14425: if (length($ip) == 4) {
14426: $ip = &IO::Socket::inet_ntoa($ip);
14427: }
14428: }
14429: if ($ip) {
14430: @hosts = get_hosts_from_ip($ip);
14431: return $hosts[0];
14432: }
14433: return undef;
1.986 foxr 14434: }
1.992 raeburn 14435:
1.1074 raeburn 14436: sub get_internet_names {
14437: my ($lonid) = @_;
14438: return if ($lonid eq '');
14439: my ($idnref,$cached)=
14440: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14441: if ($cached) {
14442: return $idnref;
14443: }
14444: my $ip = &get_host_ip($lonid);
14445: my @hosts = &get_hosts_from_ip($ip);
14446: my %iphost = &get_iphost();
14447: my (@idns,%seen);
14448: foreach my $id (@hosts) {
14449: my $dom = &host_domain($id);
14450: my $prim_id = &domain($dom,'primary');
14451: my $prim_ip = &get_host_ip($prim_id);
14452: next if ($seen{$prim_ip});
14453: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14454: foreach my $id (@{$iphost{$prim_ip}}) {
14455: my $intdom = &internet_dom($id);
14456: unless (grep(/^\Q$intdom\E$/,@idns)) {
14457: push(@idns,$intdom);
14458: }
14459: }
14460: }
14461: $seen{$prim_ip} = 1;
14462: }
1.1172.2.23 raeburn 14463: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14464: }
14465:
1.986 foxr 14466: }
14467:
1.1079 raeburn 14468: sub all_loncaparevs {
1.1172.2.39 raeburn 14469: 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 14470: }
14471:
1.1172.2.27 raeburn 14472: # ------------------------------------------------------- Read loncaparev table
14473: {
14474: sub load_loncaparevs {
14475: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 14476: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 14477: while (my $configline=<$config>) {
14478: chomp($configline);
14479: my ($hostid,$loncaparev)=split(/:/,$configline);
14480: $loncaparevs{$hostid}=$loncaparev;
14481: }
14482: close($config);
14483: }
14484: }
14485: }
14486: }
14487:
14488: # ----------------------------------------------------- Read serverhostID table
14489: {
14490: sub load_serverhomeIDs {
14491: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 14492: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 14493: while (my $configline=<$config>) {
14494: chomp($configline);
14495: my ($name,$id)=split(/:/,$configline);
14496: $serverhomeIDs{$name}=$id;
14497: }
14498: close($config);
14499: }
14500: }
14501: }
14502: }
14503:
14504:
1.862 albertel 14505: BEGIN {
14506:
14507: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14508: unless ($readit) {
14509: {
14510: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14511: %perlvar = (%perlvar,%{$configvars});
14512: }
14513:
14514:
1.1 albertel 14515: # ------------------------------------------------------ Read spare server file
14516: {
1.1172.2.96 raeburn 14517: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14518:
14519: while (my $configline=<$config>) {
14520: chomp($configline);
1.284 matthew 14521: if ($configline) {
1.784 albertel 14522: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14523: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14524: push(@{ $spareid{$type} }, $host);
1.1 albertel 14525: }
14526: }
1.448 albertel 14527: close($config);
1.1 albertel 14528: }
1.11 www 14529: # ------------------------------------------------------------ Read permissions
14530: {
1.1172.2.96 raeburn 14531: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14532:
14533: while (my $configline=<$config>) {
1.448 albertel 14534: chomp($configline);
14535: if ($configline) {
14536: my ($role,$perm)=split(/ /,$configline);
14537: if ($perm ne '') { $pr{$role}=$perm; }
14538: }
1.11 www 14539: }
1.448 albertel 14540: close($config);
1.11 www 14541: }
14542:
14543: # -------------------------------------------- Read plain texts for permissions
14544: {
1.1172.2.96 raeburn 14545: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14546:
14547: while (my $configline=<$config>) {
1.448 albertel 14548: chomp($configline);
14549: if ($configline) {
1.742 raeburn 14550: my ($short,@plain)=split(/:/,$configline);
14551: %{$prp{$short}} = ();
14552: if (@plain > 0) {
14553: $prp{$short}{'std'} = $plain[0];
14554: for (my $i=1; $i<@plain; $i++) {
14555: $prp{$short}{'alt'.$i} = $plain[$i];
14556: }
14557: }
1.448 albertel 14558: }
1.135 www 14559: }
1.448 albertel 14560: close($config);
1.135 www 14561: }
14562:
14563: # ---------------------------------------------------------- Read package table
14564: {
1.1172.2.96 raeburn 14565: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14566:
14567: while (my $configline=<$config>) {
1.483 albertel 14568: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14569: chomp($configline);
14570: my ($short,$plain)=split(/:/,$configline);
14571: my ($pack,$name)=split(/\&/,$short);
14572: if ($plain ne '') {
14573: $packagetab{$pack.'&'.$name.'&name'}=$name;
14574: $packagetab{$short}=$plain;
14575: }
1.11 www 14576: }
1.448 albertel 14577: close($config);
1.329 matthew 14578: }
14579:
1.1172.2.27 raeburn 14580: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 14581:
1.1172.2.27 raeburn 14582: &load_loncaparevs();
14583:
14584: # ------------------------------------------------------- Read serverhostID table
14585:
14586: &load_serverhomeIDs();
1.1074 raeburn 14587:
1.1172.2.27 raeburn 14588: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14589: {
14590: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14591: if (-e $file) {
14592: my $parser = HTML::LCParser->new($file);
14593: while (my $token = $parser->get_token()) {
14594: if ($token->[0] eq 'S') {
14595: my $item = $token->[1];
14596: my $name = $token->[2]{'name'};
14597: my $value = $token->[2]{'value'};
14598: if ($item ne '' && $name ne '' && $value ne '') {
14599: my $release = $parser->get_text();
14600: $release =~ s/(^\s*|\s*$ )//gx;
14601: $needsrelease{$item.':'.$name.':'.$value} = $release;
14602: }
14603: }
14604: }
14605: }
1.1073 raeburn 14606: }
14607:
1.1138 raeburn 14608: # ---------------------------------------------------------- Read managers table
14609: {
14610: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 14611: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14612: while (my $configline=<$config>) {
14613: chomp($configline);
14614: next if ($configline =~ /^\#/);
14615: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14616: $managerstab{$configline} = 1;
14617: }
14618: }
14619: close($config);
14620: }
14621: }
14622: }
14623:
1.329 matthew 14624: # ------------- set up temporary directory
14625: {
1.1117 foxr 14626: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14627:
1.11 www 14628: }
14629:
1.1172.2.104 raeburn 14630: # ------------- set default texengine (domain default overrides this)
14631: {
14632: $deftex = LONCAPA::texengine();
14633: }
14634:
1.1172.2.114 raeburn 14635: # ------------- set default minimum length for passwords for internal auth users
14636: {
14637: $passwdmin = LONCAPA::passwd_min();
14638: }
14639:
1.794 albertel 14640: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14641: 'compress_threshold'=> 20_000,
14642: });
1.185 www 14643:
1.281 www 14644: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14645: $dumpcount=0;
1.958 www 14646: $locknum=0;
1.22 www 14647:
1.163 harris41 14648: &logtouch();
1.672 albertel 14649: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14650: $readit=1;
1.564 albertel 14651: {
14652: use integer;
14653: my $test=(2**32)+1;
1.568 albertel 14654: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14655: &logthis(" Detected 64bit platform ($_64bit)");
14656: }
1.195 www 14657: }
1.1 albertel 14658: }
1.179 www 14659:
1.1 albertel 14660: 1;
1.191 harris41 14661: __END__
14662:
1.243 albertel 14663: =pod
14664:
1.191 harris41 14665: =head1 NAME
14666:
1.243 albertel 14667: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14668:
14669: =head1 SYNOPSIS
14670:
1.243 albertel 14671: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14672:
14673: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14674:
1.243 albertel 14675: Common parameters:
14676:
14677: =over 4
14678:
14679: =item *
14680:
14681: $uname : an internal username (if $cname expecting a course Id specifically)
14682:
14683: =item *
14684:
14685: $udom : a domain (if $cdom expecting a course's domain specifically)
14686:
14687: =item *
14688:
14689: $symb : a resource instance identifier
14690:
14691: =item *
14692:
14693: $namespace : the name of a .db file that contains the data needed or
14694: being set.
14695:
14696: =back
14697:
1.394 bowersj2 14698: =head1 OVERVIEW
1.191 harris41 14699:
1.394 bowersj2 14700: lonnet provides subroutines which interact with the
14701: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14702: about classes, users, and resources.
1.243 albertel 14703:
14704: For many of these objects you can also use this to store data about
14705: them or modify them in various ways.
1.191 harris41 14706:
1.394 bowersj2 14707: =head2 Symbs
1.191 harris41 14708:
1.394 bowersj2 14709: To identify a specific instance of a resource, LON-CAPA uses symbols
14710: or "symbs"X<symb>. These identifiers are built from the URL of the
14711: map, the resource number of the resource in the map, and the URL of
14712: the resource itself. The latter is somewhat redundant, but might help
14713: if maps change.
14714:
14715: An example is
14716:
14717: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14718:
14719: The respective map entry is
14720:
14721: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14722: title="Problem 2">
14723: </resource>
14724:
14725: Symbs are used by the random number generator, as well as to store and
14726: restore data specific to a certain instance of for example a problem.
14727:
14728: =head2 Storing And Retrieving Data
14729:
14730: X<store()>X<cstore()>X<restore()>Three of the most important functions
14731: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14732: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14733: is is the non-critical message twin of cstore. These functions are for
14734: handlers to store a perl hash to a user's permanent data space in an
14735: easy manner, and to retrieve it again on another call. It is expected
14736: that a handler would use this once at the beginning to retrieve data,
14737: and then again once at the end to send only the new data back.
14738:
14739: The data is stored in the user's data directory on the user's
14740: homeserver under the ID of the course.
14741:
14742: The hash that is returned by restore will have all of the previous
14743: value for all of the elements of the hash.
14744:
14745: Example:
14746:
14747: #creating a hash
14748: my %hash;
14749: $hash{'foo'}='bar';
14750:
14751: #storing it
14752: &Apache::lonnet::cstore(\%hash);
14753:
14754: #changing a value
14755: $hash{'foo'}='notbar';
14756:
14757: #adding a new value
14758: $hash{'bar'}='foo';
14759: &Apache::lonnet::cstore(\%hash);
14760:
14761: #retrieving the hash
14762: my %history=&Apache::lonnet::restore();
14763:
14764: #print the hash
14765: foreach my $key (sort(keys(%history))) {
14766: print("\%history{$key} = $history{$key}");
14767: }
14768:
14769: Will print out:
1.191 harris41 14770:
1.394 bowersj2 14771: %history{1:foo} = bar
14772: %history{1:keys} = foo:timestamp
14773: %history{1:timestamp} = 990455579
14774: %history{2:bar} = foo
14775: %history{2:foo} = notbar
14776: %history{2:keys} = foo:bar:timestamp
14777: %history{2:timestamp} = 990455580
14778: %history{bar} = foo
14779: %history{foo} = notbar
14780: %history{timestamp} = 990455580
14781: %history{version} = 2
14782:
14783: Note that the special hash entries C<keys>, C<version> and
14784: C<timestamp> were added to the hash. C<version> will be equal to the
14785: total number of versions of the data that have been stored. The
14786: C<timestamp> attribute will be the UNIX time the hash was
14787: stored. C<keys> is available in every historical section to list which
14788: keys were added or changed at a specific historical revision of a
14789: hash.
14790:
14791: B<Warning>: do not store the hash that restore returns directly. This
14792: will cause a mess since it will restore the historical keys as if the
14793: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14794:
1.394 bowersj2 14795: Calling convention:
1.191 harris41 14796:
1.1172.2.27 raeburn 14797: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 14798: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14799:
1.394 bowersj2 14800: For more detailed information, see lonnet specific documentation.
1.191 harris41 14801:
1.394 bowersj2 14802: =head1 RETURN MESSAGES
1.191 harris41 14803:
1.394 bowersj2 14804: =over 4
1.191 harris41 14805:
1.394 bowersj2 14806: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14807:
1.394 bowersj2 14808: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14809: when the connection is brought back up
1.191 harris41 14810:
1.394 bowersj2 14811: =item * B<con_failed>: unable to contact remote host and unable to save message
14812: for later delivery
1.191 harris41 14813:
1.967 bisitz 14814: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14815:
1.394 bowersj2 14816: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14817: that was requested
1.191 harris41 14818:
1.243 albertel 14819: =back
1.191 harris41 14820:
1.243 albertel 14821: =head1 PUBLIC SUBROUTINES
1.191 harris41 14822:
1.243 albertel 14823: =head2 Session Environment Functions
1.191 harris41 14824:
1.243 albertel 14825: =over 4
1.191 harris41 14826:
1.394 bowersj2 14827: =item *
14828: X<appenv()>
1.949 raeburn 14829: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14830: the user envirnoment file, and will be restored for each access this
1.620 albertel 14831: user makes during this session, also modifies the %env for the current
1.949 raeburn 14832: process. Optional rolesarrayref - if defined contains a reference to an array
14833: of roles which are exempt from the restriction on modifying user.role entries
14834: in the user's environment.db and in %env.
1.191 harris41 14835:
14836: =item *
1.394 bowersj2 14837: X<delenv()>
1.987 raeburn 14838: B<delenv($delthis,$regexp)>: removes all items from the session
14839: environment file that begin with $delthis. If the
14840: optional second arg - $regexp - is true, $delthis is treated as a
14841: regular expression, otherwise \Q$delthis\E is used.
14842: The values are also deleted from the current processes %env.
1.191 harris41 14843:
1.795 albertel 14844: =item * get_env_multiple($name)
14845:
14846: gets $name from the %env hash, it seemlessly handles the cases where multiple
14847: values may be defined and end up as an array ref.
14848:
14849: returns an array of values
14850:
1.243 albertel 14851: =back
14852:
14853: =head2 User Information
1.191 harris41 14854:
1.243 albertel 14855: =over 4
1.191 harris41 14856:
14857: =item *
1.394 bowersj2 14858: X<queryauthenticate()>
14859: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14860: authentication scheme
14861:
14862: =item *
1.394 bowersj2 14863: X<authenticate()>
1.1073 raeburn 14864: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14865: authenticate user from domain's lib servers (first use the current
14866: one). C<$upass> should be the users password.
1.1073 raeburn 14867: $checkdefauth is optional (value is 1 if a check should be made to
14868: authenticate user using default authentication method, and allow
14869: account creation if username does not have account in the domain).
14870: $clientcancheckhost is optional (value is 1 if checking whether the
14871: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14872:
14873: =item *
1.394 bowersj2 14874: X<homeserver()>
14875: B<homeserver($uname,$udom)>: find the server which has
14876: the user's directory and files (there must be only one), this caches
14877: the answer, and also caches if there is a borken connection.
1.191 harris41 14878:
14879: =item *
1.394 bowersj2 14880: X<idget()>
14881: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14882: (IDs are a unique resource in a domain, there must be only 1 ID per
14883: username, and only 1 username per ID in a specific domain) (returns
14884: hash: id=>name,id=>name)
1.191 harris41 14885:
14886: =item *
1.394 bowersj2 14887: X<idrget()>
14888: B<idrget($udom,@unames)>: find the IDs behind a list of
14889: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14890:
14891: =item *
1.394 bowersj2 14892: X<idput()>
14893: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 14894:
14895: =item *
1.394 bowersj2 14896: X<rolesinit()>
1.1169 droeschl 14897: B<rolesinit($udom,$username)>: get user privileges.
14898: returns user role, first access and timer interval hashes
1.243 albertel 14899:
14900: =item *
1.1171 droeschl 14901: X<privileged()>
14902: B<privileged($username,$domain)>: returns a true if user has a
14903: privileged and active role (i.e. su or dc), false otherwise.
14904:
14905: =item *
1.551 albertel 14906: X<getsection()>
14907: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14908: course $cname, return section name/number or '' for "not in course"
14909: and '-1' for "no section"
14910:
14911: =item *
1.394 bowersj2 14912: X<userenvironment()>
14913: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14914: passed in @what from the requested user's environment, returns a hash
14915:
1.858 raeburn 14916: =item *
14917: X<userlog_query()>
1.859 albertel 14918: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14919: activity.log file. %filters defines filters applied when parsing the
14920: log file. These can be start or end timestamps, or the type of action
14921: - log to look for Login or Logout events, check for Checkin or
14922: Checkout, role for role selection. The response is in the form
14923: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14924: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14925:
1.243 albertel 14926: =back
14927:
14928: =head2 User Roles
14929:
14930: =over 4
14931:
14932: =item *
14933:
1.1172.2.65 raeburn 14934: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14935: returns codes for allowed actions.
14936:
14937: The first argument is required, all others are optional.
14938:
14939: $priv is the privilege being checked.
14940: $uri contains additional information about what is being checked for access (e.g.,
14941: URL, course ID etc.).
14942: $symb is the unique resource instance identifier in a course; if needed,
14943: but not provided, it will be retrieved via a call to &symbread().
14944: $role is the role for which a priv is being checked (only used if priv is evb).
14945: $clientip is the user's IP address (only used when checking for access to portfolio
14946: files).
14947: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14948: prevents recursive calls to &allowed.
14949:
1.243 albertel 14950: F: full access
14951: U,I,K: authentication modes (cxx only)
14952: '': forbidden
14953: 1: user needs to choose course
14954: 2: browse allowed
1.766 albertel 14955: A: passphrase authentication needed
1.1172.2.65 raeburn 14956: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14957:
14958: =item *
14959:
1.1172.2.13 raeburn 14960: constructaccess($url,$setpriv) : check for access to construction space URL
14961:
14962: See if the owner domain and name in the URL match those in the
14963: expected environment. If so, return three element list
14964: ($ownername,$ownerdomain,$ownerhome).
14965:
14966: Otherwise return the null string.
14967:
14968: If second argument 'setpriv' is true, it assigns the privileges,
14969: and returns the same three element list, unless the owner has
14970: blocked "ad hoc" Domain Coordinator access to the Author Space,
14971: in which case the null string is returned.
14972:
14973: =item *
14974:
1.1172.2.84 raeburn 14975: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14976: define a custom role rolename set privileges in format of lonTabs/roles.tab
14977: for system, domain, and course level. $uname and $udom are optional (current
14978: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14979:
14980: =item *
14981:
1.988 raeburn 14982: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14983: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14984: $type is Course (default) or Community.
1.988 raeburn 14985: If $forcedefault evaluates to true, text returned will be default
14986: text for $type. Otherwise, if this is a course, the text returned
14987: will be a custom name for the role (if defined in the course's
14988: environment). If no custom name is defined the default is returned.
14989:
1.832 raeburn 14990: =item *
14991:
1.1172.2.23 raeburn 14992: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14993: All arguments are optional. Returns a hash of a roles, either for
14994: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14995: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14996: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14997: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14998: For each key, value is set to colon-separated start and end times for
14999: the role. If no username and domain are specified, will default to
1.934 raeburn 15000: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 15001: of role statuses (active, future or previous), roles
15002: (e.g., cc,in, st etc.) and domains of the roles which can be used
15003: to restrict the list of roles reported. If no array ref is
15004: provided for types, will default to return only active roles.
1.834 albertel 15005:
1.1172.2.13 raeburn 15006: =item *
15007:
15008: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15009: user: $uname:$udom has a role in the course: $cdom_$cnum.
15010:
15011: Additional optional arguments are: $type (if role checking is to be restricted
15012: to certain user status types -- previous (expired roles), active (currently
15013: available roles) or future (roles available in the future), and
15014: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 15015: have active Domain Coordinator role in course's domain or in additional
15016: domains (specified in 'Domains to check for privileged users' in course
15017: environment -- set via: Course Settings -> Classlists and staff listing).
15018:
15019: =item *
15020:
15021: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15022: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15023: $possdomains and $possroles are optional array refs -- to domains to check and
15024: roles to check. If $possdomains is not specified, a dump will be done of the
15025: users' roles.db to check for a dc or su role in any domain. This can be
15026: time consuming if &privileged is called repeatedly (e.g., when displaying a
15027: classlist), so in such cases, supplying a $possdomains array is preferred, as
15028: this then allows &privileged_by_domain() to be used, which caches the identity
15029: of privileged users, eliminating the need for repeated calls to &dump().
15030:
15031: =item *
15032:
15033: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15034: where the outer hash keys are domains specified in the $possdomains array ref,
15035: next inner hash keys are privileged roles specified in the $roles array ref,
15036: and the innermost hash contains key = value pairs for username:domain = end:start
15037: for active or future "privileged" users with that role in that domain. To avoid
15038: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15039: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 15040:
1.243 albertel 15041: =back
15042:
15043: =head2 User Modification
15044:
15045: =over 4
15046:
15047: =item *
15048:
1.957 raeburn 15049: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 15050: user for the level given by URL. Optional start and end dates (leave empty
15051: string or zero for "no date")
1.191 harris41 15052:
15053: =item *
15054:
1.243 albertel 15055: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15056: change a users, password, possible return values are: ok,
15057: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15058: refused
1.191 harris41 15059:
15060: =item *
15061:
1.243 albertel 15062: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 15063:
15064: =item *
15065:
1.1058 raeburn 15066: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15067: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15068:
15069: will update user information (firstname,middlename,lastname,generation,
15070: permanentemail), and if forceid is true, student/employee ID also.
15071: A user's institutional affiliation(s) can also be updated.
15072: User information fields will not be overwritten with empty entries
15073: unless the field is included in the $candelete array reference.
15074: This array is included when a single user is modified via "Manage Users",
15075: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 15076:
15077: =item *
15078:
1.286 matthew 15079: modifystudent
15080:
1.957 raeburn 15081: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 15082: The course id is resolved based on the current user's environment.
15083: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 15084: associated with a course.
15085:
1.297 matthew 15086: This call is essentially a wrapper for lonnet::modifyuser and
15087: lonnet::modify_student_enrollment
1.286 matthew 15088:
15089: Inputs:
15090:
15091: =over 4
15092:
1.957 raeburn 15093: =item B<$udom> Student's loncapa domain
1.286 matthew 15094:
1.957 raeburn 15095: =item B<$uname> Student's loncapa login name
1.286 matthew 15096:
1.964 bisitz 15097: =item B<$uid> Student/Employee ID
1.286 matthew 15098:
1.957 raeburn 15099: =item B<$umode> Student's authentication mode
1.286 matthew 15100:
1.957 raeburn 15101: =item B<$upass> Student's password
1.286 matthew 15102:
1.957 raeburn 15103: =item B<$first> Student's first name
1.286 matthew 15104:
1.957 raeburn 15105: =item B<$middle> Student's middle name
1.286 matthew 15106:
1.957 raeburn 15107: =item B<$last> Student's last name
1.286 matthew 15108:
1.957 raeburn 15109: =item B<$gene> Student's generation
1.286 matthew 15110:
1.957 raeburn 15111: =item B<$usec> Student's section in course
1.286 matthew 15112:
15113: =item B<$end> Unix time of the roles expiration
15114:
15115: =item B<$start> Unix time of the roles start date
15116:
15117: =item B<$forceid> If defined, allow $uid to be changed
15118:
15119: =item B<$desiredhome> server to use as home server for student
15120:
1.957 raeburn 15121: =item B<$email> Student's permanent e-mail address
15122:
15123: =item B<$type> Type of enrollment (auto or manual)
15124:
1.963 raeburn 15125: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
15126:
15127: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 15128:
1.963 raeburn 15129: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 15130:
1.963 raeburn 15131: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 15132:
1.1172.2.19 raeburn 15133: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15134:
15135: =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 15136:
1.286 matthew 15137: =back
1.297 matthew 15138:
15139: =item *
15140:
15141: modify_student_enrollment
15142:
1.1172.2.31 raeburn 15143: Change a student's enrollment status in a class. The environment variable
1.297 matthew 15144: 'role.request.course' must be defined for this function to proceed.
15145:
15146: Inputs:
15147:
15148: =over 4
15149:
1.1172.2.31 raeburn 15150: =item $udom, student's domain
1.297 matthew 15151:
1.1172.2.31 raeburn 15152: =item $uname, student's name
1.297 matthew 15153:
1.1172.2.31 raeburn 15154: =item $uid, student's user id
1.297 matthew 15155:
1.1172.2.31 raeburn 15156: =item $first, student's first name
1.297 matthew 15157:
15158: =item $middle
15159:
15160: =item $last
15161:
15162: =item $gene
15163:
15164: =item $usec
15165:
15166: =item $end
15167:
15168: =item $start
15169:
1.957 raeburn 15170: =item $type
15171:
15172: =item $locktype
15173:
15174: =item $cid
15175:
15176: =item $selfenroll
15177:
15178: =item $context
15179:
1.1172.2.19 raeburn 15180: =item $credits, number of credits student will earn from this class
15181:
1.1172.2.76 raeburn 15182: =item $instsec, institutional course section code for student
15183:
1.297 matthew 15184: =back
15185:
1.191 harris41 15186:
15187: =item *
15188:
1.243 albertel 15189: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15190: custom role; give a custom role to a user for the level given by URL. Specify
15191: name and domain of role author, and role name
1.191 harris41 15192:
15193: =item *
15194:
1.243 albertel 15195: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 15196:
15197: =item *
15198:
1.243 albertel 15199: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15200:
15201: =back
15202:
15203: =head2 Course Infomation
15204:
15205: =over 4
1.191 harris41 15206:
15207: =item *
15208:
1.1118 foxr 15209: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 15210: specified course id, including all environment settings for the
15211: course, the description of the course will be in the hash under the
15212: key 'description'
1.191 harris41 15213:
1.1118 foxr 15214: $options is an optional parameter that if supplied is a hash reference that controls
15215: what how this function works. It has the following key/values:
15216:
15217: =over 4
15218:
15219: =item freshen_cache
15220:
15221: If defined, and the environment cache for the course is valid, it is
15222: returned in the returned hash.
15223:
15224: =item one_time
15225:
15226: If defined, the last cache time is set to _now_
15227:
15228: =item user
15229:
15230: If defined, the supplied username is used instead of the current user.
15231:
15232:
15233: =back
15234:
1.191 harris41 15235: =item *
15236:
1.624 albertel 15237: resdata($name,$domain,$type,@which) : request for current parameter
15238: setting for a specific $type, where $type is either 'course' or 'user',
15239: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 15240: answers for 10 minutes.
1.243 albertel 15241:
1.877 foxr 15242: =item *
15243:
15244: get_courseresdata($courseid, $domain) : dump the entire course resource
15245: data base, returning a hash that is keyed by the resource name and has
15246: values that are the resource value. I believe that the timestamps and
15247: versions are also returned.
15248:
1.1172.2.31 raeburn 15249: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15250: supplemental content area. This routine caches the number of files for
15251: 10 minutes.
15252:
1.243 albertel 15253: =back
15254:
15255: =head2 Course Modification
15256:
15257: =over 4
1.191 harris41 15258:
15259: =item *
15260:
1.243 albertel 15261: writecoursepref($courseid,%prefs) : write preferences (environment
15262: database) for a course
1.191 harris41 15263:
15264: =item *
15265:
1.1011 raeburn 15266: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15267:
15268: =item *
15269:
1.1038 raeburn 15270: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 15271:
1.1167 droeschl 15272: =item *
15273:
15274: is_course($courseid), is_course($cdom, $cnum)
15275:
15276: Accepts either a combined $courseid (in the form of domain_courseid) or the
15277: two component version $cdom, $cnum. It checks if the specified course exists.
15278:
15279: Returns:
15280: undef if the course doesn't exist, otherwise
15281: in scalar context the combined courseid.
15282: in list context the two components of the course identifier, domain and
15283: courseid.
15284:
1.243 albertel 15285: =back
15286:
1.1172.2.109 raeburn 15287: =head2 Bubblesheet Configuration
15288:
15289: =over 4
15290:
15291: =item *
15292:
15293: get_scantron_config($which)
15294:
15295: $which - the name of the configuration to parse from the file.
15296:
15297: Parses and returns the bubblesheet configuration line selected as a
15298: hash of configuration file fields.
15299:
15300:
15301: Returns:
15302: If the named configuration is not in the file, an empty
15303: hash is returned.
15304:
15305: a hash with the fields
15306: name - internal name for the this configuration setup
15307: description - text to display to operator that describes this config
15308: CODElocation - if 0 or the string 'none'
15309: - no CODE exists for this config
15310: if -1 || the string 'letter'
15311: - a CODE exists for this config and is
15312: a string of letters
15313: Unsupported value (but planned for future support)
15314: if a positive integer
15315: - The CODE exists as the first n items from
15316: the question section of the form
15317: if the string 'number'
15318: - The CODE exists for this config and is
15319: a string of numbers
15320: CODEstart - (only matter if a CODE exists) column in the line where
15321: the CODE starts
15322: CODElength - length of the CODE
15323: IDstart - column where the student/employee ID starts
15324: IDlength - length of the student/employee ID info
15325: Qstart - column where the information from the bubbled
15326: 'questions' start
15327: Qlength - number of columns comprising a single bubble line from
15328: the sheet. (usually either 1 or 10)
15329: Qon - either a single character representing the character used
15330: to signal a bubble was chosen in the positional setup, or
15331: the string 'letter' if the letter of the chosen bubble is
15332: in the final, or 'number' if a number representing the
15333: chosen bubble is in the file (1->A 0->J)
15334: Qoff - the character used to represent that a bubble was
15335: left blank
15336: PaperID - if the scanning process generates a unique number for each
15337: sheet scanned the column that this ID number starts in
15338: PaperIDlength - number of columns that comprise the unique ID number
15339: for the sheet of paper
15340: FirstName - column that the first name starts in
15341: FirstNameLength - number of columns that the first name spans
15342: LastName - column that the last name starts in
15343: LastNameLength - number of columns that the last name spans
15344: BubblesPerRow - number of bubbles available in each row used to
15345: bubble an answer. (If not specified, 10 assumed).
15346:
15347:
15348: =item *
15349:
15350: get_scantronformat_file($cdom)
15351:
15352: $cdom - the course's domain (optional); if not supplied, uses
15353: domain for current $env{'request.course.id'}.
15354:
15355: Returns an array containing lines from the scantron format file for
15356: the domain of the course.
15357:
15358: If a url for a custom.tab file is listed in domain's configuration.db,
15359: lines are from this file.
15360:
15361: Otherwise, if a default.tab has been published in RES space by the
15362: domainconfig user, lines are from this file.
15363:
15364: Otherwise, fall back to getting lines from the legacy file on the
15365: local server: /home/httpd/lonTabs/default_scantronformat.tab
15366:
15367: =back
15368:
1.243 albertel 15369: =head2 Resource Subroutines
15370:
15371: =over 4
1.191 harris41 15372:
15373: =item *
15374:
1.243 albertel 15375: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 15376:
15377: =item *
15378:
1.243 albertel 15379: repcopy($filename) : subscribes to the requested file, and attempts to
15380: replicate from the owning library server, Might return
1.607 raeburn 15381: 'unavailable', 'not_found', 'forbidden', 'ok', or
15382: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 15383: resource. Expects the local filesystem pathname
15384: (/home/httpd/html/res/....)
15385:
15386: =back
15387:
15388: =head2 Resource Information
15389:
15390: =over 4
1.191 harris41 15391:
15392: =item *
15393:
1.1172.2.28 raeburn 15394: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15395: and returns the value of a variety of different possible values,
15396: $varname should be a request string, and the other parameters can be
15397: used to specify who and what one is asking about. Ordinarily, $cid
15398: does not need to be specified, as it is retrived from
15399: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15400: within lonuserstate::loadmap() when initializing a course, before
15401: $env{'request.course.id'} has been set, so it needs to be provided
15402: in that one case.
1.243 albertel 15403:
15404: Possible values for $varname are environment.lastname (or other item
15405: from the envirnment hash), user.name (or someother aspect about the
15406: user), resource.0.maxtries (or some other part and parameter of a
15407: resource)
1.204 albertel 15408:
15409: =item *
15410:
1.243 albertel 15411: directcondval($number) : get current value of a condition; reads from a state
15412: string
1.204 albertel 15413:
15414: =item *
15415:
1.243 albertel 15416: condval($condidx) : value of condition index based on state
1.204 albertel 15417:
15418: =item *
15419:
1.243 albertel 15420: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15421: resource's metadata, $what should be either a specific key, or either
15422: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15423: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15424:
15425: this function automatically caches all requests
1.191 harris41 15426:
15427: =item *
15428:
1.243 albertel 15429: metadata_query($query,$custom,$customshow) : make a metadata query against the
15430: network of library servers; returns file handle of where SQL and regex results
15431: will be stored for query
1.191 harris41 15432:
15433: =item *
15434:
1.1172.2.66 raeburn 15435: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15436: return symbolic list entry (all arguments optional).
15437:
15438: Args: filename is the filename (including path) for the file for which a symb
15439: is required; donotrecurse, if true will prevent calls to allowed() being made
15440: to check access status if more than one resource was found in the bighash
15441: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15442: a randompick); ignorecachednull, if true will prevent a symb of '' being
15443: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15444: cause possible symbs to be checked to determine if they are subject to content
15445: blocking, if so they will not be included as possible symbs; possibles is a
15446: ref to a hash, which, as a side effect, will be populated with all possible
15447: symbs (content blocking not tested).
15448:
1.243 albertel 15449: returns the data handle
1.191 harris41 15450:
15451: =item *
15452:
1.1172.2.17 raeburn 15453: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 15454: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15455: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 15456: on failure, user must be in a course, as it assumes the existence of
15457: the course initial hash, and uses $env('request.course.id'}. The third
15458: arg is an optional reference to a scalar. If this arg is passed in the
15459: call to symbverify, it will be set to 1 if the symb has been set to be
15460: encrypted; otherwise it will be null.
1.243 albertel 15461:
1.191 harris41 15462: =item *
15463:
1.243 albertel 15464: symbclean($symb) : removes versions numbers from a symb, returns the
15465: cleaned symb
1.191 harris41 15466:
15467: =item *
15468:
1.243 albertel 15469: is_on_map($uri) : checks if the $uri is somewhere on the current
15470: course map, user must be in a course for it to work.
1.191 harris41 15471:
15472: =item *
15473:
1.243 albertel 15474: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15475:
15476: =item *
15477:
1.243 albertel 15478: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15479: a random seed, all arguments are optional, if they aren't sent it uses the
15480: environment to derive them. Note: if symb isn't sent and it can't get one
15481: from &symbread it will use the current time as its return value
1.191 harris41 15482:
15483: =item *
15484:
1.243 albertel 15485: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15486: unfakeable, receipt
1.191 harris41 15487:
15488: =item *
15489:
1.620 albertel 15490: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15491:
15492: =item *
15493:
1.243 albertel 15494: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15495:
15496: =item *
15497:
1.243 albertel 15498: 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 15499:
15500: =item *
15501:
1.243 albertel 15502: 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 15503:
15504: =item *
15505:
1.243 albertel 15506: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15507:
15508: =item *
15509:
1.243 albertel 15510: devalidate($symb) : devalidate temporary spreadsheet calculations,
15511: forcing spreadsheet to reevaluate the resource scores next time.
15512:
1.1172.2.13 raeburn 15513: =item *
15514:
15515: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15516: when viewing in course context.
15517:
15518: input: six args -- filename (decluttered), course number, course domain,
15519: url, symb (if registered) and group (if this is a
15520: group item -- e.g., bulletin board, group page etc.).
15521:
15522: output: array of five scalars --
15523: $cfile -- url for file editing if editable on current server
15524: $home -- homeserver of resource (i.e., for author if published,
15525: or course if uploaded.).
15526: $switchserver -- 1 if server switch will be needed.
15527: $forceedit -- 1 if icon/link should be to go to edit mode
15528: $forceview -- 1 if icon/link should be to go to view mode
15529:
15530: =item *
15531:
15532: is_course_upload($file,$cnum,$cdom)
15533:
15534: Used in course context to determine if current file was uploaded to
15535: the course (i.e., would be found in /userfiles/docs on the course's
15536: homeserver.
15537:
15538: input: 3 args -- filename (decluttered), course number and course domain.
15539: output: boolean -- 1 if file was uploaded.
15540:
1.243 albertel 15541: =back
15542:
15543: =head2 Storing/Retreiving Data
15544:
15545: =over 4
1.191 harris41 15546:
15547: =item *
15548:
1.1172.2.64 raeburn 15549: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15550: permanently for this url; hashref needs to be given and should be a \%hashname;
15551: the remaining args aren't required and if they aren't passed or are '' they will
15552: be derived from the env (with the exception of $laststore, which is an
15553: optional arg used when a user's submission is stored in grading).
15554: $laststore is $version=$timestamp, where $version is the most recent version
15555: number retrieved for the corresponding $symb in the $namespace db file, and
15556: $timestamp is the timestamp for that transaction (UNIX time).
15557: $laststore is currently only passed when cstore() is called by
15558: structuretags::finalize_storage().
1.191 harris41 15559:
15560: =item *
15561:
1.1172.2.64 raeburn 15562: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15563: but uses critical subroutine
1.191 harris41 15564:
15565: =item *
15566:
1.243 albertel 15567: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15568: all args are optional
1.191 harris41 15569:
15570: =item *
15571:
1.717 albertel 15572: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15573: dumps the complete (or key matching regexp) namespace into a hash
15574: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15575: normally &store()ed into
15576:
15577: $range should be either an integer '100' (give me the first 100
15578: matching records)
15579: or be two integers sperated by a - with no spaces
15580: '30-50' (give me the 30th through the 50th matching
15581: records)
15582:
15583:
15584: =item *
15585:
1.1172.2.59 raeburn 15586: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15587: replaces a &store() version of data with a replacement set of data
15588: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 15589: reference. If $tolog is true, the transaction is logged in the courselog
15590: with an action=PUTSTORE.
1.717 albertel 15591:
15592: =item *
15593:
1.243 albertel 15594: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15595: works very similar to store/cstore, but all data is stored in a
15596: temporary location and can be reset using tmpreset, $storehash should
15597: be a hash reference, returns nothing on success
1.191 harris41 15598:
15599: =item *
15600:
1.243 albertel 15601: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15602: similar to restore, but all data is stored in a temporary location and
15603: can be reset using tmpreset. Returns a hash of values on success,
15604: error string otherwise.
1.191 harris41 15605:
15606: =item *
15607:
1.243 albertel 15608: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15609: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15610:
15611: =item *
15612:
1.243 albertel 15613: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15614: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15615:
15616: =item *
15617:
1.243 albertel 15618: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15619: namesp ($udom and $uname are optional)
1.191 harris41 15620:
15621: =item *
15622:
1.702 albertel 15623: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15624: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15625: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15626:
1.702 albertel 15627: $range should be either an integer '100' (give me the first 100
15628: matching records)
15629: or be two integers sperated by a - with no spaces
15630: '30-50' (give me the 30th through the 50th matching
15631: records)
1.449 matthew 15632: =item *
15633:
15634: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15635: $store can be a scalar, an array reference, or if the amount to be
15636: incremented is > 1, a hash reference.
15637:
15638: ($udom and $uname are optional)
1.191 harris41 15639:
15640: =item *
15641:
1.243 albertel 15642: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15643: ($udom and $uname are optional)
1.191 harris41 15644:
15645: =item *
15646:
1.243 albertel 15647: cput($namespace,$storehash,$udom,$uname) : critical put
15648: ($udom and $uname are optional)
1.191 harris41 15649:
15650: =item *
15651:
1.748 albertel 15652: newput($namespace,$storehash,$udom,$uname) :
15653:
15654: Attempts to store the items in the $storehash, but only if they don't
15655: currently exist, if this succeeds you can be certain that you have
15656: successfully created a new key value pair in the $namespace db.
15657:
15658:
15659: Args:
15660: $namespace: name of database to store values to
15661: $storehash: hashref to store to the db
15662: $udom: (optional) domain of user containing the db
15663: $uname: (optional) name of user caontaining the db
15664:
15665: Returns:
15666: 'ok' -> succeeded in storing all keys of $storehash
15667: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15668: least <key> already existed in the db (other
15669: requested keys may also already exist)
1.967 bisitz 15670: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15671: 'con_lost' -> unable to contact request server
15672: 'refused' -> action was not allowed by remote machine
15673:
15674:
15675: =item *
15676:
1.243 albertel 15677: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15678: reference filled in from namesp (encrypts the return communication)
15679: ($udom and $uname are optional)
1.191 harris41 15680:
15681: =item *
15682:
1.243 albertel 15683: log($udom,$name,$home,$message) : write to permanent log for user; use
15684: critical subroutine
15685:
1.806 raeburn 15686: =item *
15687:
1.860 raeburn 15688: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15689: array reference filled in from namespace found in domain level on either
15690: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15691:
15692: =item *
15693:
1.860 raeburn 15694: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15695: domain level either on specified domain server ($uhome) or primary domain
15696: server ($udom and $uhome are optional)
1.806 raeburn 15697:
1.943 raeburn 15698: =item *
15699:
1.1172.2.35 raeburn 15700: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15701: for: authentication, language, quotas, timezone, date locale, and portal URL in
15702: the target domain.
15703:
15704: May also include additional key => value pairs for the following groups:
15705:
15706: =over
15707:
15708: =item
15709: disk quotas (MB allocated by default to portfolios and authoring spaces).
15710:
15711: =over
15712:
15713: =item defaultquota, authorquota
15714:
15715: =back
15716:
15717: =item
15718: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15719: portfolio for users).
15720:
15721: =over
15722:
15723: =item
15724: aboutme, blog, webdav, portfolio
15725:
15726: =back
15727:
15728: =item
15729: requestcourses: ability to request courses, and how requests are processed.
15730:
15731: =over
15732:
15733: =item
1.1172.2.37 raeburn 15734: official, unofficial, community, textbook
1.1172.2.35 raeburn 15735:
15736: =back
15737:
15738: =item
15739: inststatus: types of institutional affiliation, and order in which they are displayed.
15740:
15741: =over
15742:
15743: =item
1.1172.2.44 raeburn 15744: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 15745:
15746: =back
15747:
15748: =item
15749: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15750: for course's uploaded content.
15751:
15752: =over
15753:
15754: =item
1.1172.2.68 raeburn 15755: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15756: communityquota, textbookquota
1.1172.2.35 raeburn 15757:
15758: =back
15759:
15760: =item
15761: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15762: on your servers.
15763:
15764: =over
15765:
15766: =item
15767: remotesessions, hostedsessions
15768:
15769: =back
15770:
15771: =back
15772:
15773: In cases where a domain coordinator has never used the "Set Domain Configuration"
15774: utility to create a configuration.db file on a domain's primary library server
15775: only the following domain defaults: auth_def, auth_arg_def, lang_def
15776: -- corresponding values are authentication type (internal, krb4, krb5,
15777: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15778: will be available. Values are retrieved from cache (if current), unless the
15779: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15780: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15781:
15782: Typical usage:
1.943 raeburn 15783:
1.1172.2.35 raeburn 15784: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 15785:
1.243 albertel 15786: =back
15787:
15788: =head2 Network Status Functions
15789:
15790: =over 4
1.191 harris41 15791:
15792: =item *
15793:
1.1137 raeburn 15794: dirlist() : return directory list based on URI (first arg).
15795:
15796: Inputs: 1 required, 5 optional.
15797:
15798: =over
15799:
15800: =item
15801: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15802:
15803: =item
15804: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15805:
15806: =item
15807: $username - username of user/course to be listed. Extracted from $uri if absent.
15808:
15809: =item
15810: $getpropath - boolean: 1 if prepend path using &propath().
15811:
15812: =item
15813: $getuserdir - boolean: 1 if prepend path for "userfiles".
15814:
15815: =item
15816: $alternateRoot - path to prepend in place of path from $uri.
15817:
15818: =back
15819:
15820: Returns: Array of up to two items.
15821:
15822: =over
15823:
15824: a reference to an array of files/subdirectories
15825:
15826: =over
15827:
15828: Each element in the array of files/subdirectories is a & separated list of
15829: item name and the result of running stat on the item. If dirlist was requested
15830: for a file instead of a directory, the item name will be ''. For a directory
15831: listing, if the item is a metadata file, the element will end &N&M
15832: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15833: default copyright set (1).
15834:
15835: =back
15836:
15837: a scalar containing error condition (if encountered).
15838:
15839: =over
15840:
15841: =item
15842: no_host (no homeserver identified for $username:$domain).
15843:
15844: =item
15845: no_such_host (server contacted for listing not identified as valid host).
15846:
15847: =item
15848: con_lost (connection to remote server failed).
15849:
15850: =item
15851: refused (invalid $username:$domain received on lond side).
15852:
15853: =item
15854: no_such_dir (directory at specified path on lond side does not exist).
15855:
15856: =item
15857: empty (directory at specified path on lond side is empty).
15858:
15859: =over
15860:
15861: This is currently not encountered because the &ls3, &ls2,
15862: &ls (_handler) routines on the lond side do not filter out
15863: . and .. from a directory listing.
15864:
15865: =back
15866:
15867: =back
15868:
15869: =back
1.191 harris41 15870:
15871: =item *
15872:
1.243 albertel 15873: spareserver() : find server with least workload from spare.tab
15874:
1.986 foxr 15875:
15876: =item *
15877:
15878: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15879: if there is no corresponding loncapa host.
15880:
1.243 albertel 15881: =back
15882:
1.986 foxr 15883:
1.243 albertel 15884: =head2 Apache Request
15885:
15886: =over 4
1.191 harris41 15887:
15888: =item *
15889:
1.243 albertel 15890: ssi($url,%hash) : server side include, does a complete request cycle on url to
15891: localhost, posts hash
15892:
15893: =back
15894:
15895: =head2 Data to String to Data
15896:
15897: =over 4
1.191 harris41 15898:
15899: =item *
15900:
1.243 albertel 15901: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15902: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15903:
15904: =item *
15905:
1.243 albertel 15906: hashref2str($hashref) : convert a hashref into a string complete with
15907: escaping and '=' and '&' separators, supports elements that are
15908: arrayrefs and hashrefs
1.191 harris41 15909:
15910: =item *
15911:
1.243 albertel 15912: arrayref2str($arrayref) : convert an arrayref into a string complete
15913: with escaping and '&' separators, supports elements that are arrayrefs
15914: and hashrefs
1.191 harris41 15915:
15916: =item *
15917:
1.243 albertel 15918: str2hash($string) : convert string to hash using unescaping and
15919: splitting on '=' and '&', supports elements that are arrayrefs and
15920: hashrefs
1.191 harris41 15921:
15922: =item *
15923:
1.243 albertel 15924: str2array($string) : convert string to hash using unescaping and
15925: splitting on '&', supports elements that are arrayrefs and hashrefs
15926:
15927: =back
15928:
15929: =head2 Logging Routines
15930:
15931:
15932: These routines allow one to make log messages in the lonnet.log and
15933: lonnet.perm logfiles.
1.191 harris41 15934:
1.1119 foxr 15935: =over 4
15936:
1.191 harris41 15937: =item *
15938:
1.243 albertel 15939: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15940:
15941: =item *
15942:
1.243 albertel 15943: logthis() : append message to the normal lonnet.log file, it gets
15944: preiodically rolled over and deleted.
1.191 harris41 15945:
15946: =item *
15947:
1.243 albertel 15948: logperm() : append a permanent message to lonnet.perm.log, this log
15949: file never gets deleted by any automated portion of the system, only
15950: messages of critical importance should go in here.
15951:
1.1119 foxr 15952:
1.243 albertel 15953: =back
15954:
15955: =head2 General File Helper Routines
15956:
15957: =over 4
1.191 harris41 15958:
15959: =item *
15960:
1.481 raeburn 15961: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15962: (a) files in /uploaded
15963: (i) If a local copy of the file exists -
15964: compares modification date of local copy with last-modified date for
15965: definitive version stored on home server for course. If local copy is
15966: stale, requests a new version from the home server and stores it.
15967: If the original has been removed from the home server, then local copy
15968: is unlinked.
15969: (ii) If local copy does not exist -
15970: requests the file from the home server and stores it.
15971:
15972: If $caller is 'uploadrep':
15973: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15974: for request for files originally uploaded via DOCS.
15975: - returns 'ok' if fresh local copy now available, -1 otherwise.
15976:
15977: Otherwise:
15978: This indicates a call from the content generation phase of the request.
15979: - returns the entire contents of the file or -1.
15980:
15981: (b) files in /res
15982: - returns the entire contents of a file or -1;
15983: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 15984:
1.712 albertel 15985:
15986: =item *
15987:
15988: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15989: reference
15990:
15991: returns either a stat() list of data about the file or an empty list
15992: if the file doesn't exist or couldn't find out about it (connection
15993: problems or user unknown)
15994:
1.191 harris41 15995: =item *
15996:
1.243 albertel 15997: filelocation($dir,$file) : returns file system location of a file
15998: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15999: directory that relative $file lookups are to looked in ($dir of /a/dir
16000: and a file of ../bob will become /a/bob)
1.191 harris41 16001:
16002: =item *
16003:
16004: hreflocation($dir,$file) : returns file system location or a URL; same as
16005: filelocation except for hrefs
16006:
16007: =item *
16008:
1.1172.2.49 raeburn 16009: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16010: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 16011:
1.243 albertel 16012: =back
16013:
1.608 albertel 16014: =head2 Usererfile file routines (/uploaded*)
16015:
16016: =over 4
16017:
16018: =item *
16019:
16020: userfileupload(): main rotine for putting a file in a user or course's
16021: filespace, arguments are,
16022:
1.620 albertel 16023: formname - required - this is the name of the element in $env where the
1.608 albertel 16024: filename, and the contents of the file to create/modifed exist
1.620 albertel 16025: the filename is in $env{'form.'.$formname.'.filename'} and the
16026: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 16027: context - if coursedoc, store the file in the course of the active role
16028: of the current user;
16029: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16030: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 16031: subdir - required - subdirectory to put the file in under ../userfiles/
16032: if undefined, it will be placed in "unknown"
16033:
16034: (This routine calls clean_filename() to remove any dangerous
16035: characters from the filename, and then calls finuserfileupload() to
16036: complete the transaction)
16037:
16038: returns either the url of the uploaded file (/uploaded/....) if successful
16039: and /adm/notfound.html if unsuccessful
16040:
16041: =item *
16042:
16043: clean_filename(): routine for cleaing a filename up for storage in
16044: userfile space, argument is:
16045:
16046: filename - proposed filename
16047:
16048: returns: the new clean filename
16049:
16050: =item *
16051:
1.1090 raeburn 16052: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 16053: userspace, probably shouldn't be called directly
16054:
16055: docuname: username or courseid of destination for the file
16056: docudom: domain of user/course of destination for the file
16057: formname: same as for userfileupload()
1.1090 raeburn 16058: fname: filename (including subdirectories) for the file
16059: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 16060: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 16061: allfiles: reference to hash used to store objects found by parser
16062: codebase: reference to hash used for codebases of java objects found by parser
16063: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16064: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16065: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16066: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16067: context: if 'overwrite', will move the uploaded file from its temporary location to
16068: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 16069: mimetype: reference to scalar to accommodate mime type determined
16070: from File::MMagic if $parser = parse.
1.608 albertel 16071:
16072: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 16073: and /adm/notfound.html if unsuccessful (or an error message if context
16074: was 'overwrite').
16075:
1.608 albertel 16076:
16077: =item *
16078:
16079: renameuserfile(): renames an existing userfile to a new name
16080:
16081: Args:
16082: docuname: username or courseid of destination for the file
16083: docudom: domain of user/course of destination for the file
16084: old: current file name (including any subdirs under userfiles)
16085: new: desired file name (including any subdirs under userfiles)
16086:
16087: =item *
16088:
16089: mkdiruserfile(): creates a directory is a userfiles dir
16090:
16091: Args:
16092: docuname: username or courseid of destination for the file
16093: docudom: domain of user/course of destination for the file
16094: dir: dir to create (including any subdirs under userfiles)
16095:
16096: =item *
16097:
16098: removeuserfile(): removes a file that exists in userfiles
16099:
16100: Args:
16101: docuname: username or courseid of destination for the file
16102: docudom: domain of user/course of destination for the file
16103: fname: filname to delete (including any subdirs under userfiles)
16104:
16105: =item *
16106:
16107: removeuploadedurl(): convience function for removeuserfile()
16108:
16109: Args:
16110: url: a full /uploaded/... url to delete
16111:
1.747 albertel 16112: =item *
16113:
16114: get_portfile_permissions():
16115: Args:
16116: domain: domain of user or course contain the portfolio files
16117: user: name of user or num of course contain the portfolio files
16118: Returns:
16119: hashref of a dump of the proper file_permissions.db
16120:
16121:
16122: =item *
16123:
16124: get_access_controls():
16125:
16126: Args:
16127: current_permissions: the hash ref returned from get_portfile_permissions()
16128: group: (optional) the group you want the files associated with
16129: file: (optional) the file you want access info on
16130:
16131: Returns:
1.749 raeburn 16132: a hash (keys are file names) of hashes containing
16133: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16134: values are XML containing access control settings (see below)
1.747 albertel 16135:
16136: Internal notes:
16137:
1.749 raeburn 16138: access controls are stored in file_permissions.db as key=value pairs.
16139: key -> path to file/file_name\0uniqueID:scope_end_start
16140: where scope -> public,guest,course,group,domains or users.
16141: end -> UNIX time for end of access (0 -> no end date)
16142: start -> UNIX time for start of access
16143:
16144: value -> XML description of access control
16145: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16146: <start></start>
16147: <end></end>
16148:
16149: <password></password> for scope type = guest
16150:
16151: <domain></domain> for scope type = course or group
16152: <number></number>
16153: <roles id="">
16154: <role></role>
16155: <access></access>
16156: <section></section>
16157: <group></group>
16158: </roles>
16159:
16160: <dom></dom> for scope type = domains
16161:
16162: <users> for scope type = users
16163: <user>
16164: <uname></uname>
16165: <udom></udom>
16166: </user>
16167: </users>
16168: </scope>
16169:
16170: Access data is also aggregated for each file in an additional key=value pair:
16171: key -> path to file/file_name\0accesscontrol
16172: value -> reference to hash
16173: hash contains key = value pairs
16174: where key = uniqueID:scope_end_start
16175: value = UNIX time record was last updated
16176:
16177: Used to improve speed of look-ups of access controls for each file.
16178:
16179: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16180:
1.1172.2.13 raeburn 16181: =item *
16182:
1.749 raeburn 16183: modify_access_controls():
16184:
16185: Modifies access controls for a portfolio file
16186: Args
16187: 1. file name
16188: 2. reference to hash of required changes,
16189: 3. domain
16190: 4. username
16191: where domain,username are the domain of the portfolio owner
16192: (either a user or a course)
16193:
16194: Returns:
16195: 1. result of additions or updates ('ok' or 'error', with error message).
16196: 2. result of deletions ('ok' or 'error', with error message).
16197: 3. reference to hash of any new or updated access controls.
16198: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16199: key = integer (inbound ID)
1.1172.2.13 raeburn 16200: value = uniqueID
16201:
16202: =item *
16203:
16204: get_timebased_id():
16205:
16206: Attempts to get a unique timestamp-based suffix for use with items added to a
16207: course via the Course Editor (e.g., folders, composite pages,
16208: group bulletin boards).
16209:
16210: Args: (first three required; six others optional)
16211:
16212: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16213: docssequence, or name of group
16214:
16215: 2. keyid (alphanumeric): name of temporary locking key in hash,
16216: e.g., num, boardids
16217:
16218: 3. namespace: name of gdbm file used to store suffixes already assigned;
16219: file will be named nohist_namespace.db
16220:
16221: 4. cdom: domain of course; default is current course domain from %env
16222:
16223: 5. cnum: course number; default is current course number from %env
16224:
16225: 6. idtype: set to concat if an additional digit is to be appended to the
16226: unix timestamp to form the suffix, if the plain timestamp is already
16227: in use. Default is to not do this, but simply increment the unix
16228: timestamp by 1 until a unique key is obtained.
16229:
16230: 7. who: holder of locking key; defaults to user:domain for user.
16231:
16232: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16233: retrying); default is 3.
16234:
16235: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16236:
16237: Returns:
16238:
16239: 1. suffix obtained (numeric)
16240:
16241: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16242:
16243: 3. error: contains (localized) error message if an error occurred.
16244:
1.747 albertel 16245:
1.608 albertel 16246: =back
16247:
1.243 albertel 16248: =head2 HTTP Helper Routines
16249:
16250: =over 4
16251:
1.191 harris41 16252: =item *
16253:
16254: escape() : unpack non-word characters into CGI-compatible hex codes
16255:
16256: =item *
16257:
16258: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16259:
1.243 albertel 16260: =back
16261:
16262: =head1 PRIVATE SUBROUTINES
16263:
16264: =head2 Underlying communication routines (Shouldn't call)
16265:
16266: =over 4
16267:
16268: =item *
16269:
16270: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16271:
16272: =item *
16273:
16274: reply() : uses subreply to send a message to remote machine, logs all failures
16275:
16276: =item *
16277:
16278: critical() : passes a critical message to another server; if cannot
16279: get through then place message in connection buffer directory and
16280: returns con_delayed, if incapable of saving message, returns
16281: con_failed
16282:
16283: =item *
16284:
16285: reconlonc() : tries to reconnect lonc client processes.
16286:
16287: =back
16288:
16289: =head2 Resource Access Logging
16290:
16291: =over 4
16292:
16293: =item *
16294:
16295: flushcourselogs() : flush (save) buffer logs and access logs
16296:
16297: =item *
16298:
16299: courselog($what) : save message for course in hash
16300:
16301: =item *
16302:
16303: courseacclog($what) : save message for course using &courselog(). Perform
16304: special processing for specific resource types (problems, exams, quizzes, etc).
16305:
1.191 harris41 16306: =item *
16307:
16308: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16309: as a PerlChildExitHandler
1.243 albertel 16310:
16311: =back
16312:
16313: =head2 Other
16314:
16315: =over 4
16316:
16317: =item *
16318:
16319: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 16320:
16321: =back
16322:
16323: =cut
1.877 foxr 16324:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>