Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.98
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.98! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.97 2018/09/04 20:22:43 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1172.2.36 raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.1172.2.79 raeburn 92: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.1172.2.79 raeburn 105: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.1172.2.9 raeburn 112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 113: {
114: my $logid;
1.1172.2.9 raeburn 115: sub write_log {
116: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if ($context eq 'course') {
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.957 raeburn 122: }
1.1172.2.13 raeburn 123: $logid ++;
1.957 raeburn 124: my $now = time();
125: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 126: my $logentry = {
127: $id => {
128: 'exe_uname' => $env{'user.name'},
129: 'exe_udom' => $env{'user.domain'},
130: 'exe_time' => $now,
131: 'exe_ip' => $ENV{'REMOTE_ADDR'},
132: 'delflag' => $delflag,
133: 'logentry' => $storehash,
134: 'uname' => $uname,
135: 'udom' => $udom,
136: }
137: };
138: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 139: }
140: }
1.1 albertel 141:
1.163 harris41 142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 144: unless (-e "$execdir/logs/lonnet.log") {
1.1172.2.96 raeburn 145: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
1.1 albertel 152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
1.1172.2.96 raeburn 157: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
1.448 albertel 160: close($fh);
161: }
1.1 albertel 162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
1.1172.2.96 raeburn 170: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
1.1 albertel 174: return 1;
175: }
176:
1.850 albertel 177: sub create_connection {
1.853 albertel 178: my ($hostname,$lonid) = @_;
1.851 albertel 179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
1.890 albertel 183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
1.983 raeburn 190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
1.850 albertel 204:
1.1106 raeburn 205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
1.993 raeburn 228: sub get_server_loncaparev {
1.1073 raeburn 229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
1.1073 raeburn 244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
1.1082 raeburn 263: $ua->timeout(4);
1.1073 raeburn 264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
1.1081 raeburn 271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
1.1081 raeburn 278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 279: $loncaparev = $1;
280: }
1.993 raeburn 281: }
1.1073 raeburn 282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 283: }
284: }
285:
1.1074 raeburn 286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
1.1121 raeburn 314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 320: my ($response,$cached);
1.1121 raeburn 321: unless ($ignore_cache) {
1.1125 raeburn 322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 323: }
324: if (defined($cached)) {
1.1125 raeburn 325: $returnhash{$what} = $response;
1.1121 raeburn 326: } else {
1.1125 raeburn 327: $whatneeded{$what} = 1;
1.1121 raeburn 328: }
329: }
1.1125 raeburn 330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
1.1121 raeburn 333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
1.1121 raeburn 340: my @pairs=split(/\&/,$rep);
1.1125 raeburn 341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 347: }
348: }
349: }
350: }
1.1125 raeburn 351: return ($result,\%returnhash);
1.1121 raeburn 352: }
353:
1.1124 raeburn 354: sub remote_devalidate_cache {
1.1172.2.35 raeburn 355: my ($lonhost,$cachekeys) = @_;
356: my $items;
357: return unless (ref($cachekeys) eq 'ARRAY');
358: my $cachestr = join('&',@{$cachekeys});
359: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 360: }
361:
1.1 albertel 362: # -------------------------------------------------- Non-critical communication
363: sub subreply {
364: my ($cmd,$server)=@_;
1.838 albertel 365: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 366: #
367: # With loncnew process trimming, there's a timing hole between lonc server
368: # process exit and the master server picking up the listen on the AF_UNIX
369: # socket. In that time interval, a lock file will exist:
370:
371: my $lockfile=$peerfile.".lock";
372: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 373: sleep(0.1);
1.549 foxr 374: }
375: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 376: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 377: #
1.550 foxr 378: # We'll give the connection a few tries before abandoning it. If
379: # connection is not possible, we'll con_lost back to the client.
380: #
381: my $client;
382: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
383: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
384: Type => SOCK_STREAM,
385: Timeout => 10);
1.869 albertel 386: if ($client) {
1.550 foxr 387: last; # Connected!
1.850 albertel 388: } else {
1.853 albertel 389: &create_connection(&hostname($server),$server);
1.550 foxr 390: }
1.1172.2.79 raeburn 391: sleep(0.1); # Try again later if failed connection.
1.550 foxr 392: }
393: my $answer;
394: if ($client) {
1.704 albertel 395: print $client "sethost:$server:$cmd\n";
1.550 foxr 396: $answer=<$client>;
397: if (!$answer) { $answer="con_lost"; }
398: chomp($answer);
399: } else {
400: $answer = 'con_lost'; # Failed connection.
401: }
1.1 albertel 402: return $answer;
403: }
404:
405: sub reply {
406: my ($cmd,$server)=@_;
1.838 albertel 407: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 408: my $answer=subreply($cmd,$server);
1.65 www 409: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 410: &logthis("<font color=\"blue\">WARNING:".
1.12 www 411: " $cmd to $server returned $answer</font>");
412: }
1.1 albertel 413: return $answer;
414: }
415:
416: # ----------------------------------------------------------- Send USR1 to lonc
417:
418: sub reconlonc {
1.891 albertel 419: my ($lonid) = @_;
420: if ($lonid) {
1.1172.2.72 raeburn 421: my $hostname = &hostname($lonid);
1.891 albertel 422: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
423: if ($hostname && -e $peerfile) {
424: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
425: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
426: Type => SOCK_STREAM,
427: Timeout => 10);
428: if ($client) {
429: print $client ("reset_retries\n");
430: my $answer=<$client>;
431: #reset just this one.
432: }
433: }
434: return;
435: }
436:
1.836 www 437: &logthis("Trying to reconnect lonc");
1.1 albertel 438: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96 raeburn 439: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 440: my $loncpid=<$fh>;
441: chomp($loncpid);
442: if (kill 0 => $loncpid) {
443: &logthis("lonc at pid $loncpid responding, sending USR1");
444: kill USR1 => $loncpid;
445: sleep 1;
1.836 www 446: } else {
1.12 www 447: &logthis(
1.672 albertel 448: "<font color=\"blue\">WARNING:".
1.12 www 449: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 450: }
451: } else {
1.836 www 452: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 453: }
454: }
455:
456: # ------------------------------------------------------ Critical communication
1.12 www 457:
1.1 albertel 458: sub critical {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (&hostname($server)) {
1.672 albertel 461: &logthis("<font color=\"blue\">WARNING:".
1.89 www 462: " Critical message to unknown server ($server)</font>");
463: return 'no_such_host';
464: }
1.1 albertel 465: my $answer=reply($cmd,$server);
466: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 467: &reconlonc($server);
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
1.1172.2.96 raeburn 479: if (open($dfh,">",$dfilename)) {
1.448 albertel 480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
1.1172.2.79 raeburn 484: sleep 1;
1.1 albertel 485: my $wcmd='';
486: {
1.448 albertel 487: my $dfh;
1.1172.2.96 raeburn 488: if (open($dfh,"<",$dfilename)) {
1.448 albertel 489: $wcmd=<$dfh>;
490: close($dfh);
491: }
1.1 albertel 492: }
493: chomp($wcmd);
1.7 www 494: if ($wcmd eq $cmd) {
1.672 albertel 495: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 496: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 497: &logperm("D:$server:$cmd");
498: return 'con_delayed';
499: } else {
1.672 albertel 500: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 501: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 502: &logperm("F:$server:$cmd");
503: return 'con_failed';
504: }
505: }
506: }
507: return $answer;
1.405 albertel 508: }
509:
1.755 albertel 510: # ------------------------------------------- check if return value is an error
511:
512: sub error {
513: my ($result) = @_;
1.756 albertel 514: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 515: if ($2 == 2) { return undef; }
516: return $1;
517: }
518: return undef;
519: }
520:
1.783 albertel 521: sub convert_and_load_session_env {
522: my ($lonidsdir,$handle)=@_;
523: my @profile;
524: {
1.917 albertel 525: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
526: if (!$opened) {
1.915 albertel 527: return 0;
528: }
1.783 albertel 529: flock($idf,LOCK_SH);
530: @profile=<$idf>;
531: close($idf);
532: }
533: my %temp_env;
534: foreach my $line (@profile) {
1.786 albertel 535: if ($line !~ m/=/) {
536: return 0;
537: }
1.783 albertel 538: chomp($line);
539: my ($envname,$envvalue)=split(/=/,$line,2);
540: $temp_env{&unescape($envname)} = &unescape($envvalue);
541: }
542: unlink("$lonidsdir/$handle.id");
543: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
544: 0640)) {
545: %disk_env = %temp_env;
546: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
547: untie(%disk_env);
548: }
1.786 albertel 549: return 1;
1.783 albertel 550: }
551:
1.374 www 552: # ------------------------------------------- Transfer profile into environment
1.780 albertel 553: my $env_loaded;
554: sub transfer_profile_to_env {
1.788 albertel 555: my ($lonidsdir,$handle,$force_transfer) = @_;
556: if (!$force_transfer && $env_loaded) { return; }
1.374 www 557:
1.720 albertel 558: if (!defined($lonidsdir)) {
559: $lonidsdir = $perlvar{'lonIDsDir'};
560: }
561: if (!defined($handle)) {
562: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
563: }
564:
1.786 albertel 565: my $convert;
566: {
1.917 albertel 567: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
568: if (!$opened) {
1.915 albertel 569: return;
570: }
1.786 albertel 571: flock($idf,LOCK_SH);
572: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
573: &GDBM_READER(),0640)) {
574: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
575: untie(%disk_env);
576: } else {
577: $convert = 1;
578: }
579: }
580: if ($convert) {
581: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
582: &logthis("Failed to load session, or convert session.");
583: }
1.374 www 584: }
1.783 albertel 585:
1.786 albertel 586: my %remove;
1.783 albertel 587: while ( my $envname = each(%env) ) {
1.433 matthew 588: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
589: if ($time < time-300) {
1.783 albertel 590: $remove{$key}++;
1.433 matthew 591: }
592: }
593: }
1.783 albertel 594:
1.619 albertel 595: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 596: $env_loaded=1;
1.783 albertel 597: foreach my $expired_key (keys(%remove)) {
1.433 matthew 598: &delenv($expired_key);
1.374 www 599: }
1.1 albertel 600: }
601:
1.916 albertel 602: # ---------------------------------------------------- Check for valid session
603: sub check_for_valid_session {
1.1172.2.96 raeburn 604: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 605: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 606: if ($name eq '') {
607: $name = 'lonID';
608: }
609: my $lonid=$cookies{$name};
1.916 albertel 610: return undef if (!$lonid);
611:
612: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 613: my $lonidsdir;
614: if ($name eq 'lonDAV') {
615: $lonidsdir=$r->dir_config('lonDAVsessDir');
616: } else {
617: $lonidsdir=$r->dir_config('lonIDsDir');
618: }
1.1172.2.96 raeburn 619: if (!-e "$lonidsdir/$handle.id") {
620: if ((ref($domref)) && ($name eq 'lonID') &&
621: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
622: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
623: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
624: $$domref = $possudom;
625: }
626: }
627: return undef;
628: }
1.916 albertel 629:
1.917 albertel 630: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
631: return undef if (!$opened);
1.916 albertel 632:
633: flock($idf,LOCK_SH);
634: my %disk_env;
635: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
636: &GDBM_READER(),0640)) {
637: return undef;
638: }
639:
640: if (!defined($disk_env{'user.name'})
641: || !defined($disk_env{'user.domain'})) {
642: return undef;
643: }
1.1172.2.18 raeburn 644:
1.1172.2.36 raeburn 645: if (ref($userhashref) eq 'HASH') {
646: $userhashref->{'name'} = $disk_env{'user.name'};
647: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 648: }
649:
1.916 albertel 650: return $handle;
651: }
652:
1.830 albertel 653: sub timed_flock {
654: my ($file,$lock_type) = @_;
655: my $failed=0;
656: eval {
657: local $SIG{__DIE__}='DEFAULT';
658: local $SIG{ALRM}=sub {
659: $failed=1;
660: die("failed lock");
661: };
662: alarm(13);
663: flock($file,$lock_type);
664: alarm(0);
665: };
666: if ($failed) {
667: return undef;
668: } else {
669: return 1;
670: }
671: }
672:
1.5 www 673: # ---------------------------------------------------------- Append Environment
674:
675: sub appenv {
1.949 raeburn 676: my ($newenv,$roles) = @_;
677: if (ref($newenv) eq 'HASH') {
678: foreach my $key (keys(%{$newenv})) {
679: my $refused = 0;
680: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
681: $refused = 1;
682: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 683: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 684: if (grep(/^\Q$role\E$/,@{$roles})) {
685: $refused = 0;
686: }
687: }
688: }
689: if ($refused) {
690: &logthis("<font color=\"blue\">WARNING: ".
691: "Attempt to modify environment ".$key." to ".$newenv->{$key}
692: .'</font>');
693: delete($newenv->{$key});
694: } else {
695: $env{$key}=$newenv->{$key};
696: }
697: }
1.1172.2.96 raeburn 698: my $lonids = $perlvar{'lonIDsDir'};
699: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
700: my $opened = open(my $env_file,'+<',$env{'user.environment'});
701: if ($opened
702: && &timed_flock($env_file,LOCK_EX)
703: &&
704: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
705: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
706: while (my ($key,$value) = each(%{$newenv})) {
707: $disk_env{$key} = $value;
708: }
709: untie(%disk_env);
710: }
1.35 www 711: }
1.191 harris41 712: }
1.56 www 713: return 'ok';
714: }
715: # ----------------------------------------------------- Delete from Environment
716:
717: sub delenv {
1.1104 raeburn 718: my ($delthis,$regexp,$roles) = @_;
719: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
720: my $refused = 1;
721: if (ref($roles) eq 'ARRAY') {
722: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
723: if (grep(/^\Q$role\E$/,@{$roles})) {
724: $refused = 0;
725: }
726: }
727: if ($refused) {
728: &logthis("<font color=\"blue\">WARNING: ".
729: "Attempt to delete from environment ".$delthis);
730: return 'error';
731: }
1.56 www 732: }
1.917 albertel 733: my $opened = open(my $env_file,'+<',$env{'user.environment'});
734: if ($opened
1.915 albertel 735: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 736: &&
737: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
738: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 739: foreach my $key (keys(%disk_env)) {
1.987 raeburn 740: if ($regexp) {
741: if ($key=~/^$delthis/) {
742: delete($env{$key});
743: delete($disk_env{$key});
744: }
745: } else {
746: if ($key=~/^\Q$delthis\E/) {
747: delete($env{$key});
748: delete($disk_env{$key});
749: }
750: }
1.448 albertel 751: }
1.783 albertel 752: untie(%disk_env);
1.5 www 753: }
754: return 'ok';
1.369 albertel 755: }
756:
1.790 albertel 757: sub get_env_multiple {
758: my ($name) = @_;
759: my @values;
760: if (defined($env{$name})) {
761: # exists is it an array
762: if (ref($env{$name})) {
763: @values=@{ $env{$name} };
764: } else {
765: $values[0]=$env{$name};
766: }
767: }
768: return(@values);
769: }
770:
1.958 www 771: # ------------------------------------------------------------------- Locking
772:
773: sub set_lock {
774: my ($text)=@_;
775: $locknum++;
776: my $id=$$.'-'.$locknum;
777: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
778: 'session.lock.'.$id => $text});
779: return $id;
780: }
781:
782: sub get_locks {
783: my $num=0;
784: my %texts=();
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if ($lock=~/\w/) {
787: $num++;
788: $texts{$lock}=$env{'session.lock.'.$lock};
789: }
790: }
791: return ($num,%texts);
792: }
793:
794: sub remove_lock {
795: my ($id)=@_;
796: my $newlocks='';
797: foreach my $lock (split(/\,/,$env{'session.locks'})) {
798: if (($lock=~/\w/) && ($lock ne $id)) {
799: $newlocks.=','.$lock;
800: }
801: }
802: &appenv({'session.locks' => $newlocks});
803: &delenv('session.lock.'.$id);
804: }
805:
806: sub remove_all_locks {
807: my $activelocks=$env{'session.locks'};
808: foreach my $lock (split(/\,/,$env{'session.locks'})) {
809: if ($lock=~/\w/) {
810: &remove_lock($lock);
811: }
812: }
813: }
814:
815:
1.369 albertel 816: # ------------------------------------------ Find out current server userload
817: sub userload {
818: my $numusers=0;
819: {
820: opendir(LONIDS,$perlvar{'lonIDsDir'});
821: my $filename;
822: my $curtime=time;
823: while ($filename=readdir(LONIDS)) {
1.925 albertel 824: next if ($filename eq '.' || $filename eq '..');
825: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 826: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 827: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 828: }
829: closedir(LONIDS);
830: }
831: my $userloadpercent=0;
832: my $maxuserload=$perlvar{'lonUserLoadLim'};
833: if ($maxuserload) {
1.371 albertel 834: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 835: }
1.372 albertel 836: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 837: return $userloadpercent;
1.283 www 838: }
839:
1.1 albertel 840: # ------------------------------ Find server with least workload from spare.tab
1.11 www 841:
1.1 albertel 842: sub spareserver {
1.1083 raeburn 843: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 844: my $spare_server;
1.370 albertel 845: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 846: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
847: : $userloadpercent;
1.1083 raeburn 848: my ($uint_dom,$remotesessions);
849: if (($udom ne '') && (&domain($udom) ne '')) {
850: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
851: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
852: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
853: $remotesessions = $udomdefaults{'remotesessions'};
854: }
1.1123 raeburn 855: my $spareshash = &this_host_spares($udom);
856: if (ref($spareshash) eq 'HASH') {
857: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
858: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 859: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
860: $try_server));
1.1123 raeburn 861: ($spare_server, $lowest_load) =
862: &compare_server_load($try_server, $spare_server, $lowest_load);
863: }
1.1083 raeburn 864: }
1.784 albertel 865:
1.1123 raeburn 866: my $found_server = ($spare_server ne '' && $lowest_load < 100);
867:
868: if (!$found_server) {
869: if (ref($spareshash->{'default'}) eq 'ARRAY') {
870: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 871: next unless (&spare_can_host($udom,$uint_dom,
872: $remotesessions,$try_server));
1.1123 raeburn 873: ($spare_server, $lowest_load) =
874: &compare_server_load($try_server, $spare_server, $lowest_load);
875: }
876: }
877: }
1.784 albertel 878: }
879:
880: if (!$want_server_name) {
1.968 raeburn 881: my $protocol = 'http';
882: if ($protocol{$spare_server} eq 'https') {
883: $protocol = $protocol{$spare_server};
884: }
1.1001 raeburn 885: if (defined($spare_server)) {
886: my $hostname = &hostname($spare_server);
1.1083 raeburn 887: if (defined($hostname)) {
1.1001 raeburn 888: $spare_server = $protocol.'://'.$hostname;
889: }
890: }
1.784 albertel 891: }
892: return $spare_server;
893: }
894:
895: sub compare_server_load {
1.1172.2.41 raeburn 896: my ($try_server, $spare_server, $lowest_load, $required) = @_;
897:
898: if ($required) {
899: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
900: my $remoterev = &get_server_loncaparev(undef,$try_server);
901: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
902: if (($major eq '' && $minor eq '') ||
903: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
904: return ($spare_server,$lowest_load);
905: }
906: }
1.784 albertel 907:
908: my $loadans = &reply('load', $try_server);
909: my $userloadans = &reply('userload',$try_server);
910:
911: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 912: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 913: }
914:
915: my $load;
916: if ($loadans =~ /\d/) {
917: if ($userloadans =~ /\d/) {
918: #both are numbers, pick the bigger one
919: $load = ($loadans > $userloadans) ? $loadans
920: : $userloadans;
1.411 albertel 921: } else {
1.784 albertel 922: $load = $loadans;
1.411 albertel 923: }
1.784 albertel 924: } else {
925: $load = $userloadans;
926: }
927:
928: if (($load =~ /\d/) && ($load < $lowest_load)) {
929: $spare_server = $try_server;
930: $lowest_load = $load;
1.370 albertel 931: }
1.784 albertel 932: return ($spare_server,$lowest_load);
1.202 matthew 933: }
1.914 albertel 934:
935: # --------------------------- ask offload servers if user already has a session
936: sub find_existing_session {
937: my ($udom,$uname) = @_;
1.1123 raeburn 938: my $spareshash = &this_host_spares($udom);
939: if (ref($spareshash) eq 'HASH') {
940: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
941: foreach my $try_server (@{ $spareshash->{'primary'} }) {
942: return $try_server if (&has_user_session($try_server, $udom, $uname));
943: }
944: }
945: if (ref($spareshash->{'default'}) eq 'ARRAY') {
946: foreach my $try_server (@{ $spareshash->{'default'} }) {
947: return $try_server if (&has_user_session($try_server, $udom, $uname));
948: }
949: }
1.914 albertel 950: }
951: return;
952: }
953:
954: # -------------------------------- ask if server already has a session for user
955: sub has_user_session {
956: my ($lonid,$udom,$uname) = @_;
957: my $result = &reply(join(':','userhassession',
958: map {&escape($_)} ($udom,$uname)),$lonid);
959: return 1 if ($result eq 'ok');
960:
961: return 0;
962: }
963:
1.1076 raeburn 964: # --------- determine least loaded server in a user's domain which allows login
965:
966: sub choose_server {
1.1172.2.47 raeburn 967: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 968: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 969: my %servers = &get_servers($udom);
1.1076 raeburn 970: my $lowest_load = 30000;
1.1172.2.47 raeburn 971: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
972: if ($skiploadbal) {
973: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
974: unless (defined($cached)) {
975: my $cachetime = 60*60*24;
976: my %domconfig =
977: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
978: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
979: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
980: $cachetime);
981: }
982: }
983: }
1.1076 raeburn 984: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 985: my $loginvia;
1.1172.2.47 raeburn 986: if ($skiploadbal) {
987: if (ref($balancers) eq 'HASH') {
988: next if (exists($balancers->{$lonhost}));
989: }
990: }
1.1115 raeburn 991: if ($checkloginvia) {
992: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 993: if ($loginvia) {
994: my ($server,$path) = split(/:/,$loginvia);
995: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 996: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 997: if ($login_host eq $server) {
998: $portal_path = $path;
1.1151 raeburn 999: $isredirect = 1;
1.1116 raeburn 1000: }
1001: } else {
1002: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1003: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1004: if ($login_host eq $lonhost) {
1005: $portal_path = '';
1.1151 raeburn 1006: $isredirect = '';
1.1116 raeburn 1007: }
1008: }
1009: } else {
1.1076 raeburn 1010: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1011: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1012: }
1013: }
1014: if ($login_host ne '') {
1.1116 raeburn 1015: $hostname = &hostname($login_host);
1.1076 raeburn 1016: }
1.1172.2.88 raeburn 1017: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1018: }
1019:
1.202 matthew 1020: # --------------------------------------------- Try to change a user's password
1021:
1022: sub changepass {
1.799 raeburn 1023: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1024: $currentpass = &escape($currentpass);
1025: $newpass = &escape($newpass);
1.1030 raeburn 1026: my $lonhost = $perlvar{'lonHostID'};
1027: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1028: $server);
1029: if (! $answer) {
1030: &logthis("No reply on password change request to $server ".
1031: "by $uname in domain $udom.");
1032: } elsif ($answer =~ "^ok") {
1033: &logthis("$uname in $udom successfully changed their password ".
1034: "on $server.");
1035: } elsif ($answer =~ "^pwchange_failure") {
1036: &logthis("$uname in $udom was unable to change their password ".
1037: "on $server. The action was blocked by either lcpasswd ".
1038: "or pwchange");
1039: } elsif ($answer =~ "^non_authorized") {
1040: &logthis("$uname in $udom did not get their password correct when ".
1041: "attempting to change it on $server.");
1042: } elsif ($answer =~ "^auth_mode_error") {
1043: &logthis("$uname in $udom attempted to change their password despite ".
1044: "not being locally or internally authenticated on $server.");
1045: } elsif ($answer =~ "^unknown_user") {
1046: &logthis("$uname in $udom attempted to change their password ".
1047: "on $server but were unable to because $server is not ".
1048: "their home server.");
1049: } elsif ($answer =~ "^refused") {
1050: &logthis("$server refused to change $uname in $udom password because ".
1051: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1052: } elsif ($answer =~ "invalid_client") {
1053: &logthis("$server refused to change $uname in $udom password because ".
1054: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1055: }
1056: return $answer;
1.1 albertel 1057: }
1058:
1.169 harris41 1059: # ----------------------- Try to determine user's current authentication scheme
1060:
1061: sub queryauthenticate {
1062: my ($uname,$udom)=@_;
1.456 albertel 1063: my $uhome=&homeserver($uname,$udom);
1064: if (!$uhome) {
1065: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1066: return 'no_host';
1067: }
1068: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1069: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1070: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1071: }
1.456 albertel 1072: return $answer;
1.169 harris41 1073: }
1074:
1.1 albertel 1075: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1076:
1.1 albertel 1077: sub authenticate {
1.1073 raeburn 1078: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1079: $upass=&escape($upass);
1080: $uname= &LONCAPA::clean_username($uname);
1.836 www 1081: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1082: my $newhome;
1.836 www 1083: if ((!$uhome) || ($uhome eq 'no_host')) {
1084: # Maybe the machine was offline and only re-appeared again recently?
1085: &reconlonc();
1086: # One more
1.952 raeburn 1087: $uhome=&homeserver($uname,$udom,1);
1088: if (($uhome eq 'no_host') && $checkdefauth) {
1089: if (defined(&domain($udom,'primary'))) {
1090: $newhome=&domain($udom,'primary');
1091: }
1092: if ($newhome ne '') {
1093: $uhome = $newhome;
1094: }
1095: }
1.836 www 1096: if ((!$uhome) || ($uhome eq 'no_host')) {
1097: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1098: return 'no_host';
1099: }
1.1 albertel 1100: }
1.1073 raeburn 1101: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1102: if ($answer eq 'authorized') {
1.952 raeburn 1103: if ($newhome) {
1104: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1105: return 'no_account_on_host';
1106: } else {
1107: &logthis("User $uname at $udom authorized by $uhome");
1108: return $uhome;
1109: }
1.471 albertel 1110: }
1111: if ($answer eq 'non_authorized') {
1112: &logthis("User $uname at $udom rejected by $uhome");
1113: return 'no_host';
1.9 www 1114: }
1.471 albertel 1115: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1116: return 'no_host';
1117: }
1118:
1.1073 raeburn 1119: sub can_host_session {
1.1074 raeburn 1120: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1121: my $canhost = 1;
1.1074 raeburn 1122: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1123: if (ref($remotesessions) eq 'HASH') {
1124: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1125: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1126: $canhost = 0;
1127: } else {
1128: $canhost = 1;
1129: }
1130: }
1131: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1132: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1133: $canhost = 1;
1134: } else {
1135: $canhost = 0;
1136: }
1137: }
1138: if ($canhost) {
1139: if ($remotesessions->{'version'} ne '') {
1140: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1141: if ($reqmajor ne '' && $reqminor ne '') {
1142: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1143: my $major = $1;
1144: my $minor = $2;
1145: if (($major < $reqmajor ) ||
1146: (($major == $reqmajor) && ($minor < $reqminor))) {
1147: $canhost = 0;
1148: }
1149: } else {
1150: $canhost = 0;
1151: }
1152: }
1153: }
1154: }
1155: }
1156: if ($canhost) {
1157: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1158: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1159: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1160: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1161: if (($uint_dom ne '') &&
1162: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1163: $canhost = 0;
1164: } else {
1165: $canhost = 1;
1166: }
1167: }
1168: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1169: if (($uint_dom ne '') &&
1170: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1171: $canhost = 1;
1172: } else {
1173: $canhost = 0;
1174: }
1175: }
1176: }
1177: }
1178: return $canhost;
1179: }
1180:
1.1083 raeburn 1181: sub spare_can_host {
1182: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1183: my $canhost=1;
1.1172.2.62 raeburn 1184: my $try_server_hostname = &hostname($try_server);
1185: my $serverhomeID = &get_server_homeID($try_server_hostname);
1186: my $serverhomedom = &host_domain($serverhomeID);
1187: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1188: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1189: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1190: $canhost = 0;
1191: }
1192: }
1193: if (($canhost) && ($uint_dom)) {
1194: my @intdoms;
1195: my $internet_names = &get_internet_names($try_server);
1196: if (ref($internet_names) eq 'ARRAY') {
1197: @intdoms = @{$internet_names};
1198: }
1199: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1200: my $remoterev = &get_server_loncaparev(undef,$try_server);
1201: $canhost = &can_host_session($udom,$try_server,$remoterev,
1202: $remotesessions,
1203: $defdomdefaults{'hostedsessions'});
1204: }
1.1083 raeburn 1205: }
1206: return $canhost;
1207: }
1208:
1.1123 raeburn 1209: sub this_host_spares {
1210: my ($dom) = @_;
1.1126 raeburn 1211: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1212: my @hosts = ¤t_machine_ids();
1213: foreach my $lonhost (@hosts) {
1214: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1215: $dom_in_use = $dom;
1216: $lonhost_in_use = $lonhost;
1.1123 raeburn 1217: last;
1218: }
1219: }
1.1126 raeburn 1220: if ($dom_in_use ne '') {
1221: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1222: }
1223: if (ref($result) ne 'HASH') {
1224: $lonhost_in_use = $perlvar{'lonHostID'};
1225: $dom_in_use = &host_domain($lonhost_in_use);
1226: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1227: if (ref($result) ne 'HASH') {
1228: $result = \%spareid;
1229: }
1230: }
1231: return $result;
1232: }
1233:
1234: sub spares_for_offload {
1235: my ($dom_in_use,$lonhost_in_use) = @_;
1236: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1237: if (defined($cached)) {
1238: return $result;
1239: } else {
1.1126 raeburn 1240: my $cachetime = 60*60*24;
1241: my %domconfig =
1242: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1243: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1244: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1245: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1246: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1247: }
1248: }
1249: }
1250: }
1.1126 raeburn 1251: return;
1.1123 raeburn 1252: }
1253:
1.1129 raeburn 1254: sub get_lonbalancer_config {
1255: my ($servers) = @_;
1256: my ($currbalancer,$currtargets);
1257: if (ref($servers) eq 'HASH') {
1258: foreach my $server (keys(%{$servers})) {
1259: my %what = (
1260: spareid => 1,
1261: perlvar => 1,
1262: );
1263: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1264: if ($result eq 'ok') {
1265: if (ref($returnhash) eq 'HASH') {
1266: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1267: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1268: $currbalancer = $server;
1269: $currtargets = {};
1270: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1271: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1272: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1273: }
1274: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1275: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1276: }
1277: }
1278: last;
1279: }
1280: }
1281: }
1282: }
1283: }
1284: }
1285: return ($currbalancer,$currtargets);
1286: }
1287:
1288: sub check_loadbalancing {
1.1172.2.88 raeburn 1289: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1290: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1291: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1292: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1293: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1294: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1295: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1296: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1297: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1298: my $domneedscache;
1.1129 raeburn 1299: my $cachetime = 60*60*24;
1300:
1301: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1302: $dom_in_use = $udom;
1303: $homeintdom = 1;
1304: } else {
1305: $dom_in_use = $serverhomedom;
1306: }
1307: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1308: unless (defined($cached)) {
1309: my %domconfig =
1310: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1311: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1312: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1313: } else {
1314: $domneedscache = $dom_in_use;
1.1129 raeburn 1315: }
1316: }
1317: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1318: ($is_balancer,$currtargets,$currrules) =
1319: &check_balancer_result($result,@hosts);
1.1129 raeburn 1320: if ($is_balancer) {
1321: if (ref($currrules) eq 'HASH') {
1322: if ($homeintdom) {
1323: if ($uname ne '') {
1324: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1325: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1326: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1327: $rule_in_effect = $currrules->{'_LC_author'};
1328: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1329: $rule_in_effect = $currrules->{'_LC_adv'}
1330: }
1331: }
1332: if ($rule_in_effect eq '') {
1333: my %userenv = &userenvironment($udom,$uname,'inststatus');
1334: if ($userenv{'inststatus'} ne '') {
1335: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1336: my ($othertitle,$usertypes,$types) =
1337: &Apache::loncommon::sorted_inst_types($udom);
1338: if (ref($types) eq 'ARRAY') {
1339: foreach my $type (@{$types}) {
1340: if (grep(/^\Q$type\E$/,@statuses)) {
1341: if (exists($currrules->{$type})) {
1342: $rule_in_effect = $currrules->{$type};
1343: }
1344: }
1345: }
1346: }
1347: } else {
1348: if (exists($currrules->{'default'})) {
1349: $rule_in_effect = $currrules->{'default'};
1350: }
1351: }
1352: }
1353: } else {
1354: if (exists($currrules->{'default'})) {
1355: $rule_in_effect = $currrules->{'default'};
1356: }
1357: }
1358: } else {
1359: if ($currrules->{'_LC_external'} ne '') {
1360: $rule_in_effect = $currrules->{'_LC_external'};
1361: }
1362: }
1363: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1364: $uname,$udom);
1365: }
1366: }
1367: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1368: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1369: unless (defined($cached)) {
1370: my %domconfig =
1371: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1372: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1373: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1374: } else {
1375: $domneedscache = $serverhomedom;
1.1129 raeburn 1376: }
1377: }
1378: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1379: ($is_balancer,$currtargets,$currrules) =
1380: &check_balancer_result($result,@hosts);
1381: if ($is_balancer) {
1.1129 raeburn 1382: if (ref($currrules) eq 'HASH') {
1383: if ($currrules->{'_LC_internetdom'} ne '') {
1384: $rule_in_effect = $currrules->{'_LC_internetdom'};
1385: }
1386: }
1387: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1388: $uname,$udom);
1389: }
1390: } else {
1391: if ($perlvar{'lonBalancer'} eq 'yes') {
1392: $is_balancer = 1;
1393: $offloadto = &this_host_spares($dom_in_use);
1394: }
1.1172.2.75 raeburn 1395: unless (defined($cached)) {
1396: $domneedscache = $serverhomedom;
1397: }
1.1129 raeburn 1398: }
1399: } else {
1400: if ($perlvar{'lonBalancer'} eq 'yes') {
1401: $is_balancer = 1;
1402: $offloadto = &this_host_spares($dom_in_use);
1403: }
1.1172.2.75 raeburn 1404: unless (defined($cached)) {
1405: $domneedscache = $serverhomedom;
1406: }
1407: }
1408: if ($domneedscache) {
1409: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1410: }
1.1172.2.5 raeburn 1411: if ($is_balancer) {
1412: my $lowest_load = 30000;
1413: if (ref($offloadto) eq 'HASH') {
1414: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1415: foreach my $try_server (@{$offloadto->{'primary'}}) {
1416: ($otherserver,$lowest_load) =
1417: &compare_server_load($try_server,$otherserver,$lowest_load);
1418: }
1.1129 raeburn 1419: }
1.1172.2.5 raeburn 1420: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1421:
1.1172.2.5 raeburn 1422: if (!$found_server) {
1423: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1424: foreach my $try_server (@{$offloadto->{'default'}}) {
1425: ($otherserver,$lowest_load) =
1426: &compare_server_load($try_server,$otherserver,$lowest_load);
1427: }
1428: }
1429: }
1430: } elsif (ref($offloadto) eq 'ARRAY') {
1431: if (@{$offloadto} == 1) {
1432: $otherserver = $offloadto->[0];
1433: } elsif (@{$offloadto} > 1) {
1434: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1435: ($otherserver,$lowest_load) =
1436: &compare_server_load($try_server,$otherserver,$lowest_load);
1437: }
1438: }
1439: }
1.1172.2.88 raeburn 1440: unless ($caller eq 'login') {
1441: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1442: $is_balancer = 0;
1443: if ($uname ne '' && $udom ne '') {
1444: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1172.2.5 raeburn 1445:
1.1172.2.88 raeburn 1446: &appenv({'user.loadbalexempt' => $lonhost,
1447: 'user.loadbalcheck.time' => time});
1448: }
1.1172.2.5 raeburn 1449: }
1.1129 raeburn 1450: }
1451: }
1452: }
1453: return ($is_balancer,$otherserver);
1454: }
1455:
1.1172.2.12 raeburn 1456: sub check_balancer_result {
1457: my ($result,@hosts) = @_;
1458: my ($is_balancer,$currtargets,$currrules);
1459: if (ref($result) eq 'HASH') {
1460: if ($result->{'lonhost'} ne '') {
1461: my $currbalancer = $result->{'lonhost'};
1462: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1463: $is_balancer = 1;
1464: $currtargets = $result->{'targets'};
1465: $currrules = $result->{'rules'};
1466: }
1467: } else {
1468: foreach my $key (keys(%{$result})) {
1469: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1470: (ref($result->{$key}) eq 'HASH')) {
1471: $is_balancer = 1;
1472: $currrules = $result->{$key}{'rules'};
1473: $currtargets = $result->{$key}{'targets'};
1474: last;
1475: }
1476: }
1477: }
1478: }
1479: return ($is_balancer,$currtargets,$currrules);
1480: }
1481:
1.1129 raeburn 1482: sub get_loadbalancer_targets {
1483: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1484: my $offloadto;
1.1172.2.4 raeburn 1485: if ($rule_in_effect eq 'none') {
1486: return [$perlvar{'lonHostID'}];
1487: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1488: $offloadto = $currtargets;
1489: } else {
1490: if ($rule_in_effect eq 'homeserver') {
1491: my $homeserver = &homeserver($uname,$udom);
1492: if ($homeserver ne 'no_host') {
1493: $offloadto = [$homeserver];
1494: }
1495: } elsif ($rule_in_effect eq 'externalbalancer') {
1496: my %domconfig =
1497: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1498: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1499: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1500: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1501: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1502: }
1503: }
1504: } else {
1.1172.2.7 raeburn 1505: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1506: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1507: if (&hostname($remotebalancer) ne '') {
1508: $offloadto = [$remotebalancer];
1509: }
1510: }
1511: } elsif (&hostname($rule_in_effect) ne '') {
1512: $offloadto = [$rule_in_effect];
1513: }
1514: }
1515: return $offloadto;
1516: }
1517:
1.1127 raeburn 1518: sub internet_dom_servers {
1519: my ($dom) = @_;
1520: my (%uniqservers,%servers);
1521: my $primaryserver = &hostname(&domain($dom,'primary'));
1522: my @machinedoms = &machine_domains($primaryserver);
1523: foreach my $mdom (@machinedoms) {
1524: my %currservers = %servers;
1525: my %server = &get_servers($mdom);
1526: %servers = (%currservers,%server);
1527: }
1528: my %by_hostname;
1529: foreach my $id (keys(%servers)) {
1530: push(@{$by_hostname{$servers{$id}}},$id);
1531: }
1532: foreach my $hostname (sort(keys(%by_hostname))) {
1533: if (@{$by_hostname{$hostname}} > 1) {
1534: my $match = 0;
1535: foreach my $id (@{$by_hostname{$hostname}}) {
1536: if (&host_domain($id) eq $dom) {
1537: $uniqservers{$id} = $hostname;
1538: $match = 1;
1539: }
1540: }
1541: unless ($match) {
1542: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1543: }
1544: } else {
1545: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1546: }
1547: }
1548: return %uniqservers;
1549: }
1550:
1.1 albertel 1551: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1552:
1.599 albertel 1553: my %homecache;
1.1 albertel 1554: sub homeserver {
1.230 stredwic 1555: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1556: my $index="$uname:$udom";
1.426 albertel 1557:
1.599 albertel 1558: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1559:
1560: my %servers = &get_servers($udom,'library');
1561: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1562: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1563: exists($badServerCache{$tryserver}));
1.841 albertel 1564:
1565: my $answer=reply("home:$udom:$uname",$tryserver);
1566: if ($answer eq 'found') {
1567: delete($badServerCache{$tryserver});
1568: return $homecache{$index}=$tryserver;
1569: } elsif ($answer eq 'no_host') {
1570: $badServerCache{$tryserver}=1;
1571: }
1.1 albertel 1572: }
1573: return 'no_host';
1.70 www 1574: }
1575:
1576: # ------------------------------------- Find the usernames behind a list of IDs
1577:
1578: sub idget {
1579: my ($udom,@ids)=@_;
1580: my %returnhash=();
1581:
1.841 albertel 1582: my %servers = &get_servers($udom,'library');
1583: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1584: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1585: $idlist=~tr/A-Z/a-z/;
1586: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1587: my @answer=();
1588: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1589: @answer=split(/\&/,$reply);
1590: } ;
1591: my $i;
1592: for ($i=0;$i<=$#ids;$i++) {
1593: if ($answer[$i]) {
1.1172.2.73 raeburn 1594: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1595: }
1596: }
1597: }
1.70 www 1598: return %returnhash;
1599: }
1600:
1601: # ------------------------------------- Find the IDs behind a list of usernames
1602:
1603: sub idrget {
1604: my ($udom,@unames)=@_;
1605: my %returnhash=();
1.800 albertel 1606: foreach my $uname (@unames) {
1607: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1608: }
1.70 www 1609: return %returnhash;
1610: }
1611:
1612: # ------------------------------- Store away a list of names and associated IDs
1613:
1614: sub idput {
1615: my ($udom,%ids)=@_;
1616: my %servers=();
1.800 albertel 1617: foreach my $uname (keys(%ids)) {
1618: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1619: my $uhom=&homeserver($uname,$udom);
1.70 www 1620: if ($uhom ne 'no_host') {
1.800 albertel 1621: my $id=&escape($ids{$uname});
1.70 www 1622: $id=~tr/A-Z/a-z/;
1.800 albertel 1623: my $esc_unam=&escape($uname);
1.70 www 1624: if ($servers{$uhom}) {
1.800 albertel 1625: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1626: } else {
1.800 albertel 1627: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1628: }
1629: }
1.191 harris41 1630: }
1.800 albertel 1631: foreach my $server (keys(%servers)) {
1632: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1633: }
1.344 www 1634: }
1635:
1.1172.2.30 raeburn 1636: # ---------------------------------------- Delete unwanted IDs from ids.db file
1637:
1638: sub iddel {
1639: my ($udom,$idshashref,$uhome)=@_;
1640: my %result=();
1641: unless (ref($idshashref) eq 'HASH') {
1642: return %result;
1643: }
1644: my %servers=();
1645: while (my ($id,$uname) = each(%{$idshashref})) {
1646: my $uhom;
1647: if ($uhome) {
1648: $uhom = $uhome;
1649: } else {
1650: $uhom=&homeserver($uname,$udom);
1651: }
1652: if ($uhom ne 'no_host') {
1653: if ($servers{$uhom}) {
1654: $servers{$uhom}.='&'.&escape($id);
1655: } else {
1656: $servers{$uhom}=&escape($id);
1657: }
1658: }
1659: }
1660: foreach my $server (keys(%servers)) {
1661: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1662: }
1663: return %result;
1664: }
1665:
1.1023 raeburn 1666: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1667: sub dump_dom {
1.1165 droeschl 1668: my ($namespace, $udom, $regexp) = @_;
1669:
1670: $udom ||= $env{'user.domain'};
1671:
1672: return () unless $udom;
1673:
1674: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1675: }
1676:
1.1023 raeburn 1677: # ------------------------------------------ get items from domain db files
1.806 raeburn 1678:
1679: sub get_dom {
1.860 raeburn 1680: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1681: return if ($udom eq 'public');
1.806 raeburn 1682: my $items='';
1683: foreach my $item (@$storearr) {
1684: $items.=&escape($item).'&';
1685: }
1686: $items=~s/\&$//;
1.860 raeburn 1687: if (!$udom) {
1688: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1689: return if ($udom eq 'public');
1.860 raeburn 1690: if (defined(&domain($udom,'primary'))) {
1691: $uhome=&domain($udom,'primary');
1692: } else {
1.874 albertel 1693: undef($uhome);
1.860 raeburn 1694: }
1695: } else {
1696: if (!$uhome) {
1697: if (defined(&domain($udom,'primary'))) {
1698: $uhome=&domain($udom,'primary');
1699: }
1700: }
1701: }
1702: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1703: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1704: my %returnhash;
1.875 albertel 1705: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1706: return %returnhash;
1707: }
1.806 raeburn 1708: my @pairs=split(/\&/,$rep);
1709: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1710: return @pairs;
1711: }
1712: my $i=0;
1713: foreach my $item (@$storearr) {
1714: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1715: $i++;
1716: }
1717: return %returnhash;
1718: } else {
1.880 banghart 1719: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1720: }
1721: }
1722:
1723: # -------------------------------------------- put items in domain db files
1724:
1725: sub put_dom {
1.860 raeburn 1726: my ($namespace,$storehash,$udom,$uhome)=@_;
1727: if (!$udom) {
1728: $udom=$env{'user.domain'};
1729: if (defined(&domain($udom,'primary'))) {
1730: $uhome=&domain($udom,'primary');
1731: } else {
1.874 albertel 1732: undef($uhome);
1.860 raeburn 1733: }
1734: } else {
1735: if (!$uhome) {
1736: if (defined(&domain($udom,'primary'))) {
1737: $uhome=&domain($udom,'primary');
1738: }
1739: }
1740: }
1741: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1742: my $items='';
1743: foreach my $item (keys(%$storehash)) {
1744: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1745: }
1746: $items=~s/\&$//;
1747: return &reply("putdom:$udom:$namespace:$items",$uhome);
1748: } else {
1.860 raeburn 1749: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1750: }
1751: }
1752:
1.1023 raeburn 1753: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1754: sub newput_dom {
1.1023 raeburn 1755: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1756: my $result;
1757: if (!$udom) {
1758: $udom=$env{'user.domain'};
1759: }
1.1023 raeburn 1760: if ($udom) {
1761: my $uname = &get_domainconfiguser($udom);
1762: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1763: }
1764: return $result;
1765: }
1766:
1.1023 raeburn 1767: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1768: sub del_dom {
1.1023 raeburn 1769: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1770: if (ref($storearr) eq 'ARRAY') {
1771: if (!$udom) {
1772: $udom=$env{'user.domain'};
1773: }
1.1023 raeburn 1774: if ($udom) {
1775: my $uname = &get_domainconfiguser($udom);
1776: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1777: }
1778: }
1779: }
1780:
1.1023 raeburn 1781: # ----------------------------------construct domainconfig user for a domain
1782: sub get_domainconfiguser {
1783: my ($udom) = @_;
1784: return $udom.'-domainconfig';
1785: }
1786:
1.837 raeburn 1787: sub retrieve_inst_usertypes {
1788: my ($udom) = @_;
1789: my (%returnhash,@order);
1.989 raeburn 1790: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1791: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1792: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1793: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1794: } else {
1795: if (defined(&domain($udom,'primary'))) {
1796: my $uhome=&domain($udom,'primary');
1797: my $rep=&reply("inst_usertypes:$udom",$uhome);
1798: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1799: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1800: return (\%returnhash,\@order);
1801: }
1802: my ($hashitems,$orderitems) = split(/:/,$rep);
1803: my @pairs=split(/\&/,$hashitems);
1804: foreach my $item (@pairs) {
1805: my ($key,$value)=split(/=/,$item,2);
1806: $key = &unescape($key);
1807: next if ($key =~ /^error: 2 /);
1808: $returnhash{$key}=&thaw_unescape($value);
1809: }
1810: my @esc_order = split(/\&/,$orderitems);
1811: foreach my $item (@esc_order) {
1812: push(@order,&unescape($item));
1813: }
1814: } else {
1.1172.2.44 raeburn 1815: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1816: }
1.1172.2.44 raeburn 1817: return (\%returnhash,\@order);
1.837 raeburn 1818: }
1819: }
1820:
1.868 raeburn 1821: sub is_domainimage {
1822: my ($url) = @_;
1.1172.2.74 raeburn 1823: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1824: if (&domain($1) ne '') {
1825: return '1';
1826: }
1827: }
1828: return;
1829: }
1830:
1.899 raeburn 1831: sub inst_directory_query {
1832: my ($srch) = @_;
1833: my $udom = $srch->{'srchdomain'};
1834: my %results;
1835: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1836: my $outcome;
1.899 raeburn 1837: if ($homeserver ne '') {
1.904 albertel 1838: my $queryid=&reply("querysend:instdirsearch:".
1839: &escape($srch->{'srchby'}).':'.
1840: &escape($srch->{'srchterm'}).':'.
1841: &escape($srch->{'srchtype'}),$homeserver);
1842: my $host=&hostname($homeserver);
1843: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96 raeburn 1844: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 1845: return;
1846: }
1847: my $response = &get_query_reply($queryid);
1848: my $maxtries = 5;
1849: my $tries = 1;
1850: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1851: $response = &get_query_reply($queryid);
1852: $tries ++;
1853: }
1854:
1855: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1856: if ($response eq 'unavailable') {
1857: $outcome = $response;
1858: } else {
1859: $outcome = 'ok';
1860: my @matches = split(/\n/,$response);
1861: foreach my $match (@matches) {
1862: my ($key,$value) = split(/=/,$match);
1863: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1864: }
1.899 raeburn 1865: }
1866: }
1867: }
1.909 raeburn 1868: return ($outcome,%results);
1.899 raeburn 1869: }
1870:
1871: sub usersearch {
1872: my ($srch) = @_;
1873: my $dom = $srch->{'srchdomain'};
1874: my %results;
1875: my %libserv = &all_library();
1876: my $query = 'usersearch';
1877: foreach my $tryserver (keys(%libserv)) {
1878: if (&host_domain($tryserver) eq $dom) {
1879: my $host=&hostname($tryserver);
1880: my $queryid=
1.911 raeburn 1881: &reply("querysend:".&escape($query).':'.
1882: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1883: &escape($srch->{'srchtype'}).':'.
1884: &escape($srch->{'srchterm'}),$tryserver);
1885: if ($queryid !~/^\Q$host\E\_/) {
1886: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1887: next;
1.899 raeburn 1888: }
1889: my $reply = &get_query_reply($queryid);
1890: my $maxtries = 1;
1891: my $tries = 1;
1892: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1893: $reply = &get_query_reply($queryid);
1894: $tries ++;
1895: }
1896: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1897: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1898: } else {
1.911 raeburn 1899: my @matches;
1900: if ($reply =~ /\n/) {
1901: @matches = split(/\n/,$reply);
1902: } else {
1903: @matches = split(/\&/,$reply);
1904: }
1.899 raeburn 1905: foreach my $match (@matches) {
1906: my ($uname,$udom,%userhash);
1.911 raeburn 1907: foreach my $entry (split(/:/,$match)) {
1908: my ($key,$value) =
1909: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1910: $userhash{$key} = $value;
1911: if ($key eq 'username') {
1912: $uname = $value;
1913: } elsif ($key eq 'domain') {
1914: $udom = $value;
1.911 raeburn 1915: }
1.899 raeburn 1916: }
1917: $results{$uname.':'.$udom} = \%userhash;
1918: }
1919: }
1920: }
1921: }
1922: return %results;
1923: }
1924:
1.912 raeburn 1925: sub get_instuser {
1926: my ($udom,$uname,$id) = @_;
1927: my $homeserver = &domain($udom,'primary');
1928: my ($outcome,%results);
1929: if ($homeserver ne '') {
1930: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1931: &escape($id).':'.&escape($udom),$homeserver);
1932: my $host=&hostname($homeserver);
1933: if ($queryid !~/^\Q$host\E\_/) {
1934: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1935: return;
1936: }
1937: my $response = &get_query_reply($queryid);
1938: my $maxtries = 5;
1939: my $tries = 1;
1940: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1941: $response = &get_query_reply($queryid);
1942: $tries ++;
1943: }
1944: if (!&error($response) && $response ne 'refused') {
1945: if ($response eq 'unavailable') {
1946: $outcome = $response;
1947: } else {
1948: $outcome = 'ok';
1949: my @matches = split(/\n/,$response);
1950: foreach my $match (@matches) {
1951: my ($key,$value) = split(/=/,$match);
1952: $results{&unescape($key)} = &thaw_unescape($value);
1953: }
1954: }
1955: }
1956: }
1957: my %userinfo;
1958: if (ref($results{$uname}) eq 'HASH') {
1959: %userinfo = %{$results{$uname}};
1960: }
1961: return ($outcome,%userinfo);
1962: }
1963:
1.1172.2.69 raeburn 1964: sub get_multiple_instusers {
1965: my ($udom,$users,$caller) = @_;
1966: my ($outcome,$results);
1967: if (ref($users) eq 'HASH') {
1968: my $count = keys(%{$users});
1969: my $requested = &freeze_escape($users);
1970: my $homeserver = &domain($udom,'primary');
1971: if ($homeserver ne '') {
1972: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
1973: my $host=&hostname($homeserver);
1974: if ($queryid !~/^\Q$host\E\_/) {
1975: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
1976: ' for host: '.$homeserver.'in domain '.$udom);
1977: return ($outcome,$results);
1978: }
1979: my $response = &get_query_reply($queryid);
1980: my $maxtries = 5;
1981: if ($count > 100) {
1982: $maxtries = 1+int($count/20);
1983: }
1984: my $tries = 1;
1985: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
1986: $response = &get_query_reply($queryid);
1987: $tries ++;
1988: }
1989: if ($response eq '') {
1990: $results = {};
1991: foreach my $key (keys(%{$users})) {
1992: my ($uname,$id);
1993: if ($caller eq 'id') {
1994: $id = $key;
1995: } else {
1996: $uname = $key;
1997: }
1998: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1999: $outcome = $resp;
2000: if ($resp eq 'ok') {
2001: %{$results} = (%{$results}, %info);
2002: } else {
2003: last;
2004: }
2005: }
2006: } elsif(!&error($response) && ($response ne 'refused')) {
2007: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2008: $outcome = $response;
2009: } else {
2010: ($outcome,my $userdata) = split(/=/,$response,2);
2011: if ($outcome eq 'ok') {
2012: $results = &thaw_unescape($userdata);
2013: }
2014: }
2015: }
2016: }
2017: }
2018: return ($outcome,$results);
2019: }
2020:
1.912 raeburn 2021: sub inst_rulecheck {
1.923 raeburn 2022: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2023: my %returnhash;
2024: if ($udom ne '') {
2025: if (ref($rules) eq 'ARRAY') {
2026: @{$rules} = map {&escape($_);} (@{$rules});
2027: my $rulestr = join(':',@{$rules});
2028: my $homeserver=&domain($udom,'primary');
2029: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2030: my $response;
2031: if ($item eq 'username') {
2032: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2033: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2034: $homeserver));
1.923 raeburn 2035: } elsif ($item eq 'id') {
2036: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2037: ':'.&escape($id).':'.$rulestr,
2038: $homeserver));
1.945 raeburn 2039: } elsif ($item eq 'selfcreate') {
2040: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2041: &escape($udom).':'.&escape($uname).
2042: ':'.$rulestr,$homeserver));
1.923 raeburn 2043: }
1.912 raeburn 2044: if ($response ne 'refused') {
2045: my @pairs=split(/\&/,$response);
2046: foreach my $item (@pairs) {
2047: my ($key,$value)=split(/=/,$item,2);
2048: $key = &unescape($key);
2049: next if ($key =~ /^error: 2 /);
2050: $returnhash{$key}=&thaw_unescape($value);
2051: }
2052: }
2053: }
2054: }
2055: }
2056: return %returnhash;
2057: }
2058:
2059: sub inst_userrules {
1.923 raeburn 2060: my ($udom,$check) = @_;
1.912 raeburn 2061: my (%ruleshash,@ruleorder);
2062: if ($udom ne '') {
2063: my $homeserver=&domain($udom,'primary');
2064: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2065: my $response;
2066: if ($check eq 'id') {
2067: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2068: $homeserver);
1.943 raeburn 2069: } elsif ($check eq 'email') {
2070: $response=&reply('instemailrules:'.&escape($udom),
2071: $homeserver);
1.923 raeburn 2072: } else {
2073: $response=&reply('instuserrules:'.&escape($udom),
2074: $homeserver);
2075: }
1.912 raeburn 2076: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2077: ($response ne 'unknown_cmd') &&
1.912 raeburn 2078: ($response ne 'no_such_host')) {
2079: my ($hashitems,$orderitems) = split(/:/,$response);
2080: my @pairs=split(/\&/,$hashitems);
2081: foreach my $item (@pairs) {
2082: my ($key,$value)=split(/=/,$item,2);
2083: $key = &unescape($key);
2084: next if ($key =~ /^error: 2 /);
2085: $ruleshash{$key}=&thaw_unescape($value);
2086: }
2087: my @esc_order = split(/\&/,$orderitems);
2088: foreach my $item (@esc_order) {
2089: push(@ruleorder,&unescape($item));
2090: }
2091: }
2092: }
2093: }
2094: return (\%ruleshash,\@ruleorder);
2095: }
2096:
1.976 raeburn 2097: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2098:
2099: sub get_domain_defaults {
1.1172.2.35 raeburn 2100: my ($domain,$ignore_cache) = @_;
2101: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2102: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2103: unless ($ignore_cache) {
2104: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2105: if (defined($cached)) {
2106: if (ref($result) eq 'HASH') {
2107: return %{$result};
2108: }
1.943 raeburn 2109: }
2110: }
2111: my %domdefaults;
2112: my %domconfig =
1.989 raeburn 2113: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2114: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2115: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2116: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2117: 'coursecategories','autoenroll',
2118: 'helpsettings'],$domain);
1.1172.2.41 raeburn 2119: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2120: if (ref($domconfig{'defaults'}) eq 'HASH') {
2121: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2122: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2123: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2124: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2125: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2126: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2127: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2128: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2129: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2130: } else {
2131: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2132: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2133: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2134: }
1.976 raeburn 2135: if (ref($domconfig{'quotas'}) eq 'HASH') {
2136: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2137: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2138: } else {
2139: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2140: }
1.1172.2.6 raeburn 2141: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2142: foreach my $item (@usertools) {
2143: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2144: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2145: }
2146: }
1.1172.2.29 raeburn 2147: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2148: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2149: }
1.976 raeburn 2150: }
1.985 raeburn 2151: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2152: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2153: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2154: }
2155: }
1.1172.2.9 raeburn 2156: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2157: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2158: }
1.989 raeburn 2159: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2160: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2161: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2162: }
2163: }
1.1047 raeburn 2164: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2165: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2166: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2167: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2168: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2169: }
1.1172.2.41 raeburn 2170: foreach my $type (@coursetypes) {
2171: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2172: unless ($type eq 'community') {
2173: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2174: }
2175: }
2176: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2177: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2178: }
1.1172.2.60 raeburn 2179: if ($domdefaults{'postsubmit'} eq 'on') {
2180: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2181: $domdefaults{$type.'postsubtimeout'} =
2182: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2183: }
2184: }
1.1172.2.30 raeburn 2185: }
1.1172.2.67 raeburn 2186: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2187: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2188: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2189: if (@clonecodes) {
2190: $domdefaults{'canclone'} = join('+',@clonecodes);
2191: }
2192: }
2193: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2194: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2195: }
1.1047 raeburn 2196: }
1.1073 raeburn 2197: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2198: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2199: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2200: }
2201: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2202: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2203: }
1.1172.2.62 raeburn 2204: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2205: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2206: }
1.1073 raeburn 2207: }
1.1172.2.41 raeburn 2208: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2209: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2210: my @settings = ('types','registered','enroll_dates','access_dates','section',
2211: 'approval','limit');
2212: foreach my $type (@coursetypes) {
2213: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2214: my @mgrdc = ();
2215: foreach my $item (@settings) {
2216: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2217: push(@mgrdc,$item);
2218: }
2219: }
2220: if (@mgrdc) {
2221: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2222: }
2223: }
2224: }
2225: }
2226: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2227: foreach my $type (@coursetypes) {
2228: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2229: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2230: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2231: }
2232: }
2233: }
2234: }
2235: }
1.1172.2.46 raeburn 2236: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2237: $domdefaults{'catauth'} = 'std';
2238: $domdefaults{'catunauth'} = 'std';
2239: if ($domconfig{'coursecategories'}{'auth'}) {
2240: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2241: }
2242: if ($domconfig{'coursecategories'}{'unauth'}) {
2243: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2244: }
2245: }
1.1172.2.76 raeburn 2246: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2247: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2248: }
1.1172.2.89 raeburn 2249: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2250: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2251: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2252: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2253: }
2254: }
1.1172.2.23 raeburn 2255: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2256: return %domdefaults;
2257: }
2258:
1.344 www 2259: # --------------------------------------------------- Assign a key to a student
2260:
2261: sub assign_access_key {
1.364 www 2262: #
2263: # a valid key looks like uname:udom#comments
2264: # comments are being appended
2265: #
1.498 www 2266: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2267: $kdom=
1.620 albertel 2268: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2269: $knum=
1.620 albertel 2270: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2271: $cdom=
1.620 albertel 2272: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2273: $cnum=
1.620 albertel 2274: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2275: $udom=$env{'user.name'} unless (defined($udom));
2276: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2277: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2278: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2279: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2280: # assigned to this person
2281: # - this should not happen,
1.345 www 2282: # unless something went wrong
2283: # the first time around
2284: # ready to assign
1.364 www 2285: $logentry=$1.'; '.$logentry;
1.496 www 2286: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2287: $kdom,$knum) eq 'ok') {
1.345 www 2288: # key now belongs to user
1.346 www 2289: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2290: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2291: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2292: return 'ok';
2293: } else {
2294: return
2295: 'error: Count not permanently assign key, will need to be re-entered later.';
2296: }
2297: } else {
2298: return 'error: Could not assign key, try again later.';
2299: }
1.364 www 2300: } elsif (!$existing{$ckey}) {
1.345 www 2301: # the key does not exist
2302: return 'error: The key does not exist';
2303: } else {
2304: # the key is somebody else's
2305: return 'error: The key is already in use';
2306: }
1.344 www 2307: }
2308:
1.364 www 2309: # ------------------------------------------ put an additional comment on a key
2310:
2311: sub comment_access_key {
2312: #
2313: # a valid key looks like uname:udom#comments
2314: # comments are being appended
2315: #
2316: my ($ckey,$cdom,$cnum,$logentry)=@_;
2317: $cdom=
1.620 albertel 2318: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2319: $cnum=
1.620 albertel 2320: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2321: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2322: if ($existing{$ckey}) {
2323: $existing{$ckey}.='; '.$logentry;
2324: # ready to assign
1.367 www 2325: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2326: $cdom,$cnum) eq 'ok') {
2327: return 'ok';
2328: } else {
2329: return 'error: Count not store comment.';
2330: }
2331: } else {
2332: # the key does not exist
2333: return 'error: The key does not exist';
2334: }
2335: }
2336:
1.344 www 2337: # ------------------------------------------------------ Generate a set of keys
2338:
2339: sub generate_access_keys {
1.364 www 2340: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2341: $cdom=
1.620 albertel 2342: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2343: $cnum=
1.620 albertel 2344: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2345: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2346: unless (($cdom) && ($cnum)) { return 0; }
2347: if ($number>10000) { return 0; }
2348: sleep(2); # make sure don't get same seed twice
2349: srand(time()^($$+($$<<15))); # from "Programming Perl"
2350: my $total=0;
2351: for (my $i=1;$i<=$number;$i++) {
2352: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2353: sprintf("%lx",int(100000*rand)).'-'.
2354: sprintf("%lx",int(100000*rand));
2355: $newkey=~s/1/g/g; # folks mix up 1 and l
2356: $newkey=~s/0/h/g; # and also 0 and O
2357: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2358: if ($existing{$newkey}) {
2359: $i--;
2360: } else {
1.364 www 2361: if (&put('accesskeys',
2362: { $newkey => '# generated '.localtime().
1.620 albertel 2363: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2364: '; '.$logentry },
2365: $cdom,$cnum) eq 'ok') {
1.344 www 2366: $total++;
2367: }
2368: }
2369: }
1.620 albertel 2370: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2371: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2372: return $total;
2373: }
2374:
2375: # ------------------------------------------------------- Validate an accesskey
2376:
2377: sub validate_access_key {
2378: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2379: $cdom=
1.620 albertel 2380: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2381: $cnum=
1.620 albertel 2382: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2383: $udom=$env{'user.domain'} unless (defined($udom));
2384: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2385: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2386: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2387: }
2388:
2389: # ------------------------------------- Find the section of student in a course
1.652 albertel 2390: sub devalidate_getsection_cache {
2391: my ($udom,$unam,$courseid)=@_;
2392: my $hashid="$udom:$unam:$courseid";
2393: &devalidate_cache_new('getsection',$hashid);
2394: }
1.298 matthew 2395:
1.815 albertel 2396: sub courseid_to_courseurl {
2397: my ($courseid) = @_;
2398: #already url style courseid
2399: return $courseid if ($courseid =~ m{^/});
2400:
2401: if (exists($env{'course.'.$courseid.'.num'})) {
2402: my $cnum = $env{'course.'.$courseid.'.num'};
2403: my $cdom = $env{'course.'.$courseid.'.domain'};
2404: return "/$cdom/$cnum";
2405: }
2406:
2407: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2408: if (exists($courseinfo{'num'})) {
2409: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2410: }
2411:
2412: return undef;
2413: }
2414:
1.298 matthew 2415: sub getsection {
2416: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2417: my $cachetime=1800;
1.551 albertel 2418:
2419: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2420: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2421: if (defined($cached)) { return $result; }
2422:
1.298 matthew 2423: my %Pending;
2424: my %Expired;
2425: #
2426: # Each role can either have not started yet (pending), be active,
2427: # or have expired.
2428: #
2429: # If there is an active role, we are done.
2430: #
2431: # If there is more than one role which has not started yet,
2432: # choose the one which will start sooner
2433: # If there is one role which has not started yet, return it.
2434: #
2435: # If there is more than one expired role, choose the one which ended last.
2436: # If there is a role which has expired, return it.
2437: #
1.815 albertel 2438: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2439: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2440: foreach my $key (keys(%roleshash)) {
1.479 albertel 2441: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2442: my $section=$1;
2443: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2444: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2445: my $now=time;
1.548 albertel 2446: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2447: $Expired{$end}=$section;
2448: next;
2449: }
1.548 albertel 2450: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2451: $Pending{$start}=$section;
2452: next;
2453: }
1.599 albertel 2454: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2455: }
2456: #
2457: # Presumedly there will be few matching roles from the above
2458: # loop and the sorting time will be negligible.
2459: if (scalar(keys(%Pending))) {
2460: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2461: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2462: }
2463: if (scalar(keys(%Expired))) {
2464: my @sorted = sort {$a <=> $b} keys(%Expired);
2465: my $time = pop(@sorted);
1.599 albertel 2466: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2467: }
1.599 albertel 2468: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2469: }
1.70 www 2470:
1.599 albertel 2471: sub save_cache {
2472: &purge_remembered();
1.722 albertel 2473: #&Apache::loncommon::validate_page();
1.620 albertel 2474: undef(%env);
1.780 albertel 2475: undef($env_loaded);
1.599 albertel 2476: }
1.452 albertel 2477:
1.599 albertel 2478: my $to_remember=-1;
2479: my %remembered;
2480: my %accessed;
2481: my $kicks=0;
2482: my $hits=0;
1.849 albertel 2483: sub make_key {
2484: my ($name,$id) = @_;
1.872 albertel 2485: if (length($id) > 65
2486: && length(&escape($id)) > 200) {
2487: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2488: }
1.849 albertel 2489: return &escape($name.':'.$id);
2490: }
2491:
1.599 albertel 2492: sub devalidate_cache_new {
2493: my ($name,$id,$debug) = @_;
2494: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2495: my $remembered_id=$name.':'.$id;
1.849 albertel 2496: $id=&make_key($name,$id);
1.599 albertel 2497: $memcache->delete($id);
1.1172.2.81 raeburn 2498: delete($remembered{$remembered_id});
2499: delete($accessed{$remembered_id});
1.599 albertel 2500: }
2501:
2502: sub is_cached_new {
2503: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2504: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2505: # keys in %remembered hash, which persists for
2506: # duration of request (no restriction on key length).
2507: if (exists($remembered{$remembered_id})) {
2508: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2509: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2510: $hits++;
1.1172.2.81 raeburn 2511: return ($remembered{$remembered_id},1);
1.599 albertel 2512: }
1.1172.2.81 raeburn 2513: $id=&make_key($name,$id);
1.599 albertel 2514: my $value = $memcache->get($id);
2515: if (!(defined($value))) {
2516: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2517: return (undef,undef);
1.416 albertel 2518: }
1.599 albertel 2519: if ($value eq '__undef__') {
2520: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2521: $value=undef;
2522: }
1.1172.2.81 raeburn 2523: &make_room($remembered_id,$value,$debug);
1.599 albertel 2524: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2525: return ($value,1);
2526: }
2527:
2528: sub do_cache_new {
2529: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2530: my $remembered_id=$name.':'.$id;
1.849 albertel 2531: $id=&make_key($name,$id);
1.599 albertel 2532: my $setvalue=$value;
2533: if (!defined($setvalue)) {
2534: $setvalue='__undef__';
2535: }
1.623 albertel 2536: if (!defined($time) ) {
2537: $time=600;
2538: }
1.599 albertel 2539: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2540: my $result = $memcache->set($id,$setvalue,$time);
2541: if (! $result) {
1.872 albertel 2542: &logthis("caching of id -> $id failed");
1.910 albertel 2543: $memcache->disconnect_all();
1.872 albertel 2544: }
1.600 albertel 2545: # need to make a copy of $value
1.1172.2.81 raeburn 2546: &make_room($remembered_id,$value,$debug);
1.599 albertel 2547: return $value;
2548: }
2549:
2550: sub make_room {
1.1172.2.81 raeburn 2551: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2552:
1.1172.2.81 raeburn 2553: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2554: : $value;
1.599 albertel 2555: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2556: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2557: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2558: my $to_kick;
2559: my $max_time=0;
2560: foreach my $other (keys(%accessed)) {
2561: if (&tv_interval($accessed{$other}) > $max_time) {
2562: $to_kick=$other;
2563: $max_time=&tv_interval($accessed{$other});
2564: }
2565: }
2566: delete($remembered{$to_kick});
2567: delete($accessed{$to_kick});
2568: $kicks++;
2569: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2570: return;
2571: }
2572:
1.599 albertel 2573: sub purge_remembered {
1.604 albertel 2574: #&logthis("Tossing ".scalar(keys(%remembered)));
2575: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2576: undef(%remembered);
2577: undef(%accessed);
1.428 albertel 2578: }
1.70 www 2579: # ------------------------------------- Read an entry from a user's environment
2580:
2581: sub userenvironment {
2582: my ($udom,$unam,@what)=@_;
1.976 raeburn 2583: my $items;
2584: foreach my $item (@what) {
2585: $items.=&escape($item).'&';
2586: }
2587: $items=~s/\&$//;
1.70 www 2588: my %returnhash=();
1.1009 raeburn 2589: my $uhome = &homeserver($unam,$udom);
2590: unless ($uhome eq 'no_host') {
2591: my @answer=split(/\&/,
2592: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2593: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2594: return %returnhash;
2595: }
1.1009 raeburn 2596: my $i;
2597: for ($i=0;$i<=$#what;$i++) {
2598: $returnhash{$what[$i]}=&unescape($answer[$i]);
2599: }
1.70 www 2600: }
2601: return %returnhash;
1.1 albertel 2602: }
2603:
1.617 albertel 2604: # ---------------------------------------------------------- Get a studentphoto
2605: sub studentphoto {
2606: my ($udom,$unam,$ext) = @_;
2607: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2608: if (defined($env{'request.course.id'})) {
1.708 raeburn 2609: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2610: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2611: return(&retrievestudentphoto($udom,$unam,$ext));
2612: } else {
2613: my ($result,$perm_reqd)=
1.707 albertel 2614: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2615: if ($result eq 'ok') {
2616: if (!($perm_reqd eq 'yes')) {
2617: return(&retrievestudentphoto($udom,$unam,$ext));
2618: }
2619: }
2620: }
2621: }
2622: } else {
2623: my ($result,$perm_reqd) =
1.707 albertel 2624: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2625: if ($result eq 'ok') {
2626: if (!($perm_reqd eq 'yes')) {
2627: return(&retrievestudentphoto($udom,$unam,$ext));
2628: }
2629: }
2630: }
2631: return '/adm/lonKaputt/lonlogo_broken.gif';
2632: }
2633:
2634: sub retrievestudentphoto {
2635: my ($udom,$unam,$ext,$type) = @_;
2636: my $home=&Apache::lonnet::homeserver($unam,$udom);
2637: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2638: if ($ret eq 'ok') {
2639: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2640: if ($type eq 'thumbnail') {
2641: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2642: }
2643: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2644: return $tokenurl;
2645: } else {
2646: if ($type eq 'thumbnail') {
2647: return '/adm/lonKaputt/genericstudent_tn.gif';
2648: } else {
2649: return '/adm/lonKaputt/lonlogo_broken.gif';
2650: }
1.617 albertel 2651: }
2652: }
2653:
1.263 www 2654: # -------------------------------------------------------------------- New chat
2655:
2656: sub chatsend {
1.724 raeburn 2657: my ($newentry,$anon,$group)=@_;
1.620 albertel 2658: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2659: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2660: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2661: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2662: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2663: &escape($newentry)).':'.$group,$chome);
1.292 www 2664: }
2665:
2666: # ------------------------------------------ Find current version of a resource
2667:
2668: sub getversion {
2669: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2670: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2671: return ¤tversion(&filelocation('',$fname));
2672: }
2673:
2674: sub currentversion {
2675: my $fname=shift;
2676: my $author=$fname;
2677: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2678: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2679: my $home=&homeserver($uname,$udom);
1.292 www 2680: if ($home eq 'no_host') {
2681: return -1;
2682: }
1.1112 www 2683: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2684: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2685: return -1;
2686: }
1.1112 www 2687: return $answer;
1.263 www 2688: }
2689:
1.1111 www 2690: #
2691: # Return special version number of resource if set by override, empty otherwise
2692: #
2693: sub usedversion {
2694: my $fname=shift;
2695: unless ($fname) { $fname=$env{'request.uri'}; }
2696: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2697: if ($urlversion) { return $urlversion; }
2698: return '';
2699: }
2700:
1.1 albertel 2701: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2702:
1.1 albertel 2703: sub subscribe {
2704: my $fname=shift;
1.761 raeburn 2705: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2706: $fname=~s/[\n\r]//g;
1.1 albertel 2707: my $author=$fname;
2708: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2709: my ($udom,$uname)=split(/\//,$author);
2710: my $home=homeserver($uname,$udom);
1.335 albertel 2711: if ($home eq 'no_host') {
2712: return 'not_found';
1.1 albertel 2713: }
2714: my $answer=reply("sub:$fname",$home);
1.64 www 2715: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2716: $answer.=' by '.$home;
2717: }
1.1 albertel 2718: return $answer;
2719: }
2720:
1.8 www 2721: # -------------------------------------------------------------- Replicate file
2722:
2723: sub repcopy {
2724: my $filename=shift;
1.23 www 2725: $filename=~s/\/+/\//g;
1.1142 raeburn 2726: my $londocroot = $perlvar{'lonDocRoot'};
2727: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2728: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2729: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2730: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2731: return &repcopy_userfile($filename);
2732: }
1.532 albertel 2733: $filename=~s/[\n\r]//g;
1.8 www 2734: my $transname="$filename.in.transfer";
1.828 www 2735: # FIXME: this should flock
1.607 raeburn 2736: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2737: my $remoteurl=subscribe($filename);
1.64 www 2738: if ($remoteurl =~ /^con_lost by/) {
2739: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2740: return 'unavailable';
1.8 www 2741: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2742: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2743: return 'not_found';
1.64 www 2744: } elsif ($remoteurl =~ /^rejected by/) {
2745: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2746: return 'forbidden';
1.20 www 2747: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2748: return 'ok';
1.8 www 2749: } else {
1.290 www 2750: my $author=$filename;
2751: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2752: my ($udom,$uname)=split(/\//,$author);
2753: my $home=homeserver($uname,$udom);
2754: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2755: my @parts=split(/\//,$filename);
2756: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2757: if ($path ne "$londocroot/res") {
1.8 www 2758: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2759: return 'bad_request';
1.8 www 2760: }
2761: my $count;
2762: for ($count=5;$count<$#parts;$count++) {
2763: $path.="/$parts[$count]";
2764: if ((-e $path)!=1) {
2765: mkdir($path,0777);
2766: }
2767: }
2768: my $ua=new LWP::UserAgent;
2769: my $request=new HTTP::Request('GET',"$remoteurl");
2770: my $response=$ua->request($request,$transname);
2771: if ($response->is_error()) {
2772: unlink($transname);
2773: my $message=$response->status_line;
1.672 albertel 2774: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2775: ." LWP get: $message: $filename</font>");
1.607 raeburn 2776: return 'unavailable';
1.8 www 2777: } else {
1.16 www 2778: if ($remoteurl!~/\.meta$/) {
2779: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2780: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2781: if ($mresponse->is_error()) {
2782: unlink($filename.'.meta');
2783: &logthis(
1.672 albertel 2784: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2785: }
2786: }
1.8 www 2787: rename($transname,$filename);
1.607 raeburn 2788: return 'ok';
1.8 www 2789: }
1.290 www 2790: }
1.8 www 2791: }
1.330 www 2792: }
2793:
2794: # ------------------------------------------------ Get server side include body
2795: sub ssi_body {
1.381 albertel 2796: my ($filelink,%form)=@_;
1.606 matthew 2797: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2798: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2799: }
1.953 www 2800: my $output='';
2801: my $response;
1.980 raeburn 2802: if ($filelink=~/^https?\:/) {
1.954 raeburn 2803: ($output,$response)=&externalssi($filelink);
1.953 www 2804: } else {
1.1004 droeschl 2805: $filelink .= $filelink=~/\?/ ? '&' : '?';
2806: $filelink .= 'inhibitmenu=yes';
1.953 www 2807: ($output,$response)=&ssi($filelink,%form);
2808: }
1.778 albertel 2809: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2810: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2811: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2812: if (wantarray) {
2813: return ($output, $response);
2814: } else {
2815: return $output;
2816: }
1.8 www 2817: }
2818:
1.15 www 2819: # --------------------------------------------------------- Server Side Include
2820:
1.782 albertel 2821: sub absolute_url {
2822: my ($host_name) = @_;
2823: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2824: if ($host_name eq '') {
2825: $host_name = $ENV{'SERVER_NAME'};
2826: }
2827: return $protocol.$host_name;
2828: }
2829:
1.942 foxr 2830: #
2831: # Server side include.
2832: # Parameters:
2833: # fn Possibly encrypted resource name/id.
2834: # form Hash that describes how the rendering should be done
2835: # and other things.
1.944 foxr 2836: # Returns:
1.950 raeburn 2837: # Scalar context: The content of the response.
2838: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2839: #
1.15 www 2840: sub ssi {
2841:
1.944 foxr 2842: my ($fn,%form)=@_;
1.15 www 2843: my $ua=new LWP::UserAgent;
1.23 www 2844: my $request;
1.711 albertel 2845:
2846: $form{'no_update_last_known'}=1;
1.895 albertel 2847: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2848: if (%form) {
1.782 albertel 2849: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2850: $request->content(join('&',map {
2851: my $name = escape($_);
2852: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2853: ? join("&$name=", map {escape($_) } @{$form{$_}})
2854: : &escape($form{$_}) );
2855: } keys(%form)));
1.23 www 2856: } else {
1.782 albertel 2857: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2858: }
2859:
1.15 www 2860: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2861: my $response= $ua->request($request);
1.944 foxr 2862: if (wantarray) {
1.1172.2.3 raeburn 2863: return ($response->content, $response);
1.944 foxr 2864: } else {
1.1172.2.3 raeburn 2865: return $response->content;
1.942 foxr 2866: }
1.324 www 2867: }
2868:
2869: sub externalssi {
2870: my ($url)=@_;
2871: my $ua=new LWP::UserAgent;
2872: my $request=new HTTP::Request('GET',$url);
2873: my $response=$ua->request($request);
1.954 raeburn 2874: if (wantarray) {
2875: return ($response->content, $response);
2876: } else {
2877: return $response->content;
2878: }
1.15 www 2879: }
1.254 www 2880:
1.1172.2.98! raeburn 2881: # If the local copy of a replicated resource is outdated, trigger a
! 2882: # connection from the homeserver to flush the delayed queue. If no update
! 2883: # happens, remove local copies of outdated resource (and corresponding
! 2884: # metadata file).
! 2885:
! 2886: sub remove_stale_resfile {
! 2887: my ($url) = @_;
! 2888: my $removed;
! 2889: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
! 2890: my $audom = $1;
! 2891: my $auname = $2;
! 2892: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
! 2893: my $homeserver = &homeserver($auname,$audom);
! 2894: unless (($homeserver eq 'no_host') ||
! 2895: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
! 2896: my $fname = &filelocation('',$url);
! 2897: if (-e $fname) {
! 2898: my $ua=new LWP::UserAgent;
! 2899: $ua->timeout(5);
! 2900: my $protocol = $protocol{$homeserver};
! 2901: $protocol = 'http' if ($protocol ne 'https');
! 2902: my $hostname = &hostname($homeserver);
! 2903: if ($hostname) {
! 2904: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
! 2905: my $request=new HTTP::Request('HEAD',$uri);
! 2906: my $response=$ua->request($request);
! 2907: if ($response->is_success()) {
! 2908: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
! 2909: my $locmodtime = (stat($fname))[9];
! 2910: if ($locmodtime < $remmodtime) {
! 2911: my $stale;
! 2912: my $answer = &reply('pong',$homeserver);
! 2913: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
! 2914: sleep(0.2);
! 2915: $locmodtime = (stat($fname))[9];
! 2916: if ($locmodtime < $remmodtime) {
! 2917: my $posstransfer = $fname.'.in.transfer';
! 2918: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
! 2919: $removed = 1;
! 2920: } else {
! 2921: $stale = 1;
! 2922: }
! 2923: } else {
! 2924: $removed = 1;
! 2925: }
! 2926: } else {
! 2927: $stale = 1;
! 2928: }
! 2929: if ($stale) {
! 2930: unlink($fname);
! 2931: if ($uri!~/\.meta$/) {
! 2932: unlink($fname.'.meta');
! 2933: }
! 2934: &reply("unsub:$fname",$homeserver);
! 2935: $removed = 1;
! 2936: }
! 2937: }
! 2938: }
! 2939: }
! 2940: }
! 2941: }
! 2942: }
! 2943: }
! 2944: return $removed;
! 2945: }
! 2946:
1.492 albertel 2947: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2948:
2949: sub allowuploaded {
2950: my ($srcurl,$url)=@_;
2951: $url=&clutter(&declutter($url));
2952: my $dir=$url;
2953: $dir=~s/\/[^\/]+$//;
2954: my %httpref=();
2955: my $httpurl=&hreflocation('',$url);
2956: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2957: &Apache::lonnet::appenv(\%httpref);
1.254 www 2958: }
1.477 raeburn 2959:
1.1172.2.13 raeburn 2960: #
2961: # Determine if the current user should be able to edit a particular resource,
2962: # when viewing in course context.
2963: # (a) When viewing resource used to determine if "Edit" item is included in
2964: # Functions.
2965: # (b) When displaying folder contents in course editor, used to determine if
2966: # "Edit" link will be displayed alongside resource.
2967: #
2968: # input: six args -- filename (decluttered), course number, course domain,
2969: # url, symb (if registered) and group (if this is a group
2970: # item -- e.g., bulletin board, group page etc.).
2971: # output: array of five scalars --
2972: # $cfile -- url for file editing if editable on current server
2973: # $home -- homeserver of resource (i.e., for author if published,
2974: # or course if uploaded.).
2975: # $switchserver -- 1 if server switch will be needed.
2976: # $forceedit -- 1 if icon/link should be to go to edit mode
2977: # $forceview -- 1 if icon/link should be to go to view mode
2978: #
2979:
2980: sub can_edit_resource {
2981: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2982: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2983: #
2984: # For aboutme pages user can only edit his/her own.
2985: #
2986: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2987: my ($sdom,$sname) = ($1,$2);
2988: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2989: $home = $env{'user.home'};
2990: $cfile = $resurl;
2991: if ($env{'form.forceedit'}) {
2992: $forceview = 1;
2993: } else {
2994: $forceedit = 1;
2995: }
2996: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2997: } else {
2998: return;
2999: }
3000: }
3001:
3002: if ($env{'request.course.id'}) {
3003: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3004: if ($group ne '') {
3005: # if this is a group homepage or group bulletin board, check group privs
3006: my $allowed = 0;
3007: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3008: if ((&allowed('mdg',$env{'request.course.id'}.
3009: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3010: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3011: $allowed = 1;
3012: }
3013: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3014: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3015: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3016: $allowed = 1;
3017: }
3018: }
3019: if ($allowed) {
3020: $home=&homeserver($cnum,$cdom);
3021: if ($env{'form.forceedit'}) {
3022: $forceview = 1;
3023: } else {
3024: $forceedit = 1;
3025: }
3026: $cfile = $resurl;
3027: } else {
3028: return;
3029: }
3030: } else {
1.1172.2.15 raeburn 3031: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3032: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3033: return;
3034: }
3035: } elsif (!$crsedit) {
1.1172.2.13 raeburn 3036: #
3037: # No edit allowed where CC has switched to student role.
3038: #
3039: return;
3040: }
3041: }
3042: }
3043:
3044: if ($file ne '') {
3045: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3046: if (&is_course_upload($file,$cnum,$cdom)) {
3047: $uploaded = 1;
3048: $incourse = 1;
3049: if ($file =~/\.(htm|html|css|js|txt)$/) {
3050: $cfile = &hreflocation('',$file);
3051: if ($env{'form.forceedit'}) {
3052: $forceview = 1;
3053: } else {
3054: $forceedit = 1;
3055: }
3056: }
3057: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3058: $incourse = 1;
3059: if ($env{'form.forceedit'}) {
3060: $forceview = 1;
3061: } else {
3062: $forceedit = 1;
3063: }
3064: $cfile = $resurl;
3065: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3066: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3067: $incourse = 1;
3068: if ($env{'form.forceedit'}) {
3069: $forceview = 1;
3070: } else {
3071: $forceedit = 1;
3072: }
3073: $cfile = $resurl;
3074: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3075: $incourse = 1;
3076: $cfile = $resurl.'/smpedit';
3077: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3078: $incourse = 1;
3079: if ($env{'form.forceedit'}) {
3080: $forceview = 1;
3081: } else {
3082: $forceedit = 1;
3083: }
3084: $cfile = $resurl;
1.1172.2.15 raeburn 3085: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3086: $incourse = 1;
3087: if ($env{'form.forceedit'}) {
3088: $forceview = 1;
3089: } else {
3090: $forceedit = 1;
3091: }
3092: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3093: }
3094: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3095: my $template = '/res/lib/templates/simpleproblem.problem';
3096: if (&is_on_map($template)) {
3097: $incourse = 1;
3098: $forceview = 1;
3099: $cfile = $template;
3100: }
3101: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3102: $incourse = 1;
3103: if ($env{'form.forceedit'}) {
3104: $forceview = 1;
3105: } else {
3106: $forceedit = 1;
3107: }
3108: $cfile = $resurl;
3109: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3110: $incourse = 1;
3111: $forceview = 1;
3112: if ($symb) {
3113: my ($map,$id,$res)=&decode_symb($symb);
3114: $env{'request.symb'} = $symb;
3115: $cfile = &clutter($res);
3116: } else {
3117: $cfile = $env{'form.suppurl'};
3118: $cfile =~ s{^http://}{};
3119: $cfile = '/adm/wrapper/ext/'.$cfile;
3120: }
1.1172.2.31 raeburn 3121: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3122: if ($env{'form.forceedit'}) {
3123: $forceview = 1;
3124: } else {
3125: $forceedit = 1;
3126: }
3127: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3128: }
3129: }
3130: if ($uploaded || $incourse) {
3131: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3132: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3133: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3134: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3135: # Check that the user has permission to edit this resource
3136: my $setpriv = 1;
3137: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3138: if (defined($cfudom)) {
3139: $home=&homeserver($cfuname,$cfudom);
3140: $cfile=$file;
3141: }
3142: }
3143: if (($cfile ne '') && (!$incourse || $uploaded) &&
3144: (($home ne '') && ($home ne 'no_host'))) {
3145: my @ids=¤t_machine_ids();
3146: unless (grep(/^\Q$home\E$/,@ids)) {
3147: $switchserver=1;
3148: }
3149: }
3150: }
3151: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3152: }
3153:
3154: sub is_course_upload {
3155: my ($file,$cnum,$cdom) = @_;
3156: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3157: $uploadpath =~ s{^\/}{};
3158: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3159: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3160: return 1;
3161: }
3162: return;
3163: }
3164:
3165: sub in_course {
3166: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3167: if ($hideprivileged) {
3168: my $skipuser;
1.1172.2.23 raeburn 3169: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3170: my @possdoms = ($cdom);
3171: if ($coursehash{'checkforpriv'}) {
3172: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3173: }
3174: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3175: $skipuser = 1;
3176: if ($coursehash{'nothideprivileged'}) {
3177: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3178: my $user;
3179: if ($item =~ /:/) {
3180: $user = $item;
3181: } else {
3182: $user = join(':',split(/[\@]/,$item));
3183: }
3184: if ($user eq $uname.':'.$udom) {
3185: undef($skipuser);
3186: last;
3187: }
3188: }
3189: }
3190: if ($skipuser) {
3191: return 0;
3192: }
3193: }
3194: }
3195: $type ||= 'any';
3196: if (!defined($cdom) || !defined($cnum)) {
3197: my $cid = $env{'request.course.id'};
3198: $cdom = $env{'course.'.$cid.'.domain'};
3199: $cnum = $env{'course.'.$cid.'.num'};
3200: }
3201: my $typesref;
3202: if (($type eq 'any') || ($type eq 'all')) {
3203: $typesref = ['active','previous','future'];
3204: } elsif ($type eq 'previous' || $type eq 'future') {
3205: $typesref = [$type];
3206: }
3207: my %roles = &get_my_roles($uname,$udom,'userroles',
3208: $typesref,undef,[$cdom]);
3209: my ($tmp) = keys(%roles);
3210: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3211: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3212: if (@course_roles > 0) {
3213: return 1;
3214: }
3215: return 0;
3216: }
3217:
1.478 albertel 3218: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3219: # input: action, courseID, current domain, intended
1.637 raeburn 3220: # path to file, source of file, instruction to parse file for objects,
3221: # ref to hash for embedded objects,
3222: # ref to hash for codebase of java objects.
1.1095 raeburn 3223: # reference to scalar to accommodate mime type determined
3224: # from File::MMagic if $parser = parse.
1.637 raeburn 3225: #
1.485 raeburn 3226: # output: url to file (if action was uploaddoc),
3227: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3228: #
1.478 albertel 3229: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3230: # course.
1.477 raeburn 3231: #
1.478 albertel 3232: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3233: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3234: # course's home server.
1.477 raeburn 3235: #
1.478 albertel 3236: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3237: # be copied from $source (current location) to
3238: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3239: # and will then be copied to
3240: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3241: # course's home server.
1.485 raeburn 3242: #
1.481 raeburn 3243: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3244: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3245: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3246: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3247: # in course's home server.
1.637 raeburn 3248: #
1.477 raeburn 3249:
3250: sub process_coursefile {
1.1095 raeburn 3251: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3252: $mimetype)=@_;
1.477 raeburn 3253: my $fetchresult;
1.638 albertel 3254: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3255: if ($action eq 'propagate') {
1.638 albertel 3256: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3257: $home);
1.481 raeburn 3258: } else {
1.477 raeburn 3259: my $fpath = '';
3260: my $fname = $file;
1.478 albertel 3261: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3262: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3263: my $filepath = &build_filepath($fpath);
1.481 raeburn 3264: if ($action eq 'copy') {
3265: if ($source eq '') {
3266: $fetchresult = 'no source file';
3267: return $fetchresult;
3268: } else {
3269: my $destination = $filepath.'/'.$fname;
3270: rename($source,$destination);
3271: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3272: $home);
1.481 raeburn 3273: }
3274: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 3275: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3276: print $fh $env{'form.'.$source};
1.481 raeburn 3277: close($fh);
1.637 raeburn 3278: if ($parser eq 'parse') {
1.1024 raeburn 3279: my $mm = new File::MMagic;
1.1095 raeburn 3280: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3281: if ($type eq 'text/html') {
1.1024 raeburn 3282: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3283: unless ($parse_result eq 'ok') {
3284: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3285: }
1.637 raeburn 3286: }
1.1095 raeburn 3287: if (ref($mimetype)) {
3288: $$mimetype = $type;
3289: }
1.637 raeburn 3290: }
1.477 raeburn 3291: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3292: $home);
1.481 raeburn 3293: if ($fetchresult eq 'ok') {
3294: return '/uploaded/'.$fpath.'/'.$fname;
3295: } else {
3296: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3297: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3298: return '/adm/notfound.html';
3299: }
1.477 raeburn 3300: }
3301: }
1.485 raeburn 3302: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3303: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3304: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3305: }
3306: return $fetchresult;
3307: }
3308:
1.637 raeburn 3309: sub build_filepath {
3310: my ($fpath) = @_;
3311: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3312: unless ($fpath eq '') {
3313: my @parts=split('/',$fpath);
3314: foreach my $part (@parts) {
3315: $filepath.= '/'.$part;
3316: if ((-e $filepath)!=1) {
3317: mkdir($filepath,0777);
3318: }
3319: }
3320: }
3321: return $filepath;
3322: }
3323:
3324: sub store_edited_file {
1.638 albertel 3325: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3326: my $file = $primary_url;
3327: $file =~ s#^/uploaded/$docudom/$docuname/##;
3328: my $fpath = '';
3329: my $fname = $file;
3330: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3331: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3332: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 3333: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3334: print $fh $content;
3335: close($fh);
1.638 albertel 3336: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3337: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3338: $home);
1.637 raeburn 3339: if ($$fetchresult eq 'ok') {
3340: return '/uploaded/'.$fpath.'/'.$fname;
3341: } else {
1.638 albertel 3342: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3343: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3344: return '/adm/notfound.html';
3345: }
3346: }
3347:
1.531 albertel 3348: sub clean_filename {
1.831 albertel 3349: my ($fname,$args)=@_;
1.315 www 3350: # Replace Windows backslashes by forward slashes
1.257 www 3351: $fname=~s/\\/\//g;
1.831 albertel 3352: if (!$args->{'keep_path'}) {
3353: # Get rid of everything but the actual filename
3354: $fname=~s/^.*\/([^\/]+)$/$1/;
3355: }
1.315 www 3356: # Replace spaces by underscores
3357: $fname=~s/\s+/\_/g;
3358: # Replace all other weird characters by nothing
1.831 albertel 3359: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3360: # Replace all .\d. sequences with _\d. so they no longer look like version
3361: # numbers
3362: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3363: return $fname;
3364: }
1.1051 raeburn 3365: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3366: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3367: # image with the same aspect ratio as the original, but with dimensions which do
3368: # not exceed $resizewidth and $resizeheight.
3369:
1.984 neumanie 3370: sub resizeImage {
1.1051 raeburn 3371: my ($img_path,$resizewidth,$resizeheight) = @_;
3372: my $ima = Image::Magick->new;
3373: my $resized;
3374: if (-e $img_path) {
3375: $ima->Read($img_path);
3376: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3377: my $width = $ima->Get('width');
3378: my $height = $ima->Get('height');
3379: if ($width > $resizewidth) {
3380: my $factor = $width/$resizewidth;
3381: my $newheight = $height/$factor;
3382: $ima->Scale(width=>$resizewidth,height=>$newheight);
3383: $resized = 1;
3384: }
3385: }
3386: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3387: my $width = $ima->Get('width');
3388: my $height = $ima->Get('height');
3389: if ($height > $resizeheight) {
3390: my $factor = $height/$resizeheight;
3391: my $newwidth = $width/$factor;
3392: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3393: $resized = 1;
3394: }
3395: }
3396: if ($resized) {
3397: $ima->Write($img_path);
3398: }
3399: }
3400: return;
1.977 amueller 3401: }
3402:
1.608 albertel 3403: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3404: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3405: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3406: # $context - possible values: coursedoc, existingfile, overwrite,
3407: # canceloverwrite, or ''.
3408: # if 'coursedoc': upload to the current course
3409: # if 'existingfile': write file to tmp/overwrites directory
3410: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3411: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3412: # $subdir - directory in userfile to store the file into
1.858 raeburn 3413: # $parser - instruction to parse file for objects ($parser = parse)
3414: # $allfiles - reference to hash for embedded objects
3415: # $codebase - reference to hash for codebase of java objects
3416: # $desuname - username for permanent storage of uploaded file
3417: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3418: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3419: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3420: # $resizewidth - width (pixels) to which to resize uploaded image
3421: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3422: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3423: # from File::MMagic.
1.858 raeburn 3424: #
1.686 albertel 3425: # output: url of file in userspace, or error: <message>
3426: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3427:
1.531 albertel 3428: sub userfileupload {
1.1090 raeburn 3429: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3430: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3431: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3432: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3433: $fname=&clean_filename($fname);
1.1090 raeburn 3434: # See if there is anything left
1.257 www 3435: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3436: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3437: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3438: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3439: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3440: my $now = time;
1.1090 raeburn 3441: my $filepath;
1.1095 raeburn 3442: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3443: $filepath = 'tmp/helprequests/'.$now;
3444: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3445: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3446: '_'.$env{'user.domain'}.'/pending';
3447: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3448: my ($docuname,$docudom);
1.1172.2.96 raeburn 3449: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3450: $docudom = $destudom;
3451: } else {
3452: $docudom = $env{'user.domain'};
3453: }
1.1172.2.96 raeburn 3454: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3455: $docuname = $destuname;
3456: } else {
3457: $docuname = $env{'user.name'};
3458: }
3459: if (exists($env{'form.group'})) {
3460: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3461: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3462: }
3463: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3464: if ($context eq 'canceloverwrite') {
3465: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3466: if (-e $tempfile) {
3467: my @info = stat($tempfile);
3468: if ($info[9] eq $env{'form.timestamp'}) {
3469: unlink($tempfile);
3470: }
3471: }
3472: return;
1.523 raeburn 3473: }
3474: }
1.1090 raeburn 3475: # Create the directory if not present
1.741 raeburn 3476: my @parts=split(/\//,$filepath);
3477: my $fullpath = $perlvar{'lonDaemons'};
3478: for (my $i=0;$i<@parts;$i++) {
3479: $fullpath .= '/'.$parts[$i];
3480: if ((-e $fullpath)!=1) {
3481: mkdir($fullpath,0777);
3482: }
3483: }
1.1172.2.96 raeburn 3484: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3485: print $fh $env{'form.'.$formname};
3486: close($fh);
1.1090 raeburn 3487: if ($context eq 'existingfile') {
3488: my @info = stat($fullpath.'/'.$fname);
3489: return ($fullpath.'/'.$fname,$info[9]);
3490: } else {
3491: return $fullpath.'/'.$fname;
3492: }
1.523 raeburn 3493: }
1.995 raeburn 3494: if ($subdir eq 'scantron') {
3495: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3496: } else {
1.995 raeburn 3497: $fname="$subdir/$fname";
3498: }
1.1090 raeburn 3499: if ($context eq 'coursedoc') {
1.638 albertel 3500: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3501: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3502: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3503: return &finishuserfileupload($docuname,$docudom,
3504: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3505: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3506: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3507: } else {
1.1172.2.21 raeburn 3508: if ($env{'form.folder'}) {
3509: $fname=$env{'form.folder'}.'/'.$fname;
3510: }
1.638 albertel 3511: return &process_coursefile('uploaddoc',$docuname,$docudom,
3512: $fname,$formname,$parser,
1.1095 raeburn 3513: $allfiles,$codebase,$mimetype);
1.481 raeburn 3514: }
1.719 banghart 3515: } elsif (defined($destuname)) {
3516: my $docuname=$destuname;
3517: my $docudom=$destudom;
1.860 raeburn 3518: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3519: $parser,$allfiles,$codebase,
1.1051 raeburn 3520: $thumbwidth,$thumbheight,
1.1095 raeburn 3521: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3522: } else {
1.638 albertel 3523: my $docuname=$env{'user.name'};
3524: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3525: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3526: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3527: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3528: }
1.860 raeburn 3529: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3530: $parser,$allfiles,$codebase,
1.1051 raeburn 3531: $thumbwidth,$thumbheight,
1.1095 raeburn 3532: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3533: }
1.271 www 3534: }
3535:
3536: sub finishuserfileupload {
1.860 raeburn 3537: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3538: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3539: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3540: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3541:
1.860 raeburn 3542: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3543: $file=$fname;
3544: if ($fname=~m|/|) {
3545: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3546: $path.=$fnamepath.'/';
3547: }
1.259 www 3548: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3549: my $count;
3550: for ($count=4;$count<=$#parts;$count++) {
3551: $filepath.="/$parts[$count]";
3552: if ((-e $filepath)!=1) {
3553: mkdir($filepath,0777);
3554: }
3555: }
1.984 neumanie 3556:
1.258 www 3557: # Save the file
3558: {
1.1172.2.96 raeburn 3559: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 3560: &logthis('Failed to create '.$filepath.'/'.$file);
3561: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3562: return '/adm/notfound.html';
3563: }
1.1090 raeburn 3564: if ($context eq 'overwrite') {
1.1117 foxr 3565: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3566: my $target = $filepath.'/'.$file;
3567: if (-e $source) {
3568: my @info = stat($source);
3569: if ($info[9] eq $env{'form.timestamp'}) {
3570: unless (&File::Copy::move($source,$target)) {
3571: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3572: return "Moving from $source failed";
3573: }
3574: } else {
3575: return "Temporary file: $source had unexpected date/time for last modification";
3576: }
3577: } else {
3578: return "Temporary file: $source missing";
3579: }
3580: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3581: &logthis('Failed to write to '.$filepath.'/'.$file);
3582: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3583: return '/adm/notfound.html';
3584: }
1.570 albertel 3585: close(FH);
1.1051 raeburn 3586: if ($resizewidth && $resizeheight) {
3587: my $mm = new File::MMagic;
3588: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3589: if ($mime_type =~ m{^image/}) {
3590: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3591: }
1.977 amueller 3592: }
1.258 www 3593: }
1.1152 raeburn 3594: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3595: if (ref($mimetype)) {
3596: if ($$mimetype eq '') {
3597: my $mm = new File::MMagic;
3598: my $type = $mm->checktype_filename($filepath.'/'.$file);
3599: $$mimetype = $type;
3600: }
3601: }
3602: }
1.637 raeburn 3603: if ($parser eq 'parse') {
1.1152 raeburn 3604: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3605: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3606: $allfiles,$codebase);
3607: unless ($parse_result eq 'ok') {
3608: &logthis('Failed to parse '.$filepath.$file.
3609: ' for embedded media: '.$parse_result);
3610: }
1.637 raeburn 3611: }
3612: }
1.860 raeburn 3613: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3614: my $input = $filepath.'/'.$file;
3615: my $output = $filepath.'/'.'tn-'.$file;
3616: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96 raeburn 3617: my @args = ('convert','-sample',$thumbsize,$input,$output);
3618: system({$args[0]} @args);
1.860 raeburn 3619: if (-e $filepath.'/'.'tn-'.$file) {
3620: $fetchthumb = 1;
3621: }
3622: }
1.858 raeburn 3623:
1.259 www 3624: # Notify homeserver to grep it
3625: #
1.984 neumanie 3626: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3627: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3628: if ($fetchresult eq 'ok') {
1.860 raeburn 3629: if ($fetchthumb) {
3630: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3631: if ($thumbresult ne 'ok') {
3632: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3633: $docuhome.': '.$thumbresult);
3634: }
3635: }
1.259 www 3636: #
1.258 www 3637: # Return the URL to it
1.494 albertel 3638: return '/uploaded/'.$path.$file;
1.263 www 3639: } else {
1.494 albertel 3640: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3641: ': '.$fetchresult);
1.263 www 3642: return '/adm/notfound.html';
1.858 raeburn 3643: }
1.493 albertel 3644: }
3645:
1.637 raeburn 3646: sub extract_embedded_items {
1.961 raeburn 3647: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3648: my @state = ();
1.1164 raeburn 3649: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3650: my %javafiles = (
3651: codebase => '',
3652: code => '',
3653: archive => ''
3654: );
3655: my %mediafiles = (
3656: src => '',
3657: movie => '',
3658: );
1.648 raeburn 3659: my $p;
3660: if ($content) {
3661: $p = HTML::LCParser->new($content);
3662: } else {
1.961 raeburn 3663: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3664: }
1.641 albertel 3665: while (my $t=$p->get_token()) {
1.640 albertel 3666: if ($t->[0] eq 'S') {
3667: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3668: push(@state, $tagname);
1.648 raeburn 3669: if (lc($tagname) eq 'allow') {
3670: &add_filetype($allfiles,$attr->{'src'},'src');
3671: }
1.640 albertel 3672: if (lc($tagname) eq 'img') {
3673: &add_filetype($allfiles,$attr->{'src'},'src');
3674: }
1.886 albertel 3675: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3676: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3677: &add_filetype($allfiles,$attr->{'href'},'href');
3678: }
1.886 albertel 3679: }
1.645 raeburn 3680: if (lc($tagname) eq 'script') {
1.1164 raeburn 3681: my $src;
1.645 raeburn 3682: if ($attr->{'archive'} =~ /\.jar$/i) {
3683: &add_filetype($allfiles,$attr->{'archive'},'archive');
3684: } else {
1.1164 raeburn 3685: if ($attr->{'src'} ne '') {
3686: $src = $attr->{'src'};
3687: &add_filetype($allfiles,$src,'src');
3688: }
3689: }
3690: my $text = $p->get_trimmed_text();
3691: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3692: my @swfargs = split(/,/,$1);
3693: foreach my $item (@swfargs) {
3694: $item =~ s/["']//g;
3695: $item =~ s/^\s+//;
3696: $item =~ s/\s+$//;
3697: }
3698: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3699: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3700: push(@{$related{$swfargs[0]}},$swfargs[2]);
3701: } else {
3702: $related{$swfargs[0]} = [$swfargs[2]];
3703: }
3704: }
1.645 raeburn 3705: }
3706: }
3707: if (lc($tagname) eq 'link') {
3708: if (lc($attr->{'rel'}) eq 'stylesheet') {
3709: &add_filetype($allfiles,$attr->{'href'},'href');
3710: }
3711: }
1.640 albertel 3712: if (lc($tagname) eq 'object' ||
3713: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3714: foreach my $item (keys(%javafiles)) {
3715: $javafiles{$item} = '';
3716: }
1.1164 raeburn 3717: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3718: $lastids{lc($tagname)} = $attr->{'id'};
3719: }
1.640 albertel 3720: }
3721: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3722: my $name = lc($attr->{'name'});
3723: foreach my $item (keys(%javafiles)) {
3724: if ($name eq $item) {
3725: $javafiles{$item} = $attr->{'value'};
3726: last;
3727: }
3728: }
1.1164 raeburn 3729: my $pathfrom;
1.640 albertel 3730: foreach my $item (keys(%mediafiles)) {
3731: if ($name eq $item) {
1.1164 raeburn 3732: $pathfrom = $attr->{'value'};
3733: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3734: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3735: last;
3736: }
3737: }
1.1164 raeburn 3738: if ($name eq 'flashvars') {
3739: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3740: }
3741: if ($pathfrom ne '') {
3742: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3743: $pathfrom);
3744: }
1.640 albertel 3745: }
3746: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3747: foreach my $item (keys(%javafiles)) {
3748: if ($attr->{$item}) {
3749: $javafiles{$item} = $attr->{$item};
3750: last;
3751: }
3752: }
3753: foreach my $item (keys(%mediafiles)) {
3754: if ($attr->{$item}) {
3755: &add_filetype($allfiles,$attr->{$item},$item);
3756: last;
3757: }
3758: }
1.1164 raeburn 3759: if (lc($tagname) eq 'embed') {
3760: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3761: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3762: $attr->{'src'});
3763: }
3764: }
1.640 albertel 3765: }
1.1172.2.35 raeburn 3766: if (lc($tagname) eq 'iframe') {
3767: my $src = $attr->{'src'} ;
3768: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3769: &add_filetype($allfiles,$src,'src');
3770: } elsif ($src =~ m{^/}) {
3771: if ($env{'request.course.id'}) {
3772: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3773: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3774: my $url = &hreflocation('',$fullpath);
3775: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3776: my $relpath = $1;
3777: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3778: &add_filetype($allfiles,$1,'src');
3779: }
3780: }
3781: }
3782: }
3783: }
1.1164 raeburn 3784: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3785: pop(@state);
1.1164 raeburn 3786: }
1.640 albertel 3787: } elsif ($t->[0] eq 'E') {
3788: my ($tagname) = ($t->[1]);
3789: if ($javafiles{'codebase'} ne '') {
3790: $javafiles{'codebase'} .= '/';
3791: }
3792: if (lc($tagname) eq 'applet' ||
3793: lc($tagname) eq 'object' ||
3794: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3795: ) {
3796: foreach my $item (keys(%javafiles)) {
3797: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3798: my $file=$javafiles{'codebase'}.$javafiles{$item};
3799: &add_filetype($allfiles,$file,$item);
3800: }
3801: }
3802: }
3803: pop @state;
3804: }
3805: }
1.1164 raeburn 3806: foreach my $id (sort(keys(%flashvars))) {
3807: if ($shockwave{$id} ne '') {
3808: my @pairs = split(/\&/,$flashvars{$id});
3809: foreach my $pair (@pairs) {
3810: my ($key,$value) = split(/\=/,$pair);
3811: if ($key eq 'thumb') {
3812: &add_filetype($allfiles,$value,$key);
3813: } elsif ($key eq 'content') {
3814: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3815: my ($ext) = ($value =~ /\.([^.]+)$/);
3816: if ($ext ne '') {
3817: &add_filetype($allfiles,$path.$value,$ext);
3818: }
3819: }
3820: }
3821: }
3822: }
1.637 raeburn 3823: return 'ok';
3824: }
3825:
1.639 albertel 3826: sub add_filetype {
3827: my ($allfiles,$file,$type)=@_;
3828: if (exists($allfiles->{$file})) {
3829: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3830: push(@{$allfiles->{$file}}, &escape($type));
3831: }
3832: } else {
3833: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3834: }
3835: }
3836:
1.1164 raeburn 3837: sub embedded_dependency {
3838: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3839: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3840: if (($identifier ne '') &&
3841: (ref($related->{$identifier}) eq 'ARRAY') &&
3842: ($pathfrom ne '')) {
3843: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3844: foreach my $dep (@{$related->{$identifier}}) {
3845: &add_filetype($allfiles,$path.$dep,'object');
3846: }
3847: }
3848: }
3849: return;
3850: }
3851:
1.493 albertel 3852: sub removeuploadedurl {
1.984 neumanie 3853: my ($url)=@_;
3854: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3855: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3856: }
3857:
3858: sub removeuserfile {
3859: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3860: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3861: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3862: if ($result eq 'ok') {
1.798 raeburn 3863: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3864: my $metafile = $fname.'.meta';
3865: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3866: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3867: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3868: my $sqlresult =
1.823 albertel 3869: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3870: 'portfolio_metadata',$group,
3871: 'delete');
1.798 raeburn 3872: }
3873: }
3874: return $result;
1.257 www 3875: }
1.15 www 3876:
1.530 albertel 3877: sub mkdiruserfile {
3878: my ($docuname,$docudom,$dir)=@_;
3879: my $home=&homeserver($docuname,$docudom);
3880: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3881: }
3882:
1.531 albertel 3883: sub renameuserfile {
3884: my ($docuname,$docudom,$old,$new)=@_;
3885: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3886: my $result = &reply("renameuserfile:$docudom:$docuname:".
3887: &escape("$old").':'.&escape("$new"),$home);
3888: if ($result eq 'ok') {
3889: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3890: my $oldmeta = $old.'.meta';
3891: my $newmeta = $new.'.meta';
3892: my $metaresult =
3893: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3894: my $url = "/uploaded/$docudom/$docuname/$old";
3895: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3896: my $sqlresult =
1.823 albertel 3897: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3898: 'portfolio_metadata',$group,
3899: 'delete');
1.798 raeburn 3900: }
3901: }
3902: return $result;
1.531 albertel 3903: }
3904:
1.14 www 3905: # ------------------------------------------------------------------------- Log
3906:
3907: sub log {
3908: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3909: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3910: }
3911:
3912: # ------------------------------------------------------------------ Course Log
1.352 www 3913: #
3914: # This routine flushes several buffers of non-mission-critical nature
3915: #
1.157 www 3916:
3917: sub flushcourselogs {
1.352 www 3918: &logthis('Flushing log buffers');
3919: #
3920: # course logs
3921: # This is a log of all transactions in a course, which can be used
3922: # for data mining purposes
3923: #
3924: # It also collects the courseid database, which lists last transaction
3925: # times and course titles for all courseids
3926: #
3927: my %courseidbuffer=();
1.921 raeburn 3928: foreach my $crsid (keys(%courselogs)) {
1.352 www 3929: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3930: &escape($courselogs{$crsid}),
3931: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3932: delete $courselogs{$crsid};
3933: } else {
3934: &logthis('Failed to flush log buffer for '.$crsid);
3935: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3936: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3937: " exceeded maximum size, deleting.</font>");
3938: delete $courselogs{$crsid};
3939: }
1.352 www 3940: }
1.920 raeburn 3941: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3942: 'description' => $coursedescrbuf{$crsid},
3943: 'inst_code' => $courseinstcodebuf{$crsid},
3944: 'type' => $coursetypebuf{$crsid},
3945: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3946: };
1.191 harris41 3947: }
1.352 www 3948: #
3949: # Write course id database (reverse lookup) to homeserver of courses
3950: # Is used in pickcourse
3951: #
1.840 albertel 3952: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3953: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3954: $courseidbuffer{$crs_home},
3955: $crs_home,'timeonly');
1.352 www 3956: }
3957: #
3958: # File accesses
3959: # Writes to the dynamic metadata of resources to get hit counts, etc.
3960: #
1.449 matthew 3961: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3962: if ($entry =~ /___count$/) {
3963: my ($dom,$name);
1.807 albertel 3964: ($dom,$name,undef)=
1.811 albertel 3965: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3966: if (! defined($dom) || $dom eq '' ||
3967: ! defined($name) || $name eq '') {
1.620 albertel 3968: my $cid = $env{'request.course.id'};
3969: $dom = $env{'request.'.$cid.'.domain'};
3970: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3971: }
1.450 matthew 3972: my $value = $accesshash{$entry};
3973: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3974: my %temphash=($url => $value);
1.449 matthew 3975: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3976: if ($result eq 'ok') {
3977: delete $accesshash{$entry};
3978: }
3979: } else {
1.811 albertel 3980: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3981: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3982: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3983: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3984: delete $accesshash{$entry};
3985: }
1.185 www 3986: }
1.191 harris41 3987: }
1.352 www 3988: #
3989: # Roles
3990: # Reverse lookup of user roles for course faculty/staff and co-authorship
3991: #
1.800 albertel 3992: foreach my $entry (keys(%userrolehash)) {
1.351 www 3993: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3994: split(/\:/,$entry);
3995: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3996: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3997: $rudom,$runame) eq 'ok') {
3998: delete $userrolehash{$entry};
3999: }
4000: }
1.662 raeburn 4001: #
1.1172.2.90 raeburn 4002: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4003: #
4004: my %domrolebuffer = ();
1.1000 raeburn 4005: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4006: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4007: if ($domrolebuffer{$rudom}) {
4008: $domrolebuffer{$rudom}.='&'.&escape($entry).
4009: '='.&escape($domainrolehash{$entry});
4010: } else {
4011: $domrolebuffer{$rudom}.=&escape($entry).
4012: '='.&escape($domainrolehash{$entry});
4013: }
4014: delete $domainrolehash{$entry};
4015: }
4016: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4017: my %servers;
4018: if (defined(&domain($dom,'primary'))) {
4019: my $primary=&domain($dom,'primary');
4020: my $hostname=&hostname($primary);
4021: $servers{$primary} = $hostname;
4022: } else {
4023: %servers = &get_servers($dom,'library');
4024: }
1.841 albertel 4025: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4026: if (&reply('domroleput:'.$dom.':'.
4027: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4028: last;
4029: } else {
1.841 albertel 4030: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4031: }
1.662 raeburn 4032: }
4033: }
1.186 www 4034: $dumpcount++;
1.157 www 4035: }
4036:
4037: sub courselog {
4038: my $what=shift;
1.158 www 4039: $what=time.':'.$what;
1.620 albertel 4040: unless ($env{'request.course.id'}) { return ''; }
4041: $coursedombuf{$env{'request.course.id'}}=
4042: $env{'course.'.$env{'request.course.id'}.'.domain'};
4043: $coursenumbuf{$env{'request.course.id'}}=
4044: $env{'course.'.$env{'request.course.id'}.'.num'};
4045: $coursehombuf{$env{'request.course.id'}}=
4046: $env{'course.'.$env{'request.course.id'}.'.home'};
4047: $coursedescrbuf{$env{'request.course.id'}}=
4048: $env{'course.'.$env{'request.course.id'}.'.description'};
4049: $courseinstcodebuf{$env{'request.course.id'}}=
4050: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4051: $courseownerbuf{$env{'request.course.id'}}=
4052: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4053: $coursetypebuf{$env{'request.course.id'}}=
4054: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4055: if (defined $courselogs{$env{'request.course.id'}}) {
4056: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4057: } else {
1.620 albertel 4058: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4059: }
1.620 albertel 4060: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4061: &flushcourselogs();
4062: }
1.158 www 4063: }
4064:
4065: sub courseacclog {
4066: my $fnsymb=shift;
1.620 albertel 4067: unless ($env{'request.course.id'}) { return ''; }
4068: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4069: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4070: $what.=':POST';
1.583 matthew 4071: # FIXME: Probably ought to escape things....
1.800 albertel 4072: foreach my $key (keys(%env)) {
4073: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4074: my $formitem = $1;
4075: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4076: $what.=':'.$formitem.'='.$env{$key};
4077: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4078: $what.=':'.$formitem.'='.$env{$key};
4079: }
1.158 www 4080: }
1.191 harris41 4081: }
1.583 matthew 4082: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4083: # FIXME: We should not be depending on a form parameter that someone
4084: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4085: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4086: $what.= ':POST';
4087: # FIXME: Probably ought to escape things....
4088: foreach my $element ('courseexp','crsfulltext','crsrelated',
4089: 'crsdiscuss') {
1.620 albertel 4090: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4091: }
4092: }
1.158 www 4093: }
4094: &courselog($what);
1.149 www 4095: }
4096:
1.185 www 4097: sub countacc {
4098: my $url=&declutter(shift);
1.458 matthew 4099: return if (! defined($url) || $url eq '');
1.620 albertel 4100: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4101: #
4102: # Mark that this url was used in this course
4103: #
1.620 albertel 4104: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4105: #
4106: # Increase the access count for this resource in this child process
4107: #
1.281 www 4108: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4109: $accesshash{$key}++;
1.185 www 4110: }
1.349 www 4111:
1.361 www 4112: sub linklog {
4113: my ($from,$to)=@_;
4114: $from=&declutter($from);
4115: $to=&declutter($to);
4116: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4117: $accesshash{$to.'___'.$from.'___goto'}=1;
4118: }
1.1160 www 4119:
4120: sub statslog {
4121: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4122: if ($users<2) { return; }
4123: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4124: 'course' => $env{'request.course.id'},
4125: 'sections' => '"all"',
4126: 'num_students' => $users,
4127: 'part' => $part,
4128: 'symb' => $symb,
4129: 'mean_tries' => $av_attempts,
4130: 'deg_of_diff' => $degdiff});
4131: foreach my $key (keys(%dynstore)) {
4132: $accesshash{$key}=$dynstore{$key};
4133: }
4134: }
1.361 www 4135:
1.349 www 4136: sub userrolelog {
4137: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4138: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4139: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4140: $userrolehash
4141: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4142: =$tend.':'.$tstart;
1.662 raeburn 4143: }
1.1169 droeschl 4144: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4145: $userrolehash
4146: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4147: =$tend.':'.$tstart;
4148: }
1.1172.2.90 raeburn 4149: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4150: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4151: $domainrolehash
4152: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4153: = $tend.':'.$tstart;
4154: }
1.351 www 4155: }
4156:
1.957 raeburn 4157: sub courserolelog {
4158: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4159: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4160: my $cdom = $1;
4161: my $cnum = $2;
4162: my $sec = $3;
4163: my $namespace = 'rolelog';
4164: my %storehash = (
4165: role => $trole,
4166: start => $tstart,
4167: end => $tend,
4168: selfenroll => $selfenroll,
4169: context => $context,
4170: );
4171: if ($trole eq 'gr') {
4172: $namespace = 'groupslog';
4173: $storehash{'group'} = $sec;
4174: } else {
4175: $storehash{'section'} = $sec;
4176: }
4177: &write_log('course',$namespace,\%storehash,$delflag,$username,
4178: $domain,$cnum,$cdom);
4179: if (($trole ne 'st') || ($sec ne '')) {
4180: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4181: }
4182: }
4183: return;
4184: }
4185:
1.1172.2.9 raeburn 4186: sub domainrolelog {
4187: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4188: if ($area =~ m{^/($match_domain)/$}) {
4189: my $cdom = $1;
4190: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4191: my $namespace = 'rolelog';
4192: my %storehash = (
4193: role => $trole,
4194: start => $tstart,
4195: end => $tend,
4196: context => $context,
4197: );
4198: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4199: $domain,$domconfiguser,$cdom);
4200: }
4201: return;
4202:
4203: }
4204:
4205: sub coauthorrolelog {
4206: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4207: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4208: my $audom = $1;
4209: my $auname = $2;
4210: my $namespace = 'rolelog';
4211: my %storehash = (
4212: role => $trole,
4213: start => $tstart,
4214: end => $tend,
4215: context => $context,
4216: );
4217: &write_log('author',$namespace,\%storehash,$delflag,$username,
4218: $domain,$auname,$audom);
4219: }
4220: return;
4221: }
4222:
1.351 www 4223: sub get_course_adv_roles {
1.948 raeburn 4224: my ($cid,$codes) = @_;
1.620 albertel 4225: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4226: my %coursehash=&coursedescription($cid);
1.988 raeburn 4227: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4228: my %nothide=();
1.800 albertel 4229: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4230: if ($user !~ /:/) {
4231: $nothide{join(':',split(/[\@]/,$user))}=1;
4232: } else {
4233: $nothide{$user}=1;
4234: }
1.470 www 4235: }
1.1172.2.23 raeburn 4236: my @possdoms = ($coursehash{'domain'});
4237: if ($coursehash{'checkforpriv'}) {
4238: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4239: }
1.351 www 4240: my %returnhash=();
4241: my %dumphash=
4242: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4243: my $now=time;
1.997 raeburn 4244: my %privileged;
1.1000 raeburn 4245: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4246: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4247: if (($tstart) && ($tstart<0)) { next; }
4248: if (($tend) && ($tend<$now)) { next; }
4249: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4250: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4251: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4252: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4253: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4254: if ($role eq 'cr') { next; }
1.948 raeburn 4255: if ($codes) {
4256: if ($section) { $role .= ':'.$section; }
4257: if ($returnhash{$role}) {
4258: $returnhash{$role}.=','.$username.':'.$domain;
4259: } else {
4260: $returnhash{$role}=$username.':'.$domain;
4261: }
1.351 www 4262: } else {
1.988 raeburn 4263: my $key=&plaintext($role,$crstype);
1.973 bisitz 4264: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4265: if ($returnhash{$key}) {
4266: $returnhash{$key}.=','.$username.':'.$domain;
4267: } else {
4268: $returnhash{$key}=$username.':'.$domain;
4269: }
1.351 www 4270: }
1.948 raeburn 4271: }
1.400 www 4272: return %returnhash;
4273: }
4274:
4275: sub get_my_roles {
1.937 raeburn 4276: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4277: unless (defined($uname)) { $uname=$env{'user.name'}; }
4278: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4279: my (%dumphash,%nothide);
1.1086 raeburn 4280: if ($context eq 'userroles') {
1.1166 raeburn 4281: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4282: } else {
1.1172.2.23 raeburn 4283: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4284: if ($hidepriv) {
4285: my %coursehash=&coursedescription($udom.'_'.$uname);
4286: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4287: if ($user !~ /:/) {
4288: $nothide{join(':',split(/[\@]/,$user))} = 1;
4289: } else {
4290: $nothide{$user} = 1;
4291: }
4292: }
4293: }
1.858 raeburn 4294: }
1.400 www 4295: my %returnhash=();
4296: my $now=time;
1.999 raeburn 4297: my %privileged;
1.800 albertel 4298: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4299: my ($role,$tend,$tstart);
4300: if ($context eq 'userroles') {
1.1149 raeburn 4301: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4302: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4303: } else {
4304: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4305: }
1.400 www 4306: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4307: my $status = 'active';
1.939 raeburn 4308: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4309: $status = 'previous';
4310: }
4311: if (($tstart) && ($now<$tstart)) {
4312: $status = 'future';
4313: }
4314: if (ref($types) eq 'ARRAY') {
4315: if (!grep(/^\Q$status\E$/,@{$types})) {
4316: next;
4317: }
4318: } else {
4319: if ($status ne 'active') {
4320: next;
4321: }
4322: }
1.867 raeburn 4323: my ($rolecode,$username,$domain,$section,$area);
4324: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4325: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4326: (undef,$domain,$username,$section) = split(/\//,$area);
4327: } else {
4328: ($role,$username,$domain,$section) = split(/\:/,$entry);
4329: }
1.832 raeburn 4330: if (ref($roledoms) eq 'ARRAY') {
4331: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4332: next;
4333: }
4334: }
4335: if (ref($roles) eq 'ARRAY') {
4336: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4337: if ($role =~ /^cr\//) {
4338: if (!grep(/^cr$/,@{$roles})) {
4339: next;
4340: }
1.1104 raeburn 4341: } elsif ($role =~ /^gr\//) {
4342: if (!grep(/^gr$/,@{$roles})) {
4343: next;
4344: }
1.922 raeburn 4345: } else {
4346: next;
4347: }
1.832 raeburn 4348: }
1.867 raeburn 4349: }
1.937 raeburn 4350: if ($hidepriv) {
1.1172.2.23 raeburn 4351: my @privroles = ('dc','su');
1.999 raeburn 4352: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4353: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4354: } else {
1.1172.2.23 raeburn 4355: my $possdoms = [$domain];
4356: if (ref($roledoms) eq 'ARRAY') {
4357: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4358: }
1.1172.2.23 raeburn 4359: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4360: if (!$nothide{$username.':'.$domain}) {
4361: next;
4362: }
4363: }
1.937 raeburn 4364: }
4365: }
1.933 raeburn 4366: if ($withsec) {
4367: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4368: $tstart.':'.$tend;
4369: } else {
4370: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4371: }
1.832 raeburn 4372: }
1.373 www 4373: return %returnhash;
1.399 www 4374: }
4375:
1.1172.2.89 raeburn 4376: sub get_all_adhocroles {
4377: my ($dom) = @_;
4378: my @roles_by_num = ();
4379: my %domdefaults = &get_domain_defaults($dom);
4380: my (%description,%access_in_dom,%access_info);
4381: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4382: my $count = 0;
4383: my %domcurrent = %{$domdefaults{'adhocroles'}};
4384: my %ordered;
4385: foreach my $role (sort(keys(%domcurrent))) {
4386: my ($order,$desc,$access_in_dom);
4387: if (ref($domcurrent{$role}) eq 'HASH') {
4388: $order = $domcurrent{$role}{'order'};
4389: $desc = $domcurrent{$role}{'desc'};
4390: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4391: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4392: }
4393: if ($order eq '') {
4394: $order = $count;
4395: }
4396: $ordered{$order} = $role;
4397: if ($desc ne '') {
4398: $description{$role} = $desc;
4399: } else {
4400: $description{$role}= $role;
4401: }
4402: $count++;
4403: }
4404: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4405: push(@roles_by_num,$ordered{$item});
4406: }
4407: }
4408: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4409: }
4410:
4411: sub get_my_adhocroles {
4412: my ($cid,$checkreg) = @_;
4413: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4414: if ($env{'request.course.id'} eq $cid) {
4415: $cdom = $env{'course.'.$cid.'.domain'};
4416: $cnum = $env{'course.'.$cid.'.num'};
4417: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4418: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4419: $cdom = $1;
4420: $cnum = $2;
4421: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4422: $cdom,$cnum);
4423: }
4424: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4425: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4426: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4427: if ($rosterhash{$user} ne '') {
4428: my $type = (split(/:/,$rosterhash{$user}))[5];
4429: return ([],{}) if ($type eq 'auto');
4430: }
4431: }
4432: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 4433: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 4434: my $then=$env{'user.login.time'};
4435: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 4436: if (!$update) {
4437: $update = $then;
4438: }
4439: my @liveroles;
4440: foreach my $role ('dh','da') {
4441: if ($env{"user.role.$role./$cdom/"}) {
4442: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
4443: my $limit = $update;
4444: if ($env{'request.role'} eq "$role./$cdom/") {
4445: $limit = $then;
4446: }
4447: my $activerole = 1;
4448: if ($tstart && $tstart>$limit) { $activerole = 0; }
4449: if ($tend && $tend <$limit) { $activerole = 0; }
4450: if ($activerole) {
4451: push(@liveroles,$role);
4452: }
4453: }
4454: }
4455: if (@liveroles) {
1.1172.2.89 raeburn 4456: if (&homeserver($cnum,$cdom) ne 'no_host') {
4457: my ($accessref,$accessinfo,%access_in_dom);
4458: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4459: if (ref($roles_by_num) eq 'ARRAY') {
4460: if (@{$roles_by_num}) {
4461: my %settings;
4462: if ($env{'request.course.id'} eq $cid) {
4463: foreach my $envkey (keys(%env)) {
4464: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4465: $settings{$1} = $env{$envkey};
4466: }
4467: }
4468: } else {
4469: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4470: }
4471: my %setincrs;
4472: if ($settings{'internal.adhocaccess'}) {
4473: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4474: }
4475: my @statuses;
4476: if ($env{'environment.inststatus'}) {
4477: @statuses = split(/,/,$env{'environment.inststatus'});
4478: }
4479: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4480: if (ref($accessref) eq 'HASH') {
4481: %access_in_dom = %{$accessref};
4482: }
4483: foreach my $role (@{$roles_by_num}) {
4484: my ($curraccess,@okstatus,@personnel);
4485: if ($setincrs{$role}) {
4486: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4487: if ($curraccess eq 'status') {
4488: @okstatus = split(/\&/,$rest);
4489: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4490: @personnel = split(/\&/,$rest);
4491: }
4492: } else {
4493: $curraccess = $access_in_dom{$role};
4494: if (ref($accessinfo) eq 'HASH') {
4495: if ($curraccess eq 'status') {
4496: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4497: @okstatus = @{$accessinfo->{$role}};
4498: }
4499: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4500: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4501: @personnel = @{$accessinfo->{$role}};
4502: }
4503: }
4504: }
4505: }
4506: if ($curraccess eq 'none') {
4507: next;
4508: } elsif ($curraccess eq 'all') {
4509: push(@possroles,$role);
1.1172.2.90 raeburn 4510: } elsif ($curraccess eq 'dh') {
4511: if (grep(/^dh$/,@liveroles)) {
4512: push(@possroles,$role);
4513: } else {
4514: next;
4515: }
4516: } elsif ($curraccess eq 'da') {
4517: if (grep(/^da$/,@liveroles)) {
4518: push(@possroles,$role);
4519: } else {
4520: next;
4521: }
1.1172.2.89 raeburn 4522: } elsif ($curraccess eq 'status') {
4523: if (@okstatus) {
4524: if (!@statuses) {
4525: if (grep(/^default$/,@okstatus)) {
4526: push(@possroles,$role);
4527: }
4528: } else {
4529: foreach my $status (@okstatus) {
4530: if (grep(/^\Q$status\E$/,@statuses)) {
4531: push(@possroles,$role);
4532: last;
4533: }
4534: }
4535: }
4536: }
4537: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4538: if (grep(/^\Q$user\E$/,@personnel)) {
4539: if ($curraccess eq 'exc') {
4540: push(@possroles,$role);
4541: }
4542: } elsif ($curraccess eq 'inc') {
4543: push(@possroles,$role);
4544: }
4545: }
4546: }
4547: }
4548: }
4549: }
4550: }
4551: }
4552: }
4553: unless (ref($description) eq 'HASH') {
4554: if (ref($roles_by_num) eq 'ARRAY') {
4555: my %desc;
4556: map { $desc{$_} = $_; } (@{$roles_by_num});
4557: $description = \%desc;
4558: } else {
4559: $description = {};
4560: }
4561: }
4562: return (\@possroles,$description);
4563: }
4564:
1.399 www 4565: # ----------------------------------------------------- Frontpage Announcements
4566: #
4567: #
4568:
4569: sub postannounce {
4570: my ($server,$text)=@_;
1.844 albertel 4571: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4572: unless ($text=~/\w/) { $text=''; }
4573: return &reply('setannounce:'.&escape($text),$server);
4574: }
4575:
4576: sub getannounce {
1.448 albertel 4577:
1.1172.2.96 raeburn 4578: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4579: my $announcement='';
1.800 albertel 4580: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4581: close($fh);
1.399 www 4582: if ($announcement=~/\w/) {
4583: return
4584: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4585: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4586: } else {
4587: return '';
4588: }
4589: } else {
4590: return '';
4591: }
1.351 www 4592: }
1.353 www 4593:
4594: # ---------------------------------------------------------- Course ID routines
4595: # Deal with domain's nohist_courseid.db files
4596: #
4597:
4598: sub courseidput {
1.921 raeburn 4599: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4600: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4601: my $outcome;
4602: if ($caller eq 'timeonly') {
4603: my $cids = '';
4604: foreach my $item (keys(%$storehash)) {
4605: $cids.=&escape($item).'&';
4606: }
4607: $cids=~s/\&$//;
4608: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4609: $coursehome);
4610: } else {
4611: my $items = '';
4612: foreach my $item (keys(%$storehash)) {
4613: $items.= &escape($item).'='.
4614: &freeze_escape($$storehash{$item}).'&';
4615: }
4616: $items=~s/\&$//;
4617: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4618: $coursehome);
1.918 raeburn 4619: }
4620: if ($outcome eq 'unknown_cmd') {
4621: my $what;
4622: foreach my $cid (keys(%$storehash)) {
4623: $what .= &escape($cid).'=';
1.921 raeburn 4624: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4625: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4626: }
4627: $what =~ s/\:$/&/;
4628: }
4629: $what =~ s/\&$//;
4630: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4631: } else {
4632: return $outcome;
4633: }
1.353 www 4634: }
4635:
4636: sub courseiddump {
1.921 raeburn 4637: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4638: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4639: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4640: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 4641: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4642: my $as_hash = 1;
4643: my %returnhash;
4644: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4645: my %libserv = &all_library();
4646: foreach my $tryserver (keys(%libserv)) {
4647: if ( ( $hostidflag == 1
4648: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4649: || (!defined($hostidflag)) ) {
4650:
1.918 raeburn 4651: if (($domfilter eq '') ||
4652: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4653: my $rep;
4654: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4655: $rep = &LONCAPA::Lond::dump_course_id_handler(
4656: join(":", (&host_domain($tryserver), $sincefilter,
4657: &escape($descfilter), &escape($instcodefilter),
4658: &escape($ownerfilter), &escape($coursefilter),
4659: &escape($typefilter), &escape($regexp_ok),
4660: $as_hash, &escape($selfenrollonly),
4661: &escape($catfilter), $showhidden, $caller,
4662: &escape($cloner), &escape($cc_clone), $cloneonly,
4663: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 4664: &escape($creationcontext),$domcloner,$hasuniquecode,
4665: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 4666: } else {
4667: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4668: $sincefilter.':'.&escape($descfilter).':'.
4669: &escape($instcodefilter).':'.&escape($ownerfilter).
4670: ':'.&escape($coursefilter).':'.&escape($typefilter).
4671: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4672: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4673: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4674: &escape($cc_clone).':'.$cloneonly.':'.
4675: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 4676: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4677: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 4678: }
4679:
1.918 raeburn 4680: my @pairs=split(/\&/,$rep);
4681: foreach my $item (@pairs) {
4682: my ($key,$value)=split(/\=/,$item,2);
4683: $key = &unescape($key);
4684: next if ($key =~ /^error: 2 /);
4685: my $result = &thaw_unescape($value);
4686: if (ref($result) eq 'HASH') {
4687: $returnhash{$key}=$result;
4688: } else {
1.921 raeburn 4689: my @responses = split(/:/,$value);
4690: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4691: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4692: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4693: }
1.1008 raeburn 4694: }
1.353 www 4695: }
4696: }
4697: }
4698: }
4699: return %returnhash;
4700: }
4701:
1.1055 raeburn 4702: sub courselastaccess {
4703: my ($cdom,$cnum,$hostidref) = @_;
4704: my %returnhash;
4705: if ($cdom && $cnum) {
4706: my $chome = &homeserver($cnum,$cdom);
4707: if ($chome ne 'no_host') {
4708: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4709: &extract_lastaccess(\%returnhash,$rep);
4710: }
4711: } else {
4712: if (!$cdom) { $cdom=''; }
4713: my %libserv = &all_library();
4714: foreach my $tryserver (keys(%libserv)) {
4715: if (ref($hostidref) eq 'ARRAY') {
4716: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4717: }
4718: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4719: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4720: &extract_lastaccess(\%returnhash,$rep);
4721: }
4722: }
4723: }
4724: return %returnhash;
4725: }
4726:
4727: sub extract_lastaccess {
4728: my ($returnhash,$rep) = @_;
4729: if (ref($returnhash) eq 'HASH') {
4730: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4731: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4732: $rep eq '') {
4733: my @pairs=split(/\&/,$rep);
4734: foreach my $item (@pairs) {
4735: my ($key,$value)=split(/\=/,$item,2);
4736: $key = &unescape($key);
4737: next if ($key =~ /^error: 2 /);
4738: $returnhash->{$key} = &thaw_unescape($value);
4739: }
4740: }
4741: }
4742: return;
4743: }
4744:
1.658 raeburn 4745: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4746:
4747: sub dcmailput {
1.685 raeburn 4748: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4749: my $status = &Apache::lonnet::critical(
1.740 www 4750: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4751: &escape($message),$server);
1.662 raeburn 4752: return $status;
4753: }
4754:
1.658 raeburn 4755: sub dcmaildump {
4756: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4757: my %returnhash=();
1.846 albertel 4758:
4759: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4760: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4761: &escape($enddate).':';
4762: my @esc_senders=map { &escape($_)} @$senders;
4763: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4764: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4765: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4766: if (($key) && ($value)) {
4767: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4768: }
4769: }
4770: }
4771: return %returnhash;
4772: }
1.662 raeburn 4773: # ---------------------------------------------------------- Domain roles
4774:
4775: sub get_domain_roles {
4776: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4777: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4778: $startdate = '.';
4779: }
1.1018 raeburn 4780: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4781: $enddate = '.';
4782: }
1.922 raeburn 4783: my $rolelist;
4784: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4785: $rolelist = join('&',@{$roles});
1.922 raeburn 4786: }
1.662 raeburn 4787: my %personnel = ();
1.841 albertel 4788:
4789: my %servers = &get_servers($dom,'library');
4790: foreach my $tryserver (keys(%servers)) {
4791: %{$personnel{$tryserver}}=();
4792: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4793: &escape($startdate).':'.
4794: &escape($enddate).':'.
4795: &escape($rolelist), $tryserver))) {
4796: my ($key,$value) = split(/\=/,$line,2);
4797: if (($key) && ($value)) {
4798: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4799: }
4800: }
1.662 raeburn 4801: }
4802: return %personnel;
4803: }
1.658 raeburn 4804:
1.1172.2.89 raeburn 4805: sub get_active_domroles {
4806: my ($dom,$roles) = @_;
4807: return () unless (ref($roles) eq 'ARRAY');
4808: my $now = time;
4809: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
4810: my %domroles;
4811: foreach my $server (keys(%dompersonnel)) {
4812: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
4813: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
4814: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
4815: }
4816: }
4817: return %domroles;
4818: }
4819:
1.1057 www 4820: # ----------------------------------------------------------- Interval timing
1.149 www 4821:
1.1153 www 4822: {
4823: # Caches needed for speedup of navmaps
4824: # We don't want to cache this for very long at all (5 seconds at most)
4825: #
4826: # The user for whom we cache
4827: my $cachedkey='';
4828: # The cached times for this user
4829: my %cachedtimes=();
4830: # When this was last done
1.1172.2.66 raeburn 4831: my $cachedtime='';
1.1153 www 4832:
4833: sub load_all_first_access {
1.1154 raeburn 4834: my ($uname,$udom)=@_;
1.1156 www 4835: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4836: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4837: return;
4838: }
4839: $cachedtime=time;
4840: $cachedkey=$uname.':'.$udom;
4841: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4842: }
4843:
1.504 albertel 4844: sub get_first_access {
1.1162 raeburn 4845: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4846: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4847: if ($argsymb) { $symb=$argsymb; }
4848: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4849: if ($argmap) { $map = $argmap; }
1.926 albertel 4850: if ($type eq 'course') {
4851: $res='course';
4852: } elsif ($type eq 'map') {
1.588 albertel 4853: $res=&symbread($map);
4854: } else {
4855: $res=$symb;
4856: }
1.1153 www 4857: &load_all_first_access($uname,$udom);
4858: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4859: }
4860:
4861: sub set_first_access {
1.1162 raeburn 4862: my ($type,$interval)=@_;
1.790 albertel 4863: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4864: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4865: if ($type eq 'course') {
4866: $res='course';
4867: } elsif ($type eq 'map') {
1.588 albertel 4868: $res=&symbread($map);
4869: } else {
4870: $res=$symb;
4871: }
1.1153 www 4872: $cachedkey='';
1.1162 raeburn 4873: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4874: if (!$firstaccess) {
1.1162 raeburn 4875: my $start = time;
4876: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4877: $udom,$uname);
4878: if ($putres eq 'ok') {
4879: &put('timerinterval',{"$courseid\0$res"=>$interval},
4880: $udom,$uname);
4881: &appenv(
4882: {
4883: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4884: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4885: }
4886: );
1.1172.2.97 raeburn 4887: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
4888: $cachedtimes{"$courseid\0$res"} = $start;
4889: }
1.1162 raeburn 4890: }
4891: return $putres;
1.505 albertel 4892: }
4893: return 'already_set';
1.504 albertel 4894: }
1.1153 www 4895: }
1.1172.2.32 raeburn 4896:
4897: sub checkout {
4898: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4899: my $now=time;
4900: my $lonhost=$perlvar{'lonHostID'};
4901: my $infostr=&escape(
4902: 'CHECKOUTTOKEN&'.
4903: $tuname.'&'.
4904: $tudom.'&'.
4905: $tcrsid.'&'.
4906: $symb.'&'.
4907: $now.'&'.$ENV{'REMOTE_ADDR'});
4908: my $token=&reply('tmpput:'.$infostr,$lonhost);
4909: if ($token=~/^error\:/) {
4910: &logthis("<font color=\"blue\">WARNING: ".
4911: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4912: "</font>");
4913: return '';
4914: }
4915:
4916: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4917: $token=~tr/a-z/A-Z/;
4918:
4919: my %infohash=('resource.0.outtoken' => $token,
4920: 'resource.0.checkouttime' => $now,
4921: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4922:
4923: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4924: return '';
4925: } else {
4926: &logthis("<font color=\"blue\">WARNING: ".
4927: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4928: "</font>");
4929: }
4930:
4931: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4932: &escape('Checkout '.$infostr.' - '.
4933: $token)) ne 'ok') {
4934: return '';
4935: } else {
4936: &logthis("<font color=\"blue\">WARNING: ".
4937: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4938: "</font>");
4939: }
4940: return $token;
4941: }
4942:
4943: # ------------------------------------------------------------ Check in an item
4944:
4945: sub checkin {
4946: my $token=shift;
4947: my $now=time;
4948: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4949: $lonhost=~tr/A-Z/a-z/;
4950: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4951: $dtoken=~s/\W/\_/g;
4952: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4953: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4954:
4955: unless (($tuname) && ($tudom)) {
4956: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4957: return '';
4958: }
4959:
4960: unless (&allowed('mgr',$tcrsid)) {
4961: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4962: $env{'user.name'}.' - '.$env{'user.domain'});
4963: return '';
4964: }
4965:
4966: my %infohash=('resource.0.intoken' => $token,
4967: 'resource.0.checkintime' => $now,
4968: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4969:
4970: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4971: return '';
4972: }
4973:
4974: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4975: &escape('Checkin - '.$token)) ne 'ok') {
4976: return '';
4977: }
4978:
4979: return ($symb,$tuname,$tudom,$tcrsid);
4980: }
4981:
1.110 www 4982: # --------------------------------------------- Set Expire Date for Spreadsheet
4983:
4984: sub expirespread {
4985: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4986: my $cid=$env{'request.course.id'};
1.110 www 4987: if ($cid) {
4988: my $now=time;
4989: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4990: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4991: $env{'course.'.$cid.'.num'}.
1.110 www 4992: ':nohist_expirationdates:'.
4993: &escape($key).'='.$now,
1.620 albertel 4994: $env{'course.'.$cid.'.home'})
1.110 www 4995: }
4996: return 'ok';
1.14 www 4997: }
4998:
1.109 www 4999: # ----------------------------------------------------- Devalidate Spreadsheets
5000:
5001: sub devalidate {
1.325 www 5002: my ($symb,$uname,$udom)=@_;
1.620 albertel 5003: my $cid=$env{'request.course.id'};
1.109 www 5004: if ($cid) {
1.391 matthew 5005: # delete the stored spreadsheets for
5006: # - the student level sheet of this user in course's homespace
5007: # - the assessment level sheet for this resource
5008: # for this user in user's homespace
1.553 albertel 5009: # - current conditional state info
1.325 www 5010: my $key=$uname.':'.$udom.':';
1.109 www 5011: my $status=
1.299 matthew 5012: &del('nohist_calculatedsheets',
1.391 matthew 5013: [$key.'studentcalc:'],
1.620 albertel 5014: $env{'course.'.$cid.'.domain'},
5015: $env{'course.'.$cid.'.num'})
1.133 albertel 5016: .' '.
5017: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5018: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5019: unless ($status eq 'ok ok') {
5020: &logthis('Could not devalidate spreadsheet '.
1.325 www 5021: $uname.' at '.$udom.' for '.
1.109 www 5022: $symb.': '.$status);
1.133 albertel 5023: }
1.553 albertel 5024: &delenv('user.state.'.$cid);
1.109 www 5025: }
5026: }
5027:
1.265 albertel 5028: sub get_scalar {
5029: my ($string,$end) = @_;
5030: my $value;
5031: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5032: $value = $1;
5033: } elsif ($$string =~ s/^([^&]*?)&//) {
5034: $value = $1;
5035: }
5036: return &unescape($value);
5037: }
5038:
5039: sub array2str {
5040: my (@array) = @_;
5041: my $result=&arrayref2str(\@array);
5042: $result=~s/^__ARRAY_REF__//;
5043: $result=~s/__END_ARRAY_REF__$//;
5044: return $result;
5045: }
5046:
1.204 albertel 5047: sub arrayref2str {
5048: my ($arrayref) = @_;
1.265 albertel 5049: my $result='__ARRAY_REF__';
1.204 albertel 5050: foreach my $elem (@$arrayref) {
1.265 albertel 5051: if(ref($elem) eq 'ARRAY') {
5052: $result.=&arrayref2str($elem).'&';
5053: } elsif(ref($elem) eq 'HASH') {
5054: $result.=&hashref2str($elem).'&';
5055: } elsif(ref($elem)) {
5056: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5057: } else {
5058: $result.=&escape($elem).'&';
5059: }
5060: }
5061: $result=~s/\&$//;
1.265 albertel 5062: $result .= '__END_ARRAY_REF__';
1.204 albertel 5063: return $result;
5064: }
5065:
1.168 albertel 5066: sub hash2str {
1.204 albertel 5067: my (%hash) = @_;
5068: my $result=&hashref2str(\%hash);
1.265 albertel 5069: $result=~s/^__HASH_REF__//;
5070: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5071: return $result;
5072: }
5073:
5074: sub hashref2str {
5075: my ($hashref)=@_;
1.265 albertel 5076: my $result='__HASH_REF__';
1.800 albertel 5077: foreach my $key (sort(keys(%$hashref))) {
5078: if (ref($key) eq 'ARRAY') {
5079: $result.=&arrayref2str($key).'=';
5080: } elsif (ref($key) eq 'HASH') {
5081: $result.=&hashref2str($key).'=';
5082: } elsif (ref($key)) {
1.265 albertel 5083: $result.='=';
1.800 albertel 5084: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5085: } else {
1.1132 raeburn 5086: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5087: }
5088:
1.800 albertel 5089: if(ref($hashref->{$key}) eq 'ARRAY') {
5090: $result.=&arrayref2str($hashref->{$key}).'&';
5091: } elsif(ref($hashref->{$key}) eq 'HASH') {
5092: $result.=&hashref2str($hashref->{$key}).'&';
5093: } elsif(ref($hashref->{$key})) {
1.265 albertel 5094: $result.='&';
1.800 albertel 5095: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5096: } else {
1.800 albertel 5097: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5098: }
5099: }
1.168 albertel 5100: $result=~s/\&$//;
1.265 albertel 5101: $result .= '__END_HASH_REF__';
1.168 albertel 5102: return $result;
5103: }
5104:
5105: sub str2hash {
1.265 albertel 5106: my ($string)=@_;
5107: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5108: return %$hash;
5109: }
5110:
5111: sub str2hashref {
1.168 albertel 5112: my ($string) = @_;
1.265 albertel 5113:
5114: my %hash;
5115:
5116: if($string !~ /^__HASH_REF__/) {
5117: if (! ($string eq '' || !defined($string))) {
5118: $hash{'error'}='Not hash reference';
5119: }
5120: return (\%hash, $string);
5121: }
5122:
5123: $string =~ s/^__HASH_REF__//;
5124:
5125: while($string !~ /^__END_HASH_REF__/) {
5126: #key
5127: my $key='';
5128: if($string =~ /^__HASH_REF__/) {
5129: ($key, $string)=&str2hashref($string);
5130: if(defined($key->{'error'})) {
5131: $hash{'error'}='Bad data';
5132: return (\%hash, $string);
5133: }
5134: } elsif($string =~ /^__ARRAY_REF__/) {
5135: ($key, $string)=&str2arrayref($string);
5136: if($key->[0] eq 'Array reference error') {
5137: $hash{'error'}='Bad data';
5138: return (\%hash, $string);
5139: }
5140: } else {
5141: $string =~ s/^(.*?)=//;
1.267 albertel 5142: $key=&unescape($1);
1.265 albertel 5143: }
5144: $string =~ s/^=//;
5145:
5146: #value
5147: my $value='';
5148: if($string =~ /^__HASH_REF__/) {
5149: ($value, $string)=&str2hashref($string);
5150: if(defined($value->{'error'})) {
5151: $hash{'error'}='Bad data';
5152: return (\%hash, $string);
5153: }
5154: } elsif($string =~ /^__ARRAY_REF__/) {
5155: ($value, $string)=&str2arrayref($string);
5156: if($value->[0] eq 'Array reference error') {
5157: $hash{'error'}='Bad data';
5158: return (\%hash, $string);
5159: }
5160: } else {
5161: $value=&get_scalar(\$string,'__END_HASH_REF__');
5162: }
5163: $string =~ s/^&//;
5164:
5165: $hash{$key}=$value;
1.204 albertel 5166: }
1.265 albertel 5167:
5168: $string =~ s/^__END_HASH_REF__//;
5169:
5170: return (\%hash, $string);
1.204 albertel 5171: }
5172:
5173: sub str2array {
1.265 albertel 5174: my ($string)=@_;
5175: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5176: return @$array;
5177: }
5178:
5179: sub str2arrayref {
1.204 albertel 5180: my ($string) = @_;
1.265 albertel 5181: my @array;
5182:
5183: if($string !~ /^__ARRAY_REF__/) {
5184: if (! ($string eq '' || !defined($string))) {
5185: $array[0]='Array reference error';
5186: }
5187: return (\@array, $string);
5188: }
5189:
5190: $string =~ s/^__ARRAY_REF__//;
5191:
5192: while($string !~ /^__END_ARRAY_REF__/) {
5193: my $value='';
5194: if($string =~ /^__HASH_REF__/) {
5195: ($value, $string)=&str2hashref($string);
5196: if(defined($value->{'error'})) {
5197: $array[0] ='Array reference error';
5198: return (\@array, $string);
5199: }
5200: } elsif($string =~ /^__ARRAY_REF__/) {
5201: ($value, $string)=&str2arrayref($string);
5202: if($value->[0] eq 'Array reference error') {
5203: $array[0] ='Array reference error';
5204: return (\@array, $string);
5205: }
5206: } else {
5207: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5208: }
5209: $string =~ s/^&//;
5210:
5211: push(@array, $value);
1.191 harris41 5212: }
1.265 albertel 5213:
5214: $string =~ s/^__END_ARRAY_REF__//;
5215:
5216: return (\@array, $string);
1.168 albertel 5217: }
5218:
1.167 albertel 5219: # -------------------------------------------------------------------Temp Store
5220:
1.168 albertel 5221: sub tmpreset {
5222: my ($symb,$namespace,$domain,$stuname) = @_;
5223: if (!$symb) {
5224: $symb=&symbread();
1.620 albertel 5225: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5226: }
5227: $symb=escape($symb);
5228:
1.620 albertel 5229: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5230: $namespace=~s/\//\_/g;
5231: $namespace=~s/\W//g;
5232:
1.620 albertel 5233: if (!$domain) { $domain=$env{'user.domain'}; }
5234: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5235: if ($domain eq 'public' && $stuname eq 'public') {
5236: $stuname=$ENV{'REMOTE_ADDR'};
5237: }
1.1117 foxr 5238: my $path=LONCAPA::tempdir();
1.168 albertel 5239: my %hash;
5240: if (tie(%hash,'GDBM_File',
5241: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5242: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5243: foreach my $key (keys(%hash)) {
1.180 albertel 5244: if ($key=~ /:$symb/) {
1.168 albertel 5245: delete($hash{$key});
5246: }
5247: }
5248: }
5249: }
5250:
1.167 albertel 5251: sub tmpstore {
1.168 albertel 5252: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5253:
5254: if (!$symb) {
5255: $symb=&symbread();
1.620 albertel 5256: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5257: }
5258: $symb=escape($symb);
5259:
5260: if (!$namespace) {
5261: # I don't think we would ever want to store this for a course.
5262: # it seems this will only be used if we don't have a course.
1.620 albertel 5263: #$namespace=$env{'request.course.id'};
1.168 albertel 5264: #if (!$namespace) {
1.620 albertel 5265: $namespace=$env{'request.state'};
1.168 albertel 5266: #}
5267: }
5268: $namespace=~s/\//\_/g;
5269: $namespace=~s/\W//g;
1.620 albertel 5270: if (!$domain) { $domain=$env{'user.domain'}; }
5271: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5272: if ($domain eq 'public' && $stuname eq 'public') {
5273: $stuname=$ENV{'REMOTE_ADDR'};
5274: }
1.168 albertel 5275: my $now=time;
5276: my %hash;
1.1117 foxr 5277: my $path=LONCAPA::tempdir();
1.168 albertel 5278: if (tie(%hash,'GDBM_File',
5279: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5280: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5281: $hash{"version:$symb"}++;
5282: my $version=$hash{"version:$symb"};
5283: my $allkeys='';
5284: foreach my $key (keys(%$storehash)) {
5285: $allkeys.=$key.':';
1.591 albertel 5286: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5287: }
5288: $hash{"$version:$symb:timestamp"}=$now;
5289: $allkeys.='timestamp';
5290: $hash{"$version:keys:$symb"}=$allkeys;
5291: if (untie(%hash)) {
5292: return 'ok';
5293: } else {
5294: return "error:$!";
5295: }
5296: } else {
5297: return "error:$!";
5298: }
5299: }
1.167 albertel 5300:
1.168 albertel 5301: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5302:
1.168 albertel 5303: sub tmprestore {
5304: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5305:
1.168 albertel 5306: if (!$symb) {
5307: $symb=&symbread();
1.620 albertel 5308: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5309: }
5310: $symb=escape($symb);
5311:
1.620 albertel 5312: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5313:
1.620 albertel 5314: if (!$domain) { $domain=$env{'user.domain'}; }
5315: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5316: if ($domain eq 'public' && $stuname eq 'public') {
5317: $stuname=$ENV{'REMOTE_ADDR'};
5318: }
1.168 albertel 5319: my %returnhash;
5320: $namespace=~s/\//\_/g;
5321: $namespace=~s/\W//g;
5322: my %hash;
1.1117 foxr 5323: my $path=LONCAPA::tempdir();
1.168 albertel 5324: if (tie(%hash,'GDBM_File',
5325: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5326: &GDBM_READER(),0640)) {
1.168 albertel 5327: my $version=$hash{"version:$symb"};
5328: $returnhash{'version'}=$version;
5329: my $scope;
5330: for ($scope=1;$scope<=$version;$scope++) {
5331: my $vkeys=$hash{"$scope:keys:$symb"};
5332: my @keys=split(/:/,$vkeys);
5333: my $key;
5334: $returnhash{"$scope:keys"}=$vkeys;
5335: foreach $key (@keys) {
1.591 albertel 5336: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5337: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5338: }
5339: }
1.168 albertel 5340: if (!(untie(%hash))) {
5341: return "error:$!";
5342: }
5343: } else {
5344: return "error:$!";
5345: }
5346: return %returnhash;
1.167 albertel 5347: }
5348:
1.9 www 5349: # ----------------------------------------------------------------------- Store
5350:
5351: sub store {
1.1172.2.64 raeburn 5352: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5353: my $home='';
5354:
1.168 albertel 5355: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5356:
1.213 www 5357: $symb=&symbclean($symb);
1.122 albertel 5358: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5359:
1.620 albertel 5360: if (!$domain) { $domain=$env{'user.domain'}; }
5361: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5362:
5363: &devalidate($symb,$stuname,$domain);
1.109 www 5364:
5365: $symb=escape($symb);
1.187 www 5366: if (!$namespace) {
1.620 albertel 5367: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5368: return '';
5369: }
5370: }
1.620 albertel 5371: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5372:
5373: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5374: $$storehash{'host'}=$perlvar{'lonHostID'};
5375:
1.12 www 5376: my $namevalue='';
1.800 albertel 5377: foreach my $key (keys(%$storehash)) {
5378: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5379: }
1.12 www 5380: $namevalue=~s/\&$//;
1.187 www 5381: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5382: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5383: }
5384:
1.47 www 5385: # -------------------------------------------------------------- Critical Store
5386:
5387: sub cstore {
1.1172.2.64 raeburn 5388: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5389: my $home='';
5390:
1.168 albertel 5391: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5392:
1.213 www 5393: $symb=&symbclean($symb);
1.122 albertel 5394: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5395:
1.620 albertel 5396: if (!$domain) { $domain=$env{'user.domain'}; }
5397: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5398:
5399: &devalidate($symb,$stuname,$domain);
1.109 www 5400:
5401: $symb=escape($symb);
1.187 www 5402: if (!$namespace) {
1.620 albertel 5403: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5404: return '';
5405: }
5406: }
1.620 albertel 5407: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5408:
5409: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5410: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5411:
1.47 www 5412: my $namevalue='';
1.800 albertel 5413: foreach my $key (keys(%$storehash)) {
5414: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5415: }
1.47 www 5416: $namevalue=~s/\&$//;
1.187 www 5417: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5418: return critical
1.1172.2.64 raeburn 5419: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5420: }
5421:
1.9 www 5422: # --------------------------------------------------------------------- Restore
5423:
5424: sub restore {
1.124 www 5425: my ($symb,$namespace,$domain,$stuname) = @_;
5426: my $home='';
5427:
1.168 albertel 5428: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5429:
1.122 albertel 5430: if (!$symb) {
1.1172.2.26 raeburn 5431: return if ($namespace eq 'courserequests');
5432: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5433: } else {
1.1172.2.26 raeburn 5434: unless ($namespace eq 'courserequests') {
5435: $symb=&escape(&symbclean($symb));
5436: }
1.122 albertel 5437: }
1.188 www 5438: if (!$namespace) {
1.620 albertel 5439: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5440: return '';
5441: }
5442: }
1.620 albertel 5443: if (!$domain) { $domain=$env{'user.domain'}; }
5444: if (!$stuname) { $stuname=$env{'user.name'}; }
5445: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5446: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5447:
1.12 www 5448: my %returnhash=();
1.800 albertel 5449: foreach my $line (split(/\&/,$answer)) {
5450: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5451: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5452: }
1.75 www 5453: my $version;
5454: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5455: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5456: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5457: }
1.75 www 5458: }
1.13 www 5459: return %returnhash;
1.34 www 5460: }
5461:
5462: # ---------------------------------------------------------- Course Description
1.1118 foxr 5463: #
5464: #
1.34 www 5465:
5466: sub coursedescription {
1.731 albertel 5467: my ($courseid,$args)=@_;
1.34 www 5468: $courseid=~s/^\///;
1.49 www 5469: $courseid=~s/\_/\//g;
1.34 www 5470: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5471: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5472: my $normalid=$cdomain.'_'.$cnum;
5473: # need to always cache even if we get errors otherwise we keep
5474: # trying and trying and trying to get the course description.
5475: my %envhash=();
5476: my %returnhash=();
1.731 albertel 5477:
5478: my $expiretime=600;
5479: if ($env{'request.course.id'} eq $normalid) {
5480: $expiretime=120;
5481: }
5482:
5483: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5484: if (!$args->{'freshen_cache'}
5485: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5486: foreach my $key (keys(%env)) {
5487: next if ($key !~ /^\Q$prefix\E(.*)/);
5488: my ($setting) = $1;
5489: $returnhash{$setting} = $env{$key};
5490: }
5491: return %returnhash;
5492: }
5493:
1.1118 foxr 5494: # get the data again
5495:
1.731 albertel 5496: if (!$args->{'one_time'}) {
5497: $envhash{'course.'.$normalid.'.last_cache'}=time;
5498: }
1.811 albertel 5499:
1.34 www 5500: if ($chome ne 'no_host') {
1.302 albertel 5501: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5502: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5503: my $username = $env{'user.name'}; # Defult username
5504: if(defined $args->{'user'}) {
5505: $username = $args->{'user'};
5506: }
1.129 albertel 5507: $returnhash{'home'}= $chome;
5508: $returnhash{'domain'} = $cdomain;
5509: $returnhash{'num'} = $cnum;
1.741 raeburn 5510: if (!defined($returnhash{'type'})) {
5511: $returnhash{'type'} = 'Course';
5512: }
1.130 albertel 5513: while (my ($name,$value) = each %returnhash) {
1.53 www 5514: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5515: }
1.270 www 5516: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5517: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5518: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5519: $envhash{'course.'.$normalid.'.home'}=$chome;
5520: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5521: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5522: }
5523: }
1.731 albertel 5524: if (!$args->{'one_time'}) {
1.949 raeburn 5525: &appenv(\%envhash);
1.731 albertel 5526: }
1.302 albertel 5527: return %returnhash;
1.461 www 5528: }
5529:
1.1080 raeburn 5530: sub update_released_required {
5531: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5532: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5533: $cid = $env{'request.course.id'};
5534: $cdom = $env{'course.'.$cid.'.domain'};
5535: $cnum = $env{'course.'.$cid.'.num'};
5536: $chome = $env{'course.'.$cid.'.home'};
5537: }
5538: if ($needsrelease) {
5539: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5540: my $needsupdate;
5541: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5542: $needsupdate = 1;
5543: } else {
5544: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5545: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5546: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5547: $needsupdate = 1;
5548: }
5549: }
5550: if ($needsupdate) {
5551: my %needshash = (
5552: 'internal.releaserequired' => $needsrelease,
5553: );
5554: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5555: if ($putresult eq 'ok') {
5556: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5557: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5558: if (ref($crsinfo{$cid}) eq 'HASH') {
5559: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5560: &courseidput($cdom,\%crsinfo,$chome,'notime');
5561: }
5562: }
5563: }
5564: }
5565: return;
5566: }
5567:
1.461 www 5568: # -------------------------------------------------See if a user is privileged
5569:
5570: sub privileged {
1.1172.2.23 raeburn 5571: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5572: my $now = time;
1.1172.2.23 raeburn 5573: my $roles;
5574: if (ref($possroles) eq 'ARRAY') {
5575: $roles = $possroles;
5576: } else {
5577: $roles = ['dc','su'];
5578: }
5579: if (ref($possdomains) eq 'ARRAY') {
5580: my %privileged = &privileged_by_domain($possdomains,$roles);
5581: foreach my $dom (@{$possdomains}) {
5582: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5583: (ref($privileged{$dom}) eq 'HASH')) {
5584: foreach my $role (@{$roles}) {
5585: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5586: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5587: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5588: return 1 unless (($end && $end < $now) ||
5589: ($start && $start > $now));
5590: }
5591: }
5592: }
5593: }
5594: }
5595: } else {
5596: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5597: my $now = time;
1.1170 droeschl 5598:
1.1172.2.58 raeburn 5599: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5600: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5601: if (grep(/^\Q$trole\E$/,@{$roles})) {
5602: return 1 unless ($tend && $tend < $now)
5603: or ($tstart && $tstart > $now);
1.1170 droeschl 5604: }
1.1172.2.23 raeburn 5605: }
5606: }
1.461 www 5607: return 0;
1.9 www 5608: }
1.1 albertel 5609:
1.1172.2.23 raeburn 5610: sub privileged_by_domain {
5611: my ($domains,$roles) = @_;
5612: my %privileged = ();
5613: my $cachetime = 60*60*24;
5614: my $now = time;
5615: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5616: return %privileged;
5617: }
5618: foreach my $dom (@{$domains}) {
5619: next if (ref($privileged{$dom}) eq 'HASH');
5620: my $needroles;
5621: foreach my $role (@{$roles}) {
5622: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5623: if (defined($cached)) {
5624: if (ref($result) eq 'HASH') {
5625: $privileged{$dom}{$role} = $result;
5626: }
5627: } else {
5628: $needroles = 1;
5629: }
5630: }
5631: if ($needroles) {
5632: my %dompersonnel = &get_domain_roles($dom,$roles);
5633: $privileged{$dom} = {};
5634: foreach my $server (keys(%dompersonnel)) {
5635: if (ref($dompersonnel{$server}) eq 'HASH') {
5636: foreach my $item (keys(%{$dompersonnel{$server}})) {
5637: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5638: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5639: next if ($end && $end < $now);
5640: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5641: $dompersonnel{$server}{$item};
5642: }
5643: }
5644: }
5645: if (ref($privileged{$dom}) eq 'HASH') {
5646: foreach my $role (@{$roles}) {
5647: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5648: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5649: } else {
5650: my %hash = ();
5651: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5652: }
5653: }
5654: }
5655: }
5656: }
5657: return %privileged;
5658: }
5659:
1.103 harris41 5660: # -------------------------------------------------------- Get user privileges
1.11 www 5661:
5662: sub rolesinit {
1.1169 droeschl 5663: my ($domain, $username) = @_;
5664: my %userroles = ('user.login.time' => time);
5665: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5666:
5667: # firstaccess and timerinterval are related to timed maps/resources.
5668: # also, blocking can be triggered by an activating timer
5669: # it's saved in the user's %env.
5670: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5671: my %timerinterval = &dump('timerinterval', $domain, $username);
5672: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5673: %timerintchk, %timerintenv);
5674:
1.1162 raeburn 5675: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5676: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5677: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5678: }
1.1169 droeschl 5679:
1.1162 raeburn 5680: foreach my $key (keys(%timerinterval)) {
5681: my ($cid,$rest) = split(/\0/,$key);
5682: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5683: }
1.1169 droeschl 5684:
1.11 www 5685: my %allroles=();
1.1162 raeburn 5686: my %allgroups=();
1.11 www 5687:
1.1172.2.58 raeburn 5688: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5689: my $role = $rolesdump{$area};
5690: $area =~ s/\_\w\w$//;
5691:
5692: my ($trole, $tend, $tstart, $group_privs);
5693:
5694: if ($role =~ /^cr/) {
5695: # Custom role, defined by a user
5696: # e.g., user.role.cr/msu/smith/mynewrole
5697: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5698: $trole = $1;
5699: ($tend, $tstart) = split('_', $2);
5700: } else {
5701: $trole = $role;
5702: }
5703: } elsif ($role =~ m|^gr/|) {
5704: # Role of member in a group, defined within a course/community
5705: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5706: ($trole, $tend, $tstart) = split(/_/, $role);
5707: next if $tstart eq '-1';
5708: ($trole, $group_privs) = split(/\//, $trole);
5709: $group_privs = &unescape($group_privs);
5710: } else {
5711: # Just a normal role, defined in roles.tab
5712: ($trole, $tend, $tstart) = split(/_/,$role);
5713: }
5714:
5715: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5716: $username);
5717: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5718:
5719: # role expired or not available yet?
5720: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5721: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5722:
5723: next if $area eq '' or $trole eq '';
5724:
5725: my $spec = "$trole.$area";
5726: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5727:
5728: if ($trole =~ /^cr\//) {
5729: # Custom role, defined by a user
5730: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5731: } elsif ($trole eq 'gr') {
5732: # Role of a member in a group, defined within a course/community
5733: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5734: next;
5735: } else {
5736: # Normal role, defined in roles.tab
5737: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5738: }
5739:
5740: my $cid = $tdomain.'_'.$trest;
5741: unless ($firstaccchk{$cid}) {
5742: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5743: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5744: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5745: $coursetimerstarts{$cid}{$item};
5746: }
5747: }
5748: $firstaccchk{$cid} = 1;
5749: }
5750: unless ($timerintchk{$cid}) {
5751: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5752: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5753: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5754: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5755: }
1.12 www 5756: }
1.1169 droeschl 5757: $timerintchk{$cid} = 1;
1.191 harris41 5758: }
1.11 www 5759: }
1.1169 droeschl 5760:
1.1172.2.91 raeburn 5761: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
5762: \%allroles, \%allgroups);
1.1169 droeschl 5763: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 5764: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 5765:
1.1162 raeburn 5766: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5767: }
5768:
1.567 raeburn 5769: sub set_arearole {
1.1172.2.19 raeburn 5770: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5771: unless ($nolog) {
1.567 raeburn 5772: # log the associated role with the area
1.1172.2.19 raeburn 5773: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5774: }
1.743 albertel 5775: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5776: }
5777:
5778: sub custom_roleprivs {
5779: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5780: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5781: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5782: if (&hostname($homsvr) ne '') {
1.567 raeburn 5783: my ($rdummy,$roledef)=
5784: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5785: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5786: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5787: if (defined($syspriv)) {
1.1043 raeburn 5788: if ($trest =~ /^$match_community$/) {
5789: $syspriv =~ s/bre\&S//;
5790: }
1.567 raeburn 5791: $$allroles{'cm./'}.=':'.$syspriv;
5792: $$allroles{$spec.'./'}.=':'.$syspriv;
5793: }
5794: if ($tdomain ne '') {
5795: if (defined($dompriv)) {
5796: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5797: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5798: }
5799: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 5800: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
5801: my $rolename = $1;
5802: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
5803: }
1.567 raeburn 5804: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5805: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5806: }
5807: }
5808: }
5809: }
5810: }
5811:
1.1172.2.89 raeburn 5812: sub course_adhocrole_privs {
5813: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
5814: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
5815: if ($overrides{"internal.adhocpriv.$rolename"}) {
5816: my (%currprivs,%storeprivs);
5817: foreach my $item (split(/:/,$coursepriv)) {
5818: my ($priv,$restrict) = split(/\&/,$item);
5819: $currprivs{$priv} = $restrict;
5820: }
5821: my (%possadd,%possremove,%full);
5822: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
5823: my ($priv,$restrict)=split(/\&/,$item);
5824: $full{$priv} = $restrict;
5825: }
5826: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
5827: next if ($item eq '');
5828: my ($rule,$rest) = split(/=/,$item);
5829: next unless (($rule eq 'off') || ($rule eq 'on'));
5830: foreach my $priv (split(/:/,$rest)) {
5831: if ($priv ne '') {
5832: if ($rule eq 'off') {
5833: $possremove{$priv} = 1;
5834: } else {
5835: $possadd{$priv} = 1;
5836: }
5837: }
5838: }
5839: }
5840: foreach my $priv (sort(keys(%full))) {
5841: if (exists($currprivs{$priv})) {
5842: unless (exists($possremove{$priv})) {
5843: $storeprivs{$priv} = $currprivs{$priv};
5844: }
5845: } elsif (exists($possadd{$priv})) {
5846: $storeprivs{$priv} = $full{$priv};
5847: }
5848: }
5849: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
5850: }
5851: return $coursepriv;
5852: }
5853:
1.678 raeburn 5854: sub group_roleprivs {
5855: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5856: my $access = 1;
5857: my $now = time;
5858: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5859: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5860: if ($access) {
1.811 albertel 5861: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5862: $$allgroups{$course}{$group} .=':'.$group_privs;
5863: }
5864: }
1.567 raeburn 5865:
5866: sub standard_roleprivs {
5867: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5868: if (defined($pr{$trole.':s'})) {
5869: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5870: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5871: }
5872: if ($tdomain ne '') {
5873: if (defined($pr{$trole.':d'})) {
5874: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5875: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5876: }
5877: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5878: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5879: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5880: }
5881: }
5882: }
5883:
5884: sub set_userprivs {
1.1064 raeburn 5885: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5886: my $author=0;
5887: my $adv=0;
1.1172.2.91 raeburn 5888: my $rar=0;
1.678 raeburn 5889: my %grouproles = ();
5890: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5891: my @groupkeys;
1.1000 raeburn 5892: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5893: push(@groupkeys,$role);
5894: }
5895: if (ref($groups_roles) eq 'HASH') {
5896: foreach my $key (keys(%{$groups_roles})) {
5897: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5898: push(@groupkeys,$key);
5899: }
5900: }
5901: }
5902: if (@groupkeys > 0) {
5903: foreach my $role (@groupkeys) {
5904: my ($trole,$area,$sec,$extendedarea);
5905: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5906: $trole = $1;
5907: $area = $2;
5908: $sec = $3;
5909: $extendedarea = $area.$sec;
5910: if (exists($$allgroups{$area})) {
5911: foreach my $group (keys(%{$$allgroups{$area}})) {
5912: my $spec = $trole.'.'.$extendedarea;
5913: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5914: $$allgroups{$area}{$group};
1.1064 raeburn 5915: }
1.678 raeburn 5916: }
5917: }
5918: }
5919: }
5920: }
1.800 albertel 5921: foreach my $group (keys(%grouproles)) {
5922: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5923: }
1.800 albertel 5924: foreach my $role (keys(%{$allroles})) {
5925: my %thesepriv;
1.941 raeburn 5926: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5927: foreach my $item (split(/:/,$$allroles{$role})) {
5928: if ($item ne '') {
5929: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5930: if ($restrictions eq '') {
5931: $thesepriv{$privilege}='F';
5932: } elsif ($thesepriv{$privilege} ne 'F') {
5933: $thesepriv{$privilege}.=$restrictions;
5934: }
5935: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 5936: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 5937: }
5938: }
5939: my $thesestr='';
1.1104 raeburn 5940: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5941: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5942: }
5943: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5944: }
1.1172.2.91 raeburn 5945: return ($author,$adv,$rar);
1.567 raeburn 5946: }
5947:
1.994 raeburn 5948: sub role_status {
1.1104 raeburn 5949: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5950: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5951: my ($one,$two) = split(m{\./},$rolekey,2);
5952: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5953: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5954: $$where = '/'.$two;
1.994 raeburn 5955: $$trolecode=$$role.'.'.$$where;
5956: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5957: $$tstatus='is';
1.1104 raeburn 5958: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5959: $$tstatus='future';
1.1034 raeburn 5960: if ($$tstart<$now) {
5961: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5962: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5963: my (%allroles,%allgroups,$group_privs,
5964: %groups_roles,@rolecodes);
1.1002 raeburn 5965: my %userroles = (
5966: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5967: );
1.1064 raeburn 5968: @rolecodes = ('cm');
1.1002 raeburn 5969: my $spec=$$role.'.'.$$where;
5970: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5971: if ($$role =~ /^cr\//) {
5972: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5973: push(@rolecodes,'cr');
1.1002 raeburn 5974: } elsif ($$role eq 'gr') {
1.1064 raeburn 5975: push(@rolecodes,$$role);
1.1002 raeburn 5976: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5977: $env{'user.name'});
1.1064 raeburn 5978: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5979: (undef,my $group_privs) = split(/\//,$trole);
5980: $group_privs = &unescape($group_privs);
5981: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5982: 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 5983: &get_groups_roles($tdomain,$trest,
5984: \%course_roles,\@rolecodes,
5985: \%groups_roles);
1.1002 raeburn 5986: } else {
1.1064 raeburn 5987: push(@rolecodes,$$role);
1.1002 raeburn 5988: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5989: }
1.1172.2.91 raeburn 5990: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
5991: \%groups_roles);
1.1064 raeburn 5992: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 5993: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 5994: }
5995: }
1.1034 raeburn 5996: $$tstatus = 'is';
1.1002 raeburn 5997: }
1.994 raeburn 5998: }
5999: if ($$tend) {
1.1104 raeburn 6000: if ($$tend<$update) {
1.994 raeburn 6001: $$tstatus='expired';
6002: } elsif ($$tend<$now) {
6003: $$tstatus='will_not';
6004: }
6005: }
6006: }
6007: }
6008: }
6009:
1.1104 raeburn 6010: sub get_groups_roles {
6011: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6012: return unless((ref($cdom_courseroles) eq 'HASH') &&
6013: (ref($rolecodes) eq 'ARRAY') &&
6014: (ref($groups_roles) eq 'HASH'));
6015: if (keys(%{$cdom_courseroles}) > 0) {
6016: my ($cnum) = ($rest =~ /^($match_courseid)/);
6017: if ($cdom ne '' && $cnum ne '') {
6018: foreach my $key (keys(%{$cdom_courseroles})) {
6019: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6020: my $crsrole = $1;
6021: my $crssec = $2;
6022: if ($crsrole =~ /^cr/) {
6023: unless (grep(/^cr$/,@{$rolecodes})) {
6024: push(@{$rolecodes},'cr');
6025: }
6026: } else {
6027: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6028: push(@{$rolecodes},$crsrole);
6029: }
6030: }
6031: my $rolekey = "$crsrole./$cdom/$cnum";
6032: if ($crssec ne '') {
6033: $rolekey .= "/$crssec";
6034: }
6035: $rolekey .= './';
6036: $groups_roles->{$rolekey} = $rolecodes;
6037: }
6038: }
6039: }
6040: }
6041: return;
6042: }
6043:
6044: sub delete_env_groupprivs {
6045: my ($where,$courseroles,$possroles) = @_;
6046: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6047: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6048: unless (ref($courseroles->{$udom}) eq 'HASH') {
6049: %{$courseroles->{$udom}} =
6050: &get_my_roles('','','userroles',['active'],
6051: $possroles,[$udom],1);
6052: }
6053: if (ref($courseroles->{$udom}) eq 'HASH') {
6054: foreach my $item (keys(%{$courseroles->{$udom}})) {
6055: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6056: my $area = '/'.$cdom.'/'.$cnum;
6057: my $privkey = "user.priv.$crsrole.$area";
6058: if ($crssec ne '') {
6059: $privkey .= '/'.$crssec;
6060: }
6061: $privkey .= ".$area/$group";
6062: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6063: }
6064: }
6065: return;
6066: }
6067:
1.994 raeburn 6068: sub check_adhoc_privs {
1.1172.2.86 raeburn 6069: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6070: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6071: if ($sec) {
6072: $cckey .= '/'.$sec;
6073: }
1.1172.2.9 raeburn 6074: my $setprivs;
1.994 raeburn 6075: if ($env{$cckey}) {
6076: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6077: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6078: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6079: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6080: $setprivs = 1;
1.994 raeburn 6081: }
6082: } else {
1.1172.2.87 raeburn 6083: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6084: $setprivs = 1;
1.994 raeburn 6085: }
1.1172.2.9 raeburn 6086: return $setprivs;
1.994 raeburn 6087: }
6088:
6089: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6090: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6091: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6092: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6093: if ($sec ne '') {
6094: $area .= '/'.$sec;
6095: }
1.994 raeburn 6096: my $spec = $role.'.'.$area;
6097: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6098: $env{'user.name'},1);
1.1172.2.84 raeburn 6099: my %rolehash = ();
1.1172.2.89 raeburn 6100: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6101: my $rolename = $1;
1.1172.2.84 raeburn 6102: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6103: my %domdef = &get_domain_defaults($dcdom);
6104: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6105: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6106: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6107: }
6108: }
1.1172.2.84 raeburn 6109: } else {
6110: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6111: }
1.1172.2.91 raeburn 6112: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6113: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6114: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6115: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6116: &appenv( {'request.role' => $spec,
6117: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6118: 'request.course.sec' => $sec,
1.1088 raeburn 6119: }
6120: );
6121: my $tadv=0;
6122: if (&allowed('adv') eq 'F') { $tadv=1; }
6123: &appenv({'request.role.adv' => $tadv});
6124: }
1.994 raeburn 6125: }
6126:
1.12 www 6127: # --------------------------------------------------------------- get interface
6128:
6129: sub get {
1.131 albertel 6130: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6131: my $items='';
1.800 albertel 6132: foreach my $item (@$storearr) {
6133: $items.=&escape($item).'&';
1.191 harris41 6134: }
1.12 www 6135: $items=~s/\&$//;
1.620 albertel 6136: if (!$udomain) { $udomain=$env{'user.domain'}; }
6137: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6138: my $uhome=&homeserver($uname,$udomain);
6139:
1.133 albertel 6140: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6141: my @pairs=split(/\&/,$rep);
1.273 albertel 6142: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6143: return @pairs;
6144: }
1.15 www 6145: my %returnhash=();
1.42 www 6146: my $i=0;
1.800 albertel 6147: foreach my $item (@$storearr) {
6148: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6149: $i++;
1.191 harris41 6150: }
1.15 www 6151: return %returnhash;
1.27 www 6152: }
6153:
6154: # --------------------------------------------------------------- del interface
6155:
6156: sub del {
1.133 albertel 6157: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6158: my $items='';
1.800 albertel 6159: foreach my $item (@$storearr) {
6160: $items.=&escape($item).'&';
1.191 harris41 6161: }
1.984 neumanie 6162:
1.27 www 6163: $items=~s/\&$//;
1.620 albertel 6164: if (!$udomain) { $udomain=$env{'user.domain'}; }
6165: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6166: my $uhome=&homeserver($uname,$udomain);
6167: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6168: }
6169:
6170: # -------------------------------------------------------------- dump interface
6171:
1.1172.2.22 raeburn 6172: sub unserialize {
6173: my ($rep, $escapedkeys) = @_;
6174:
6175: return {} if $rep =~ /^error/;
6176:
6177: my %returnhash=();
6178: foreach my $item (split(/\&/,$rep)) {
6179: my ($key, $value) = split(/=/, $item, 2);
6180: $key = unescape($key) unless $escapedkeys;
6181: next if $key =~ /^error: 2 /;
6182: $returnhash{$key} = &thaw_unescape($value);
6183: }
6184: return \%returnhash;
6185: }
6186:
6187: # see Lond::dump_with_regexp
6188: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6189: sub dump {
1.1172.2.22 raeburn 6190: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6191: if (!$udomain) { $udomain=$env{'user.domain'}; }
6192: if (!$uname) { $uname=$env{'user.name'}; }
6193: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6194:
1.1172.2.55 raeburn 6195: if ($regexp) {
6196: $regexp=&escape($regexp);
6197: } else {
6198: $regexp='.';
6199: }
1.1172.2.22 raeburn 6200: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6201: # user is hosted on this machine
1.1172.2.55 raeburn 6202: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6203: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6204: return %{&unserialize($reply, $escapedkeys)};
6205: }
1.1166 raeburn 6206: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6207: my @pairs=split(/\&/,$rep);
6208: my %returnhash=();
1.1098 foxr 6209: if (!($rep =~ /^error/ )) {
6210: foreach my $item (@pairs) {
6211: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6212: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6213: next if ($key =~ /^error: 2 /);
6214: $returnhash{$key}=&thaw_unescape($value);
6215: }
1.755 albertel 6216: }
6217: return %returnhash;
1.407 www 6218: }
6219:
1.1098 foxr 6220:
1.717 albertel 6221: # --------------------------------------------------------- dumpstore interface
6222:
6223: sub dumpstore {
6224: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6225: # same as dump but keys must be escaped. They may contain colon separated
6226: # lists of values that may themself contain colons (e.g. symbs).
6227: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6228: }
6229:
1.407 www 6230: # -------------------------------------------------------------- keys interface
6231:
6232: sub getkeys {
6233: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6234: if (!$udomain) { $udomain=$env{'user.domain'}; }
6235: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6236: my $uhome=&homeserver($uname,$udomain);
6237: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6238: my @keyarray=();
1.800 albertel 6239: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6240: next if ($key =~ /^error: 2 /);
1.800 albertel 6241: push(@keyarray,&unescape($key));
1.407 www 6242: }
6243: return @keyarray;
1.318 matthew 6244: }
6245:
1.319 matthew 6246: # --------------------------------------------------------------- currentdump
6247: sub currentdump {
1.328 matthew 6248: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6249: $courseid = $env{'request.course.id'} if (! defined($courseid));
6250: $sdom = $env{'user.domain'} if (! defined($sdom));
6251: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6252: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6253: my $rep;
6254:
6255: if (grep { $_ eq $uhome } current_machine_ids()) {
6256: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6257: $courseid)));
6258: } else {
6259: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6260: }
6261:
1.318 matthew 6262: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6263: #
1.318 matthew 6264: my %returnhash=();
1.319 matthew 6265: #
6266: if ($rep eq "unknown_cmd") {
6267: # an old lond will not know currentdump
6268: # Do a dump and make it look like a currentdump
1.822 albertel 6269: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6270: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6271: my %hash = @tmp;
6272: @tmp=();
1.424 matthew 6273: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6274: } else {
6275: my @pairs=split(/\&/,$rep);
1.800 albertel 6276: foreach my $pair (@pairs) {
6277: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6278: my ($symb,$param) = split(/:/,$key);
6279: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6280: &thaw_unescape($value);
1.319 matthew 6281: }
1.191 harris41 6282: }
1.12 www 6283: return %returnhash;
1.424 matthew 6284: }
6285:
6286: sub convert_dump_to_currentdump{
6287: my %hash = %{shift()};
6288: my %returnhash;
6289: # Code ripped from lond, essentially. The only difference
6290: # here is the unescaping done by lonnet::dump(). Conceivably
6291: # we might run in to problems with parameter names =~ /^v\./
6292: while (my ($key,$value) = each(%hash)) {
6293: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6294: $symb = &unescape($symb);
6295: $param = &unescape($param);
1.424 matthew 6296: next if ($v eq 'version' || $symb eq 'keys');
6297: next if (exists($returnhash{$symb}) &&
6298: exists($returnhash{$symb}->{$param}) &&
6299: $returnhash{$symb}->{'v.'.$param} > $v);
6300: $returnhash{$symb}->{$param}=$value;
6301: $returnhash{$symb}->{'v.'.$param}=$v;
6302: }
6303: #
6304: # Remove all of the keys in the hashes which keep track of
6305: # the version of the parameter.
6306: while (my ($symb,$param_hash) = each(%returnhash)) {
6307: # use a foreach because we are going to delete from the hash.
6308: foreach my $key (keys(%$param_hash)) {
6309: delete($param_hash->{$key}) if ($key =~ /^v\./);
6310: }
6311: }
6312: return \%returnhash;
1.12 www 6313: }
6314:
1.627 albertel 6315: # ------------------------------------------------------ critical inc interface
6316:
6317: sub cinc {
6318: return &inc(@_,'critical');
6319: }
6320:
1.449 matthew 6321: # --------------------------------------------------------------- inc interface
6322:
6323: sub inc {
1.627 albertel 6324: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6325: if (!$udomain) { $udomain=$env{'user.domain'}; }
6326: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6327: my $uhome=&homeserver($uname,$udomain);
6328: my $items='';
6329: if (! ref($store)) {
6330: # got a single value, so use that instead
6331: $items = &escape($store).'=&';
6332: } elsif (ref($store) eq 'SCALAR') {
6333: $items = &escape($$store).'=&';
6334: } elsif (ref($store) eq 'ARRAY') {
6335: $items = join('=&',map {&escape($_);} @{$store});
6336: } elsif (ref($store) eq 'HASH') {
6337: while (my($key,$value) = each(%{$store})) {
6338: $items.= &escape($key).'='.&escape($value).'&';
6339: }
6340: }
6341: $items=~s/\&$//;
1.627 albertel 6342: if ($critical) {
6343: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6344: } else {
6345: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6346: }
1.449 matthew 6347: }
6348:
1.12 www 6349: # --------------------------------------------------------------- put interface
6350:
6351: sub put {
1.134 albertel 6352: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6353: if (!$udomain) { $udomain=$env{'user.domain'}; }
6354: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6355: my $uhome=&homeserver($uname,$udomain);
1.12 www 6356: my $items='';
1.800 albertel 6357: foreach my $item (keys(%$storehash)) {
6358: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6359: }
1.12 www 6360: $items=~s/\&$//;
1.134 albertel 6361: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6362: }
6363:
1.631 albertel 6364: # ------------------------------------------------------------ newput interface
6365:
6366: sub newput {
6367: my ($namespace,$storehash,$udomain,$uname)=@_;
6368: if (!$udomain) { $udomain=$env{'user.domain'}; }
6369: if (!$uname) { $uname=$env{'user.name'}; }
6370: my $uhome=&homeserver($uname,$udomain);
6371: my $items='';
6372: foreach my $key (keys(%$storehash)) {
6373: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6374: }
6375: $items=~s/\&$//;
6376: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6377: }
6378:
6379: # --------------------------------------------------------- putstore interface
6380:
1.524 raeburn 6381: sub putstore {
1.1172.2.59 raeburn 6382: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6383: if (!$udomain) { $udomain=$env{'user.domain'}; }
6384: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6385: my $uhome=&homeserver($uname,$udomain);
6386: my $items='';
1.715 albertel 6387: foreach my $key (keys(%$storehash)) {
6388: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6389: }
1.715 albertel 6390: $items=~s/\&$//;
1.716 albertel 6391: my $esc_symb=&escape($symb);
6392: my $esc_v=&escape($version);
1.715 albertel 6393: my $reply =
1.716 albertel 6394: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6395: $uhome);
1.1172.2.59 raeburn 6396: if (($tolog) && ($reply eq 'ok')) {
6397: my $namevalue='';
6398: foreach my $key (keys(%{$storehash})) {
6399: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6400: }
6401: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6402: '&host='.&escape($perlvar{'lonHostID'}).
6403: '&version='.$esc_v.
6404: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6405: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6406: }
1.715 albertel 6407: if ($reply eq 'unknown_cmd') {
1.716 albertel 6408: # gfall back to way things use to be done
1.715 albertel 6409: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6410: $uname);
1.524 raeburn 6411: }
1.715 albertel 6412: return $reply;
6413: }
6414:
6415: sub old_putstore {
1.716 albertel 6416: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6417: if (!$udomain) { $udomain=$env{'user.domain'}; }
6418: if (!$uname) { $uname=$env{'user.name'}; }
6419: my $uhome=&homeserver($uname,$udomain);
6420: my %newstorehash;
1.800 albertel 6421: foreach my $item (keys(%$storehash)) {
6422: my $key = $version.':'.&escape($symb).':'.$item;
6423: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6424: }
6425: my $items='';
6426: my %allitems = ();
1.800 albertel 6427: foreach my $item (keys(%newstorehash)) {
6428: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6429: my $key = $1.':keys:'.$2;
6430: $allitems{$key} .= $3.':';
6431: }
1.800 albertel 6432: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6433: }
1.800 albertel 6434: foreach my $item (keys(%allitems)) {
6435: $allitems{$item} =~ s/\:$//;
6436: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6437: }
6438: $items=~s/\&$//;
6439: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6440: }
6441:
1.47 www 6442: # ------------------------------------------------------ critical put interface
6443:
6444: sub cput {
1.134 albertel 6445: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6446: if (!$udomain) { $udomain=$env{'user.domain'}; }
6447: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6448: my $uhome=&homeserver($uname,$udomain);
1.47 www 6449: my $items='';
1.800 albertel 6450: foreach my $item (keys(%$storehash)) {
6451: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6452: }
1.47 www 6453: $items=~s/\&$//;
1.134 albertel 6454: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6455: }
6456:
6457: # -------------------------------------------------------------- eget interface
6458:
6459: sub eget {
1.133 albertel 6460: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6461: my $items='';
1.800 albertel 6462: foreach my $item (@$storearr) {
6463: $items.=&escape($item).'&';
1.191 harris41 6464: }
1.12 www 6465: $items=~s/\&$//;
1.620 albertel 6466: if (!$udomain) { $udomain=$env{'user.domain'}; }
6467: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6468: my $uhome=&homeserver($uname,$udomain);
6469: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6470: my @pairs=split(/\&/,$rep);
6471: my %returnhash=();
1.42 www 6472: my $i=0;
1.800 albertel 6473: foreach my $item (@$storearr) {
6474: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6475: $i++;
1.191 harris41 6476: }
1.12 www 6477: return %returnhash;
6478: }
6479:
1.667 albertel 6480: # ------------------------------------------------------------ tmpput interface
6481: sub tmpput {
1.802 raeburn 6482: my ($storehash,$server,$context)=@_;
1.667 albertel 6483: my $items='';
1.800 albertel 6484: foreach my $item (keys(%$storehash)) {
6485: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6486: }
6487: $items=~s/\&$//;
1.802 raeburn 6488: if (defined($context)) {
6489: $items .= ':'.&escape($context);
6490: }
1.667 albertel 6491: return &reply("tmpput:$items",$server);
6492: }
6493:
6494: # ------------------------------------------------------------ tmpget interface
6495: sub tmpget {
1.688 albertel 6496: my ($token,$server)=@_;
6497: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6498: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6499: my %returnhash;
1.1172.2.85 raeburn 6500: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6501: return %returnhash;
6502: }
1.667 albertel 6503: foreach my $item (split(/\&/,$rep)) {
6504: my ($key,$value)=split(/=/,$item);
6505: $returnhash{&unescape($key)}=&thaw_unescape($value);
6506: }
6507: return %returnhash;
6508: }
6509:
1.1113 raeburn 6510: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6511: sub tmpdel {
6512: my ($token,$server)=@_;
6513: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6514: return &reply("tmpdel:$token",$server);
6515: }
6516:
1.1172.2.13 raeburn 6517: # ------------------------------------------------------------ get_timebased_id
6518:
6519: sub get_timebased_id {
6520: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6521: $maxtries) = @_;
6522: my ($newid,$error,$dellock);
6523: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6524: return ('','ok','invalid call to get suffix');
6525: }
6526:
6527: # set defaults for any optional args for which values were not supplied
6528: if ($who eq '') {
6529: $who = $env{'user.name'}.':'.$env{'user.domain'};
6530: }
6531: if (!$locktries) {
6532: $locktries = 3;
6533: }
6534: if (!$maxtries) {
6535: $maxtries = 10;
6536: }
6537:
6538: if (($cdom eq '') || ($cnum eq '')) {
6539: if ($env{'request.course.id'}) {
6540: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6541: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6542: }
6543: if (($cdom eq '') || ($cnum eq '')) {
6544: return ('','ok','call to get suffix not in course context');
6545: }
6546: }
6547:
6548: # construct locking item
6549: my $lockhash = {
6550: $prefix."\0".'locked_'.$keyid => $who,
6551: };
6552: my $tries = 0;
6553:
6554: # attempt to get lock on nohist_$namespace file
6555: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6556: while (($gotlock ne 'ok') && $tries <$locktries) {
6557: $tries ++;
6558: sleep 1;
6559: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6560: }
6561:
6562: # attempt to get unique identifier, based on current timestamp
6563: if ($gotlock eq 'ok') {
6564: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6565: my $id = time;
6566: $newid = $id;
1.1172.2.56 raeburn 6567: if ($idtype eq 'addcode') {
6568: $newid .= &sixnum_code();
6569: }
1.1172.2.13 raeburn 6570: my $idtries = 0;
6571: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6572: if ($idtype eq 'concat') {
6573: $newid = $id.$idtries;
1.1172.2.56 raeburn 6574: } elsif ($idtype eq 'addcode') {
6575: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6576: } else {
6577: $newid ++;
6578: }
6579: $idtries ++;
6580: }
6581: if (!exists($inuse{$prefix."\0".$newid})) {
6582: my %new_item = (
6583: $prefix."\0".$newid => $who,
6584: );
6585: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6586: $cdom,$cnum);
6587: if ($putresult ne 'ok') {
6588: undef($newid);
6589: $error = 'error saving new item: '.$putresult;
6590: }
6591: } else {
1.1172.2.56 raeburn 6592: undef($newid);
1.1172.2.13 raeburn 6593: $error = ('error: no unique suffix available for the new item ');
6594: }
6595: # remove lock
6596: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6597: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6598: } else {
6599: $error = "error: could not obtain lockfile\n";
6600: $dellock = 'ok';
1.1172.2.58 raeburn 6601: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6602: $dellock = 'nolock';
6603: }
1.1172.2.13 raeburn 6604: }
6605: return ($newid,$dellock,$error);
6606: }
6607:
1.1172.2.56 raeburn 6608: sub sixnum_code {
6609: my $code;
6610: for (0..6) {
6611: $code .= int( rand(9) );
6612: }
6613: return $code;
6614: }
6615:
1.765 albertel 6616: # -------------------------------------------------- portfolio access checking
6617:
6618: sub portfolio_access {
1.1172.2.77 raeburn 6619: my ($requrl,$clientip) = @_;
1.765 albertel 6620: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 6621: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6622: if ($result) {
6623: my %setters;
6624: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6625: my ($startblock,$endblock) =
6626: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6627: if ($startblock && $endblock) {
6628: return 'B';
6629: }
6630: } else {
6631: my ($startblock,$endblock) =
6632: &Apache::loncommon::blockcheck(\%setters,'port');
6633: if ($startblock && $endblock) {
6634: return 'B';
6635: }
6636: }
6637: }
1.765 albertel 6638: if ($result eq 'ok') {
1.766 albertel 6639: return 'F';
1.765 albertel 6640: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6641: return 'A';
1.765 albertel 6642: }
1.766 albertel 6643: return '';
1.765 albertel 6644: }
6645:
6646: sub get_portfolio_access {
1.1172.2.77 raeburn 6647: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6648:
6649: if (!ref($access_hash)) {
6650: my $current_perms = &get_portfile_permissions($udom,$unum);
6651: my %access_controls = &get_access_controls($current_perms,$group,
6652: $file_name);
6653: $access_hash = $access_controls{$file_name};
6654: }
6655:
1.1172.2.77 raeburn 6656: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6657: my $now = time;
6658: if (ref($access_hash) eq 'HASH') {
6659: foreach my $key (keys(%{$access_hash})) {
6660: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6661: if ($start > $now) {
6662: next;
6663: }
6664: if ($end && $end<$now) {
6665: next;
6666: }
6667: if ($scope eq 'public') {
6668: $public = $key;
6669: last;
6670: } elsif ($scope eq 'guest') {
6671: $guest = $key;
6672: } elsif ($scope eq 'domains') {
6673: push(@domains,$key);
6674: } elsif ($scope eq 'users') {
6675: push(@users,$key);
6676: } elsif ($scope eq 'course') {
6677: push(@courses,$key);
6678: } elsif ($scope eq 'group') {
6679: push(@groups,$key);
1.1172.2.77 raeburn 6680: } elsif ($scope eq 'ip') {
6681: push(@ips,$key);
1.765 albertel 6682: }
6683: }
6684: if ($public) {
6685: return 'ok';
1.1172.2.77 raeburn 6686: } elsif (@ips > 0) {
6687: my $allowed;
6688: foreach my $ipkey (@ips) {
6689: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6690: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6691: $allowed = 1;
6692: last;
6693: }
6694: }
6695: }
6696: if ($allowed) {
6697: return 'ok';
6698: }
1.765 albertel 6699: }
6700: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6701: if ($guest) {
6702: return $guest;
6703: }
6704: } else {
6705: if (@domains > 0) {
6706: foreach my $domkey (@domains) {
6707: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6708: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6709: return 'ok';
6710: }
6711: }
6712: }
6713: }
6714: if (@users > 0) {
6715: foreach my $userkey (@users) {
1.865 raeburn 6716: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6717: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6718: if (ref($item) eq 'HASH') {
6719: if (($item->{'uname'} eq $env{'user.name'}) &&
6720: ($item->{'udom'} eq $env{'user.domain'})) {
6721: return 'ok';
6722: }
6723: }
6724: }
6725: }
1.765 albertel 6726: }
6727: }
6728: my %roleshash;
6729: my @courses_and_groups = @courses;
6730: push(@courses_and_groups,@groups);
6731: if (@courses_and_groups > 0) {
6732: my (%allgroups,%allroles);
6733: my ($start,$end,$role,$sec,$group);
6734: foreach my $envkey (%env) {
1.1060 raeburn 6735: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6736: my $cid = $2.'_'.$3;
6737: if ($1 eq 'gr') {
6738: $group = $4;
6739: $allgroups{$cid}{$group} = $env{$envkey};
6740: } else {
6741: if ($4 eq '') {
6742: $sec = 'none';
6743: } else {
6744: $sec = $4;
6745: }
6746: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6747: }
1.811 albertel 6748: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6749: my $cid = $2.'_'.$3;
6750: if ($4 eq '') {
6751: $sec = 'none';
6752: } else {
6753: $sec = $4;
6754: }
6755: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6756: }
6757: }
6758: if (keys(%allroles) == 0) {
6759: return;
6760: }
6761: foreach my $key (@courses_and_groups) {
6762: my %content = %{$$access_hash{$key}};
6763: my $cnum = $content{'number'};
6764: my $cdom = $content{'domain'};
6765: my $cid = $cdom.'_'.$cnum;
6766: if (!exists($allroles{$cid})) {
6767: next;
6768: }
6769: foreach my $role_id (keys(%{$content{'roles'}})) {
6770: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6771: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6772: my @status = @{$content{'roles'}{$role_id}{'access'}};
6773: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6774: foreach my $role (keys(%{$allroles{$cid}})) {
6775: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6776: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6777: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6778: if (grep/^all$/,@sections) {
6779: return 'ok';
6780: } else {
6781: if (grep/^$sec$/,@sections) {
6782: return 'ok';
6783: }
6784: }
6785: }
6786: }
6787: if (keys(%{$allgroups{$cid}}) == 0) {
6788: if (grep/^none$/,@groups) {
6789: return 'ok';
6790: }
6791: } else {
6792: if (grep/^all$/,@groups) {
6793: return 'ok';
6794: }
6795: foreach my $group (keys(%{$allgroups{$cid}})) {
6796: if (grep/^$group$/,@groups) {
6797: return 'ok';
6798: }
6799: }
6800: }
6801: }
6802: }
6803: }
6804: }
6805: }
6806: if ($guest) {
6807: return $guest;
6808: }
6809: }
6810: }
6811: return;
6812: }
6813:
6814: sub course_group_datechecker {
6815: my ($dates,$now,$status) = @_;
6816: my ($start,$end) = split(/\./,$dates);
6817: if (!$start && !$end) {
6818: return 'ok';
6819: }
6820: if (grep/^active$/,@{$status}) {
6821: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6822: return 'ok';
6823: }
6824: }
6825: if (grep/^previous$/,@{$status}) {
6826: if ($end > $now ) {
6827: return 'ok';
6828: }
6829: }
6830: if (grep/^future$/,@{$status}) {
6831: if ($start > $now) {
6832: return 'ok';
6833: }
6834: }
6835: return;
6836: }
6837:
6838: sub parse_portfolio_url {
6839: my ($url) = @_;
6840:
6841: my ($type,$udom,$unum,$group,$file_name);
6842:
1.823 albertel 6843: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6844: $type = 1;
6845: $udom = $1;
6846: $unum = $2;
6847: $file_name = $3;
1.823 albertel 6848: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6849: $type = 2;
6850: $udom = $1;
6851: $unum = $2;
6852: $group = $3;
6853: $file_name = $3.'/'.$4;
6854: }
6855: if (wantarray) {
6856: return ($type,$udom,$unum,$file_name,$group);
6857: }
6858: return $type;
6859: }
6860:
6861: sub is_portfolio_url {
6862: my ($url) = @_;
6863: return scalar(&parse_portfolio_url($url));
6864: }
6865:
1.798 raeburn 6866: sub is_portfolio_file {
6867: my ($file) = @_;
1.820 raeburn 6868: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6869: return 1;
6870: }
6871: return;
6872: }
6873:
1.976 raeburn 6874: sub usertools_access {
1.1084 raeburn 6875: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6876: my ($access,%tools);
6877: if ($context eq '') {
6878: $context = 'tools';
6879: }
6880: if ($context eq 'requestcourses') {
6881: %tools = (
6882: official => 1,
6883: unofficial => 1,
1.1006 raeburn 6884: community => 1,
1.1172.2.37 raeburn 6885: textbook => 1,
1.985 raeburn 6886: );
1.1172.2.9 raeburn 6887: } elsif ($context eq 'requestauthor') {
6888: %tools = (
6889: requestauthor => 1,
6890: );
1.985 raeburn 6891: } else {
6892: %tools = (
6893: aboutme => 1,
6894: blog => 1,
1.1172.2.6 raeburn 6895: webdav => 1,
1.985 raeburn 6896: portfolio => 1,
6897: );
6898: }
1.976 raeburn 6899: return if (!defined($tools{$tool}));
6900:
1.1172.2.35 raeburn 6901: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6902: $udom = $env{'user.domain'};
6903: $uname = $env{'user.name'};
6904: }
6905:
1.978 raeburn 6906: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6907: if ($action ne 'reload') {
1.985 raeburn 6908: if ($context eq 'requestcourses') {
6909: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6910: } elsif ($context eq 'requestauthor') {
6911: return $env{'environment.canrequest.author'};
1.985 raeburn 6912: } else {
6913: return $env{'environment.availabletools.'.$tool};
6914: }
6915: }
1.976 raeburn 6916: }
6917:
1.1172.2.9 raeburn 6918: my ($toolstatus,$inststatus,$envkey);
6919: if ($context eq 'requestauthor') {
6920: $envkey = $context;
6921: } else {
6922: $envkey = $context.'.'.$tool;
6923: }
1.976 raeburn 6924:
1.985 raeburn 6925: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6926: ($action ne 'reload')) {
1.1172.2.9 raeburn 6927: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6928: $inststatus = $env{'environment.inststatus'};
6929: } else {
1.1084 raeburn 6930: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6931: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6932: $inststatus = $userenvref->{'inststatus'};
6933: } else {
1.1172.2.9 raeburn 6934: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6935: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6936: $inststatus = $userenv{'inststatus'};
6937: }
1.976 raeburn 6938: }
6939:
6940: if ($toolstatus ne '') {
6941: if ($toolstatus) {
6942: $access = 1;
6943: } else {
6944: $access = 0;
6945: }
6946: return $access;
6947: }
6948:
1.1084 raeburn 6949: my ($is_adv,%domdef);
6950: if (ref($is_advref) eq 'HASH') {
6951: $is_adv = $is_advref->{'is_adv'};
6952: } else {
6953: $is_adv = &is_advanced_user($udom,$uname);
6954: }
6955: if (ref($domdefref) eq 'HASH') {
6956: %domdef = %{$domdefref};
6957: } else {
6958: %domdef = &get_domain_defaults($udom);
6959: }
1.976 raeburn 6960: if (ref($domdef{$tool}) eq 'HASH') {
6961: if ($is_adv) {
6962: if ($domdef{$tool}{'_LC_adv'} ne '') {
6963: if ($domdef{$tool}{'_LC_adv'}) {
6964: $access = 1;
6965: } else {
6966: $access = 0;
6967: }
6968: return $access;
6969: }
6970: }
6971: if ($inststatus ne '') {
6972: my ($hasaccess,$hasnoaccess);
6973: foreach my $affiliation (split(/:/,$inststatus)) {
6974: if ($domdef{$tool}{$affiliation} ne '') {
6975: if ($domdef{$tool}{$affiliation}) {
6976: $hasaccess = 1;
6977: } else {
6978: $hasnoaccess = 1;
6979: }
6980: }
6981: }
6982: if ($hasaccess || $hasnoaccess) {
6983: if ($hasaccess) {
6984: $access = 1;
6985: } elsif ($hasnoaccess) {
6986: $access = 0;
6987: }
6988: return $access;
6989: }
6990: } else {
6991: if ($domdef{$tool}{'default'} ne '') {
6992: if ($domdef{$tool}{'default'}) {
6993: $access = 1;
6994: } elsif ($domdef{$tool}{'default'} == 0) {
6995: $access = 0;
6996: }
6997: return $access;
6998: }
6999: }
7000: } else {
1.1172.2.6 raeburn 7001: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7002: $access = 1;
7003: } else {
7004: $access = 0;
7005: }
1.976 raeburn 7006: return $access;
7007: }
7008: }
7009:
1.1050 raeburn 7010: sub is_course_owner {
7011: my ($cdom,$cnum,$udom,$uname) = @_;
7012: if (($udom eq '') || ($uname eq '')) {
7013: $udom = $env{'user.domain'};
7014: $uname = $env{'user.name'};
7015: }
7016: unless (($udom eq '') || ($uname eq '')) {
7017: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7018: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7019: return 1;
7020: } else {
7021: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7022: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7023: return 1;
7024: }
7025: }
7026: }
7027: }
7028: return;
7029: }
7030:
1.976 raeburn 7031: sub is_advanced_user {
7032: my ($udom,$uname) = @_;
1.1085 raeburn 7033: if ($udom ne '' && $uname ne '') {
7034: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7035: if (wantarray) {
7036: return ($env{'user.adv'},$env{'user.author'});
7037: } else {
7038: return $env{'user.adv'};
7039: }
1.1085 raeburn 7040: }
7041: }
1.976 raeburn 7042: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7043: my %allroles;
1.1128 raeburn 7044: my ($is_adv,$is_author);
1.976 raeburn 7045: foreach my $role (keys(%roleshash)) {
7046: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7047: my $area = '/'.$tdomain.'/'.$trest;
7048: if ($sec ne '') {
7049: $area .= '/'.$sec;
7050: }
7051: if (($area ne '') && ($trole ne '')) {
7052: my $spec=$trole.'.'.$area;
7053: if ($trole =~ /^cr\//) {
7054: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7055: } elsif ($trole ne 'gr') {
7056: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7057: }
1.1128 raeburn 7058: if ($trole eq 'au') {
7059: $is_author = 1;
7060: }
1.976 raeburn 7061: }
7062: }
7063: foreach my $role (keys(%allroles)) {
7064: last if ($is_adv);
7065: foreach my $item (split(/:/,$allroles{$role})) {
7066: if ($item ne '') {
7067: my ($privilege,$restrictions)=split(/&/,$item);
7068: if ($privilege eq 'adv') {
7069: $is_adv = 1;
7070: last;
7071: }
7072: }
7073: }
7074: }
1.1128 raeburn 7075: if (wantarray) {
7076: return ($is_adv,$is_author);
7077: }
1.976 raeburn 7078: return $is_adv;
7079: }
1.798 raeburn 7080:
1.1035 raeburn 7081: sub check_can_request {
1.1036 raeburn 7082: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7083: my $canreq = 0;
7084: my ($types,$typename) = &Apache::loncommon::course_types();
7085: my @options = ('approval','validate','autolimit');
7086: my $optregex = join('|',@options);
7087: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7088: foreach my $type (@{$types}) {
7089: if (&usertools_access($env{'user.name'},
7090: $env{'user.domain'},
7091: $type,undef,'requestcourses')) {
7092: $canreq ++;
1.1036 raeburn 7093: if (ref($request_domains) eq 'HASH') {
7094: push(@{$request_domains->{$type}},$env{'user.domain'});
7095: }
1.1035 raeburn 7096: if ($dom eq $env{'user.domain'}) {
7097: $can_request->{$type} = 1;
7098: }
7099: }
7100: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7101: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7102: if (@curr > 0) {
1.1036 raeburn 7103: foreach my $item (@curr) {
7104: if (ref($request_domains) eq 'HASH') {
7105: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7106: if ($otherdom ne '') {
7107: if (ref($request_domains->{$type}) eq 'ARRAY') {
7108: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7109: push(@{$request_domains->{$type}},$otherdom);
7110: }
7111: } else {
7112: push(@{$request_domains->{$type}},$otherdom);
7113: }
7114: }
7115: }
7116: }
7117: unless($dom eq $env{'user.domain'}) {
7118: $canreq ++;
1.1035 raeburn 7119: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7120: $can_request->{$type} = 1;
7121: }
7122: }
7123: }
7124: }
7125: }
7126: }
7127: return $canreq;
7128: }
7129:
1.341 www 7130: # ---------------------------------------------- Custom access rule evaluation
7131:
7132: sub customaccess {
7133: my ($priv,$uri)=@_;
1.807 albertel 7134: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7135: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7136: $udom = &LONCAPA::clean_domain($udom);
7137: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7138: my $access=0;
1.800 albertel 7139: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7140: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7141: if ($type eq 'user') {
7142: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7143: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7144: if ($tdom) {
7145: if ($tdom ne $env{'user.domain'}) { next; }
7146: }
1.896 albertel 7147: if ($tuname) {
7148: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7149: }
7150: $access=($effect eq 'allow');
7151: last;
7152: }
7153: } else {
7154: if ($role) {
7155: if ($role ne $urole) { next; }
7156: }
7157: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7158: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7159: if ($tdom) {
7160: if ($tdom ne $udom) { next; }
7161: }
7162: if ($tcrs) {
7163: if ($tcrs ne $ucrs) { next; }
7164: }
7165: if ($tsec) {
7166: if ($tsec ne $usec) { next; }
7167: }
7168: $access=($effect eq 'allow');
7169: last;
7170: }
7171: if ($realm eq '' && $role eq '') {
7172: $access=($effect eq 'allow');
7173: }
1.402 bowersj2 7174: }
1.341 www 7175: }
7176: return $access;
7177: }
7178:
1.103 harris41 7179: # ------------------------------------------------- Check for a user privilege
1.12 www 7180:
7181: sub allowed {
1.1172.2.65 raeburn 7182: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7183: my $ver_orguri=$uri;
1.439 www 7184: $uri=&deversion($uri);
1.152 www 7185: my $orguri=$uri;
1.52 www 7186: $uri=&declutter($uri);
1.809 raeburn 7187:
1.810 raeburn 7188: if ($priv eq 'evb') {
7189: # Evade communication block restrictions for specified role in a course
7190: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7191: return $1;
7192: } else {
7193: return;
7194: }
7195: }
7196:
1.620 albertel 7197: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7198: # Free bre access to adm and meta resources
1.775 albertel 7199: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 7200: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7201: && ($priv eq 'bre')) {
1.14 www 7202: return 'F';
1.159 www 7203: }
7204:
1.545 banghart 7205: # Free bre access to user's own portfolio contents
1.714 raeburn 7206: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7207: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7208: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7209: my %setters;
7210: my ($startblock,$endblock) =
7211: &Apache::loncommon::blockcheck(\%setters,'port');
7212: if ($startblock && $endblock) {
7213: return 'B';
7214: } else {
7215: return 'F';
7216: }
1.545 banghart 7217: }
7218:
1.762 raeburn 7219: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7220: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7221: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7222: if (exists($env{'request.course.id'})) {
7223: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7224: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7225: if (($domain eq $cdom) && ($name eq $cnum)) {
7226: my $courseprivid=$env{'request.course.id'};
7227: $courseprivid=~s/\_/\//;
7228: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7229: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7230: return $1;
1.762 raeburn 7231: } else {
7232: if ($env{'request.course.sec'}) {
7233: $courseprivid.='/'.$env{'request.course.sec'};
7234: }
7235: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7236: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7237: return $2;
7238: }
1.714 raeburn 7239: }
7240: }
7241: }
7242: }
7243:
1.159 www 7244: # Free bre to public access
7245:
7246: if ($priv eq 'bre') {
1.238 www 7247: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7248: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7249: return 'F';
7250: }
1.238 www 7251: if ($copyright eq 'priv') {
7252: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7253: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7254: return '';
7255: }
7256: }
7257: if ($copyright eq 'domain') {
7258: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7259: unless (($env{'user.domain'} eq $1) ||
7260: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7261: return '';
7262: }
1.262 matthew 7263: }
1.620 albertel 7264: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7265: # Library role, so allow browsing of resources in this domain.
7266: return 'F';
1.238 www 7267: }
1.341 www 7268: if ($copyright eq 'custom') {
7269: unless (&customaccess($priv,$uri)) { return ''; }
7270: }
1.14 www 7271: }
1.264 matthew 7272: # Domain coordinator is trying to create a course
1.620 albertel 7273: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7274: # uri is the requested domain in this case.
7275: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7276: # a role of dc for the domain in question.
1.620 albertel 7277: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7278: }
1.29 www 7279:
1.52 www 7280: my $thisallowed='';
7281: my $statecond=0;
7282: my $courseprivid='';
7283:
1.1039 raeburn 7284: my $ownaccess;
1.1043 raeburn 7285: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7286: if (($priv eq 'bro') && ($env{'user.author'})) {
7287: if ($uri eq '') {
7288: $ownaccess = 1;
7289: } else {
7290: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7291: my $udom = $env{'user.domain'};
7292: my $uname = $env{'user.name'};
7293: if ($uri =~ m{^\Q$udom\E/?$}) {
7294: $ownaccess = 1;
1.1040 raeburn 7295: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7296: unless ($uri =~ m{\.\./}) {
7297: $ownaccess = 1;
7298: }
7299: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7300: my $now = time;
7301: if ($uri =~ m{^([^/]+)/?$}) {
7302: my $adom = $1;
7303: foreach my $key (keys(%env)) {
1.1042 raeburn 7304: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7305: my ($start,$end) = split('.',$env{$key});
7306: if (($now >= $start) && (!$end || $end < $now)) {
7307: $ownaccess = 1;
7308: last;
7309: }
7310: }
7311: }
7312: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7313: my $adom = $1;
7314: my $aname = $2;
1.1042 raeburn 7315: foreach my $role ('ca','aa') {
7316: if ($env{"user.role.$role./$adom/$aname"}) {
7317: my ($start,$end) =
7318: split('.',$env{"user.role.$role./$adom/$aname"});
7319: if (($now >= $start) && (!$end || $end < $now)) {
7320: $ownaccess = 1;
7321: last;
7322: }
1.1039 raeburn 7323: }
7324: }
7325: }
7326: }
7327: }
7328: }
7329: }
7330:
1.52 www 7331: # Course
7332:
1.620 albertel 7333: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7334: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7335: $thisallowed.=$1;
7336: }
1.52 www 7337: }
1.29 www 7338:
1.52 www 7339: # Domain
7340:
1.620 albertel 7341: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7342: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7343: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7344: $thisallowed.=$1;
7345: }
1.12 www 7346: }
1.52 www 7347:
1.1141 raeburn 7348: # User who is not author or co-author might still be able to edit
7349: # resource of an author in the domain (e.g., if Domain Coordinator).
7350: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7351: (&allowed('mdc',$env{'request.course.id'}))) {
7352: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7353: $thisallowed.=$1;
7354: }
7355: }
7356:
1.52 www 7357: # Course: uri itself is a course
1.66 www 7358: my $courseuri=$uri;
7359: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7360: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7361:
1.620 albertel 7362: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7363: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7364: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7365: $thisallowed.=$1;
7366: }
1.12 www 7367: }
1.29 www 7368:
1.665 albertel 7369: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7370: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7371: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7372: $thisallowed='';
1.671 raeburn 7373: my ($match)=&is_on_map($uri);
7374: if ($match) {
7375: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7376: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 7377: my $value = $1;
7378: if ($noblockcheck) {
7379: $thisallowed.=$value;
1.1162 raeburn 7380: } else {
1.1172.2.65 raeburn 7381: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7382: if (@blockers > 0) {
7383: $thisallowed = 'B';
7384: } else {
7385: $thisallowed.=$value;
7386: }
1.1162 raeburn 7387: }
1.671 raeburn 7388: }
7389: } else {
1.705 albertel 7390: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7391: if ($refuri) {
7392: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7393: $thisallowed='F';
1.671 raeburn 7394: } else {
7395: $refuri=&declutter($refuri);
7396: my ($match) = &is_on_map($refuri);
7397: if ($match) {
1.1172.2.65 raeburn 7398: if ($noblockcheck) {
1.1162 raeburn 7399: $thisallowed='F';
1.1172.2.65 raeburn 7400: } else {
7401: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7402: if (@blockers > 0) {
7403: $thisallowed = 'B';
7404: } else {
7405: $thisallowed='F';
7406: }
1.1162 raeburn 7407: }
1.671 raeburn 7408: }
1.669 raeburn 7409: }
1.671 raeburn 7410: }
7411: }
1.314 www 7412: }
1.492 albertel 7413:
1.766 albertel 7414: if ($priv eq 'bre'
7415: && $thisallowed ne 'F'
7416: && $thisallowed ne '2'
7417: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 7418: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7419: }
7420:
1.52 www 7421: # Full access at system, domain or course-wide level? Exit.
1.29 www 7422: if ($thisallowed=~/F/) {
7423: return 'F';
7424: }
7425:
1.52 www 7426: # If this is generating or modifying users, exit with special codes
1.29 www 7427:
1.643 www 7428: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7429: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7430: my ($audom,$auname)=split('/',$uri);
1.643 www 7431: # no author name given, so this just checks on the general right to make a co-author in this domain
7432: unless ($auname) { return $thisallowed; }
7433: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7434: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7435: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7436: ($audom ne $env{'request.role.domain'}))) { return ''; }
7437: }
1.52 www 7438: return $thisallowed;
7439: }
7440: #
1.103 harris41 7441: # Gathered so far: system, domain and course wide privileges
1.52 www 7442: #
7443: # Course: See if uri or referer is an individual resource that is part of
7444: # the course
7445:
1.620 albertel 7446: if ($env{'request.course.id'}) {
1.232 www 7447:
1.620 albertel 7448: $courseprivid=$env{'request.course.id'};
7449: if ($env{'request.course.sec'}) {
7450: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7451: }
7452: $courseprivid=~s/\_/\//;
7453: my $checkreferer=1;
1.232 www 7454: my ($match,$cond)=&is_on_map($uri);
7455: if ($match) {
7456: $statecond=$cond;
1.620 albertel 7457: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7458: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7459: my $value = $1;
7460: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7461: if ($noblockcheck) {
1.1162 raeburn 7462: $thisallowed.=$value;
1.1172.2.65 raeburn 7463: } else {
7464: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7465: if (@blockers > 0) {
7466: $thisallowed = 'B';
7467: } else {
7468: $thisallowed.=$value;
7469: }
1.1162 raeburn 7470: }
7471: } else {
7472: $thisallowed.=$value;
7473: }
1.52 www 7474: $checkreferer=0;
7475: }
1.29 www 7476: }
1.83 www 7477:
1.148 www 7478: if ($checkreferer) {
1.620 albertel 7479: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7480: unless ($refuri) {
1.800 albertel 7481: foreach my $key (keys(%env)) {
7482: if ($key=~/^httpref\..*\*/) {
7483: my $pattern=$key;
1.156 www 7484: $pattern=~s/^httpref\.\/res\///;
1.148 www 7485: $pattern=~s/\*/\[\^\/\]\+/g;
7486: $pattern=~s/\//\\\//g;
1.152 www 7487: if ($orguri=~/$pattern/) {
1.800 albertel 7488: $refuri=$env{$key};
1.148 www 7489: }
7490: }
1.191 harris41 7491: }
1.148 www 7492: }
1.232 www 7493:
1.148 www 7494: if ($refuri) {
1.152 www 7495: $refuri=&declutter($refuri);
1.232 www 7496: my ($match,$cond)=&is_on_map($refuri);
7497: if ($match) {
7498: my $refstatecond=$cond;
1.620 albertel 7499: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7500: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7501: my $value = $1;
7502: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7503: if ($noblockcheck) {
1.1162 raeburn 7504: $thisallowed.=$value;
1.1172.2.65 raeburn 7505: } else {
7506: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7507: if (@blockers > 0) {
7508: $thisallowed = 'B';
7509: } else {
7510: $thisallowed.=$value;
7511: }
1.1162 raeburn 7512: }
7513: } else {
7514: $thisallowed.=$value;
7515: }
1.53 www 7516: $uri=$refuri;
7517: $statecond=$refstatecond;
1.52 www 7518: }
7519: }
1.148 www 7520: }
1.29 www 7521: }
1.52 www 7522: }
1.29 www 7523:
1.52 www 7524: #
1.103 harris41 7525: # Gathered now: all privileges that could apply, and condition number
1.52 www 7526: #
7527: #
7528: # Full or no access?
7529: #
1.29 www 7530:
1.52 www 7531: if ($thisallowed=~/F/) {
7532: return 'F';
7533: }
1.29 www 7534:
1.52 www 7535: unless ($thisallowed) {
7536: return '';
7537: }
1.29 www 7538:
1.52 www 7539: # Restrictions exist, deal with them
7540: #
7541: # C:according to course preferences
7542: # R:according to resource settings
7543: # L:unless locked
7544: # X:according to user session state
7545: #
7546:
7547: # Possibly locked functionality, check all courses
1.54 www 7548: # Locks might take effect only after 10 minutes cache expiration for other
7549: # courses, and 2 minutes for current course
1.52 www 7550:
7551: my $envkey;
7552: if ($thisallowed=~/L/) {
1.1000 raeburn 7553: foreach $envkey (keys(%env)) {
1.54 www 7554: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7555: my $courseid=$2;
7556: my $roleid=$1.'.'.$2;
1.92 www 7557: $courseid=~s/^\///;
1.54 www 7558: my $expiretime=600;
1.620 albertel 7559: if ($env{'request.role'} eq $roleid) {
1.54 www 7560: $expiretime=120;
7561: }
7562: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7563: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7564: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7565: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7566: }
1.620 albertel 7567: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7568: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7569: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7570: &log($env{'user.domain'},$env{'user.name'},
7571: $env{'user.home'},
1.57 www 7572: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7573: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7574: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7575: return '';
7576: }
7577: }
1.620 albertel 7578: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7579: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7580: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7581: &log($env{'user.domain'},$env{'user.name'},
7582: $env{'user.home'},
1.57 www 7583: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7584: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7585: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7586: return '';
7587: }
7588: }
7589: }
1.29 www 7590: }
1.52 www 7591: }
7592:
7593: #
7594: # Rest of the restrictions depend on selected course
7595: #
7596:
1.620 albertel 7597: unless ($env{'request.course.id'}) {
1.766 albertel 7598: if ($thisallowed eq 'A') {
7599: return 'A';
1.814 raeburn 7600: } elsif ($thisallowed eq 'B') {
7601: return 'B';
1.766 albertel 7602: } else {
7603: return '1';
7604: }
1.52 www 7605: }
1.29 www 7606:
1.52 www 7607: #
7608: # Now user is definitely in a course
7609: #
1.53 www 7610:
7611:
7612: # Course preferences
7613:
7614: if ($thisallowed=~/C/) {
1.620 albertel 7615: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7616: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7617: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7618: =~/\Q$rolecode\E/) {
1.1103 raeburn 7619: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7620: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7621: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7622: $env{'request.course.id'});
7623: }
1.237 www 7624: return '';
7625: }
7626:
1.620 albertel 7627: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7628: =~/\Q$unamedom\E/) {
1.1103 raeburn 7629: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7630: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7631: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7632: $env{'request.course.id'});
7633: }
1.54 www 7634: return '';
7635: }
1.53 www 7636: }
7637:
7638: # Resource preferences
7639:
7640: if ($thisallowed=~/R/) {
1.620 albertel 7641: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7642: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7643: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7644: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7645: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7646: }
7647: return '';
1.54 www 7648: }
1.53 www 7649: }
1.30 www 7650:
1.246 www 7651: # Restricted by state or randomout?
1.30 www 7652:
1.52 www 7653: if ($thisallowed=~/X/) {
1.620 albertel 7654: if ($env{'acc.randomout'}) {
1.579 albertel 7655: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7656: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7657: return '';
7658: }
1.247 www 7659: }
7660: if (&condval($statecond)) {
1.52 www 7661: return '2';
7662: } else {
7663: return '';
7664: }
7665: }
1.30 www 7666:
1.766 albertel 7667: if ($thisallowed eq 'A') {
7668: return 'A';
1.814 raeburn 7669: } elsif ($thisallowed eq 'B') {
7670: return 'B';
1.766 albertel 7671: }
1.52 www 7672: return 'F';
1.232 www 7673: }
1.1162 raeburn 7674:
1.1172.2.13 raeburn 7675: # ------------------------------------------- Check construction space access
7676:
7677: sub constructaccess {
7678: my ($url,$setpriv)=@_;
7679:
7680: # We do not allow editing of previous versions of files
7681: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7682:
7683: # Get username and domain from URL
7684: my ($ownername,$ownerdomain,$ownerhome);
7685:
7686: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 7687: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 7688:
7689: # The URL does not really point to any authorspace, forget it
7690: unless (($ownername) && ($ownerdomain)) { return ''; }
7691:
7692: # Now we need to see if the user has access to the authorspace of
7693: # $ownername at $ownerdomain
7694:
7695: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7696: # Real author for this?
7697: $ownerhome = $env{'user.home'};
7698: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7699: return ($ownername,$ownerdomain,$ownerhome);
7700: }
7701: } else {
7702: # Co-author for this?
7703: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7704: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7705: $ownerhome = &homeserver($ownername,$ownerdomain);
7706: return ($ownername,$ownerdomain,$ownerhome);
7707: }
7708: }
7709:
7710: # We don't have any access right now. If we are not possibly going to do anything about this,
7711: # we might as well leave
7712: unless ($setpriv) { return ''; }
7713:
7714: # Backdoor access?
7715: my $allowed=&allowed('eco',$ownerdomain);
7716: # Nope
7717: unless ($allowed) { return ''; }
7718: # Looks like we may have access, but could be locked by the owner of the construction space
7719: if ($allowed eq 'U') {
7720: my %blocked=&get('environment',['domcoord.author'],
7721: $ownerdomain,$ownername);
7722: # Is blocked by owner
7723: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7724: }
7725: if (($allowed eq 'F') || ($allowed eq 'U')) {
7726: # Grant temporary access
7727: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7728: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7729: if (!$update) { $update = $then; }
7730: my $refresh=$env{'user.refresh.time'};
7731: if (!$refresh) { $refresh = $update; }
7732: my $now = time;
7733: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7734: $now,'ca','constructaccess');
7735: $ownerhome = &homeserver($ownername,$ownerdomain);
7736: return($ownername,$ownerdomain,$ownerhome);
7737: }
7738: # No business here
7739: return '';
7740: }
7741:
1.1172.2.66 raeburn 7742: # ----------------------------------------------------------- Content Blocking
7743:
7744: {
7745: # Caches for faster Course Contents display where content blocking
7746: # is in operation (i.e., interval param set) for timed quiz.
7747: #
7748: # User for whom data are being temporarily cached.
7749: my $cacheduser='';
7750: # Cached blockers for this user (a hash of blocking items).
7751: my %cachedblockers=();
7752: # When the data were last cached.
7753: my $cachedlast='';
7754:
7755: sub load_all_blockers {
7756: my ($uname,$udom,$blocks)=@_;
7757: if (($uname ne '') && ($udom ne '')) {
7758: if (($cacheduser eq $uname.':'.$udom) &&
7759: (abs($cachedlast-time)<5)) {
7760: return;
7761: }
7762: }
7763: $cachedlast=time;
7764: $cacheduser=$uname.':'.$udom;
7765: %cachedblockers = &get_commblock_resources($blocks);
7766: }
7767:
1.1162 raeburn 7768: sub get_comm_blocks {
7769: my ($cdom,$cnum) = @_;
7770: if ($cdom eq '' || $cnum eq '') {
7771: return unless ($env{'request.course.id'});
7772: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7773: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7774: }
7775: my %commblocks;
7776: my $hashid=$cdom.'_'.$cnum;
7777: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7778: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7779: %commblocks = %{$blocksref};
7780: } else {
7781: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7782: my $cachetime = 600;
7783: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7784: }
7785: return %commblocks;
7786: }
7787:
1.1172.2.66 raeburn 7788: sub get_commblock_resources {
7789: my ($blocks) = @_;
7790: my %blockers = ();
7791: return %blockers unless ($env{'request.course.id'});
7792: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7793: my %commblocks;
7794: if (ref($blocks) eq 'HASH') {
7795: %commblocks = %{$blocks};
7796: } else {
7797: %commblocks = &get_comm_blocks();
7798: }
1.1172.2.66 raeburn 7799: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 7800: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 7801: return %blockers unless (ref($navmap));
7802: my $now = time;
1.1162 raeburn 7803: foreach my $block (keys(%commblocks)) {
7804: if ($block =~ /^(\d+)____(\d+)$/) {
7805: my ($start,$end) = ($1,$2);
7806: if ($start <= $now && $end >= $now) {
7807: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7808: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7809: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 7810: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7811: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7812: }
7813: }
7814: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 7815: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7816: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7817: }
7818: }
7819: }
7820: }
7821: }
7822: } elsif ($block =~ /^firstaccess____(.+)$/) {
7823: my $item = $1;
1.1163 raeburn 7824: my @to_test;
1.1162 raeburn 7825: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7826: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 7827: my @interval;
7828: my $type = 'map';
7829: if ($item eq 'course') {
7830: $type = 'course';
7831: @interval=&EXT("resource.0.interval");
7832: } else {
7833: if ($item =~ /___\d+___/) {
7834: $type = 'resource';
7835: @interval=&EXT("resource.0.interval",$item);
7836: if (ref($navmap)) {
7837: my $res = $navmap->getBySymb($item);
7838: push(@to_test,$res);
7839: }
1.1162 raeburn 7840: } else {
1.1172.2.66 raeburn 7841: my $mapsymb = &symbread($item,1);
7842: if ($mapsymb) {
7843: if (ref($navmap)) {
7844: my $mapres = $navmap->getBySymb($mapsymb);
7845: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7846: foreach my $res (@to_test) {
7847: my $symb = $res->symb();
7848: next if ($symb eq $mapsymb);
7849: if ($symb ne '') {
7850: @interval=&EXT("resource.0.interval",$symb);
7851: if ($interval[1] eq 'map') {
7852: last;
1.1162 raeburn 7853: }
7854: }
7855: }
7856: }
7857: }
7858: }
1.1172.2.66 raeburn 7859: }
7860: if ($interval[0] =~ /^\d+$/) {
7861: my $first_access;
7862: if ($type eq 'resource') {
7863: $first_access=&get_first_access($interval[1],$item);
7864: } elsif ($type eq 'map') {
7865: $first_access=&get_first_access($interval[1],undef,$item);
7866: } else {
7867: $first_access=&get_first_access($interval[1]);
7868: }
7869: if ($first_access) {
7870: my $timesup = $first_access+$interval[0];
7871: if ($timesup > $now) {
7872: my $activeblock;
7873: foreach my $res (@to_test) {
7874: if ($res->answerable()) {
7875: $activeblock = 1;
7876: last;
7877: }
7878: }
7879: if ($activeblock) {
7880: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7881: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7882: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7883: }
7884: }
7885: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7886: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7887: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7888: }
1.1162 raeburn 7889: }
7890: }
7891: }
7892: }
7893: }
7894: }
7895: }
7896: }
7897: }
1.1172.2.66 raeburn 7898: return %blockers;
1.1162 raeburn 7899: }
7900:
1.1172.2.66 raeburn 7901: sub has_comm_blocking {
7902: my ($priv,$symb,$uri,$blocks) = @_;
7903: my @blockers;
7904: return unless ($env{'request.course.id'});
7905: return unless ($priv eq 'bre');
7906: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7907: return if ($env{'request.state'} eq 'construct');
7908: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7909: return unless (keys(%cachedblockers) > 0);
7910: my (%possibles,@symbs);
7911: if (!$symb) {
7912: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7913: }
1.1172.2.66 raeburn 7914: if ($symb) {
7915: @symbs = ($symb);
7916: } elsif (keys(%possibles)) {
7917: @symbs = keys(%possibles);
7918: }
7919: my $noblock;
7920: foreach my $symb (@symbs) {
7921: last if ($noblock);
7922: my ($map,$resid,$resurl)=&decode_symb($symb);
7923: foreach my $block (keys(%cachedblockers)) {
7924: if ($block =~ /^firstaccess____(.+)$/) {
7925: my $item = $1;
7926: if (($item eq $map) || ($item eq $symb)) {
7927: $noblock = 1;
7928: last;
7929: }
1.1162 raeburn 7930: }
1.1172.2.66 raeburn 7931: if (ref($cachedblockers{$block}) eq 'HASH') {
7932: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7933: if ($cachedblockers{$block}{'resources'}{$symb}) {
7934: unless (grep(/^\Q$block\E$/,@blockers)) {
7935: push(@blockers,$block);
7936: }
7937: }
7938: }
7939: }
7940: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7941: if ($cachedblockers{$block}{'maps'}{$map}) {
7942: unless (grep(/^\Q$block\E$/,@blockers)) {
7943: push(@blockers,$block);
7944: }
7945: }
1.1162 raeburn 7946: }
7947: }
7948: }
1.1172.2.66 raeburn 7949: return if ($noblock);
7950: return @blockers;
7951: }
1.1162 raeburn 7952: }
7953:
1.1172.2.66 raeburn 7954: # -------------------------------- Deversion and split uri into path an filename
7955:
1.1133 foxr 7956: #
1.1172.2.66 raeburn 7957: # Removes the version from a URI and
1.1133 foxr 7958: # splits it in to its filename and path to the filename.
7959: # Seems like File::Basename could have done this more clearly.
7960: # Parameters:
7961: # $uri - input URI
7962: # Returns:
7963: # Two element list consisting of
7964: # $pathname - the URI up to and excluding the trailing /
7965: # $filename - The part of the URI following the last /
7966: # NOTE:
7967: # Another realization of this is simply:
7968: # use File::Basename;
7969: # ...
7970: # $uri = shift;
7971: # $filename = basename($uri);
7972: # $path = dirname($uri);
7973: # return ($filename, $path);
7974: #
7975: # The implementation below is probably faster however.
7976: #
1.710 albertel 7977: sub split_uri_for_cond {
7978: my $uri=&deversion(&declutter(shift));
7979: my @uriparts=split(/\//,$uri);
7980: my $filename=pop(@uriparts);
7981: my $pathname=join('/',@uriparts);
7982: return ($pathname,$filename);
7983: }
1.232 www 7984: # --------------------------------------------------- Is a resource on the map?
7985:
7986: sub is_on_map {
1.710 albertel 7987: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7988: #Trying to find the conditional for the file
1.620 albertel 7989: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7990: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7991: if ($match) {
1.289 bowersj2 7992: return (1,$1);
7993: } else {
1.434 www 7994: return (0,0);
1.289 bowersj2 7995: }
1.12 www 7996: }
7997:
1.427 www 7998: # --------------------------------------------------------- Get symb from alias
7999:
8000: sub get_symb_from_alias {
8001: my $symb=shift;
8002: my ($map,$resid,$url)=&decode_symb($symb);
8003: # Already is a symb
8004: if ($url) { return $symb; }
8005: # Must be an alias
8006: my $aliassymb='';
8007: my %bighash;
1.620 albertel 8008: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8009: &GDBM_READER(),0640)) {
8010: my $rid=$bighash{'mapalias_'.$symb};
8011: if ($rid) {
8012: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8013: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8014: $resid,$bighash{'src_'.$rid});
1.427 www 8015: }
8016: untie %bighash;
8017: }
8018: return $aliassymb;
8019: }
8020:
1.12 www 8021: # ----------------------------------------------------------------- Define Role
8022:
8023: sub definerole {
8024: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8025: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8026: foreach my $role (split(':',$sysrole)) {
8027: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8028: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8029: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8030: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8031: return "refused:s:$crole&$cqual";
8032: }
8033: }
1.191 harris41 8034: }
1.800 albertel 8035: foreach my $role (split(':',$domrole)) {
8036: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8037: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8038: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8039: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8040: return "refused:d:$crole&$cqual";
8041: }
8042: }
1.191 harris41 8043: }
1.800 albertel 8044: foreach my $role (split(':',$courole)) {
8045: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8046: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8047: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8048: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8049: return "refused:c:$crole&$cqual";
8050: }
8051: }
1.191 harris41 8052: }
1.1172.2.84 raeburn 8053: my $uhome;
8054: if (($uname ne '') && ($udom ne '')) {
8055: $uhome = &homeserver($uname,$udom);
8056: return $uhome if ($uhome eq 'no_host');
8057: } else {
8058: $uname = $env{'user.name'};
8059: $udom = $env{'user.domain'};
8060: $uhome = $env{'user.home'};
8061: }
1.620 albertel 8062: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8063: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8064: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8065: return reply($command,$uhome);
1.12 www 8066: } else {
8067: return 'refused';
8068: }
1.105 harris41 8069: }
8070:
8071: # ---------------- Make a metadata query against the network of library servers
8072:
8073: sub metadata_query {
1.1172.2.33 raeburn 8074: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8075: my %rhash;
1.845 albertel 8076: my %libserv = &all_library();
1.244 matthew 8077: my @server_list = (defined($server_array) ? @$server_array
8078: : keys(%libserv) );
8079: for my $server (@server_list) {
1.1172.2.33 raeburn 8080: my $domains = '';
8081: if (ref($domains_hash) eq 'HASH') {
8082: $domains = $domains_hash->{$server};
8083: }
1.118 harris41 8084: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8085: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8086: $rhash{$server}=$reply;
8087: }
8088: else {
8089: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8090: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8091: $server);
8092: $rhash{$server}=$reply;
8093: }
1.112 harris41 8094: }
1.118 harris41 8095: return \%rhash;
1.240 www 8096: }
8097:
8098: # ----------------------------------------- Send log queries and wait for reply
8099:
8100: sub log_query {
8101: my ($uname,$udom,$query,%filters)=@_;
8102: my $uhome=&homeserver($uname,$udom);
8103: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8104: my $uhost=&hostname($uhome);
1.800 albertel 8105: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8106: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8107: $uhome);
1.479 albertel 8108: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8109: return get_query_reply($queryid);
8110: }
8111:
1.818 raeburn 8112: # -------------------------- Update MySQL table for portfolio file
8113:
8114: sub update_portfolio_table {
1.821 raeburn 8115: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8116: if ($group ne '') {
8117: $file_name =~s /^\Q$group\E//;
8118: }
1.818 raeburn 8119: my $homeserver = &homeserver($uname,$udom);
8120: my $queryid=
1.821 raeburn 8121: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8122: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8123: my $reply = &get_query_reply($queryid);
8124: return $reply;
8125: }
8126:
1.899 raeburn 8127: # -------------------------- Update MySQL allusers table
8128:
8129: sub update_allusers_table {
8130: my ($uname,$udom,$names) = @_;
8131: my $homeserver = &homeserver($uname,$udom);
8132: my $queryid=
8133: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8134: 'lastname='.&escape($names->{'lastname'}).'%%'.
8135: 'firstname='.&escape($names->{'firstname'}).'%%'.
8136: 'middlename='.&escape($names->{'middlename'}).'%%'.
8137: 'generation='.&escape($names->{'generation'}).'%%'.
8138: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8139: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8140: return;
1.899 raeburn 8141: }
8142:
1.508 raeburn 8143: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8144:
8145: sub fetch_enrollment_query {
1.511 raeburn 8146: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8147: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8148: my $maxtries = 1;
1.508 raeburn 8149: if ($context eq 'automated') {
8150: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8151: $sleep = 2;
8152: $loopmax = 100;
1.547 raeburn 8153: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8154: } else {
8155: $homeserver = &homeserver($cnum,$dom);
8156: }
1.838 albertel 8157: my $host=&hostname($homeserver);
1.506 raeburn 8158: my $cmd = '';
1.1000 raeburn 8159: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8160: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8161: }
8162: $cmd =~ s/%%$//;
8163: $cmd = &escape($cmd);
8164: my $query = 'fetchenrollment';
1.620 albertel 8165: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8166: unless ($queryid=~/^\Q$host\E\_/) {
8167: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8168: return 'error: '.$queryid;
8169: }
1.1172.2.93 raeburn 8170: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8171: my $tries = 1;
8172: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8173: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8174: $tries ++;
8175: }
1.526 raeburn 8176: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8177: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8178: } else {
1.901 albertel 8179: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8180: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8181: foreach my $line (@responses) {
8182: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8183: $$replyref{$key} = $value;
8184: }
8185: } else {
1.1117 foxr 8186: my $pathname = LONCAPA::tempdir();
1.800 albertel 8187: foreach my $line (@responses) {
8188: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8189: $$replyref{$key} = $value;
8190: if ($value > 0) {
1.800 albertel 8191: foreach my $item (@{$$affiliatesref{$key}}) {
8192: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8193: my $destname = $pathname.'/'.$filename;
8194: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8195: if ($xml_classlist =~ /^error/) {
8196: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8197: } else {
1.1172.2.96 raeburn 8198: if ( open(FILE,">",$destname) ) {
1.506 raeburn 8199: print FILE &unescape($xml_classlist);
8200: close(FILE);
1.526 raeburn 8201: } else {
8202: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8203: }
8204: }
8205: }
8206: }
8207: }
8208: }
8209: return 'ok';
8210: }
8211: return 'error';
8212: }
8213:
1.242 www 8214: sub get_query_reply {
1.1172.2.79 raeburn 8215: my ($queryid,$sleep,$loopmax) = @_;
8216: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8217: $sleep = 0.2;
8218: }
8219: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8220: $loopmax = 100;
8221: }
1.1117 foxr 8222: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8223: my $reply='';
1.1172.2.79 raeburn 8224: for (1..$loopmax) {
8225: sleep($sleep);
1.240 www 8226: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 8227: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 8228: $reply = join('',<$fh>);
8229: close($fh);
1.240 www 8230: } else { return 'error: reply_file_error'; }
1.242 www 8231: return &unescape($reply);
8232: }
1.240 www 8233: }
1.242 www 8234: return 'timeout:'.$queryid;
1.240 www 8235: }
8236:
8237: sub courselog_query {
1.241 www 8238: #
8239: # possible filters:
8240: # url: url or symb
8241: # username
8242: # domain
8243: # action: view, submit, grade
8244: # start: timestamp
8245: # end: timestamp
8246: #
1.240 www 8247: my (%filters)=@_;
1.620 albertel 8248: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8249: if ($filters{'url'}) {
8250: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8251: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8252: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8253: }
1.620 albertel 8254: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8255: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8256: return &log_query($cname,$cdom,'courselog',%filters);
8257: }
8258:
8259: sub userlog_query {
1.858 raeburn 8260: #
8261: # possible filters:
8262: # action: log check role
8263: # start: timestamp
8264: # end: timestamp
8265: #
1.240 www 8266: my ($uname,$udom,%filters)=@_;
8267: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8268: }
8269:
1.506 raeburn 8270: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8271:
8272: sub auto_run {
1.508 raeburn 8273: my ($cnum,$cdom) = @_;
1.876 raeburn 8274: my $response = 0;
8275: my $settings;
8276: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8277: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8278: $settings = $domconfig{'autoenroll'};
8279: if ($settings->{'run'} eq '1') {
8280: $response = 1;
8281: }
8282: } else {
1.934 raeburn 8283: my $homeserver;
8284: if (&is_course($cdom,$cnum)) {
8285: $homeserver = &homeserver($cnum,$cdom);
8286: } else {
8287: $homeserver = &domain($cdom,'primary');
8288: }
8289: if ($homeserver ne 'no_host') {
8290: $response = &reply('autorun:'.$cdom,$homeserver);
8291: }
1.876 raeburn 8292: }
1.506 raeburn 8293: return $response;
8294: }
1.776 albertel 8295:
1.506 raeburn 8296: sub auto_get_sections {
1.508 raeburn 8297: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8298: my $homeserver;
8299: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8300: $homeserver = &homeserver($cnum,$cdom);
8301: }
8302: if (!defined($homeserver)) {
8303: if ($cdom =~ /^$match_domain$/) {
8304: $homeserver = &domain($cdom,'primary');
8305: }
8306: }
8307: my @secs;
8308: if (defined($homeserver)) {
8309: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8310: unless ($response eq 'refused') {
8311: @secs = split(/:/,$response);
8312: }
1.506 raeburn 8313: }
8314: return @secs;
8315: }
1.776 albertel 8316:
1.506 raeburn 8317: sub auto_new_course {
1.1099 raeburn 8318: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8319: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8320: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8321: return $response;
8322: }
1.776 albertel 8323:
1.506 raeburn 8324: sub auto_validate_courseID {
1.508 raeburn 8325: my ($cnum,$cdom,$inst_course_id) = @_;
8326: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8327: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8328: return $response;
8329: }
1.776 albertel 8330:
1.1007 raeburn 8331: sub auto_validate_instcode {
1.1020 raeburn 8332: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8333: my ($homeserver,$response);
8334: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8335: $homeserver = &homeserver($cnum,$cdom);
8336: }
8337: if (!defined($homeserver)) {
8338: if ($cdom =~ /^$match_domain$/) {
8339: $homeserver = &domain($cdom,'primary');
8340: }
8341: }
1.1065 raeburn 8342: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8343: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 8344: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8345: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8346: }
8347:
1.506 raeburn 8348: sub auto_create_password {
1.873 raeburn 8349: my ($cnum,$cdom,$authparam,$udom) = @_;
8350: my ($homeserver,$response);
1.506 raeburn 8351: my $create_passwd = 0;
8352: my $authchk = '';
1.873 raeburn 8353: if ($udom =~ /^$match_domain$/) {
8354: $homeserver = &domain($udom,'primary');
8355: }
8356: if ($homeserver eq '') {
8357: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8358: $homeserver = &homeserver($cnum,$cdom);
8359: }
8360: }
8361: if ($homeserver eq '') {
8362: $authchk = 'nodomain';
1.506 raeburn 8363: } else {
1.873 raeburn 8364: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8365: if ($response eq 'refused') {
8366: $authchk = 'refused';
8367: } else {
1.901 albertel 8368: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8369: }
1.506 raeburn 8370: }
8371: return ($authparam,$create_passwd,$authchk);
8372: }
8373:
1.706 raeburn 8374: sub auto_photo_permission {
8375: my ($cnum,$cdom,$students) = @_;
8376: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8377: my ($outcome,$perm_reqd,$conditions) =
8378: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8379: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8380: return (undef,undef);
8381: }
1.706 raeburn 8382: return ($outcome,$perm_reqd,$conditions);
8383: }
8384:
8385: sub auto_checkphotos {
8386: my ($uname,$udom,$pid) = @_;
8387: my $homeserver = &homeserver($uname,$udom);
8388: my ($result,$resulttype);
8389: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8390: &escape($uname).':'.&escape($pid),
8391: $homeserver));
1.709 albertel 8392: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8393: return (undef,undef);
8394: }
1.706 raeburn 8395: if ($outcome) {
8396: ($result,$resulttype) = split(/:/,$outcome);
8397: }
8398: return ($result,$resulttype);
8399: }
8400:
8401: sub auto_photochoice {
8402: my ($cnum,$cdom) = @_;
8403: my $homeserver = &homeserver($cnum,$cdom);
8404: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8405: &escape($cdom),
8406: $homeserver)));
1.709 albertel 8407: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8408: return (undef,undef);
8409: }
1.706 raeburn 8410: return ($update,$comment);
8411: }
8412:
8413: sub auto_photoupdate {
8414: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8415: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8416: my $host=&hostname($homeserver);
1.706 raeburn 8417: my $cmd = '';
8418: my $maxtries = 1;
1.800 albertel 8419: foreach my $affiliate (keys(%{$affiliatesref})) {
8420: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8421: }
8422: $cmd =~ s/%%$//;
8423: $cmd = &escape($cmd);
8424: my $query = 'institutionalphotos';
8425: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8426: unless ($queryid=~/^\Q$host\E\_/) {
8427: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8428: return 'error: '.$queryid;
8429: }
8430: my $reply = &get_query_reply($queryid);
8431: my $tries = 1;
8432: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8433: $reply = &get_query_reply($queryid);
8434: $tries ++;
8435: }
8436: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8437: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8438: } else {
8439: my @responses = split(/:/,$reply);
8440: my $outcome = shift(@responses);
8441: foreach my $item (@responses) {
8442: my ($key,$value) = split(/=/,$item);
8443: $$photo{$key} = $value;
8444: }
8445: return $outcome;
8446: }
8447: return 'error';
8448: }
8449:
1.521 raeburn 8450: sub auto_instcode_format {
1.793 albertel 8451: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8452: $cat_order) = @_;
1.521 raeburn 8453: my $courses = '';
1.772 raeburn 8454: my @homeservers;
1.521 raeburn 8455: if ($caller eq 'global') {
1.841 albertel 8456: my %servers = &get_servers($codedom,'library');
8457: foreach my $tryserver (keys(%servers)) {
8458: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8459: push(@homeservers,$tryserver);
8460: }
1.584 raeburn 8461: }
1.1022 raeburn 8462: } elsif ($caller eq 'requests') {
8463: if ($codedom =~ /^$match_domain$/) {
8464: my $chome = &domain($codedom,'primary');
8465: unless ($chome eq 'no_host') {
8466: push(@homeservers,$chome);
8467: }
8468: }
1.521 raeburn 8469: } else {
1.772 raeburn 8470: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8471: }
1.793 albertel 8472: foreach my $code (keys(%{$instcodes})) {
8473: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8474: }
8475: chop($courses);
1.772 raeburn 8476: my $ok_response = 0;
8477: my $response;
8478: while (@homeservers > 0 && $ok_response == 0) {
8479: my $server = shift(@homeservers);
8480: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8481: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8482: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8483: split(/:/,$response);
1.772 raeburn 8484: %{$codes} = (%{$codes},&str2hash($codes_str));
8485: push(@{$codetitles},&str2array($codetitles_str));
8486: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8487: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8488: $ok_response = 1;
8489: }
8490: }
8491: if ($ok_response) {
1.521 raeburn 8492: return 'ok';
1.772 raeburn 8493: } else {
8494: return $response;
1.521 raeburn 8495: }
8496: }
8497:
1.792 raeburn 8498: sub auto_instcode_defaults {
8499: my ($domain,$returnhash,$code_order) = @_;
8500: my @homeservers;
1.841 albertel 8501:
8502: my %servers = &get_servers($domain,'library');
8503: foreach my $tryserver (keys(%servers)) {
8504: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8505: push(@homeservers,$tryserver);
8506: }
1.792 raeburn 8507: }
1.841 albertel 8508:
1.792 raeburn 8509: my $response;
1.841 albertel 8510: foreach my $server (@homeservers) {
1.792 raeburn 8511: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8512: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8513:
8514: foreach my $pair (split(/\&/,$response)) {
8515: my ($name,$value)=split(/\=/,$pair);
8516: if ($name eq 'code_order') {
8517: @{$code_order} = split(/\&/,&unescape($value));
8518: } else {
8519: $returnhash->{&unescape($name)}=&unescape($value);
8520: }
8521: }
8522: return 'ok';
1.792 raeburn 8523: }
1.841 albertel 8524:
8525: return $response;
1.1003 raeburn 8526: }
8527:
8528: sub auto_possible_instcodes {
1.1007 raeburn 8529: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8530: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8531: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8532: return;
8533: }
1.1003 raeburn 8534: my (@homeservers,$uhome);
8535: if (defined(&domain($domain,'primary'))) {
8536: $uhome=&domain($domain,'primary');
8537: push(@homeservers,&domain($domain,'primary'));
8538: } else {
8539: my %servers = &get_servers($domain,'library');
8540: foreach my $tryserver (keys(%servers)) {
8541: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8542: push(@homeservers,$tryserver);
8543: }
8544: }
8545: }
8546: my $response;
8547: foreach my $server (@homeservers) {
8548: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8549: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8550: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8551: split(':',$response);
8552: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8553: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8554: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8555: my ($name,$value)=split('=',$item);
8556: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8557: }
8558: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8559: my ($name,$value)=split('=',$item);
8560: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8561: }
8562: return 'ok';
8563: }
8564: return $response;
8565: }
1.792 raeburn 8566:
1.1010 raeburn 8567: sub auto_courserequest_checks {
8568: my ($dom) = @_;
1.1020 raeburn 8569: my ($homeserver,%validations);
8570: if ($dom =~ /^$match_domain$/) {
8571: $homeserver = &domain($dom,'primary');
8572: }
8573: unless ($homeserver eq 'no_host') {
8574: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8575: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8576: my @items = split(/&/,$response);
8577: foreach my $item (@items) {
8578: my ($key,$value) = split('=',$item);
8579: $validations{&unescape($key)} = &thaw_unescape($value);
8580: }
8581: }
8582: }
1.1010 raeburn 8583: return %validations;
8584: }
8585:
1.1020 raeburn 8586: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8587: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8588: my ($homeserver,$response);
8589: if ($dom =~ /^$match_domain$/) {
8590: $homeserver = &domain($dom,'primary');
8591: }
1.1172.2.43 raeburn 8592: unless ($homeserver eq 'no_host') {
8593: my $customdata;
8594: if (ref($custominfo) eq 'HASH') {
8595: $customdata = &freeze_escape($custominfo);
8596: }
1.1020 raeburn 8597: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8598: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8599: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8600: $customdata,$homeserver));
1.1020 raeburn 8601: }
8602: return $response;
8603: }
8604:
1.777 albertel 8605: sub auto_validate_class_sec {
1.918 raeburn 8606: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8607: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8608: my $ownerlist;
8609: if (ref($owners) eq 'ARRAY') {
8610: $ownerlist = join(',',@{$owners});
8611: } else {
8612: $ownerlist = $owners;
8613: }
1.773 raeburn 8614: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8615: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8616: return $response;
8617: }
8618:
1.1172.2.94 raeburn 8619: sub auto_validate_instclasses {
8620: my ($cdom,$cnum,$owners,$classesref) = @_;
8621: my ($homeserver,%validations);
8622: $homeserver = &homeserver($cnum,$cdom);
8623: unless ($homeserver eq 'no_host') {
8624: my $ownerlist;
8625: if (ref($owners) eq 'ARRAY') {
8626: $ownerlist = join(',',@{$owners});
8627: } else {
8628: $ownerlist = $owners;
8629: }
8630: if (ref($classesref) eq 'HASH') {
8631: my $classes = &freeze_escape($classesref);
8632: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
8633: ':'.$cdom.':'.$classes,$homeserver);
8634: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8635: my @items = split(/&/,$response);
8636: foreach my $item (@items) {
8637: my ($key,$value) = split('=',$item);
8638: $validations{&unescape($key)} = &thaw_unescape($value);
8639: }
8640: }
8641: }
8642: }
8643: return %validations;
8644: }
8645:
1.1172.2.38 raeburn 8646: sub auto_crsreq_update {
8647: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8648: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8649: my ($homeserver,%crsreqresponse);
8650: if ($cdom =~ /^$match_domain$/) {
8651: $homeserver = &domain($cdom,'primary');
8652: }
8653: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8654: my $info;
8655: if (ref($inbound) eq 'HASH') {
8656: $info = &freeze_escape($inbound);
8657: }
8658: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8659: ':'.&escape($action).':'.&escape($ownername).':'.
8660: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8661: &escape($title).':'.&escape($code).':'.
8662: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8663: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8664: my @items = split(/&/,$response);
8665: foreach my $item (@items) {
8666: my ($key,$value) = split('=',$item);
8667: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8668: }
8669: }
8670: }
8671: return \%crsreqresponse;
8672: }
8673:
1.1172.2.78 raeburn 8674: sub auto_export_grades {
8675: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8676: my ($homeserver,%exportresponse);
8677: if ($cdom =~ /^$match_domain$/) {
8678: $homeserver = &domain($cdom,'primary');
8679: }
8680: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8681: my $info;
8682: if (ref($inforef) eq 'HASH') {
8683: $info = &freeze_escape($inforef);
8684: }
8685: if (ref($gradesref) eq 'HASH') {
8686: my $grades = &freeze_escape($gradesref);
8687: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8688: $info.':'.$grades,$homeserver);
8689: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8690: my @items = split(/&/,$response);
8691: foreach my $item (@items) {
8692: my ($key,$value) = split('=',$item);
8693: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8694: }
8695: }
8696: }
8697: }
8698: return \%exportresponse;
8699: }
8700:
1.1172.2.68 raeburn 8701: sub check_instcode_cloning {
8702: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8703: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8704: return;
8705: }
8706: my $canclone;
8707: if (@{$code_order} > 0) {
8708: my $instcoderegexp ='^';
8709: my @clonecodes = split(/\&/,$cloner);
8710: foreach my $item (@{$code_order}) {
8711: if (grep(/^\Q$item\E=/,@clonecodes)) {
8712: foreach my $pair (@clonecodes) {
8713: my ($key,$val) = split(/\=/,$pair,2);
8714: $val = &unescape($val);
8715: if ($key eq $item) {
8716: $instcoderegexp .= '('.$val.')';
8717: last;
8718: }
8719: }
8720: } else {
8721: $instcoderegexp .= $codedefaults->{$item};
8722: }
8723: }
8724: $instcoderegexp .= '$';
8725: my (@from,@to);
8726: eval {
8727: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8728: (@to) = ($clonetocode =~ /$instcoderegexp/);
8729: };
8730: if ((@from > 0) && (@to > 0)) {
8731: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8732: if (!@diffs) {
8733: $canclone = 1;
8734: }
8735: }
8736: }
8737: return $canclone;
8738: }
8739:
8740: sub default_instcode_cloning {
8741: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8742: my (%codedefaults,@code_order,$canclone);
8743: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8744: %codedefaults = %{$codedefaultsref};
8745: @code_order = @{$codeorderref};
8746: } elsif ($clonedom) {
8747: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8748: }
8749: if (($domdefclone) && (@code_order)) {
8750: my @clonecodes = split(/\+/,$domdefclone);
8751: my $instcoderegexp ='^';
8752: foreach my $item (@code_order) {
8753: if (grep(/^\Q$item\E$/,@clonecodes)) {
8754: $instcoderegexp .= '('.$codedefaults{$item}.')';
8755: } else {
8756: $instcoderegexp .= $codedefaults{$item};
8757: }
8758: }
8759: $instcoderegexp .= '$';
8760: my (@from,@to);
8761: eval {
8762: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8763: (@to) = ($clonetocode =~ /$instcoderegexp/);
8764: };
8765: if ((@from > 0) && (@to > 0)) {
8766: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8767: if (!@diffs) {
8768: $canclone = 1;
8769: }
8770: }
8771: }
8772: return $canclone;
8773: }
8774:
1.679 raeburn 8775: # ------------------------------------------------------- Course Group routines
8776:
8777: sub get_coursegroups {
1.809 raeburn 8778: my ($cdom,$cnum,$group,$namespace) = @_;
8779: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8780: }
8781:
1.679 raeburn 8782: sub modify_coursegroup {
8783: my ($cdom,$cnum,$groupsettings) = @_;
8784: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8785: }
8786:
1.809 raeburn 8787: sub toggle_coursegroup_status {
8788: my ($cdom,$cnum,$group,$action) = @_;
8789: my ($from_namespace,$to_namespace);
8790: if ($action eq 'delete') {
8791: $from_namespace = 'coursegroups';
8792: $to_namespace = 'deleted_groups';
8793: } else {
8794: $from_namespace = 'deleted_groups';
8795: $to_namespace = 'coursegroups';
8796: }
8797: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8798: if (my $tmp = &error(%curr_group)) {
8799: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8800: return ('read error',$tmp);
8801: } else {
8802: my %savedsettings = %curr_group;
1.809 raeburn 8803: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8804: my $deloutcome;
8805: if ($result eq 'ok') {
1.809 raeburn 8806: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8807: } else {
8808: return ('write error',$result);
8809: }
8810: if ($deloutcome eq 'ok') {
8811: return 'ok';
8812: } else {
8813: return ('delete error',$deloutcome);
8814: }
8815: }
8816: }
8817:
1.679 raeburn 8818: sub modify_group_roles {
1.957 raeburn 8819: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8820: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8821: my $role = 'gr/'.&escape($userprivs);
8822: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8823: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8824: if ($result eq 'ok') {
8825: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8826: }
1.679 raeburn 8827: return $result;
8828: }
8829:
8830: sub modify_coursegroup_membership {
8831: my ($cdom,$cnum,$membership) = @_;
8832: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8833: return $result;
8834: }
8835:
1.682 raeburn 8836: sub get_active_groups {
8837: my ($udom,$uname,$cdom,$cnum) = @_;
8838: my $now = time;
8839: my %groups = ();
8840: foreach my $key (keys(%env)) {
1.811 albertel 8841: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8842: my ($start,$end) = split(/\./,$env{$key});
8843: if (($end!=0) && ($end<$now)) { next; }
8844: if (($start!=0) && ($start>$now)) { next; }
8845: if ($1 eq $cdom && $2 eq $cnum) {
8846: $groups{$3} = $env{$key} ;
8847: }
8848: }
8849: }
8850: return %groups;
8851: }
8852:
1.683 raeburn 8853: sub get_group_membership {
8854: my ($cdom,$cnum,$group) = @_;
8855: return(&dump('groupmembership',$cdom,$cnum,$group));
8856: }
8857:
8858: sub get_users_groups {
8859: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8860: my @usersgroups;
1.683 raeburn 8861: my $cachetime=1800;
8862:
8863: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8864: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8865: if (defined($cached)) {
1.734 albertel 8866: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8867: } else {
8868: $grouplist = '';
1.816 raeburn 8869: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8870: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8871: my $access_end = $env{'course.'.$courseid.
8872: '.default_enrollment_end_date'};
8873: my $now = time;
8874: foreach my $key (keys(%roleshash)) {
8875: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8876: my $group = $1;
8877: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8878: my $start = $2;
8879: my $end = $1;
8880: if ($start == -1) { next; } # deleted from group
8881: if (($start!=0) && ($start>$now)) { next; }
8882: if (($end!=0) && ($end<$now)) {
8883: if ($access_end && $access_end < $now) {
8884: if ($access_end - $end < 86400) {
8885: push(@usersgroups,$group);
1.733 raeburn 8886: }
8887: }
1.817 raeburn 8888: next;
1.733 raeburn 8889: }
1.817 raeburn 8890: push(@usersgroups,$group);
1.683 raeburn 8891: }
8892: }
8893: }
1.817 raeburn 8894: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8895: $grouplist = join(':',@usersgroups);
8896: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8897: }
1.733 raeburn 8898: return @usersgroups;
1.683 raeburn 8899: }
8900:
8901: sub devalidate_getgroups_cache {
8902: my ($udom,$uname,$cdom,$cnum)=@_;
8903: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8904:
1.683 raeburn 8905: my $hashid="$udom:$uname:$courseid";
8906: &devalidate_cache_new('getgroups',$hashid);
8907: }
8908:
1.12 www 8909: # ------------------------------------------------------------------ Plain Text
8910:
8911: sub plaintext {
1.988 raeburn 8912: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8913: if ($short =~ m{^cr/}) {
1.758 albertel 8914: return (split('/',$short))[-1];
8915: }
1.742 raeburn 8916: if (!defined($cid)) {
8917: $cid = $env{'request.course.id'};
8918: }
8919: my %rolenames = (
1.1008 raeburn 8920: Course => 'std',
8921: Community => 'alt1',
1.742 raeburn 8922: );
1.1037 raeburn 8923: if ($cid ne '') {
8924: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8925: unless ($forcedefault) {
8926: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8927: &Apache::lonlocal::mt_escape(\$roletext);
8928: return &Apache::lonlocal::mt($roletext);
8929: }
8930: }
8931: }
8932: if ((defined($type)) && (defined($rolenames{$type})) &&
8933: (defined($rolenames{$type})) &&
8934: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8935: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8936: } elsif ($cid ne '') {
8937: my $crstype = $env{'course.'.$cid.'.type'};
8938: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8939: (defined($prp{$short}{$rolenames{$crstype}}))) {
8940: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8941: }
1.742 raeburn 8942: }
1.1037 raeburn 8943: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8944: }
8945:
8946: # ----------------------------------------------------------------- Assign Role
8947:
8948: sub assignrole {
1.957 raeburn 8949: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8950: $context)=@_;
1.21 www 8951: my $mrole;
8952: if ($role =~ /^cr\//) {
1.393 www 8953: my $cwosec=$url;
1.811 albertel 8954: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8955: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8956: my $refused = 1;
8957: if ($context eq 'requestcourses') {
8958: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8959: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8960: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8961: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8962: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8963: if ($crsenv{'internal.courseowner'} eq
8964: $env{'user.name'}.':'.$env{'user.domain'}) {
8965: $refused = '';
8966: }
8967: }
8968: }
8969: }
8970: }
8971: if ($refused) {
8972: &logthis('Refused custom assignrole: '.
8973: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8974: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8975: return 'refused';
8976: }
1.104 www 8977: }
1.21 www 8978: $mrole='cr';
1.678 raeburn 8979: } elsif ($role =~ /^gr\//) {
8980: my $cwogrp=$url;
1.811 albertel 8981: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8982: unless (&allowed('mdg',$cwogrp)) {
8983: &logthis('Refused group assignrole: '.
8984: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8985: $env{'user.name'}.' at '.$env{'user.domain'});
8986: return 'refused';
8987: }
8988: $mrole='gr';
1.21 www 8989: } else {
1.82 www 8990: my $cwosec=$url;
1.811 albertel 8991: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8992: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8993: my $refused;
8994: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8995: if (!(&allowed('c'.$role,$url))) {
8996: $refused = 1;
8997: }
8998: } else {
8999: $refused = 1;
9000: }
1.947 raeburn 9001: if ($refused) {
1.1045 raeburn 9002: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9003: if (!$selfenroll && $context eq 'course') {
9004: my %crsenv;
9005: if ($role eq 'cc' || $role eq 'co') {
9006: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9007: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9008: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9009: if ($crsenv{'internal.courseowner'} eq
9010: $env{'user.name'}.':'.$env{'user.domain'}) {
9011: $refused = '';
9012: }
9013: }
9014: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9015: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9016: if ($crsenv{'internal.courseowner'} eq
9017: $env{'user.name'}.':'.$env{'user.domain'}) {
9018: $refused = '';
9019: }
9020: }
9021: }
9022: }
9023: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9024: $refused = '';
1.1017 raeburn 9025: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9026: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9027: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9028: my $wrongcc;
9029: if ($cnum =~ /^$match_community$/) {
9030: $wrongcc = 1 if ($role eq 'cc');
9031: } else {
9032: $wrongcc = 1 if ($role eq 'co');
9033: }
9034: unless ($wrongcc) {
9035: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9036: if ($crsenv{'internal.courseowner'} eq
9037: $env{'user.name'}.':'.$env{'user.domain'}) {
9038: $refused = '';
9039: }
1.1017 raeburn 9040: }
9041: }
1.1172.2.9 raeburn 9042: } elsif ($context eq 'requestauthor') {
9043: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9044: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9045: if ($env{'environment.requestauthor'} eq 'automatic') {
9046: $refused = '';
9047: } else {
9048: my %domdefaults = &get_domain_defaults($udom);
9049: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9050: my $checkbystatus;
9051: if ($env{'user.adv'}) {
9052: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9053: if ($disposition eq 'automatic') {
9054: $refused = '';
9055: } elsif ($disposition eq '') {
9056: $checkbystatus = 1;
9057: }
9058: } else {
9059: $checkbystatus = 1;
9060: }
9061: if ($checkbystatus) {
9062: if ($env{'environment.inststatus'}) {
9063: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9064: foreach my $type (@inststatuses) {
9065: if (($type ne '') &&
9066: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9067: $refused = '';
9068: }
9069: }
9070: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9071: $refused = '';
9072: }
9073: }
9074: }
9075: }
9076: }
1.1017 raeburn 9077: }
9078: if ($refused) {
1.947 raeburn 9079: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9080: ' '.$role.' '.$end.' '.$start.' by '.
9081: $env{'user.name'}.' at '.$env{'user.domain'});
9082: return 'refused';
9083: }
1.932 raeburn 9084: }
1.1131 raeburn 9085: } elsif ($role eq 'au') {
9086: if ($url ne '/'.$udom.'/') {
9087: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9088: ' to assign author role for '.$uname.':'.$udom.
9089: ' in domain: '.$url.' refused (wrong domain).');
9090: return 'refused';
9091: }
1.104 www 9092: }
1.21 www 9093: $mrole=$role;
9094: }
1.620 albertel 9095: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9096: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9097: if ($end) { $command.='_'.$end; }
1.21 www 9098: if ($start) {
9099: if ($end) {
1.81 www 9100: $command.='_'.$start;
1.21 www 9101: } else {
1.81 www 9102: $command.='_0_'.$start;
1.21 www 9103: }
9104: }
1.739 raeburn 9105: my $origstart = $start;
9106: my $origend = $end;
1.957 raeburn 9107: my $delflag;
1.357 www 9108: # actually delete
9109: if ($deleteflag) {
1.373 www 9110: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9111: # modify command to delete the role
1.620 albertel 9112: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9113: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9114: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9115: # set start and finish to negative values for userrolelog
9116: $start=-1;
9117: $end=-1;
1.957 raeburn 9118: $delflag = 1;
1.357 www 9119: }
9120: }
9121: # send command
1.349 www 9122: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9123: # log new user role if status is ok
1.349 www 9124: if ($answer eq 'ok') {
1.663 raeburn 9125: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9126: if (($role eq 'cc') || ($role eq 'in') ||
9127: ($role eq 'ep') || ($role eq 'ad') ||
9128: ($role eq 'ta') || ($role eq 'st') ||
9129: ($role=~/^cr/) || ($role eq 'gr') ||
9130: ($role eq 'co')) {
1.1172.2.13 raeburn 9131: # for course roles, perform group memberships changes triggered by role change.
9132: unless ($role =~ /^gr/) {
9133: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9134: $origstart,$selfenroll,$context);
9135: }
1.1172.2.9 raeburn 9136: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9137: $selfenroll,$context);
9138: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9139: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9140: ($role eq 'da')) {
1.1172.2.9 raeburn 9141: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9142: $context);
9143: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9144: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9145: $context);
9146: }
1.1053 raeburn 9147: if ($role eq 'cc') {
9148: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9149: }
1.349 www 9150: }
9151: return $answer;
1.169 harris41 9152: }
9153:
1.1053 raeburn 9154: sub autoupdate_coowners {
9155: my ($url,$end,$start,$uname,$udom) = @_;
9156: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9157: if (($cdom ne '') && ($cnum ne '')) {
9158: my $now = time;
9159: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9160: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9161: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9162: my $instcode = $coursehash{'internal.coursecode'};
9163: if ($instcode ne '') {
1.1056 raeburn 9164: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9165: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9166: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9167: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9168: if ($result eq 'valid') {
9169: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9170: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9171: push(@newcoowners,$coowner);
9172: }
9173: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9174: push(@newcoowners,$uname.':'.$udom);
9175: }
9176: @newcoowners = sort(@newcoowners);
9177: } else {
9178: push(@newcoowners,$uname.':'.$udom);
9179: }
9180: } else {
9181: if ($coursehash{'internal.co-owners'}) {
9182: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9183: unless ($coowner eq $uname.':'.$udom) {
9184: push(@newcoowners,$coowner);
9185: }
9186: }
9187: unless (@newcoowners > 0) {
9188: $delcoowners = 1;
9189: $coowners = '';
9190: }
9191: }
9192: }
9193: if (@newcoowners || $delcoowners) {
9194: &store_coowners($cdom,$cnum,$coursehash{'home'},
9195: $delcoowners,@newcoowners);
9196: }
9197: }
9198: }
9199: }
9200: }
9201: }
9202: }
9203:
9204: sub store_coowners {
9205: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9206: my $cid = $cdom.'_'.$cnum;
9207: my ($coowners,$delresult,$putresult);
9208: if (@newcoowners) {
9209: $coowners = join(',',@newcoowners);
9210: my %coownershash = (
9211: 'internal.co-owners' => $coowners,
9212: );
9213: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9214: if ($putresult eq 'ok') {
9215: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9216: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9217: }
9218: }
9219: }
9220: if ($delcoowners) {
9221: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9222: if ($delresult eq 'ok') {
9223: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9224: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9225: }
9226: }
9227: }
9228: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9229: my %crsinfo =
9230: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9231: if (ref($crsinfo{$cid}) eq 'HASH') {
9232: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9233: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9234: }
9235: }
9236: }
9237:
1.169 harris41 9238: # -------------------------------------------------- Modify user authentication
1.197 www 9239: # Overrides without validation
9240:
1.169 harris41 9241: sub modifyuserauth {
9242: my ($udom,$uname,$umode,$upass)=@_;
9243: my $uhome=&homeserver($uname,$udom);
1.197 www 9244: unless (&allowed('mau',$udom)) { return 'refused'; }
9245: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9246: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9247: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9248: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9249: &escape($upass),$uhome);
1.620 albertel 9250: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9251: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9252: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9253: &log($udom,,$uname,$uhome,
1.620 albertel 9254: 'Authentication changed by '.$env{'user.domain'}.', '.
9255: $env{'user.name'}.', '.$umode.
1.197 www 9256: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9257: unless ($reply eq 'ok') {
1.197 www 9258: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9259: return 'error: '.$reply;
9260: }
1.170 harris41 9261: return 'ok';
1.80 www 9262: }
9263:
1.81 www 9264: # --------------------------------------------------------------- Modify a user
1.80 www 9265:
1.81 www 9266: sub modifyuser {
1.206 matthew 9267: my ($udom, $uname, $uid,
9268: $umode, $upass, $first,
9269: $middle, $last, $gene,
1.1058 raeburn 9270: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9271: $udom= &LONCAPA::clean_domain($udom);
9272: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9273: my $showcandelete = 'none';
9274: if (ref($candelete) eq 'ARRAY') {
9275: if (@{$candelete} > 0) {
9276: $showcandelete = join(', ',@{$candelete});
9277: }
9278: }
1.81 www 9279: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9280: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9281: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9282: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9283: ' desiredhome not specified').
1.620 albertel 9284: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9285: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9286: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9287: my $newuser;
9288: if ($uhome eq 'no_host') {
9289: $newuser = 1;
9290: }
1.80 www 9291: # ----------------------------------------------------------------- Create User
1.406 albertel 9292: if (($uhome eq 'no_host') &&
9293: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9294: my $unhome='';
1.844 albertel 9295: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9296: $unhome = $desiredhome;
1.620 albertel 9297: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9298: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9299: } else { # load balancing routine for determining $unhome
1.81 www 9300: my $loadm=10000000;
1.841 albertel 9301: my %servers = &get_servers($udom,'library');
9302: foreach my $tryserver (keys(%servers)) {
9303: my $answer=reply('load',$tryserver);
9304: if (($answer=~/\d+/) && ($answer<$loadm)) {
9305: $loadm=$answer;
9306: $unhome=$tryserver;
9307: }
1.80 www 9308: }
9309: }
9310: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9311: return 'error: unable to find a home server for '.$uname.
9312: ' in domain '.$udom;
1.80 www 9313: }
9314: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9315: &escape($upass),$unhome);
9316: unless ($reply eq 'ok') {
9317: return 'error: '.$reply;
9318: }
1.230 stredwic 9319: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9320: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9321: return 'error: unable verify users home machine.';
1.80 www 9322: }
1.209 matthew 9323: } # End of creation of new user
1.80 www 9324: # ---------------------------------------------------------------------- Add ID
9325: if ($uid) {
9326: $uid=~tr/A-Z/a-z/;
9327: my %uidhash=&idrget($udom,$uname);
1.196 www 9328: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9329: && (!$forceid)) {
1.80 www 9330: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9331: return 'error: user id "'.$uid.'" does not match '.
9332: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9333: }
9334: } else {
9335: &idput($udom,($uname => $uid));
9336: }
9337: }
9338: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9339: my @tmp=&get('environment',
1.899 raeburn 9340: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9341: 'permanentemail','inststatus'],
1.134 albertel 9342: $udom,$uname);
1.1075 raeburn 9343: my (%names,%oldnames);
1.313 matthew 9344: if ($tmp[0] =~ m/^error:.*/) {
9345: %names=();
9346: } else {
9347: %names = @tmp;
1.1075 raeburn 9348: %oldnames = %names;
1.313 matthew 9349: }
1.388 www 9350: #
1.1058 raeburn 9351: # If name, email and/or uid are blank (e.g., because an uploaded file
9352: # of users did not contain them), do not overwrite existing values
9353: # unless field is in $candelete array ref.
9354: #
9355:
9356: my @fields = ('firstname','middlename','lastname','generation',
9357: 'permanentemail','id');
9358: my %newvalues;
9359: if (ref($candelete) eq 'ARRAY') {
9360: foreach my $field (@fields) {
9361: if (grep(/^\Q$field\E$/,@{$candelete})) {
9362: if ($field eq 'firstname') {
9363: $names{$field} = $first;
9364: } elsif ($field eq 'middlename') {
9365: $names{$field} = $middle;
9366: } elsif ($field eq 'lastname') {
9367: $names{$field} = $last;
9368: } elsif ($field eq 'generation') {
9369: $names{$field} = $gene;
9370: } elsif ($field eq 'permanentemail') {
9371: $names{$field} = $email;
9372: } elsif ($field eq 'id') {
9373: $names{$field} = $uid;
9374: }
9375: }
9376: }
9377: }
1.388 www 9378: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9379: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9380: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9381: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9382: if ($email) {
9383: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9384: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9385: }
1.899 raeburn 9386: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9387: if (defined($inststatus)) {
9388: $names{'inststatus'} = '';
9389: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9390: if (ref($usertypes) eq 'HASH') {
9391: my @okstatuses;
9392: foreach my $item (split(/:/,$inststatus)) {
9393: if (defined($usertypes->{$item})) {
9394: push(@okstatuses,$item);
9395: }
9396: }
9397: if (@okstatuses) {
9398: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9399: }
9400: }
9401: }
1.1075 raeburn 9402: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9403: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9404: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9405: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9406: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9407: } else {
9408: $logmsg .= ' during self creation';
9409: }
1.1075 raeburn 9410: my $changed;
9411: if ($newuser) {
9412: $changed = 1;
9413: } else {
9414: foreach my $field (@fields) {
9415: if ($names{$field} ne $oldnames{$field}) {
9416: $changed = 1;
9417: last;
9418: }
9419: }
9420: }
9421: unless ($changed) {
9422: $logmsg = 'No changes in user information needed for: '.$logmsg;
9423: &logthis($logmsg);
9424: return 'ok';
9425: }
9426: my $reply = &put('environment', \%names, $udom,$uname);
9427: if ($reply ne 'ok') {
9428: return 'error: '.$reply;
9429: }
1.1087 raeburn 9430: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9431: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9432: }
1.1075 raeburn 9433: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9434: &devalidate_cache_new('namescache',$uname.':'.$udom);
9435: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9436: &logthis($logmsg);
1.134 albertel 9437: return 'ok';
1.80 www 9438: }
9439:
1.81 www 9440: # -------------------------------------------------------------- Modify student
1.80 www 9441:
1.81 www 9442: sub modifystudent {
9443: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9444: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 9445: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9446: if (!$cid) {
1.620 albertel 9447: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9448: return 'not_in_class';
9449: }
1.80 www 9450: }
9451: # --------------------------------------------------------------- Make the user
1.81 www 9452: my $reply=&modifyuser
1.209 matthew 9453: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9454: $desiredhome,$email,$inststatus);
1.80 www 9455: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9456: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 9457: # student's environment
1.297 matthew 9458: $uid = undef if (!$forceid);
1.455 albertel 9459: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 9460: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 9461: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9462: return $reply;
9463: }
9464:
9465: sub modify_student_enrollment {
1.1172.2.23 raeburn 9466: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 9467: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9468: my ($cdom,$cnum,$chome);
9469: if (!$cid) {
1.620 albertel 9470: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9471: return 'not_in_class';
9472: }
1.620 albertel 9473: $cdom=$env{'course.'.$cid.'.domain'};
9474: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9475: } else {
9476: ($cdom,$cnum)=split(/_/,$cid);
9477: }
1.620 albertel 9478: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9479: if (!$chome) {
1.457 raeburn 9480: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9481: }
1.455 albertel 9482: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9483: # Make sure the user exists
1.81 www 9484: my $uhome=&homeserver($uname,$udom);
9485: if (($uhome eq '') || ($uhome eq 'no_host')) {
9486: return 'error: no such user';
9487: }
1.297 matthew 9488: # Get student data if we were not given enough information
9489: if (!defined($first) || $first eq '' ||
9490: !defined($last) || $last eq '' ||
9491: !defined($uid) || $uid eq '' ||
9492: !defined($middle) || $middle eq '' ||
9493: !defined($gene) || $gene eq '') {
1.294 matthew 9494: # They did not supply us with enough data to enroll the student, so
9495: # we need to pick up more information.
1.297 matthew 9496: my %tmp = &get('environment',
1.294 matthew 9497: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9498: ,$udom,$uname);
9499:
1.800 albertel 9500: #foreach my $key (keys(%tmp)) {
9501: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9502: #}
1.294 matthew 9503: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9504: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9505: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9506: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9507: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9508: }
1.556 albertel 9509: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9510: my $user = "$uname:$udom";
9511: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9512: my $reply=cput('classlist',
1.1148 raeburn 9513: {$user =>
1.1172.2.76 raeburn 9514: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9515: $cdom,$cnum);
1.1148 raeburn 9516: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9517: &devalidate_getsection_cache($udom,$uname,$cid);
9518: } else {
1.81 www 9519: return 'error: '.$reply;
9520: }
1.297 matthew 9521: # Add student role to user
1.83 www 9522: my $uurl='/'.$cid;
1.81 www 9523: $uurl=~s/\_/\//g;
9524: if ($usec) {
9525: $uurl.='/'.$usec;
9526: }
1.1148 raeburn 9527: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9528: $selfenroll,$context);
9529: if ($result ne 'ok') {
9530: if ($old_entry{$user} ne '') {
9531: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9532: } else {
9533: $reply = &del('classlist',[$user],$cdom,$cnum);
9534: }
9535: }
9536: return $result;
1.21 www 9537: }
9538:
1.556 albertel 9539: sub format_name {
9540: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9541: my $name;
9542: if ($first ne 'lastname') {
9543: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9544: } else {
9545: if ($lastname=~/\S/) {
9546: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9547: $name=~s/\s+,/,/;
9548: } else {
9549: $name.= $firstname.' '.$middlename.' '.$generation;
9550: }
9551: }
9552: $name=~s/^\s+//;
9553: $name=~s/\s+$//;
9554: $name=~s/\s+/ /g;
9555: return $name;
9556: }
9557:
1.84 www 9558: # ------------------------------------------------- Write to course preferences
9559:
9560: sub writecoursepref {
9561: my ($courseid,%prefs)=@_;
9562: $courseid=~s/^\///;
9563: $courseid=~s/\_/\//g;
9564: my ($cdomain,$cnum)=split(/\//,$courseid);
9565: my $chome=homeserver($cnum,$cdomain);
9566: if (($chome eq '') || ($chome eq 'no_host')) {
9567: return 'error: no such course';
9568: }
9569: my $cstring='';
1.800 albertel 9570: foreach my $pref (keys(%prefs)) {
9571: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9572: }
1.84 www 9573: $cstring=~s/\&$//;
9574: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9575: }
9576:
9577: # ---------------------------------------------------------- Make/modify course
9578:
9579: sub createcourse {
1.741 raeburn 9580: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9581: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9582: $url=&declutter($url);
9583: my $cid='';
1.1028 raeburn 9584: if ($context eq 'requestcourses') {
9585: my $can_create = 0;
9586: my ($ownername,$ownerdom) = split(':',$course_owner);
9587: if ($udom eq $ownerdom) {
9588: if (&usertools_access($ownername,$ownerdom,$category,undef,
9589: $context)) {
9590: $can_create = 1;
9591: }
9592: } else {
9593: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9594: $category);
9595: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9596: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9597: if (@curr > 0) {
9598: my @options = qw(approval validate autolimit);
9599: my $optregex = join('|',@options);
9600: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9601: $can_create = 1;
9602: }
9603: }
9604: }
9605: }
9606: if ($can_create) {
9607: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9608: unless (&allowed('ccc',$udom)) {
9609: return 'refused';
9610: }
1.1017 raeburn 9611: }
9612: } else {
9613: return 'refused';
9614: }
1.1028 raeburn 9615: } elsif (!&allowed('ccc',$udom)) {
9616: return 'refused';
1.84 www 9617: }
1.1011 raeburn 9618: # --------------------------------------------------------------- Get Unique ID
9619: my $uname;
9620: if ($cnum =~ /^$match_courseid$/) {
9621: my $chome=&homeserver($cnum,$udom,'true');
9622: if (($chome eq '') || ($chome eq 'no_host')) {
9623: $uname = $cnum;
9624: } else {
1.1038 raeburn 9625: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9626: }
9627: } else {
1.1038 raeburn 9628: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9629: }
9630: return $uname if ($uname =~ /^error/);
9631: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9632: if (!defined($course_server)) {
9633: if (defined(&domain($udom,'primary'))) {
9634: $course_server = &domain($udom,'primary');
9635: } else {
9636: $course_server = $env{'user.home'};
9637: }
9638: }
9639: my %host_servers =
9640: &Apache::lonnet::get_servers($udom,'library');
9641: unless ($host_servers{$course_server}) {
9642: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9643: }
1.84 www 9644: # ------------------------------------------------------------- Make the course
9645: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9646: $course_server);
1.84 www 9647: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9648: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9649: if (($uhome eq '') || ($uhome eq 'no_host')) {
9650: return 'error: no such course';
9651: }
1.271 www 9652: # ----------------------------------------------------------------- Course made
1.516 raeburn 9653: # log existence
1.1029 raeburn 9654: my $now = time;
1.918 raeburn 9655: my $newcourse = {
9656: $udom.'_'.$uname => {
1.921 raeburn 9657: description => $description,
9658: inst_code => $inst_code,
9659: owner => $course_owner,
9660: type => $crstype,
1.1029 raeburn 9661: creator => $env{'user.name'}.':'.
9662: $env{'user.domain'},
9663: created => $now,
9664: context => $context,
1.918 raeburn 9665: },
9666: };
1.921 raeburn 9667: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9668: # set toplevel url
1.271 www 9669: my $topurl=$url;
9670: unless ($nonstandard) {
9671: # ------------------------------------------ For standard courses, make top url
9672: my $mapurl=&clutter($url);
1.278 www 9673: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9674: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9675: <map>
9676: <resource id="1" type="start"></resource>
9677: <resource id="2" src="$mapurl"></resource>
9678: <resource id="3" type="finish"></resource>
9679: <link index="1" from="1" to="2"></link>
9680: <link index="2" from="2" to="3"></link>
9681: </map>
9682: ENDINITMAP
9683: $topurl=&declutter(
1.638 albertel 9684: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9685: );
9686: }
9687: # ----------------------------------------------------------- Write preferences
1.84 www 9688: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9689: ('description' => $description,
9690: 'url' => $topurl,
9691: 'internal.creator' => $env{'user.name'}.':'.
9692: $env{'user.domain'},
9693: 'internal.created' => $now,
9694: 'internal.creationcontext' => $context)
9695: );
1.84 www 9696: return '/'.$udom.'/'.$uname;
9697: }
9698:
1.1011 raeburn 9699: # ------------------------------------------------------------------- Create ID
9700: sub generate_coursenum {
1.1038 raeburn 9701: my ($udom,$crstype) = @_;
1.1011 raeburn 9702: my $domdesc = &domain($udom);
9703: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9704: my $first;
9705: if ($crstype eq 'Community') {
9706: $first = '0';
9707: } else {
9708: $first = int(1+rand(9));
9709: }
9710: my $uname=$first.
1.1011 raeburn 9711: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9712: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9713: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9714: # ----------------------------------------------- Make sure that does not exist
9715: my $uhome=&homeserver($uname,$udom,'true');
9716: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9717: if ($crstype eq 'Community') {
9718: $first = '0';
9719: } else {
9720: $first = int(1+rand(9));
9721: }
9722: $uname=$first.
1.1011 raeburn 9723: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9724: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9725: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9726: $uhome=&homeserver($uname,$udom,'true');
9727: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9728: return 'error: unable to generate unique course-ID';
9729: }
9730: }
9731: return $uname;
9732: }
9733:
1.813 albertel 9734: sub is_course {
1.1167 droeschl 9735: my ($cdom, $cnum) = scalar(@_) == 1 ?
9736: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 9737: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
9738: my $uhome=&homeserver($cnum,$cdom);
9739: my $iscourse;
9740: if (grep { $_ eq $uhome } current_machine_ids()) {
9741: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
9742: } else {
9743: my $hashid = $cdom.':'.$cnum;
9744: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
9745: unless (defined($cached)) {
9746: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
9747: $cnum,undef,undef,'.');
9748: $iscourse = 0;
9749: if (exists($courses{$cdom.'_'.$cnum})) {
9750: $iscourse = 1;
9751: }
9752: &do_cache_new('iscourse',$hashid,$iscourse,3600);
9753: }
9754: }
9755: return unless($iscourse);
1.1167 droeschl 9756: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9757: }
9758:
1.1015 raeburn 9759: sub store_userdata {
9760: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9761: my $result;
1.1016 raeburn 9762: if ($datakey ne '') {
1.1013 raeburn 9763: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9764: if ($udom eq '' || $uname eq '') {
9765: $udom = $env{'user.domain'};
9766: $uname = $env{'user.name'};
9767: }
9768: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9769: if (($uhome eq '') || ($uhome eq 'no_host')) {
9770: $result = 'error: no_host';
9771: } else {
9772: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9773: $storehash->{'host'} = $perlvar{'lonHostID'};
9774:
9775: my $namevalue='';
9776: foreach my $key (keys(%{$storehash})) {
9777: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9778: }
9779: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9780: unless ($namespace eq 'courserequests') {
9781: $datakey = &escape($datakey);
9782: }
1.1105 raeburn 9783: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9784: $namevalue,$uhome);
1.1013 raeburn 9785: }
9786: } else {
9787: $result = 'error: data to store was not a hash reference';
9788: }
9789: } else {
9790: $result= 'error: invalid requestkey';
9791: }
9792: return $result;
9793: }
9794:
1.21 www 9795: # ---------------------------------------------------------- Assign Custom Role
9796:
9797: sub assigncustomrole {
1.957 raeburn 9798: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9799: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9800: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9801: }
9802:
9803: # ----------------------------------------------------------------- Revoke Role
9804:
9805: sub revokerole {
1.957 raeburn 9806: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9807: my $now=time;
1.965 raeburn 9808: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9809: }
9810:
9811: # ---------------------------------------------------------- Revoke Custom Role
9812:
9813: sub revokecustomrole {
1.957 raeburn 9814: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9815: my $now=time;
1.357 www 9816: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9817: $deleteflag,$selfenroll,$context);
1.17 www 9818: }
9819:
1.533 banghart 9820: # ------------------------------------------------------------ Disk usage
1.535 albertel 9821: sub diskusage {
1.955 raeburn 9822: my ($udom,$uname,$directorypath,$getpropath)=@_;
9823: $directorypath =~ s/\/$//;
9824: my $listing=&reply('du2:'.&escape($directorypath).':'
9825: .&escape($getpropath).':'.&escape($uname).':'
9826: .&escape($udom),homeserver($uname,$udom));
9827: if ($listing eq 'unknown_cmd') {
9828: if ($getpropath) {
9829: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9830: }
9831: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9832: }
1.514 albertel 9833: return $listing;
1.512 banghart 9834: }
9835:
1.566 banghart 9836: sub is_locked {
1.1096 raeburn 9837: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9838: my @check;
9839: my $is_locked;
1.1093 raeburn 9840: push (@check,$file_name);
1.613 albertel 9841: my %locked = &get('file_permissions',\@check,
1.620 albertel 9842: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9843: my ($tmp)=keys(%locked);
9844: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9845:
1.566 banghart 9846: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9847: $is_locked = 'false';
9848: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9849: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9850: $is_locked = 'true';
1.1096 raeburn 9851: if (ref($which) eq 'ARRAY') {
9852: push(@{$which},$entry);
9853: } else {
9854: last;
9855: }
1.745 raeburn 9856: }
9857: }
1.566 banghart 9858: } else {
9859: $is_locked = 'false';
9860: }
1.1093 raeburn 9861: return $is_locked;
1.566 banghart 9862: }
9863:
1.759 albertel 9864: sub declutter_portfile {
9865: my ($file) = @_;
1.833 albertel 9866: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9867: return $file;
9868: }
9869:
1.559 banghart 9870: # ------------------------------------------------------------- Mark as Read Only
9871:
9872: sub mark_as_readonly {
9873: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9874: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9875: my ($tmp)=keys(%current_permissions);
9876: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9877: foreach my $file (@{$files}) {
1.759 albertel 9878: $file = &declutter_portfile($file);
1.561 banghart 9879: push(@{$current_permissions{$file}},$what);
1.559 banghart 9880: }
1.613 albertel 9881: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9882: return;
9883: }
9884:
1.572 banghart 9885: # ------------------------------------------------------------Save Selected Files
9886:
9887: sub save_selected_files {
9888: my ($user, $path, @files) = @_;
9889: my $filename = $user."savedfiles";
1.573 banghart 9890: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 9891: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 9892: foreach my $file (@files) {
1.620 albertel 9893: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9894: }
9895: foreach my $file (@other_files) {
1.574 banghart 9896: print (OUT $file."\n");
1.572 banghart 9897: }
1.574 banghart 9898: close (OUT);
1.572 banghart 9899: return 'ok';
9900: }
9901:
1.574 banghart 9902: sub clear_selected_files {
9903: my ($user) = @_;
9904: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 9905: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 9906: print (OUT undef);
9907: close (OUT);
9908: return ("ok");
9909: }
9910:
1.572 banghart 9911: sub files_in_path {
9912: my ($user, $path) = @_;
9913: my $filename = $user."savedfiles";
9914: my %return_files;
1.1172.2.96 raeburn 9915: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 9916: while (my $line_in = <IN>) {
1.574 banghart 9917: chomp ($line_in);
9918: my @paths_and_file = split (m!/!, $line_in);
9919: my $file_part = pop (@paths_and_file);
9920: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9921: $path_part.='/';
9922: my $path_and_file = $path_part.$file_part;
9923: if ($path_part eq $path) {
9924: $return_files{$file_part}= 'selected';
9925: }
9926: }
1.574 banghart 9927: close (IN);
9928: return (\%return_files);
1.572 banghart 9929: }
9930:
9931: # called in portfolio select mode, to show files selected NOT in current directory
9932: sub files_not_in_path {
9933: my ($user, $path) = @_;
9934: my $filename = $user."savedfiles";
9935: my @return_files;
9936: my $path_part;
1.1172.2.96 raeburn 9937: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 9938: while (my $line = <IN>) {
1.572 banghart 9939: #ok, I know it's clunky, but I want it to work
1.800 albertel 9940: my @paths_and_file = split(m|/|, $line);
9941: my $file_part = pop(@paths_and_file);
9942: chomp($file_part);
9943: my $path_part = join('/', @paths_and_file);
1.572 banghart 9944: $path_part .= '/';
9945: my $path_and_file = $path_part.$file_part;
9946: if ($path_part ne $path) {
1.800 albertel 9947: push(@return_files, ($path_and_file));
1.572 banghart 9948: }
9949: }
1.800 albertel 9950: close(OUT);
1.574 banghart 9951: return (@return_files);
1.572 banghart 9952: }
9953:
1.745 raeburn 9954: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9955:
1.745 raeburn 9956: sub get_portfile_permissions {
9957: my ($domain,$user) = @_;
1.613 albertel 9958: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9959: my ($tmp)=keys(%current_permissions);
9960: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9961: return \%current_permissions;
9962: }
9963:
9964: #---------------------------------------------Get portfolio file access controls
9965:
1.749 raeburn 9966: sub get_access_controls {
1.745 raeburn 9967: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9968: my %access;
9969: my $real_file = $file;
9970: $file =~ s/\.meta$//;
1.745 raeburn 9971: if (defined($file)) {
1.749 raeburn 9972: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9973: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9974: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9975: }
9976: }
1.745 raeburn 9977: } else {
1.749 raeburn 9978: foreach my $key (keys(%{$current_permissions})) {
9979: if ($key =~ /\0accesscontrol$/) {
9980: if (defined($group)) {
9981: if ($key !~ m-^\Q$group\E/-) {
9982: next;
9983: }
9984: }
9985: my ($fullpath) = split(/\0/,$key);
9986: if (ref($$current_permissions{$key}) eq 'HASH') {
9987: foreach my $control (keys(%{$$current_permissions{$key}})) {
9988: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9989: }
9990: }
9991: }
9992: }
9993: }
9994: return %access;
9995: }
9996:
9997: sub modify_access_controls {
9998: my ($file_name,$changes,$domain,$user)=@_;
9999: my ($outcome,$deloutcome);
10000: my %store_permissions;
10001: my %new_values;
10002: my %new_control;
10003: my %translation;
10004: my @deletions = ();
10005: my $now = time;
10006: if (exists($$changes{'activate'})) {
10007: if (ref($$changes{'activate'}) eq 'HASH') {
10008: my @newitems = sort(keys(%{$$changes{'activate'}}));
10009: my $numnew = scalar(@newitems);
10010: for (my $i=0; $i<$numnew; $i++) {
10011: my $newkey = $newitems[$i];
10012: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10013: if ($newkey =~ /^\d+:/) {
10014: $newkey =~ s/^(\d+)/$newid/;
10015: $translation{$1} = $newid;
10016: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10017: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10018: $translation{$1} = $newid;
10019: }
1.749 raeburn 10020: $new_values{$file_name."\0".$newkey} =
10021: $$changes{'activate'}{$newitems[$i]};
10022: $new_control{$newkey} = $now;
10023: }
10024: }
10025: }
10026: my %todelete;
10027: my %changed_items;
10028: foreach my $action ('delete','update') {
10029: if (exists($$changes{$action})) {
10030: if (ref($$changes{$action}) eq 'HASH') {
10031: foreach my $key (keys(%{$$changes{$action}})) {
10032: my ($itemnum) = ($key =~ /^([^:]+):/);
10033: if ($action eq 'delete') {
10034: $todelete{$itemnum} = 1;
10035: } else {
10036: $changed_items{$itemnum} = $key;
10037: }
10038: }
1.745 raeburn 10039: }
10040: }
1.749 raeburn 10041: }
10042: # get lock on access controls for file.
10043: my $lockhash = {
10044: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10045: ':'.$env{'user.domain'},
10046: };
10047: my $tries = 0;
10048: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10049:
1.1172.2.79 raeburn 10050: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10051: $tries ++;
1.1172.2.79 raeburn 10052: sleep(0.1);
1.749 raeburn 10053: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10054: }
10055: if ($gotlock eq 'ok') {
10056: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10057: my ($tmp)=keys(%curr_permissions);
10058: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10059: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10060: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10061: if (ref($curr_controls) eq 'HASH') {
10062: foreach my $control_item (keys(%{$curr_controls})) {
10063: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10064: if (defined($todelete{$itemnum})) {
10065: push(@deletions,$file_name."\0".$control_item);
10066: } else {
10067: if (defined($changed_items{$itemnum})) {
10068: $new_control{$changed_items{$itemnum}} = $now;
10069: push(@deletions,$file_name."\0".$control_item);
10070: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10071: } else {
10072: $new_control{$control_item} = $$curr_controls{$control_item};
10073: }
10074: }
1.745 raeburn 10075: }
10076: }
10077: }
1.970 raeburn 10078: my ($group);
10079: if (&is_course($domain,$user)) {
10080: ($group,my $file) = split(/\//,$file_name,2);
10081: }
1.749 raeburn 10082: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10083: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10084: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10085: # remove lock
10086: my @del_lock = ($file_name."\0".'locked_access_records');
10087: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10088: my $sqlresult =
1.970 raeburn 10089: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10090: $group);
1.749 raeburn 10091: } else {
10092: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10093: }
1.749 raeburn 10094: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10095: }
10096:
1.827 raeburn 10097: sub make_public_indefinitely {
10098: my ($requrl) = @_;
10099: my $now = time;
10100: my $action = 'activate';
10101: my $aclnum = 0;
10102: if (&is_portfolio_url($requrl)) {
10103: my (undef,$udom,$unum,$file_name,$group) =
10104: &parse_portfolio_url($requrl);
10105: my $current_perms = &get_portfile_permissions($udom,$unum);
10106: my %access_controls = &get_access_controls($current_perms,
10107: $group,$file_name);
10108: foreach my $key (keys(%{$access_controls{$file_name}})) {
10109: my ($num,$scope,$end,$start) =
10110: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10111: if ($scope eq 'public') {
10112: if ($start <= $now && $end == 0) {
10113: $action = 'none';
10114: } else {
10115: $action = 'update';
10116: $aclnum = $num;
10117: }
10118: last;
10119: }
10120: }
10121: if ($action eq 'none') {
10122: return 'ok';
10123: } else {
10124: my %changes;
10125: my $newend = 0;
10126: my $newstart = $now;
10127: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10128: $changes{$action}{$newkey} = {
10129: type => 'public',
10130: time => {
10131: start => $newstart,
10132: end => $newend,
10133: },
10134: };
10135: my ($outcome,$deloutcome,$new_values,$translation) =
10136: &modify_access_controls($file_name,\%changes,$udom,$unum);
10137: return $outcome;
10138: }
10139: } else {
10140: return 'invalid';
10141: }
10142: }
10143:
1.745 raeburn 10144: #------------------------------------------------------Get Marked as Read Only
10145:
10146: sub get_marked_as_readonly {
10147: my ($domain,$user,$what,$group) = @_;
10148: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10149: my @readonly_files;
1.629 banghart 10150: my $cmp1=$what;
10151: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10152: while (my ($file_name,$value) = each(%{$current_permissions})) {
10153: if (defined($group)) {
10154: if ($file_name !~ m-^\Q$group\E/-) {
10155: next;
10156: }
10157: }
1.561 banghart 10158: if (ref($value) eq "ARRAY"){
10159: foreach my $stored_what (@{$value}) {
1.629 banghart 10160: my $cmp2=$stored_what;
1.759 albertel 10161: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10162: $cmp2=join('',@{$stored_what});
1.745 raeburn 10163: }
1.629 banghart 10164: if ($cmp1 eq $cmp2) {
1.561 banghart 10165: push(@readonly_files, $file_name);
1.745 raeburn 10166: last;
1.563 banghart 10167: } elsif (!defined($what)) {
10168: push(@readonly_files, $file_name);
1.745 raeburn 10169: last;
1.561 banghart 10170: }
10171: }
1.745 raeburn 10172: }
1.561 banghart 10173: }
10174: return @readonly_files;
10175: }
1.577 banghart 10176: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10177:
1.577 banghart 10178: sub get_marked_as_readonly_hash {
1.745 raeburn 10179: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10180: my %readonly_files;
1.745 raeburn 10181: while (my ($file_name,$value) = each(%{$current_permissions})) {
10182: if (defined($group)) {
10183: if ($file_name !~ m-^\Q$group\E/-) {
10184: next;
10185: }
10186: }
1.577 banghart 10187: if (ref($value) eq "ARRAY"){
10188: foreach my $stored_what (@{$value}) {
1.745 raeburn 10189: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10190: foreach my $lock_descriptor(@{$stored_what}) {
10191: if ($lock_descriptor eq 'graded') {
10192: $readonly_files{$file_name} = 'graded';
10193: } elsif ($lock_descriptor eq 'handback') {
10194: $readonly_files{$file_name} = 'handback';
10195: } else {
10196: if (!exists($readonly_files{$file_name})) {
10197: $readonly_files{$file_name} = 'locked';
10198: }
10199: }
1.745 raeburn 10200: }
1.750 banghart 10201: }
1.577 banghart 10202: }
10203: }
10204: }
10205: return %readonly_files;
10206: }
1.559 banghart 10207: # ------------------------------------------------------------ Unmark as Read Only
10208:
10209: sub unmark_as_readonly {
1.629 banghart 10210: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10211: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10212: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10213: $file_name = &declutter_portfile($file_name);
1.634 albertel 10214: my $symb_crs = $what;
10215: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10216: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10217: my ($tmp)=keys(%current_permissions);
10218: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10219: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10220: foreach my $file (@readonly_files) {
1.759 albertel 10221: my $clean_file = &declutter_portfile($file);
10222: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10223: my $current_locks = $current_permissions{$file};
1.563 banghart 10224: my @new_locks;
10225: my @del_keys;
10226: if (ref($current_locks) eq "ARRAY"){
10227: foreach my $locker (@{$current_locks}) {
1.632 albertel 10228: my $compare=$locker;
1.749 raeburn 10229: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10230: $compare=join('',@{$locker});
1.746 raeburn 10231: if ($compare ne $symb_crs) {
10232: push(@new_locks, $locker);
10233: }
1.563 banghart 10234: }
10235: }
1.650 albertel 10236: if (scalar(@new_locks) > 0) {
1.563 banghart 10237: $current_permissions{$file} = \@new_locks;
10238: } else {
10239: push(@del_keys, $file);
1.613 albertel 10240: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10241: delete($current_permissions{$file});
1.563 banghart 10242: }
10243: }
1.561 banghart 10244: }
1.613 albertel 10245: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10246: return;
10247: }
1.512 banghart 10248:
1.17 www 10249: # ------------------------------------------------------------ Directory lister
10250:
10251: sub dirlist {
1.955 raeburn 10252: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10253: $uri=~s/^\///;
10254: $uri=~s/\/$//;
1.253 stredwic 10255: my ($udom, $uname);
1.955 raeburn 10256: if ($getuserdir) {
1.253 stredwic 10257: $udom = $userdomain;
10258: $uname = $username;
1.955 raeburn 10259: } else {
10260: (undef,$udom,$uname)=split(/\//,$uri);
10261: if(defined($userdomain)) {
10262: $udom = $userdomain;
10263: }
10264: if(defined($username)) {
10265: $uname = $username;
10266: }
1.253 stredwic 10267: }
1.955 raeburn 10268: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10269:
1.955 raeburn 10270: $dirRoot = $perlvar{'lonDocRoot'};
10271: if (defined($getpropath)) {
10272: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10273: $dirRoot =~ s/\/$//;
1.955 raeburn 10274: } elsif (defined($getuserdir)) {
10275: my $subdir=$uname.'__';
10276: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10277: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10278: ."/$udom/$subdir/$uname";
10279: } elsif (defined($alternateRoot)) {
10280: $dirRoot = $alternateRoot;
1.751 banghart 10281: }
1.253 stredwic 10282:
10283: if($udom) {
10284: if($uname) {
1.1135 raeburn 10285: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10286: if ($uhome eq 'no_host') {
10287: return ([],'no_host');
10288: }
1.955 raeburn 10289: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10290: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10291: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10292: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10293: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10294: } else {
10295: @listing_results = map { &unescape($_); } split(/:/,$listing);
10296: }
1.605 matthew 10297: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10298: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10299: @listing_results = split(/:/,$listing);
10300: } else {
10301: @listing_results = map { &unescape($_); } split(/:/,$listing);
10302: }
1.1135 raeburn 10303: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10304: ($listing eq 'rejected') || ($listing eq 'refused') ||
10305: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10306: return ([],$listing);
10307: } else {
10308: return (\@listing_results);
1.1135 raeburn 10309: }
1.955 raeburn 10310: } elsif(!$alternateRoot) {
1.1136 raeburn 10311: my (%allusers,%listerror);
1.841 albertel 10312: my %servers = &get_servers($udom,'library');
1.955 raeburn 10313: foreach my $tryserver (keys(%servers)) {
10314: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10315: &escape($udom),$tryserver);
10316: if ($listing eq 'unknown_cmd') {
10317: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10318: $udom, $tryserver);
10319: } else {
10320: @listing_results = map { &unescape($_); } split(/:/,$listing);
10321: }
1.841 albertel 10322: if ($listing eq 'unknown_cmd') {
10323: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10324: $udom, $tryserver);
10325: @listing_results = split(/:/,$listing);
10326: } else {
10327: @listing_results =
10328: map { &unescape($_); } split(/:/,$listing);
10329: }
1.1136 raeburn 10330: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10331: ($listing eq 'rejected') || ($listing eq 'refused') ||
10332: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10333: $listerror{$tryserver} = $listing;
10334: } else {
1.841 albertel 10335: foreach my $line (@listing_results) {
10336: my ($entry) = split(/&/,$line,2);
10337: $allusers{$entry} = 1;
10338: }
10339: }
1.253 stredwic 10340: }
1.1136 raeburn 10341: my @alluserslist=();
1.800 albertel 10342: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10343: push(@alluserslist,$user.'&user');
1.253 stredwic 10344: }
1.1172.2.80 raeburn 10345: if (!%listerror) {
10346: # no errors
10347: return (\@alluserslist);
10348: } elsif (scalar(keys(%servers)) == 1) {
10349: # one library server, one error
10350: my ($key) = keys(%listerror);
10351: return (\@alluserslist, $listerror{$key});
10352: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10353: # con_lost indicates that we might miss data from at least one
10354: # library server
10355: return (\@alluserslist, 'con_lost');
10356: } else {
10357: # multiple library servers and no con_lost -> data should be
10358: # complete.
10359: return (\@alluserslist);
10360: }
10361:
1.253 stredwic 10362: } else {
1.1136 raeburn 10363: return ([],'missing username');
1.253 stredwic 10364: }
1.955 raeburn 10365: } elsif(!defined($getpropath)) {
1.1136 raeburn 10366: my $path = $perlvar{'lonDocRoot'}.'/res/';
10367: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10368: return (\@all_domains);
1.955 raeburn 10369: } else {
1.1136 raeburn 10370: return ([],'missing domain');
1.275 stredwic 10371: }
10372: }
10373:
10374: # --------------------------------------------- GetFileTimestamp
10375: # This function utilizes dirlist and returns the date stamp for
10376: # when it was last modified. It will also return an error of -1
10377: # if an error occurs
10378:
10379: sub GetFileTimestamp {
1.955 raeburn 10380: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10381: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10382: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10383: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10384: undef,$getuserdir);
10385: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10386: return -1;
10387: }
10388: if (ref($fileref) eq 'ARRAY') {
10389: my @stats = split('&',$fileref->[0]);
1.375 matthew 10390: # @stats contains first the filename, then the stat output
10391: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10392: } else {
10393: return -1;
1.253 stredwic 10394: }
1.26 www 10395: }
10396:
1.712 albertel 10397: sub stat_file {
10398: my ($uri) = @_;
1.787 albertel 10399: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10400:
1.955 raeburn 10401: my ($udom,$uname,$file);
1.712 albertel 10402: if ($uri =~ m-^/(uploaded|editupload)/-) {
10403: ($udom,$uname,$file) =
1.811 albertel 10404: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10405: $file = 'userfiles/'.$file;
10406: }
10407: if ($uri =~ m-^/res/-) {
10408: ($udom,$uname) =
1.807 albertel 10409: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10410: $file = $uri;
10411: }
10412:
10413: if (!$udom || !$uname || !$file) {
10414: # unable to handle the uri
10415: return ();
10416: }
1.956 raeburn 10417: my $getpropath;
10418: if ($file =~ /^userfiles\//) {
10419: $getpropath = 1;
10420: }
1.1136 raeburn 10421: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10422: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10423: return ();
10424: } else {
10425: if (ref($listref) eq 'ARRAY') {
10426: my @stats = split('&',$listref->[0]);
10427: shift(@stats); #filename is first
10428: return @stats;
10429: }
1.712 albertel 10430: }
10431: return ();
10432: }
10433:
1.26 www 10434: # -------------------------------------------------------- Value of a Condition
10435:
1.713 albertel 10436: # gets the value of a specific preevaluated condition
10437: # stored in the string $env{user.state.<cid>}
10438: # or looks up a condition reference in the bighash and if if hasn't
10439: # already been evaluated recurses into docondval to get the value of
10440: # the condition, then memoizing it to
10441: # $env{user.state.<cid>.<condition>}
1.40 www 10442: sub directcondval {
10443: my $number=shift;
1.620 albertel 10444: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10445: &Apache::lonuserstate::evalstate();
10446: }
1.713 albertel 10447: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10448: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10449: } elsif ($number =~ /^_/) {
10450: my $sub_condition;
10451: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10452: &GDBM_READER(),0640)) {
10453: $sub_condition=$bighash{'conditions'.$number};
10454: untie(%bighash);
10455: }
10456: my $value = &docondval($sub_condition);
1.949 raeburn 10457: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10458: return $value;
10459: }
1.620 albertel 10460: if ($env{'user.state.'.$env{'request.course.id'}}) {
10461: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10462: } else {
10463: return 2;
10464: }
10465: }
10466:
1.713 albertel 10467: # get the collection of conditions for this resource
1.26 www 10468: sub condval {
10469: my $condidx=shift;
1.54 www 10470: my $allpathcond='';
1.713 albertel 10471: foreach my $cond (split(/\|/,$condidx)) {
10472: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10473: $allpathcond.=
10474: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10475: }
1.191 harris41 10476: }
1.54 www 10477: $allpathcond=~s/\|$//;
1.713 albertel 10478: return &docondval($allpathcond);
10479: }
10480:
10481: #evaluates an expression of conditions
10482: sub docondval {
10483: my ($allpathcond) = @_;
10484: my $result=0;
10485: if ($env{'request.course.id'}
10486: && defined($allpathcond)) {
10487: my $operand='|';
10488: my @stack;
10489: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10490: if ($chunk eq '(') {
10491: push @stack,($operand,$result);
10492: } elsif ($chunk eq ')') {
10493: my $before=pop @stack;
10494: if (pop @stack eq '&') {
10495: $result=$result>$before?$before:$result;
10496: } else {
10497: $result=$result>$before?$result:$before;
10498: }
10499: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10500: $operand=$chunk;
10501: } else {
10502: my $new=directcondval($chunk);
10503: if ($operand eq '&') {
10504: $result=$result>$new?$new:$result;
10505: } else {
10506: $result=$result>$new?$result:$new;
10507: }
10508: }
10509: }
1.26 www 10510: }
10511: return $result;
1.421 albertel 10512: }
10513:
10514: # ---------------------------------------------------- Devalidate courseresdata
10515:
10516: sub devalidatecourseresdata {
10517: my ($coursenum,$coursedomain)=@_;
10518: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10519: &devalidate_cache_new('courseres',$hashid);
1.28 www 10520: }
10521:
1.763 www 10522:
1.200 www 10523: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10524: #
10525: # Parameters:
10526: # $coursenum - Number of the course.
10527: # $coursedomain - Domain at which the course was created.
10528: # Returns:
10529: # A hash of the course parameters along (I think) with timestamps
10530: # and version info.
1.877 foxr 10531:
1.624 albertel 10532: sub get_courseresdata {
10533: my ($coursenum,$coursedomain)=@_;
1.200 www 10534: my $coursehom=&homeserver($coursenum,$coursedomain);
10535: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10536: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10537: my %dumpreply;
1.417 albertel 10538: unless (defined($cached)) {
1.624 albertel 10539: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10540: $result=\%dumpreply;
1.251 albertel 10541: my ($tmp) = keys(%dumpreply);
10542: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10543: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10544: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10545: return $tmp;
1.416 albertel 10546: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10547: $result=undef;
1.599 albertel 10548: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10549: }
10550: }
1.624 albertel 10551: return $result;
10552: }
10553:
1.633 albertel 10554: sub devalidateuserresdata {
10555: my ($uname,$udom)=@_;
10556: my $hashid="$udom:$uname";
10557: &devalidate_cache_new('userres',$hashid);
10558: }
10559:
1.624 albertel 10560: sub get_userresdata {
10561: my ($uname,$udom)=@_;
10562: #most student don\'t have any data set, check if there is some data
10563: if (&EXT_cache_status($udom,$uname)) { return undef; }
10564:
10565: my $hashid="$udom:$uname";
10566: my ($result,$cached)=&is_cached_new('userres',$hashid);
10567: if (!defined($cached)) {
10568: my %resourcedata=&dump('resourcedata',$udom,$uname);
10569: $result=\%resourcedata;
10570: &do_cache_new('userres',$hashid,$result,600);
10571: }
10572: my ($tmp)=keys(%$result);
10573: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10574: return $result;
10575: }
10576: #error 2 occurs when the .db doesn't exist
10577: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10578: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10579: &logthis("<font color=\"blue\">WARNING:".
10580: " Trying to get resource data for ".
10581: $uname." at ".$udom.": ".
10582: $tmp."</font>");
10583: }
1.624 albertel 10584: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10585: #&EXT_cache_set($udom,$uname);
10586: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10587: undef($tmp); # not really an error so don't send it back
1.624 albertel 10588: }
10589: return $tmp;
10590: }
1.879 foxr 10591: #----------------------------------------------- resdata - return resource data
10592: # Purpose:
10593: # Return resource data for either users or for a course.
10594: # Parameters:
10595: # $name - Course/user name.
10596: # $domain - Name of the domain the user/course is registered on.
10597: # $type - Type of thing $name is (must be 'course' or 'user'
10598: # @which - Array of names of resources desired.
10599: # Returns:
10600: # The value of the first reasource in @which that is found in the
10601: # resource hash.
10602: # Exceptional Conditions:
10603: # If the $type passed in is not valid (not the string 'course' or
10604: # 'user', an undefined reference is returned.
10605: # If none of the resources are found, an undef is returned
1.624 albertel 10606: sub resdata {
10607: my ($name,$domain,$type,@which)=@_;
10608: my $result;
10609: if ($type eq 'course') {
10610: $result=&get_courseresdata($name,$domain);
10611: } elsif ($type eq 'user') {
10612: $result=&get_userresdata($name,$domain);
10613: }
10614: if (!ref($result)) { return $result; }
1.251 albertel 10615: foreach my $item (@which) {
1.927 albertel 10616: if (defined($result->{$item->[0]})) {
10617: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10618: }
1.250 albertel 10619: }
1.291 albertel 10620: return undef;
1.200 www 10621: }
10622:
1.1172.2.31 raeburn 10623: sub get_numsuppfiles {
10624: my ($cnum,$cdom,$ignorecache)=@_;
10625: my $hashid=$cnum.':'.$cdom;
10626: my ($suppcount,$cached);
10627: unless ($ignorecache) {
10628: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10629: }
10630: unless (defined($cached)) {
10631: my $chome=&homeserver($cnum,$cdom);
10632: unless ($chome eq 'no_host') {
10633: ($suppcount,my $errors) = (0,0);
10634: my $suppmap = 'supplemental.sequence';
10635: ($suppcount,$errors) =
10636: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10637: }
10638: &do_cache_new('suppcount',$hashid,$suppcount,600);
10639: }
10640: return $suppcount;
10641: }
10642:
1.379 matthew 10643: #
10644: # EXT resource caching routines
10645: #
10646:
10647: sub clear_EXT_cache_status {
1.383 albertel 10648: &delenv('cache.EXT.');
1.379 matthew 10649: }
10650:
10651: sub EXT_cache_status {
10652: my ($target_domain,$target_user) = @_;
1.383 albertel 10653: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10654: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10655: # We know already the user has no data
10656: return 1;
10657: } else {
10658: return 0;
10659: }
10660: }
10661:
10662: sub EXT_cache_set {
10663: my ($target_domain,$target_user) = @_;
1.383 albertel 10664: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10665: #&appenv({$cachename => time});
1.379 matthew 10666: }
10667:
1.28 www 10668: # --------------------------------------------------------- Value of a Variable
1.58 www 10669: sub EXT {
1.715 albertel 10670:
1.1172.2.28 raeburn 10671: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10672: unless ($varname) { return ''; }
1.218 albertel 10673: #get real user name/domain, courseid and symb
10674: my $courseid;
1.359 albertel 10675: my $publicuser;
1.427 www 10676: if ($symbparm) {
10677: $symbparm=&get_symb_from_alias($symbparm);
10678: }
1.218 albertel 10679: if (!($uname && $udom)) {
1.790 albertel 10680: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10681: if (!$symbparm) { $symbparm=$cursymb; }
10682: } else {
1.620 albertel 10683: $courseid=$env{'request.course.id'};
1.218 albertel 10684: }
1.48 www 10685: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10686: my $rest;
1.320 albertel 10687: if (defined($therest[0])) {
1.48 www 10688: $rest=join('.',@therest);
10689: } else {
10690: $rest='';
10691: }
1.320 albertel 10692:
1.57 www 10693: my $qualifierrest=$qualifier;
10694: if ($rest) { $qualifierrest.='.'.$rest; }
10695: my $spacequalifierrest=$space;
10696: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10697: if ($realm eq 'user') {
1.48 www 10698: # --------------------------------------------------------------- user.resource
10699: if ($space eq 'resource') {
1.651 albertel 10700: if ( (defined($Apache::lonhomework::parsing_a_problem)
10701: || defined($Apache::lonhomework::parsing_a_task))
10702: &&
1.744 albertel 10703: ($symbparm eq &symbread()) ) {
10704: # if we are in the middle of processing the resource the
10705: # get the value we are planning on committing
10706: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10707: return $Apache::lonhomework::results{$qualifierrest};
10708: } else {
10709: return $Apache::lonhomework::history{$qualifierrest};
10710: }
1.335 albertel 10711: } else {
1.359 albertel 10712: my %restored;
1.620 albertel 10713: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10714: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10715: } else {
10716: %restored=&restore($symbparm,$courseid,$udom,$uname);
10717: }
1.335 albertel 10718: return $restored{$qualifierrest};
10719: }
1.48 www 10720: # ----------------------------------------------------------------- user.access
10721: } elsif ($space eq 'access') {
1.218 albertel 10722: # FIXME - not supporting calls for a specific user
1.48 www 10723: return &allowed($qualifier,$rest);
10724: # ------------------------------------------ user.preferences, user.environment
10725: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10726: if (($uname eq $env{'user.name'}) &&
10727: ($udom eq $env{'user.domain'})) {
10728: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10729: } else {
1.359 albertel 10730: my %returnhash;
10731: if (!$publicuser) {
10732: %returnhash=&userenvironment($udom,$uname,
10733: $qualifierrest);
10734: }
1.218 albertel 10735: return $returnhash{$qualifierrest};
10736: }
1.48 www 10737: # ----------------------------------------------------------------- user.course
10738: } elsif ($space eq 'course') {
1.218 albertel 10739: # FIXME - not supporting calls for a specific user
1.620 albertel 10740: return $env{join('.',('request.course',$qualifier))};
1.48 www 10741: # ------------------------------------------------------------------- user.role
10742: } elsif ($space eq 'role') {
1.218 albertel 10743: # FIXME - not supporting calls for a specific user
1.620 albertel 10744: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10745: if ($qualifier eq 'value') {
10746: return $role;
10747: } elsif ($qualifier eq 'extent') {
10748: return $where;
10749: }
10750: # ----------------------------------------------------------------- user.domain
10751: } elsif ($space eq 'domain') {
1.218 albertel 10752: return $udom;
1.48 www 10753: # ------------------------------------------------------------------- user.name
10754: } elsif ($space eq 'name') {
1.218 albertel 10755: return $uname;
1.48 www 10756: # ---------------------------------------------------- Any other user namespace
1.29 www 10757: } else {
1.359 albertel 10758: my %reply;
10759: if (!$publicuser) {
10760: %reply=&get($space,[$qualifierrest],$udom,$uname);
10761: }
10762: return $reply{$qualifierrest};
1.48 www 10763: }
1.236 www 10764: } elsif ($realm eq 'query') {
10765: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10766: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10767: [$spacequalifierrest]);
1.620 albertel 10768: return $env{'form.'.$spacequalifierrest};
1.236 www 10769: } elsif ($realm eq 'request') {
1.48 www 10770: # ------------------------------------------------------------- request.browser
10771: if ($space eq 'browser') {
1.1145 bisitz 10772: return $env{'browser.'.$qualifier};
1.57 www 10773: # ------------------------------------------------------------ request.filename
10774: } else {
1.620 albertel 10775: return $env{'request.'.$spacequalifierrest};
1.29 www 10776: }
1.28 www 10777: } elsif ($realm eq 'course') {
1.48 www 10778: # ---------------------------------------------------------- course.description
1.620 albertel 10779: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10780: } elsif ($realm eq 'resource') {
1.165 www 10781:
1.620 albertel 10782: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10783: if (!$symbparm) { $symbparm=&symbread(); }
10784: }
1.693 albertel 10785:
1.1172.2.30 raeburn 10786: if ($qualifier eq '') {
10787: if ($space eq 'title') {
10788: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10789: return &gettitle($symbparm);
10790: }
1.693 albertel 10791:
1.1172.2.30 raeburn 10792: if ($space eq 'map') {
10793: my ($map) = &decode_symb($symbparm);
10794: return &symbread($map);
10795: }
10796: if ($space eq 'maptitle') {
10797: my ($map) = &decode_symb($symbparm);
10798: return &gettitle($map);
10799: }
10800: if ($space eq 'filename') {
10801: if ($symbparm) {
10802: return &clutter((&decode_symb($symbparm))[2]);
10803: }
10804: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10805: }
1.1172.2.30 raeburn 10806:
10807: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10808: if ($space eq 'visibleparts') {
10809: my $navmap = Apache::lonnavmaps::navmap->new();
10810: my $item;
10811: if (ref($navmap)) {
10812: my $res = $navmap->getBySymb($symbparm);
10813: my $parts = $res->parts();
10814: if (ref($parts) eq 'ARRAY') {
10815: $item = join(',',@{$parts});
10816: }
10817: undef($navmap);
10818: }
10819: return $item;
10820: }
10821: }
10822: }
1.693 albertel 10823:
10824: my ($section, $group, @groups);
1.593 albertel 10825: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10826: if (($courseid eq '') && ($cid)) {
10827: $courseid = $cid;
10828: }
10829: if (($symbparm && $courseid) &&
10830: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10831:
1.218 albertel 10832: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10833:
1.60 www 10834: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10835: my $symbp=$symbparm;
1.735 albertel 10836: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10837:
10838: my $symbparm=$symbp.'.'.$spacequalifierrest;
10839: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10840:
1.620 albertel 10841: if (($env{'user.name'} eq $uname) &&
10842: ($env{'user.domain'} eq $udom)) {
10843: $section=$env{'request.course.sec'};
1.733 raeburn 10844: @groups = split(/:/,$env{'request.course.groups'});
10845: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10846: } else {
1.539 albertel 10847: if (! defined($usection)) {
1.551 albertel 10848: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10849: } else {
10850: $section = $usection;
10851: }
1.733 raeburn 10852: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10853: }
10854:
10855: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10856: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10857: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10858:
1.593 albertel 10859: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10860: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10861: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10862:
1.60 www 10863: # ----------------------------------------------------------- first, check user
1.624 albertel 10864:
10865: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10866: ([$courselevelr,'resource'],
10867: [$courselevelm,'map' ],
10868: [$courselevel, 'course' ]));
1.931 albertel 10869: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10870:
1.594 albertel 10871: # ------------------------------------------------ second, check some of course
1.684 raeburn 10872: my $coursereply;
1.691 raeburn 10873: if (@groups > 0) {
10874: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10875: $mapparm,$spacequalifierrest);
1.927 albertel 10876: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10877: }
1.96 www 10878:
1.684 raeburn 10879: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10880: $env{'course.'.$courseid.'.domain'},
10881: 'course',
10882: ([$seclevelr, 'resource'],
10883: [$seclevelm, 'map' ],
10884: [$seclevel, 'course' ],
10885: [$courselevelr,'resource']));
10886: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10887:
1.60 www 10888: # ------------------------------------------------------ third, check map parms
1.218 albertel 10889: my %parmhash=();
10890: my $thisparm='';
10891: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10892: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10893: &GDBM_READER(),0640)) {
1.218 albertel 10894: $thisparm=$parmhash{$symbparm};
10895: untie(%parmhash);
10896: }
1.927 albertel 10897: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10898: }
1.594 albertel 10899: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10900:
1.218 albertel 10901: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10902: my $filename;
10903: if (!$symbparm) { $symbparm=&symbread(); }
10904: if ($symbparm) {
1.409 www 10905: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10906: } else {
1.620 albertel 10907: $filename=$env{'request.filename'};
1.282 albertel 10908: }
10909: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10910: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10911: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10912: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10913:
1.927 albertel 10914: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10915: if ($symbparm && defined($courseid) &&
1.620 albertel 10916: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10917: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10918: $env{'course.'.$courseid.'.domain'},
10919: 'course',
1.927 albertel 10920: ([$courselevelm,'map' ],
10921: [$courselevel, 'course']));
10922: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10923: }
1.145 www 10924: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10925: unless ($space eq '0') {
1.336 albertel 10926: my @parts=split(/_/,$space);
10927: my $id=pop(@parts);
10928: my $part=join('_',@parts);
10929: if ($part eq '') { $part='0'; }
1.927 albertel 10930: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10931: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10932: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10933: }
1.395 albertel 10934: if ($recurse) { return undef; }
10935: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10936: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10937: # ---------------------------------------------------- Any other user namespace
10938: } elsif ($realm eq 'environment') {
10939: # ----------------------------------------------------------------- environment
1.620 albertel 10940: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10941: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10942: } else {
1.770 albertel 10943: if ($uname eq 'anonymous' && $udom eq '') {
10944: return '';
10945: }
1.219 albertel 10946: my %returnhash=&userenvironment($udom,$uname,
10947: $spacequalifierrest);
10948: return $returnhash{$spacequalifierrest};
10949: }
1.28 www 10950: } elsif ($realm eq 'system') {
1.48 www 10951: # ----------------------------------------------------------------- system.time
10952: if ($space eq 'time') {
10953: return time;
10954: }
1.696 albertel 10955: } elsif ($realm eq 'server') {
10956: # ----------------------------------------------------------------- system.time
10957: if ($space eq 'name') {
10958: return $ENV{'SERVER_NAME'};
10959: }
1.28 www 10960: }
1.48 www 10961: return '';
1.61 www 10962: }
10963:
1.927 albertel 10964: sub get_reply {
10965: my ($reply_value) = @_;
1.940 raeburn 10966: if (ref($reply_value) eq 'ARRAY') {
10967: if (wantarray) {
10968: return @$reply_value;
10969: }
10970: return $reply_value->[0];
10971: } else {
10972: return $reply_value;
1.927 albertel 10973: }
10974: }
10975:
1.691 raeburn 10976: sub check_group_parms {
10977: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10978: my @groupitems = ();
10979: my $resultitem;
1.927 albertel 10980: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10981: foreach my $group (@{$groups}) {
10982: foreach my $level (@levels) {
1.927 albertel 10983: my $item = $courseid.'.['.$group.'].'.$level->[0];
10984: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10985: }
10986: }
10987: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10988: $env{'course.'.$courseid.'.domain'},
10989: 'course',@groupitems);
10990: return $coursereply;
10991: }
10992:
10993: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10994: my ($courseid,@groups) = @_;
10995: @groups = sort(@groups);
1.691 raeburn 10996: return @groups;
10997: }
10998:
1.395 albertel 10999: sub packages_tab_default {
11000: my ($uri,$varname)=@_;
11001: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11002:
11003: my (@extension,@specifics,$do_default);
11004: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11005: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11006: if ($pack_type eq 'default') {
11007: $do_default=1;
11008: } elsif ($pack_type eq 'extension') {
11009: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11010: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11011: # only look at packages defaults for packages that this id is
1.738 albertel 11012: push(@specifics,[$package,$pack_type,$pack_part]);
11013: }
11014: }
11015: # first look for a package that matches the requested part id
11016: foreach my $package (@specifics) {
11017: my (undef,$pack_type,$pack_part)=@{$package};
11018: next if ($pack_part ne $part);
11019: if (defined($packagetab{"$pack_type&$name&default"})) {
11020: return $packagetab{"$pack_type&$name&default"};
11021: }
11022: }
11023: # look for any possible matching non extension_ package
11024: foreach my $package (@specifics) {
11025: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11026: if (defined($packagetab{"$pack_type&$name&default"})) {
11027: return $packagetab{"$pack_type&$name&default"};
11028: }
1.585 albertel 11029: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11030: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11031: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11032: }
11033: }
1.738 albertel 11034: # look for any posible extension_ match
11035: foreach my $package (@extension) {
11036: my ($package,$pack_type)=@{$package};
11037: if (defined($packagetab{"$pack_type&$name&default"})) {
11038: return $packagetab{"$pack_type&$name&default"};
11039: }
11040: if (defined($packagetab{$package."&$name&default"})) {
11041: return $packagetab{$package."&$name&default"};
11042: }
11043: }
11044: # look for a global default setting
11045: if ($do_default && defined($packagetab{"default&$name&default"})) {
11046: return $packagetab{"default&$name&default"};
11047: }
1.395 albertel 11048: return undef;
11049: }
11050:
1.334 albertel 11051: sub add_prefix_and_part {
11052: my ($prefix,$part)=@_;
11053: my $keyroot;
11054: if (defined($prefix) && $prefix !~ /^__/) {
11055: # prefix that has a part already
11056: $keyroot=$prefix;
11057: } elsif (defined($prefix)) {
11058: # prefix that is missing a part
11059: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11060: } else {
11061: # no prefix at all
11062: if (defined($part)) { $keyroot='_'.$part; }
11063: }
11064: return $keyroot;
11065: }
11066:
1.71 www 11067: # ---------------------------------------------------------------- Get metadata
11068:
1.599 albertel 11069: my %metaentry;
1.1070 www 11070: my %importedpartids;
1.71 www 11071: sub metadata {
1.176 www 11072: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11073: $uri=&declutter($uri);
1.288 albertel 11074: # if it is a non metadata possible uri return quickly
1.529 albertel 11075: if (($uri eq '') ||
11076: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 11077: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 11078: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11079: return undef;
11080: }
1.1172.2.49 raeburn 11081: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11082: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11083: return undef;
1.288 albertel 11084: }
1.73 www 11085: my $filename=$uri;
11086: $uri=~s/\.meta$//;
1.172 www 11087: #
11088: # Is the metadata already cached?
1.177 www 11089: # Look at timestamp of caching
1.172 www 11090: # Everything is cached by the main uri, libraries are never directly cached
11091: #
1.428 albertel 11092: if (!defined($liburi)) {
1.599 albertel 11093: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11094: if (defined($cached)) { return $result->{':'.$what}; }
11095: }
11096: {
1.1069 www 11097: # Imported parts would go here
1.1070 www 11098: my %importedids=();
11099: my @origfileimportpartids=();
1.1069 www 11100: my $importedparts=0;
1.172 www 11101: #
11102: # Is this a recursive call for a library?
11103: #
1.599 albertel 11104: # if (! exists($metacache{$uri})) {
11105: # $metacache{$uri}={};
11106: # }
1.924 albertel 11107: my $cachetime = 60*60;
1.171 www 11108: if ($liburi) {
11109: $liburi=&declutter($liburi);
11110: $filename=$liburi;
1.401 bowersj2 11111: } else {
1.599 albertel 11112: &devalidate_cache_new('meta',$uri);
11113: undef(%metaentry);
1.401 bowersj2 11114: }
1.140 www 11115: my %metathesekeys=();
1.73 www 11116: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11117: my $metastring;
1.1140 www 11118: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11119: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11120: $metastring =
1.929 albertel 11121: &Apache::lonnet::ssi_body($which,
1.924 albertel 11122: ('grade_target' => 'meta'));
11123: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11124: } elsif (($uri !~ m -^(editupload)/-) &&
11125: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11126: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11127: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11128: $metastring=&getfile($file);
1.489 albertel 11129: }
1.208 albertel 11130: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11131: my $token;
1.140 www 11132: undef %metathesekeys;
1.71 www 11133: while ($token=$parser->get_token) {
1.339 albertel 11134: if ($token->[0] eq 'S') {
11135: if (defined($token->[2]->{'package'})) {
1.172 www 11136: #
11137: # This is a package - get package info
11138: #
1.339 albertel 11139: my $package=$token->[2]->{'package'};
11140: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11141: if (defined($token->[2]->{'id'})) {
11142: $keyroot.='_'.$token->[2]->{'id'};
11143: }
1.599 albertel 11144: if ($metaentry{':packages'}) {
11145: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11146: } else {
1.599 albertel 11147: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11148: }
1.736 albertel 11149: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11150: my $part=$keyroot;
11151: $part=~s/^\_//;
1.736 albertel 11152: if ($pack_entry=~/^\Q$package\E\&/ ||
11153: $pack_entry=~/^\Q$package\E_0\&/) {
11154: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11155: # ignore package.tab specified default values
11156: # here &package_tab_default() will fetch those
11157: if ($subp eq 'default') { next; }
1.736 albertel 11158: my $value=$packagetab{$pack_entry};
1.432 albertel 11159: my $unikey;
11160: if ($pack =~ /_0$/) {
11161: $unikey='parameter_0_'.$name;
11162: $part=0;
11163: } else {
11164: $unikey='parameter'.$keyroot.'_'.$name;
11165: }
1.339 albertel 11166: if ($subp eq 'display') {
11167: $value.=' [Part: '.$part.']';
11168: }
1.599 albertel 11169: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11170: $metathesekeys{$unikey}=1;
1.599 albertel 11171: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11172: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11173: }
1.599 albertel 11174: if (defined($metaentry{':'.$unikey.'.default'})) {
11175: $metaentry{':'.$unikey}=
11176: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11177: }
1.339 albertel 11178: }
11179: }
11180: } else {
1.172 www 11181: #
11182: # This is not a package - some other kind of start tag
1.339 albertel 11183: #
11184: my $entry=$token->[1];
1.1068 www 11185: my $unikey='';
1.175 www 11186:
1.339 albertel 11187: if ($entry eq 'import') {
1.175 www 11188: #
11189: # Importing a library here
1.339 albertel 11190: #
1.1067 www 11191: my $location=$parser->get_text('/import');
11192: my $dir=$filename;
11193: $dir=~s|[^/]*$||;
11194: $location=&filelocation($dir,$location);
1.1069 www 11195:
1.1068 www 11196: my $importmode=$token->[2]->{'importmode'};
11197: if ($importmode eq 'problem') {
1.1069 www 11198: # Import as problem/response
1.1068 www 11199: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11200: } elsif ($importmode eq 'part') {
11201: # Import as part(s)
1.1069 www 11202: $importedparts=1;
11203: # We need to get the original file and the imported file to get the part order correct
11204: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11205: # Load and inspect original file
1.1070 www 11206: if ($#origfileimportpartids<0) {
11207: undef(%importedpartids);
11208: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11209: my $origfile=&getfile($origfilelocation);
11210: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11211: }
11212:
1.1069 www 11213: # Load and inspect imported file
11214: my $impfile=&getfile($location);
11215: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11216: if ($#impfilepartids>=0) {
11217: # This problem had parts
1.1070 www 11218: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11219: } else {
11220: # Importing by turning a single problem into a problem part
11221: # It gets the import-tags ID as part-ID
11222: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11223: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11224: }
1.1068 www 11225: } else {
11226: # Normal import
11227: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11228: if (defined($token->[2]->{'id'})) {
11229: $unikey.='_'.$token->[2]->{'id'};
11230: }
1.1067 www 11231: }
11232:
1.339 albertel 11233: if ($depthcount<20) {
1.736 albertel 11234: my $metadata =
11235: &metadata($uri,'keys', $location,$unikey,
11236: $depthcount+1);
11237: foreach my $meta (split(',',$metadata)) {
11238: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11239: $metathesekeys{$meta}=1;
1.339 albertel 11240: }
1.1068 www 11241:
11242: }
1.1067 www 11243: } else {
11244: #
11245: # Not importing, some other kind of non-package, non-library start tag
11246: #
11247: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11248: if (defined($token->[2]->{'id'})) {
11249: $unikey.='_'.$token->[2]->{'id'};
11250: }
1.339 albertel 11251: if (defined($token->[2]->{'name'})) {
11252: $unikey.='_'.$token->[2]->{'name'};
11253: }
11254: $metathesekeys{$unikey}=1;
1.736 albertel 11255: foreach my $param (@{$token->[3]}) {
11256: $metaentry{':'.$unikey.'.'.$param} =
11257: $token->[2]->{$param};
1.339 albertel 11258: }
11259: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11260: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11261: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11262: # only ws inside the tag, and not in default, so use default
11263: # as value
1.599 albertel 11264: $metaentry{':'.$unikey}=$default;
1.908 albertel 11265: } elsif ( $internaltext =~ /\S/ ) {
11266: # something interesting inside the tag
11267: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11268: } else {
1.908 albertel 11269: # no interesting values, don't set a default
1.339 albertel 11270: }
1.172 www 11271: # end of not-a-package not-a-library import
1.339 albertel 11272: }
1.172 www 11273: # end of not-a-package start tag
1.339 albertel 11274: }
1.172 www 11275: # the next is the end of "start tag"
1.339 albertel 11276: }
11277: }
1.483 albertel 11278: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11279: $extension = lc($extension);
11280: if ($extension eq 'htm') { $extension='html'; }
11281:
1.737 albertel 11282: foreach my $key (keys(%packagetab)) {
1.483 albertel 11283: #no specific packages #how's our extension
11284: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11285: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11286: \%metathesekeys);
11287: }
1.883 albertel 11288:
11289: if (!exists($metaentry{':packages'})
11290: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11291: foreach my $key (keys(%packagetab)) {
1.483 albertel 11292: #no specific packages well let's get default then
11293: if ($key!~/^default&/) { next; }
1.488 albertel 11294: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11295: \%metathesekeys);
11296: }
11297: }
1.338 www 11298: # are there custom rights to evaluate
1.599 albertel 11299: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11300:
1.338 www 11301: #
11302: # Importing a rights file here
1.339 albertel 11303: #
11304: unless ($depthcount) {
1.599 albertel 11305: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11306: my $dir=$filename;
11307: $dir=~s|[^/]*$||;
11308: $location=&filelocation($dir,$location);
1.736 albertel 11309: my $rights_metadata =
11310: &metadata($uri,'keys',$location,'_rights',
11311: $depthcount+1);
11312: foreach my $rights (split(',',$rights_metadata)) {
11313: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11314: $metathesekeys{$rights}=1;
1.339 albertel 11315: }
11316: }
11317: }
1.737 albertel 11318: # uniqifiy package listing
11319: my %seen;
11320: my @uniq_packages =
11321: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11322: $metaentry{':packages'} = join(',',@uniq_packages);
11323:
1.1070 www 11324: if ($importedparts) {
11325: # We had imported parts and need to rebuild partorder
11326: $metaentry{':partorder'}='';
11327: $metathesekeys{'partorder'}=1;
11328: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11329: if ($origfileimportpartids[$index] eq 'part') {
11330: # original part, part of the problem
11331: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11332: } else {
11333: # we have imported parts at this position
11334: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11335: }
11336: }
11337: $metaentry{':partorder'}=~s/^\,//;
11338: }
11339:
1.737 albertel 11340: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11341: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 11342: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11343: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11344: # this is the end of "was not already recently cached
1.71 www 11345: }
1.599 albertel 11346: return $metaentry{':'.$what};
1.261 albertel 11347: }
11348:
1.488 albertel 11349: sub metadata_create_package_def {
1.483 albertel 11350: my ($uri,$key,$package,$metathesekeys)=@_;
11351: my ($pack,$name,$subp)=split(/\&/,$key);
11352: if ($subp eq 'default') { next; }
11353:
1.599 albertel 11354: if (defined($metaentry{':packages'})) {
11355: $metaentry{':packages'}.=','.$package;
1.483 albertel 11356: } else {
1.599 albertel 11357: $metaentry{':packages'}=$package;
1.483 albertel 11358: }
11359: my $value=$packagetab{$key};
11360: my $unikey;
11361: $unikey='parameter_0_'.$name;
1.599 albertel 11362: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11363: $$metathesekeys{$unikey}=1;
1.599 albertel 11364: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11365: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11366: }
1.599 albertel 11367: if (defined($metaentry{':'.$unikey.'.default'})) {
11368: $metaentry{':'.$unikey}=
11369: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11370: }
11371: }
11372:
1.261 albertel 11373: sub metadata_generate_part0 {
11374: my ($metadata,$metacache,$uri) = @_;
11375: my %allnames;
1.737 albertel 11376: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11377: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11378: my $part=$$metacache{':'.$metakey.'.part'};
11379: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11380: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11381: $allnames{$name}=$part;
11382: }
11383: }
11384: }
11385: foreach my $name (keys(%allnames)) {
11386: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11387: my $key=":parameter_0_$name";
1.261 albertel 11388: $$metacache{"$key.part"}='0';
11389: $$metacache{"$key.name"}=$name;
1.428 albertel 11390: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11391: $allnames{$name}.'_'.$name.
11392: '.type'};
1.428 albertel 11393: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11394: '.display'};
1.644 www 11395: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11396: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11397: $$metacache{"$key.display"}=$olddis;
11398: }
1.71 www 11399: }
11400:
1.764 albertel 11401: # ------------------------------------------------------ Devalidate title cache
11402:
11403: sub devalidate_title_cache {
11404: my ($url)=@_;
11405: if (!$env{'request.course.id'}) { return; }
11406: my $symb=&symbread($url);
11407: if (!$symb) { return; }
11408: my $key=$env{'request.course.id'}."\0".$symb;
11409: &devalidate_cache_new('title',$key);
11410: }
11411:
1.1014 droeschl 11412: # ------------------------------------------------- Get the title of a course
11413:
11414: sub current_course_title {
11415: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11416: }
1.301 www 11417: # ------------------------------------------------- Get the title of a resource
11418:
11419: sub gettitle {
11420: my $urlsymb=shift;
11421: my $symb=&symbread($urlsymb);
1.534 albertel 11422: if ($symb) {
1.620 albertel 11423: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11424: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11425: if (defined($cached)) {
11426: return $result;
11427: }
1.534 albertel 11428: my ($map,$resid,$url)=&decode_symb($symb);
11429: my $title='';
1.907 albertel 11430: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11431: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11432: } else {
11433: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11434: &GDBM_READER(),0640)) {
11435: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11436: $title=$bighash{'title_'.$mapid.'.'.$resid};
11437: untie(%bighash);
11438: }
1.534 albertel 11439: }
11440: $title=~s/\&colon\;/\:/gs;
11441: if ($title) {
1.1159 www 11442: # Remember both $symb and $title for dynamic metadata
11443: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11444: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11445: # Cache this title and then return it
1.599 albertel 11446: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11447: }
11448: $urlsymb=$url;
11449: }
11450: my $title=&metadata($urlsymb,'title');
11451: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11452: return $title;
1.301 www 11453: }
1.613 albertel 11454:
1.614 albertel 11455: sub get_slot {
11456: my ($which,$cnum,$cdom)=@_;
11457: if (!$cnum || !$cdom) {
1.790 albertel 11458: (undef,my $courseid)=&whichuser();
1.620 albertel 11459: $cdom=$env{'course.'.$courseid.'.domain'};
11460: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11461: }
1.703 albertel 11462: my $key=join("\0",'slots',$cdom,$cnum,$which);
11463: my %slotinfo;
11464: if (exists($remembered{$key})) {
11465: $slotinfo{$which} = $remembered{$key};
11466: } else {
11467: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11468: &Apache::lonhomework::showhash(%slotinfo);
11469: my ($tmp)=keys(%slotinfo);
11470: if ($tmp=~/^error:/) { return (); }
11471: $remembered{$key} = $slotinfo{$which};
11472: }
1.616 albertel 11473: if (ref($slotinfo{$which}) eq 'HASH') {
11474: return %{$slotinfo{$which}};
11475: }
11476: return $slotinfo{$which};
1.614 albertel 11477: }
1.1150 raeburn 11478:
11479: sub get_reservable_slots {
11480: my ($cnum,$cdom,$uname,$udom) = @_;
11481: my $now = time;
11482: my $reservable_info;
11483: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11484: if (exists($remembered{$key})) {
11485: $reservable_info = $remembered{$key};
11486: } else {
11487: my %resv;
11488: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11489: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11490: $reservable_info = \%resv;
11491: $remembered{$key} = $reservable_info;
11492: }
11493: return $reservable_info;
11494: }
11495:
11496: sub get_course_slots {
11497: my ($cnum,$cdom) = @_;
11498: my $hashid=$cnum.':'.$cdom;
11499: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11500: if (defined($cached)) {
11501: if (ref($result) eq 'HASH') {
11502: return %{$result};
11503: }
11504: } else {
11505: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11506: my ($tmp) = keys(%slots);
11507: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 11508: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11509: return %slots;
11510: }
11511: }
11512: return;
11513: }
11514:
11515: sub devalidate_slots_cache {
11516: my ($cnum,$cdom)=@_;
11517: my $hashid=$cnum.':'.$cdom;
11518: &devalidate_cache_new('allslots',$hashid);
11519: }
11520:
1.1172.2.8 raeburn 11521: sub get_coursechange {
11522: my ($cdom,$cnum) = @_;
11523: if ($cdom eq '' || $cnum eq '') {
11524: return unless ($env{'request.course.id'});
11525: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11526: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11527: }
11528: my $hashid=$cdom.'_'.$cnum;
11529: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11530: if ((defined($cached)) && ($change ne '')) {
11531: return $change;
11532: } else {
11533: my %crshash;
11534: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11535: if ($crshash{'internal.contentchange'} eq '') {
11536: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11537: if ($change eq '') {
11538: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11539: $change = $crshash{'internal.created'};
11540: }
11541: } else {
11542: $change = $crshash{'internal.contentchange'};
11543: }
11544: my $cachetime = 600;
11545: &do_cache_new('crschange',$hashid,$change,$cachetime);
11546: }
11547: return $change;
11548: }
11549:
11550: sub devalidate_coursechange_cache {
11551: my ($cnum,$cdom)=@_;
11552: my $hashid=$cnum.':'.$cdom;
11553: &devalidate_cache_new('crschange',$hashid);
11554: }
11555:
1.31 www 11556: # ------------------------------------------------- Update symbolic store links
11557:
11558: sub symblist {
11559: my ($mapname,%newhash)=@_;
1.438 www 11560: $mapname=&deversion(&declutter($mapname));
1.31 www 11561: my %hash;
1.620 albertel 11562: if (($env{'request.course.fn'}) && (%newhash)) {
11563: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11564: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11565: foreach my $url (keys(%newhash)) {
1.711 albertel 11566: next if ($url eq 'last_known'
11567: && $env{'form.no_update_last_known'});
11568: $hash{declutter($url)}=&encode_symb($mapname,
11569: $newhash{$url}->[1],
11570: $newhash{$url}->[0]);
1.191 harris41 11571: }
1.31 www 11572: if (untie(%hash)) {
11573: return 'ok';
11574: }
11575: }
11576: }
11577: return 'error';
1.212 www 11578: }
11579:
11580: # --------------------------------------------------------------- Verify a symb
11581:
11582: sub symbverify {
1.1172.2.11 raeburn 11583: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11584: my $thisfn=$thisurl;
1.439 www 11585: $thisfn=&declutter($thisfn);
1.215 www 11586: # direct jump to resource in page or to a sequence - will construct own symbs
11587: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11588: # check URL part
1.409 www 11589: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11590:
1.431 www 11591: unless ($url eq $thisfn) { return 0; }
1.213 www 11592:
1.216 www 11593: $symb=&symbclean($symb);
1.510 www 11594: $thisurl=&deversion($thisurl);
1.439 www 11595: $thisfn=&deversion($thisfn);
1.213 www 11596:
11597: my %bighash;
11598: my $okay=0;
1.431 www 11599:
1.620 albertel 11600: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11601: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11602: my $noclutter;
1.1032 raeburn 11603: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11604: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11605: if ($map =~ m{^uploaded/.+\.page$}) {
11606: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11607: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11608: $noclutter = 1;
11609: }
11610: }
11611: my $ids;
11612: if ($noclutter) {
11613: $ids=$bighash{'ids_'.$thisurl};
11614: } else {
11615: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11616: }
1.1102 raeburn 11617: unless ($ids) {
1.1172.2.13 raeburn 11618: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11619: $ids=$bighash{$idkey};
1.216 www 11620: }
11621: if ($ids) {
11622: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11623: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11624: $symb =~ s/\?.+$//;
11625: }
1.800 albertel 11626: foreach my $id (split(/\,/,$ids)) {
11627: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11628: if (
11629: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11630: eq $symb) {
1.1172.2.11 raeburn 11631: if (ref($encstate)) {
11632: $$encstate = $bighash{'encrypted_'.$id};
11633: }
1.1172.2.13 raeburn 11634: if (($env{'request.role.adv'}) ||
11635: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11636: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11637: $okay=1;
11638: last;
11639: }
11640: }
11641: }
1.216 www 11642: }
1.213 www 11643: untie(%bighash);
11644: }
11645: return $okay;
1.31 www 11646: }
11647:
1.210 www 11648: # --------------------------------------------------------------- Clean-up symb
11649:
11650: sub symbclean {
11651: my $symb=shift;
1.568 albertel 11652: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11653: # remove version from map
11654: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11655:
1.210 www 11656: # remove version from URL
11657: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11658:
1.507 www 11659: # remove wrapper
11660:
1.510 www 11661: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11662: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11663: return $symb;
1.409 www 11664: }
11665:
11666: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11667:
11668: sub encode_symb {
11669: my ($map,$resid,$url)=@_;
11670: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11671: }
1.409 www 11672:
11673: sub decode_symb {
1.568 albertel 11674: my $symb=shift;
11675: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11676: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11677: return (&fixversion($map),$resid,&fixversion($url));
11678: }
11679:
11680: sub fixversion {
11681: my $fn=shift;
1.609 banghart 11682: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11683: my %bighash;
11684: my $uri=&clutter($fn);
1.620 albertel 11685: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11686: # is this cached?
1.599 albertel 11687: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11688: if (defined($cached)) { return $result; }
11689: # unfortunately not cached, or expired
1.620 albertel 11690: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11691: &GDBM_READER(),0640)) {
11692: if ($bighash{'version_'.$uri}) {
11693: my $version=$bighash{'version_'.$uri};
1.444 www 11694: unless (($version eq 'mostrecent') ||
11695: ($version==&getversion($uri))) {
1.440 www 11696: $uri=~s/\.(\w+)$/\.$version\.$1/;
11697: }
11698: }
11699: untie %bighash;
1.413 www 11700: }
1.599 albertel 11701: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11702: }
11703:
11704: sub deversion {
11705: my $url=shift;
11706: $url=~s/\.\d+\.(\w+)$/\.$1/;
11707: return $url;
1.210 www 11708: }
11709:
1.31 www 11710: # ------------------------------------------------------ Return symb list entry
11711:
11712: sub symbread {
1.1172.2.66 raeburn 11713: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11714: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11715: if (defined($env{$cache_str})) {
11716: if ($ignorecachednull) {
11717: return $env{$cache_str} unless ($env{$cache_str} eq '');
11718: } else {
11719: return $env{$cache_str};
11720: }
11721: }
1.242 www 11722: # no filename provided? try from environment
1.1172.2.54 raeburn 11723: unless ($thisfn) {
1.620 albertel 11724: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11725: return $env{$cache_str}=&symbclean($env{'request.symb'});
11726: }
11727: $thisfn=$env{'request.filename'};
1.44 www 11728: }
1.569 albertel 11729: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11730: # is that filename actually a symb? Verify, clean, and return
11731: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11732: if (&symbverify($thisfn,$1)) {
1.620 albertel 11733: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11734: }
1.242 www 11735: }
1.44 www 11736: $thisfn=declutter($thisfn);
1.31 www 11737: my %hash;
1.37 www 11738: my %bighash;
11739: my $syval='';
1.620 albertel 11740: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11741: my $targetfn = $thisfn;
1.609 banghart 11742: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11743: $targetfn = 'adm/wrapper/'.$thisfn;
11744: }
1.687 albertel 11745: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11746: $targetfn=$1;
11747: }
1.620 albertel 11748: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11749: &GDBM_READER(),0640)) {
1.481 raeburn 11750: $syval=$hash{$targetfn};
1.37 www 11751: untie(%hash);
11752: }
11753: # ---------------------------------------------------------- There was an entry
11754: if ($syval) {
1.601 albertel 11755: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11756: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11757: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11758: #return $env{$cache_str}='';
1.601 albertel 11759: #}
11760: #$syval.=$1;
11761: #}
1.37 www 11762: } else {
11763: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11764: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11765: &GDBM_READER(),0640)) {
1.37 www 11766: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11767: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11768: unless ($ids) {
11769: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11770: }
11771: unless ($ids) {
11772: # alias?
11773: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11774: }
1.37 www 11775: if ($ids) {
11776: # ------------------------------------------------------------------- Has ID(s)
11777: my @possibilities=split(/\,/,$ids);
1.39 www 11778: if ($#possibilities==0) {
11779: # ----------------------------------------------- There is only one possibility
1.37 www 11780: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11781: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11782: $resid,$thisfn);
1.1172.2.66 raeburn 11783: if (ref($possibles) eq 'HASH') {
11784: $possibles->{$syval} = 1;
11785: }
11786: if ($checkforblock) {
11787: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11788: if (@blockers) {
11789: $syval = '';
11790: return;
11791: }
11792: }
11793: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11794: # ------------------------------------------ There is more than one possibility
11795: my $realpossible=0;
1.800 albertel 11796: foreach my $id (@possibilities) {
11797: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11798: my $canaccess;
11799: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11800: $canaccess = 1;
11801: } else {
11802: $canaccess = &allowed('bre',$file);
11803: }
11804: if ($canaccess) {
11805: my ($mapid,$resid)=split(/\./,$id);
11806: if ($bighash{'map_type_'.$mapid} ne 'page') {
11807: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11808: $resid,$thisfn);
11809: if (ref($possibles) eq 'HASH') {
11810: $possibles->{$syval} = 1;
11811: }
11812: if ($checkforblock) {
11813: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11814: unless (@blockers > 0) {
11815: $syval = $poss_syval;
11816: $realpossible++;
11817: }
11818: } else {
11819: $syval = $poss_syval;
11820: $realpossible++;
11821: }
11822: }
1.39 www 11823: }
1.191 harris41 11824: }
1.39 www 11825: if ($realpossible!=1) { $syval=''; }
1.249 www 11826: } else {
11827: $syval='';
1.37 www 11828: }
11829: }
1.1172.2.66 raeburn 11830: untie(%bighash);
1.481 raeburn 11831: }
1.31 www 11832: }
1.62 www 11833: if ($syval) {
1.620 albertel 11834: return $env{$cache_str}=$syval;
1.62 www 11835: }
1.31 www 11836: }
1.949 raeburn 11837: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11838: return $env{$cache_str}='';
1.31 www 11839: }
11840:
11841: # ---------------------------------------------------------- Return random seed
11842:
1.32 www 11843: sub numval {
11844: my $txt=shift;
11845: $txt=~tr/A-J/0-9/;
11846: $txt=~tr/a-j/0-9/;
11847: $txt=~tr/K-T/0-9/;
11848: $txt=~tr/k-t/0-9/;
11849: $txt=~tr/U-Z/0-5/;
11850: $txt=~tr/u-z/0-5/;
11851: $txt=~s/\D//g;
1.564 albertel 11852: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11853: return int($txt);
1.368 albertel 11854: }
11855:
1.484 albertel 11856: sub numval2 {
11857: my $txt=shift;
11858: $txt=~tr/A-J/0-9/;
11859: $txt=~tr/a-j/0-9/;
11860: $txt=~tr/K-T/0-9/;
11861: $txt=~tr/k-t/0-9/;
11862: $txt=~tr/U-Z/0-5/;
11863: $txt=~tr/u-z/0-5/;
11864: $txt=~s/\D//g;
11865: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11866: my $total;
11867: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11868: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11869: return int($total);
11870: }
11871:
1.575 albertel 11872: sub numval3 {
11873: use integer;
11874: my $txt=shift;
11875: $txt=~tr/A-J/0-9/;
11876: $txt=~tr/a-j/0-9/;
11877: $txt=~tr/K-T/0-9/;
11878: $txt=~tr/k-t/0-9/;
11879: $txt=~tr/U-Z/0-5/;
11880: $txt=~tr/u-z/0-5/;
11881: $txt=~s/\D//g;
11882: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11883: my $total;
11884: foreach my $val (@txts) { $total+=$val; }
11885: if ($_64bit) { $total=(($total<<32)>>32); }
11886: return $total;
11887: }
11888:
1.675 albertel 11889: sub digest {
11890: my ($data)=@_;
11891: my $digest=&Digest::MD5::md5($data);
11892: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11893: my ($e,$f);
11894: {
11895: use integer;
11896: $e=($a+$b);
11897: $f=($c+$d);
11898: if ($_64bit) {
11899: $e=(($e<<32)>>32);
11900: $f=(($f<<32)>>32);
11901: }
11902: }
11903: if (wantarray) {
11904: return ($e,$f);
11905: } else {
11906: my $g;
11907: {
11908: use integer;
11909: $g=($e+$f);
11910: if ($_64bit) {
11911: $g=(($g<<32)>>32);
11912: }
11913: }
11914: return $g;
11915: }
11916: }
11917:
1.368 albertel 11918: sub latest_rnd_algorithm_id {
1.675 albertel 11919: return '64bit5';
1.366 albertel 11920: }
1.32 www 11921:
1.503 albertel 11922: sub get_rand_alg {
11923: my ($courseid)=@_;
1.790 albertel 11924: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11925: if ($courseid) {
1.620 albertel 11926: return $env{"course.$courseid.rndseed"};
1.503 albertel 11927: }
11928: return &latest_rnd_algorithm_id();
11929: }
11930:
1.562 albertel 11931: sub validCODE {
11932: my ($CODE)=@_;
11933: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11934: return 0;
11935: }
11936:
1.491 albertel 11937: sub getCODE {
1.620 albertel 11938: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11939: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11940: defined($Apache::lonhomework::parsing_a_task) ) &&
11941: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11942: return $Apache::lonhomework::history{'resource.CODE'};
11943: }
11944: return undef;
11945: }
1.1133 foxr 11946: #
11947: # Determines the random seed for a specific context:
11948: #
11949: # parameters:
11950: # symb - in course context the symb for the seed.
11951: # course_id - The course id of the form domain_coursenum.
11952: # domain - Domain for the user.
11953: # course - Course for the user.
11954: # cenv - environment of the course.
11955: #
11956: # NOTE:
11957: # All parameters are picked out of the environment if missing
11958: # or not defined.
11959: # If a symb cannot be determined the current time is used instead.
11960: #
11961: # For a given well defined symb, courside, domain, username,
11962: # and course environment, the seed is reproducible.
11963: #
1.31 www 11964: sub rndseed {
1.1133 foxr 11965: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11966: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11967: if (!defined($symb)) {
1.366 albertel 11968: unless ($symb=$wsymb) { return time; }
11969: }
1.1146 foxr 11970: if (!defined $courseid) {
11971: $courseid=$wcourseid;
11972: }
11973: if (!defined $domain) { $domain=$wdomain; }
11974: if (!defined $username) { $username=$wusername }
1.1133 foxr 11975:
11976: my $which;
11977: if (defined($cenv->{'rndseed'})) {
11978: $which = $cenv->{'rndseed'};
11979: } else {
11980: $which =&get_rand_alg($courseid);
11981: }
1.491 albertel 11982: if (defined(&getCODE())) {
1.675 albertel 11983: if ($which eq '64bit5') {
11984: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11985: } elsif ($which eq '64bit4') {
1.575 albertel 11986: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11987: } else {
11988: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11989: }
1.675 albertel 11990: } elsif ($which eq '64bit5') {
11991: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11992: } elsif ($which eq '64bit4') {
11993: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11994: } elsif ($which eq '64bit3') {
11995: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11996: } elsif ($which eq '64bit2') {
11997: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11998: } elsif ($which eq '64bit') {
11999: return &rndseed_64bit($symb,$courseid,$domain,$username);
12000: }
12001: return &rndseed_32bit($symb,$courseid,$domain,$username);
12002: }
12003:
12004: sub rndseed_32bit {
12005: my ($symb,$courseid,$domain,$username)=@_;
12006: {
12007: use integer;
12008: my $symbchck=unpack("%32C*",$symb) << 27;
12009: my $symbseed=numval($symb) << 22;
12010: my $namechck=unpack("%32C*",$username) << 17;
12011: my $nameseed=numval($username) << 12;
12012: my $domainseed=unpack("%32C*",$domain) << 7;
12013: my $courseseed=unpack("%32C*",$courseid);
12014: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12015: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12016: #&logthis("rndseed :$num:$symb");
1.564 albertel 12017: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12018: return $num;
12019: }
12020: }
12021:
12022: sub rndseed_64bit {
12023: my ($symb,$courseid,$domain,$username)=@_;
12024: {
12025: use integer;
12026: my $symbchck=unpack("%32S*",$symb) << 21;
12027: my $symbseed=numval($symb) << 10;
12028: my $namechck=unpack("%32S*",$username);
12029:
12030: my $nameseed=numval($username) << 21;
12031: my $domainseed=unpack("%32S*",$domain) << 10;
12032: my $courseseed=unpack("%32S*",$courseid);
12033:
12034: my $num1=$symbchck+$symbseed+$namechck;
12035: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12036: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12037: #&logthis("rndseed :$num:$symb");
1.564 albertel 12038: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12039: return "$num1,$num2";
1.155 albertel 12040: }
1.366 albertel 12041: }
12042:
1.443 albertel 12043: sub rndseed_64bit2 {
12044: my ($symb,$courseid,$domain,$username)=@_;
12045: {
12046: use integer;
12047: # strings need to be an even # of cahracters long, it it is odd the
12048: # last characters gets thrown away
12049: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12050: my $symbseed=numval($symb) << 10;
12051: my $namechck=unpack("%32S*",$username.' ');
12052:
12053: my $nameseed=numval($username) << 21;
1.501 albertel 12054: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12055: my $courseseed=unpack("%32S*",$courseid.' ');
12056:
12057: my $num1=$symbchck+$symbseed+$namechck;
12058: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12059: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12060: #&logthis("rndseed :$num:$symb");
1.803 albertel 12061: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12062: return "$num1,$num2";
12063: }
12064: }
12065:
12066: sub rndseed_64bit3 {
12067: my ($symb,$courseid,$domain,$username)=@_;
12068: {
12069: use integer;
12070: # strings need to be an even # of cahracters long, it it is odd the
12071: # last characters gets thrown away
12072: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12073: my $symbseed=numval2($symb) << 10;
12074: my $namechck=unpack("%32S*",$username.' ');
12075:
12076: my $nameseed=numval2($username) << 21;
1.443 albertel 12077: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12078: my $courseseed=unpack("%32S*",$courseid.' ');
12079:
12080: my $num1=$symbchck+$symbseed+$namechck;
12081: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12082: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12083: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12084: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12085:
1.503 albertel 12086: return "$num1:$num2";
1.443 albertel 12087: }
12088: }
12089:
1.575 albertel 12090: sub rndseed_64bit4 {
12091: my ($symb,$courseid,$domain,$username)=@_;
12092: {
12093: use integer;
12094: # strings need to be an even # of cahracters long, it it is odd the
12095: # last characters gets thrown away
12096: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12097: my $symbseed=numval3($symb) << 10;
12098: my $namechck=unpack("%32S*",$username.' ');
12099:
12100: my $nameseed=numval3($username) << 21;
12101: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12102: my $courseseed=unpack("%32S*",$courseid.' ');
12103:
12104: my $num1=$symbchck+$symbseed+$namechck;
12105: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12106: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12107: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12108: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12109:
1.575 albertel 12110: return "$num1:$num2";
12111: }
12112: }
12113:
1.675 albertel 12114: sub rndseed_64bit5 {
12115: my ($symb,$courseid,$domain,$username)=@_;
12116: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12117: return "$num1:$num2";
12118: }
12119:
1.366 albertel 12120: sub rndseed_CODE_64bit {
12121: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12122: {
1.366 albertel 12123: use integer;
1.443 albertel 12124: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12125: my $symbseed=numval2($symb);
1.491 albertel 12126: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12127: my $CODEseed=numval(&getCODE());
1.443 albertel 12128: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12129: my $num1=$symbseed+$CODEchck;
12130: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12131: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12132: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12133: if ($_64bit) { $num1=(($num1<<32)>>32); }
12134: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12135: return "$num1:$num2";
1.366 albertel 12136: }
12137: }
12138:
1.575 albertel 12139: sub rndseed_CODE_64bit4 {
12140: my ($symb,$courseid,$domain,$username)=@_;
12141: {
12142: use integer;
12143: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12144: my $symbseed=numval3($symb);
12145: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12146: my $CODEseed=numval3(&getCODE());
12147: my $courseseed=unpack("%32S*",$courseid.' ');
12148: my $num1=$symbseed+$CODEchck;
12149: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12150: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12151: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12152: if ($_64bit) { $num1=(($num1<<32)>>32); }
12153: if ($_64bit) { $num2=(($num2<<32)>>32); }
12154: return "$num1:$num2";
12155: }
12156: }
12157:
1.675 albertel 12158: sub rndseed_CODE_64bit5 {
12159: my ($symb,$courseid,$domain,$username)=@_;
12160: my $code = &getCODE();
12161: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12162: return "$num1:$num2";
12163: }
12164:
1.366 albertel 12165: sub setup_random_from_rndseed {
12166: my ($rndseed)=@_;
1.503 albertel 12167: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 12168: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12169: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12170: &Math::Random::random_set_seed_from_phrase($rndseed);
12171: } else {
12172: &Math::Random::random_set_seed($num1,$num2);
12173: }
1.366 albertel 12174: } else {
12175: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12176: }
1.36 albertel 12177: }
12178:
1.474 albertel 12179: sub latest_receipt_algorithm_id {
1.835 albertel 12180: return 'receipt3';
1.474 albertel 12181: }
12182:
1.480 www 12183: sub recunique {
12184: my $fucourseid=shift;
12185: my $unique;
1.835 albertel 12186: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12187: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12188: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12189: } else {
12190: $unique=$perlvar{'lonReceipt'};
12191: }
12192: return unpack("%32C*",$unique);
12193: }
12194:
12195: sub recprefix {
12196: my $fucourseid=shift;
12197: my $prefix;
1.835 albertel 12198: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12199: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12200: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12201: } else {
12202: $prefix=$perlvar{'lonHostID'};
12203: }
12204: return unpack("%32C*",$prefix);
12205: }
12206:
1.76 www 12207: sub ireceipt {
1.474 albertel 12208: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12209:
12210: my $return =&recprefix($fucourseid).'-';
12211:
12212: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12213: $env{'request.state'} eq 'construct') {
12214: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12215: return $return;
12216: }
12217:
1.76 www 12218: my $cuname=unpack("%32C*",$funame);
12219: my $cudom=unpack("%32C*",$fudom);
12220: my $cucourseid=unpack("%32C*",$fucourseid);
12221: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12222: my $cunique=&recunique($fucourseid);
1.474 albertel 12223: my $cpart=unpack("%32S*",$part);
1.835 albertel 12224: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12225:
1.790 albertel 12226: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12227:
12228: $return.= ($cunique%$cuname+
12229: $cunique%$cudom+
12230: $cusymb%$cuname+
12231: $cusymb%$cudom+
12232: $cucourseid%$cuname+
12233: $cucourseid%$cudom+
12234: $cpart%$cuname+
12235: $cpart%$cudom);
12236: } else {
12237: $return.= ($cunique%$cuname+
12238: $cunique%$cudom+
12239: $cusymb%$cuname+
12240: $cusymb%$cudom+
12241: $cucourseid%$cuname+
12242: $cucourseid%$cudom);
12243: }
12244: return $return;
1.76 www 12245: }
12246:
12247: sub receipt {
1.474 albertel 12248: my ($part)=@_;
1.790 albertel 12249: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12250: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12251: }
1.260 ng 12252:
1.790 albertel 12253: sub whichuser {
12254: my ($passedsymb)=@_;
12255: my ($symb,$courseid,$domain,$name,$publicuser);
12256: if (defined($env{'form.grade_symb'})) {
12257: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12258: my $allowed=&allowed('vgr',$tmp_courseid);
12259: if (!$allowed &&
12260: exists($env{'request.course.sec'}) &&
12261: $env{'request.course.sec'} !~ /^\s*$/) {
12262: $allowed=&allowed('vgr',$tmp_courseid.
12263: '/'.$env{'request.course.sec'});
12264: }
12265: if ($allowed) {
12266: ($symb)=&get_env_multiple('form.grade_symb');
12267: $courseid=$tmp_courseid;
12268: ($domain)=&get_env_multiple('form.grade_domain');
12269: ($name)=&get_env_multiple('form.grade_username');
12270: return ($symb,$courseid,$domain,$name,$publicuser);
12271: }
12272: }
12273: if (!$passedsymb) {
12274: $symb=&symbread();
12275: } else {
12276: $symb=$passedsymb;
12277: }
12278: $courseid=$env{'request.course.id'};
12279: $domain=$env{'user.domain'};
12280: $name=$env{'user.name'};
12281: if ($name eq 'public' && $domain eq 'public') {
12282: if (!defined($env{'form.username'})) {
12283: $env{'form.username'}.=time.rand(10000000);
12284: }
12285: $name.=$env{'form.username'};
12286: }
12287: return ($symb,$courseid,$domain,$name,$publicuser);
12288:
12289: }
12290:
1.36 albertel 12291: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12292: # returns either the contents of the file or
12293: # -1 if the file doesn't exist
1.481 raeburn 12294: #
12295: # if the target is a file that was uploaded via DOCS,
12296: # a check will be made to see if a current copy exists on the local server,
12297: # if it does this will be served, otherwise a copy will be retrieved from
12298: # the home server for the course and stored in /home/httpd/html/userfiles on
12299: # the local server.
1.472 albertel 12300:
1.36 albertel 12301: sub getfile {
1.538 albertel 12302: my ($file) = @_;
1.609 banghart 12303: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12304: &repcopy($file);
12305: return &readfile($file);
12306: }
12307:
12308: sub repcopy_userfile {
12309: my ($file)=@_;
1.1142 raeburn 12310: my $londocroot = $perlvar{'lonDocRoot'};
12311: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12312: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12313: my ($cdom,$cnum,$filename) =
1.811 albertel 12314: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12315: my $uri="/uploaded/$cdom/$cnum/$filename";
12316: if (-e "$file") {
1.828 www 12317: # we already have a local copy, check it out
1.538 albertel 12318: my @fileinfo = stat($file);
1.828 www 12319: my $rtncode;
12320: my $info;
1.538 albertel 12321: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12322: if ($lwpresp ne 'ok') {
1.828 www 12323: # there is no such file anymore, even though we had a local copy
1.482 albertel 12324: if ($rtncode eq '404') {
1.538 albertel 12325: unlink($file);
1.482 albertel 12326: }
12327: return -1;
12328: }
12329: if ($info < $fileinfo[9]) {
1.828 www 12330: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12331: return 'ok';
1.828 www 12332: } else {
12333: # the file is outdated, get rid of it
12334: unlink($file);
1.482 albertel 12335: }
1.828 www 12336: }
12337: # one way or the other, at this point, we don't have the file
12338: # construct the correct path for the file
12339: my @parts = ($cdom,$cnum);
12340: if ($filename =~ m|^(.+)/[^/]+$|) {
12341: push @parts, split(/\//,$1);
12342: }
12343: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12344: foreach my $part (@parts) {
12345: $path .= '/'.$part;
12346: if (!-e $path) {
12347: mkdir($path,0770);
1.482 albertel 12348: }
12349: }
1.828 www 12350: # now the path exists for sure
12351: # get a user agent
12352: my $ua=new LWP::UserAgent;
12353: my $transferfile=$file.'.in.transfer';
12354: # FIXME: this should flock
12355: if (-e $transferfile) { return 'ok'; }
12356: my $request;
12357: $uri=~s/^\///;
1.980 raeburn 12358: my $homeserver = &homeserver($cnum,$cdom);
12359: my $protocol = $protocol{$homeserver};
12360: $protocol = 'http' if ($protocol ne 'https');
12361: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12362: my $response=$ua->request($request,$transferfile);
12363: # did it work?
12364: if ($response->is_error()) {
12365: unlink($transferfile);
12366: &logthis("Userfile repcopy failed for $uri");
12367: return -1;
12368: }
12369: # worked, rename the transfer file
12370: rename($transferfile,$file);
1.607 raeburn 12371: return 'ok';
1.481 raeburn 12372: }
12373:
1.517 albertel 12374: sub tokenwrapper {
12375: my $uri=shift;
1.980 raeburn 12376: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12377: $uri=~s|^/||;
1.620 albertel 12378: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12379: my $token=$1;
1.552 albertel 12380: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12381: if ($udom && $uname && $file) {
12382: $file=~s|(\?\.*)*$||;
1.949 raeburn 12383: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12384: my $homeserver = &homeserver($uname,$udom);
12385: my $protocol = $protocol{$homeserver};
12386: $protocol = 'http' if ($protocol ne 'https');
12387: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12388: (($uri=~/\?/)?'&':'?').'token='.$token.
12389: '&tokenissued='.$perlvar{'lonHostID'};
12390: } else {
12391: return '/adm/notfound.html';
12392: }
12393: }
12394:
1.828 www 12395: # call with reqtype HEAD: get last modification time
12396: # call with reqtype GET: get the file contents
12397: # Do not call this with reqtype GET for large files! It loads everything into memory
12398: #
1.481 raeburn 12399: sub getuploaded {
12400: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12401: $uri=~s/^\///;
1.980 raeburn 12402: my $homeserver = &homeserver($cnum,$cdom);
12403: my $protocol = $protocol{$homeserver};
12404: $protocol = 'http' if ($protocol ne 'https');
12405: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12406: my $ua=new LWP::UserAgent;
12407: my $request=new HTTP::Request($reqtype,$uri);
12408: my $response=$ua->request($request);
12409: $$rtncode = $response->code;
1.482 albertel 12410: if (! $response->is_success()) {
12411: return 'failed';
12412: }
12413: if ($reqtype eq 'HEAD') {
1.486 www 12414: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12415: } elsif ($reqtype eq 'GET') {
12416: $$info = $response->content;
1.472 albertel 12417: }
1.482 albertel 12418: return 'ok';
1.36 albertel 12419: }
12420:
1.481 raeburn 12421: sub readfile {
12422: my $file = shift;
12423: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12424: my $fh;
1.1172.2.96 raeburn 12425: open($fh,"<",$file);
1.481 raeburn 12426: my $a='';
1.800 albertel 12427: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12428: return $a;
12429: }
12430:
1.36 albertel 12431: sub filelocation {
1.590 banghart 12432: my ($dir,$file) = @_;
12433: my $location;
12434: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12435:
12436: if ($file =~ m-^/adm/-) {
12437: $file=~s-^/adm/wrapper/-/-;
12438: $file=~s-^/adm/coursedocs/showdoc/-/-;
12439: }
1.882 albertel 12440:
1.1139 www 12441: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12442: $location = $file;
1.609 banghart 12443: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12444: my ($udom,$uname,$filename)=
1.811 albertel 12445: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12446: my $home=&homeserver($uname,$udom);
12447: my $is_me=0;
12448: my @ids=¤t_machine_ids();
12449: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12450: if ($is_me) {
1.1117 foxr 12451: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12452: } else {
12453: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12454: $udom.'/'.$uname.'/'.$filename;
12455: }
1.882 albertel 12456: } elsif ($file =~ m-^/adm/-) {
12457: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12458: } else {
12459: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12460: $file=~s:^/(res|priv)/:/:;
12461: my $space=$1;
1.590 banghart 12462: if ( !( $file =~ m:^/:) ) {
12463: $location = $dir. '/'.$file;
12464: } else {
1.1142 raeburn 12465: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12466: }
1.59 albertel 12467: }
1.590 banghart 12468: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12469: while ($location=~m{/\.\./}) {
12470: if ($location =~ m{/[^/]+/\.\./}) {
12471: $location=~ s{/[^/]+/\.\./}{/}g;
12472: } else {
12473: $location=~ s{/\.\./}{/}g;
12474: }
12475: } #remove dir/..
1.590 banghart 12476: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12477: return $location;
1.46 www 12478: }
1.36 albertel 12479:
1.46 www 12480: sub hreflocation {
12481: my ($dir,$file)=@_;
1.980 raeburn 12482: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12483: $file=filelocation($dir,$file);
1.700 albertel 12484: } elsif ($file=~m-^/adm/-) {
12485: $file=~s-^/adm/wrapper/-/-;
12486: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12487: }
12488: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12489: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12490: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12491: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12492: {/uploaded/$1/$2/}x;
1.46 www 12493: }
1.913 albertel 12494: if ($file=~ m{^/userfiles/}) {
12495: $file =~ s{^/userfiles/}{/uploaded/};
12496: }
1.462 albertel 12497: return $file;
1.465 albertel 12498: }
12499:
1.1139 www 12500:
12501:
12502:
12503:
1.465 albertel 12504: sub current_machine_domains {
1.853 albertel 12505: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12506: }
12507:
12508: sub machine_domains {
12509: my ($hostname) = @_;
1.465 albertel 12510: my @domains;
1.838 albertel 12511: my %hostname = &all_hostnames();
1.465 albertel 12512: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12513: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12514: if ($hostname eq $name) {
1.844 albertel 12515: push(@domains,&host_domain($id));
1.465 albertel 12516: }
12517: }
12518: return @domains;
12519: }
12520:
12521: sub current_machine_ids {
1.853 albertel 12522: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12523: }
12524:
12525: sub machine_ids {
12526: my ($hostname) = @_;
12527: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12528: my @ids;
1.888 albertel 12529: my %name_to_host = &all_names();
1.889 albertel 12530: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12531: return @{ $name_to_host{$hostname} };
12532: }
12533: return;
1.31 www 12534: }
12535:
1.824 raeburn 12536: sub additional_machine_domains {
12537: my @domains;
1.1172.2.96 raeburn 12538: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 12539: while( my $line = <$fh>) {
12540: $line =~ s/\s//g;
12541: push(@domains,$line);
12542: }
12543: return @domains;
12544: }
12545:
12546: sub default_login_domain {
12547: my $domain = $perlvar{'lonDefDomain'};
12548: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12549: foreach my $posdom (¤t_machine_domains(),
12550: &additional_machine_domains()) {
12551: if (lc($posdom) eq lc($testdomain)) {
12552: $domain=$posdom;
12553: last;
12554: }
12555: }
12556: return $domain;
12557: }
12558:
1.31 www 12559: # ------------------------------------------------------------- Declutters URLs
12560:
12561: sub declutter {
12562: my $thisfn=shift;
1.569 albertel 12563: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12564: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12565: $thisfn=~s{^/home/httpd/html}{};
12566: }
1.31 www 12567: $thisfn=~s/^\///;
1.697 albertel 12568: $thisfn=~s|^adm/wrapper/||;
12569: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12570: $thisfn=~s/^res\///;
1.1172 bisitz 12571: $thisfn=~s/^priv\///;
1.1032 raeburn 12572: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12573: $thisfn=~s/\?.+$//;
12574: }
1.268 www 12575: return $thisfn;
12576: }
12577:
12578: # ------------------------------------------------------------- Clutter up URLs
12579:
12580: sub clutter {
12581: my $thisfn='/'.&declutter(shift);
1.887 albertel 12582: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12583: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12584: $thisfn='/res'.$thisfn;
12585: }
1.1031 raeburn 12586: if ($thisfn !~m|^/adm|) {
12587: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12588: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12589: } else {
12590: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12591: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12592: if ($embstyle eq 'ssi'
12593: || ($embstyle eq 'hdn')
12594: || ($embstyle eq 'rat')
12595: || ($embstyle eq 'prv')
12596: || ($embstyle eq 'ign')) {
12597: #do nothing with these
12598: } elsif (($embstyle eq 'img')
1.695 albertel 12599: || ($embstyle eq 'emb')
12600: || ($embstyle eq 'wrp')) {
12601: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12602: } elsif ($embstyle eq 'unk'
12603: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12604: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12605: } else {
1.718 www 12606: # &logthis("Got a blank emb style");
1.695 albertel 12607: }
1.694 albertel 12608: }
12609: }
1.31 www 12610: return $thisfn;
1.12 www 12611: }
12612:
1.787 albertel 12613: sub clutter_with_no_wrapper {
12614: my $uri = &clutter(shift);
12615: if ($uri =~ m-^/adm/-) {
12616: $uri =~ s-^/adm/wrapper/-/-;
12617: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12618: }
12619: return $uri;
12620: }
12621:
1.557 albertel 12622: sub freeze_escape {
12623: my ($value)=@_;
12624: if (ref($value)) {
12625: $value=&nfreeze($value);
12626: return '__FROZEN__'.&escape($value);
12627: }
12628: return &escape($value);
12629: }
12630:
1.11 www 12631:
1.557 albertel 12632: sub thaw_unescape {
12633: my ($value)=@_;
12634: if ($value =~ /^__FROZEN__/) {
12635: substr($value,0,10,undef);
12636: $value=&unescape($value);
12637: return &thaw($value);
12638: }
12639: return &unescape($value);
12640: }
12641:
1.436 albertel 12642: sub correct_line_ends {
12643: my ($result)=@_;
12644: $$result =~s/\r\n/\n/mg;
12645: $$result =~s/\r/\n/mg;
1.415 albertel 12646: }
1.1 albertel 12647: # ================================================================ Main Program
12648:
1.184 www 12649: sub goodbye {
1.204 albertel 12650: &logthis("Starting Shut down");
1.443 albertel 12651: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12652: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12653: #converted
1.599 albertel 12654: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12655: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12656: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12657: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12658: #1.1 only
1.870 albertel 12659: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12660: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12661: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12662: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12663: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12664: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12665: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12666: &flushcourselogs();
12667: &logthis("Shutting down");
12668: }
12669:
1.852 albertel 12670: sub get_dns {
1.1172.2.17 raeburn 12671: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12672: if (!$ignore_cache) {
12673: my ($content,$cached)=
12674: &Apache::lonnet::is_cached_new('dns',$url);
12675: if ($cached) {
1.1172.2.17 raeburn 12676: &$func($content,$hashref);
1.869 albertel 12677: return;
12678: }
12679: }
12680:
12681: my %alldns;
1.1172.2.96 raeburn 12682: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
12683: foreach my $dns (<$config>) {
12684: next if ($dns !~ /^\^(\S*)/x);
12685: my $line = $1;
12686: my ($host,$protocol) = split(/:/,$line);
12687: if ($protocol ne 'https') {
12688: $protocol = 'http';
12689: }
12690: $alldns{$host} = $protocol;
1.979 raeburn 12691: }
1.1172.2.96 raeburn 12692: close($config);
1.869 albertel 12693: }
12694: while (%alldns) {
1.1172.2.52 raeburn 12695: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12696: my $ua=new LWP::UserAgent;
1.1134 raeburn 12697: $ua->timeout(30);
1.979 raeburn 12698: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12699: my $response=$ua->request($request);
1.979 raeburn 12700: delete($alldns{$dns});
1.852 albertel 12701: next if ($response->is_error());
12702: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12703: unless ($nocache) {
1.1172.2.23 raeburn 12704: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12705: }
12706: &$func(\@content,$hashref);
1.869 albertel 12707: return;
1.852 albertel 12708: }
12709: close($config);
1.871 albertel 12710: my $which = (split('/',$url))[3];
12711: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.96 raeburn 12712: open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12713: my @content = <$config>;
1.1172.2.17 raeburn 12714: &$func(\@content,$hashref);
12715: return;
12716: }
12717:
12718: # ------------------------------------------------------Get DNS checksums file
12719: sub parse_dns_checksums_tab {
12720: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12721: my $lonhost = $perlvar{'lonHostID'};
12722: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12723: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12724: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12725: my $webconfdir = '/etc/httpd/conf';
12726: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12727: $webconfdir = '/etc/apache2';
12728: } elsif ($distro =~ /^sles(\d+)$/) {
12729: if ($1 >= 10) {
12730: $webconfdir = '/etc/apache2';
12731: }
12732: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12733: if ($1 >= 10.0) {
12734: $webconfdir = '/etc/apache2';
12735: }
12736: }
1.1172.2.17 raeburn 12737: my ($release,$timestamp) = split(/\-/,$loncaparev);
12738: my (%chksum,%revnum);
12739: if (ref($lines) eq 'ARRAY') {
12740: chomp(@{$lines});
1.1172.2.34 raeburn 12741: my $version = shift(@{$lines});
12742: if ($version eq $release) {
1.1172.2.17 raeburn 12743: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12744: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12745: if ($file =~ m{^/etc/httpd/conf}) {
12746: if ($webconfdir eq '/etc/apache2') {
12747: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12748: }
12749: }
1.1172.2.34 raeburn 12750: $chksum{$file} = $shasum;
12751: $revnum{$file} = $version;
1.1172.2.17 raeburn 12752: }
12753: if (ref($hashref) eq 'HASH') {
12754: %{$hashref} = (
12755: sums => \%chksum,
12756: versions => \%revnum,
12757: );
12758: }
12759: }
12760: }
1.869 albertel 12761: return;
1.852 albertel 12762: }
1.1172.2.17 raeburn 12763:
12764: sub fetch_dns_checksums {
12765: my %checksums;
1.1172.2.34 raeburn 12766: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12767: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12768: my ($release,$timestamp) = split(/\-/,$loncaparev);
12769: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12770: \%checksums);
12771: return \%checksums;
12772: }
12773:
1.327 albertel 12774: # ------------------------------------------------------------ Read domain file
12775: {
1.852 albertel 12776: my $loaded;
1.846 albertel 12777: my %domain;
12778:
1.852 albertel 12779: sub parse_domain_tab {
12780: my ($lines) = @_;
12781: foreach my $line (@$lines) {
12782: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12783:
1.846 albertel 12784: chomp($line);
1.852 albertel 12785: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12786: my %this_domain;
12787: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12788: 'lang_def', 'city', 'longi', 'lati',
12789: 'primary') {
12790: $this_domain{$field} = shift(@elements);
12791: }
12792: $domain{$name} = \%this_domain;
1.852 albertel 12793: }
12794: }
1.864 albertel 12795:
12796: sub reset_domain_info {
12797: undef($loaded);
12798: undef(%domain);
12799: }
12800:
1.852 albertel 12801: sub load_domain_tab {
1.1172.2.70 raeburn 12802: my ($ignore_cache,$nocache) = @_;
12803: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12804: my $fh;
1.1172.2.96 raeburn 12805: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 12806: my @lines = <$fh>;
12807: &parse_domain_tab(\@lines);
1.448 albertel 12808: }
1.852 albertel 12809: close($fh);
12810: $loaded = 1;
1.327 albertel 12811: }
1.846 albertel 12812:
12813: sub domain {
1.852 albertel 12814: &load_domain_tab() if (!$loaded);
12815:
1.846 albertel 12816: my ($name,$what) = @_;
12817: return if ( !exists($domain{$name}) );
12818:
12819: if (!$what) {
12820: return $domain{$name}{'description'};
12821: }
12822: return $domain{$name}{$what};
12823: }
1.974 raeburn 12824:
12825: sub domain_info {
12826: &load_domain_tab() if (!$loaded);
12827: return %domain;
12828: }
12829:
1.327 albertel 12830: }
12831:
12832:
1.1 albertel 12833: # ------------------------------------------------------------- Read hosts file
12834: {
1.838 albertel 12835: my %hostname;
1.844 albertel 12836: my %hostdom;
1.845 albertel 12837: my %libserv;
1.852 albertel 12838: my $loaded;
1.888 albertel 12839: my %name_to_host;
1.1074 raeburn 12840: my %internetdom;
1.1107 raeburn 12841: my %LC_dns_serv;
1.852 albertel 12842:
12843: sub parse_hosts_tab {
12844: my ($file) = @_;
12845: foreach my $configline (@$file) {
12846: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12847: chomp($configline);
12848: if ($configline =~ /^\^/) {
12849: if ($configline =~ /^\^([\w.\-]+)/) {
12850: $LC_dns_serv{$1} = 1;
12851: }
12852: next;
12853: }
1.1074 raeburn 12854: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12855: $name=~s/\s//g;
12856: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 12857: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
12858: my $curr = $hostname{$id};
12859: my $skip;
12860: if (ref($name_to_host{$curr}) eq 'ARRAY') {
12861: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
12862: $skip = 1;
12863: } else {
12864: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
12865: }
12866: }
12867: unless ($skip) {
12868: push(@{$name_to_host{$name}},$id);
12869: }
12870: } else {
12871: push(@{$name_to_host{$name}},$id);
12872: }
1.852 albertel 12873: $hostname{$id}=$name;
12874: $hostdom{$id}=$domain;
12875: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12876: if (defined($protocol)) {
12877: if ($protocol eq 'https') {
12878: $protocol{$id} = $protocol;
12879: } else {
12880: $protocol{$id} = 'http';
12881: }
1.968 raeburn 12882: } else {
1.969 raeburn 12883: $protocol{$id} = 'http';
1.968 raeburn 12884: }
1.1074 raeburn 12885: if (defined($intdom)) {
12886: $internetdom{$id} = $intdom;
12887: }
1.852 albertel 12888: }
12889: }
12890: }
1.864 albertel 12891:
12892: sub reset_hosts_info {
1.897 albertel 12893: &purge_remembered();
1.864 albertel 12894: &reset_domain_info();
12895: &reset_hosts_ip_info();
1.892 albertel 12896: undef(%name_to_host);
1.864 albertel 12897: undef(%hostname);
12898: undef(%hostdom);
12899: undef(%libserv);
12900: undef($loaded);
12901: }
1.1 albertel 12902:
1.852 albertel 12903: sub load_hosts_tab {
1.1172.2.70 raeburn 12904: my ($ignore_cache,$nocache) = @_;
12905: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 12906: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 12907: my @config = <$config>;
12908: &parse_hosts_tab(\@config);
12909: close($config);
12910: $loaded=1;
1.1 albertel 12911: }
1.852 albertel 12912:
1.838 albertel 12913: sub hostname {
1.852 albertel 12914: &load_hosts_tab() if (!$loaded);
12915:
1.838 albertel 12916: my ($lonid) = @_;
12917: return $hostname{$lonid};
12918: }
1.845 albertel 12919:
1.838 albertel 12920: sub all_hostnames {
1.852 albertel 12921: &load_hosts_tab() if (!$loaded);
12922:
1.838 albertel 12923: return %hostname;
12924: }
1.845 albertel 12925:
1.888 albertel 12926: sub all_names {
1.1172.2.70 raeburn 12927: my ($ignore_cache,$nocache) = @_;
12928: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12929:
12930: return %name_to_host;
12931: }
12932:
1.974 raeburn 12933: sub all_host_domain {
12934: &load_hosts_tab() if (!$loaded);
12935: return %hostdom;
12936: }
12937:
1.845 albertel 12938: sub is_library {
1.852 albertel 12939: &load_hosts_tab() if (!$loaded);
12940:
1.845 albertel 12941: return exists($libserv{$_[0]});
12942: }
12943:
12944: sub all_library {
1.852 albertel 12945: &load_hosts_tab() if (!$loaded);
12946:
1.845 albertel 12947: return %libserv;
12948: }
12949:
1.1062 droeschl 12950: sub unique_library {
12951: #2x reverse removes all hostnames that appear more than once
12952: my %unique = reverse &all_library();
12953: return reverse %unique;
12954: }
12955:
1.841 albertel 12956: sub get_servers {
1.852 albertel 12957: &load_hosts_tab() if (!$loaded);
12958:
1.841 albertel 12959: my ($domain,$type) = @_;
12960: my %possible_hosts = ($type eq 'library') ? %libserv
12961: : %hostname;
12962: my %result;
1.842 albertel 12963: if (ref($domain) eq 'ARRAY') {
12964: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12965: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12966: $result{$host} = $hostname;
12967: }
12968: }
12969: } else {
12970: while ( my ($host,$hostname) = each(%possible_hosts)) {
12971: if ($hostdom{$host} eq $domain) {
12972: $result{$host} = $hostname;
12973: }
1.841 albertel 12974: }
12975: }
12976: return %result;
12977: }
1.845 albertel 12978:
1.1062 droeschl 12979: sub get_unique_servers {
12980: my %unique = reverse &get_servers(@_);
12981: return reverse %unique;
12982: }
12983:
1.844 albertel 12984: sub host_domain {
1.852 albertel 12985: &load_hosts_tab() if (!$loaded);
12986:
1.844 albertel 12987: my ($lonid) = @_;
12988: return $hostdom{$lonid};
12989: }
12990:
1.841 albertel 12991: sub all_domains {
1.852 albertel 12992: &load_hosts_tab() if (!$loaded);
12993:
1.841 albertel 12994: my %seen;
12995: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12996: return @uniq;
12997: }
1.1074 raeburn 12998:
12999: sub internet_dom {
13000: &load_hosts_tab() if (!$loaded);
13001:
13002: my ($lonid) = @_;
13003: return $internetdom{$lonid};
13004: }
1.1107 raeburn 13005:
13006: sub is_LC_dns {
13007: &load_hosts_tab() if (!$loaded);
13008:
13009: my ($hostname) = @_;
13010: return exists($LC_dns_serv{$hostname});
13011: }
13012:
1.1 albertel 13013: }
13014:
1.847 albertel 13015: {
13016: my %iphost;
1.856 albertel 13017: my %name_to_ip;
13018: my %lonid_to_ip;
1.869 albertel 13019:
1.847 albertel 13020: sub get_hosts_from_ip {
13021: my ($ip) = @_;
13022: my %iphosts = &get_iphost();
13023: if (ref($iphosts{$ip})) {
13024: return @{$iphosts{$ip}};
13025: }
13026: return;
1.839 albertel 13027: }
1.864 albertel 13028:
13029: sub reset_hosts_ip_info {
13030: undef(%iphost);
13031: undef(%name_to_ip);
13032: undef(%lonid_to_ip);
13033: }
1.856 albertel 13034:
13035: sub get_host_ip {
13036: my ($lonid) = @_;
13037: if (exists($lonid_to_ip{$lonid})) {
13038: return $lonid_to_ip{$lonid};
13039: }
13040: my $name=&hostname($lonid);
13041: my $ip = gethostbyname($name);
13042: return if (!$ip || length($ip) ne 4);
13043: $ip=inet_ntoa($ip);
13044: $name_to_ip{$name} = $ip;
13045: $lonid_to_ip{$lonid} = $ip;
13046: return $ip;
13047: }
1.847 albertel 13048:
13049: sub get_iphost {
1.1172.2.70 raeburn 13050: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13051:
1.869 albertel 13052: if (!$ignore_cache) {
13053: if (%iphost) {
13054: return %iphost;
13055: }
13056: my ($ip_info,$cached)=
13057: &Apache::lonnet::is_cached_new('iphost','iphost');
13058: if ($cached) {
13059: %iphost = %{$ip_info->[0]};
13060: %name_to_ip = %{$ip_info->[1]};
13061: %lonid_to_ip = %{$ip_info->[2]};
13062: return %iphost;
13063: }
13064: }
1.894 albertel 13065:
13066: # get yesterday's info for fallback
13067: my %old_name_to_ip;
13068: my ($ip_info,$cached)=
13069: &Apache::lonnet::is_cached_new('iphost','iphost');
13070: if ($cached) {
13071: %old_name_to_ip = %{$ip_info->[1]};
13072: }
13073:
1.1172.2.70 raeburn 13074: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13075: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13076: my $ip;
13077: if (!exists($name_to_ip{$name})) {
13078: $ip = gethostbyname($name);
13079: if (!$ip || length($ip) ne 4) {
1.894 albertel 13080: if (defined($old_name_to_ip{$name})) {
13081: $ip = $old_name_to_ip{$name};
13082: &logthis("Can't find $name defaulting to old $ip");
13083: } else {
13084: &logthis("Name $name no IP found");
13085: next;
13086: }
13087: } else {
13088: $ip=inet_ntoa($ip);
1.847 albertel 13089: }
13090: $name_to_ip{$name} = $ip;
13091: } else {
13092: $ip = $name_to_ip{$name};
1.653 albertel 13093: }
1.888 albertel 13094: foreach my $id (@{ $name_to_host{$name} }) {
13095: $lonid_to_ip{$id} = $ip;
13096: }
13097: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13098: }
1.1172.2.70 raeburn 13099: unless ($nocache) {
13100: &do_cache_new('iphost','iphost',
13101: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13102: 48*60*60);
13103: }
1.869 albertel 13104:
1.847 albertel 13105: return %iphost;
1.598 albertel 13106: }
13107:
1.992 raeburn 13108: #
13109: # Given a DNS returns the loncapa host name for that DNS
13110: #
13111: sub host_from_dns {
13112: my ($dns) = @_;
13113: my @hosts;
13114: my $ip;
13115:
1.993 raeburn 13116: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13117: $ip = $name_to_ip{$dns};
13118: }
13119: if (!$ip) {
13120: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13121: if (length($ip) == 4) {
13122: $ip = &IO::Socket::inet_ntoa($ip);
13123: }
13124: }
13125: if ($ip) {
13126: @hosts = get_hosts_from_ip($ip);
13127: return $hosts[0];
13128: }
13129: return undef;
1.986 foxr 13130: }
1.992 raeburn 13131:
1.1074 raeburn 13132: sub get_internet_names {
13133: my ($lonid) = @_;
13134: return if ($lonid eq '');
13135: my ($idnref,$cached)=
13136: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13137: if ($cached) {
13138: return $idnref;
13139: }
13140: my $ip = &get_host_ip($lonid);
13141: my @hosts = &get_hosts_from_ip($ip);
13142: my %iphost = &get_iphost();
13143: my (@idns,%seen);
13144: foreach my $id (@hosts) {
13145: my $dom = &host_domain($id);
13146: my $prim_id = &domain($dom,'primary');
13147: my $prim_ip = &get_host_ip($prim_id);
13148: next if ($seen{$prim_ip});
13149: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13150: foreach my $id (@{$iphost{$prim_ip}}) {
13151: my $intdom = &internet_dom($id);
13152: unless (grep(/^\Q$intdom\E$/,@idns)) {
13153: push(@idns,$intdom);
13154: }
13155: }
13156: }
13157: $seen{$prim_ip} = 1;
13158: }
1.1172.2.23 raeburn 13159: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13160: }
13161:
1.986 foxr 13162: }
13163:
1.1079 raeburn 13164: sub all_loncaparevs {
1.1172.2.39 raeburn 13165: 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 13166: }
13167:
1.1172.2.27 raeburn 13168: # ------------------------------------------------------- Read loncaparev table
13169: {
13170: sub load_loncaparevs {
13171: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 13172: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 13173: while (my $configline=<$config>) {
13174: chomp($configline);
13175: my ($hostid,$loncaparev)=split(/:/,$configline);
13176: $loncaparevs{$hostid}=$loncaparev;
13177: }
13178: close($config);
13179: }
13180: }
13181: }
13182: }
13183:
13184: # ----------------------------------------------------- Read serverhostID table
13185: {
13186: sub load_serverhomeIDs {
13187: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 13188: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 13189: while (my $configline=<$config>) {
13190: chomp($configline);
13191: my ($name,$id)=split(/:/,$configline);
13192: $serverhomeIDs{$name}=$id;
13193: }
13194: close($config);
13195: }
13196: }
13197: }
13198: }
13199:
13200:
1.862 albertel 13201: BEGIN {
13202:
13203: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13204: unless ($readit) {
13205: {
13206: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13207: %perlvar = (%perlvar,%{$configvars});
13208: }
13209:
13210:
1.1 albertel 13211: # ------------------------------------------------------ Read spare server file
13212: {
1.1172.2.96 raeburn 13213: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13214:
13215: while (my $configline=<$config>) {
13216: chomp($configline);
1.284 matthew 13217: if ($configline) {
1.784 albertel 13218: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13219: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13220: push(@{ $spareid{$type} }, $host);
1.1 albertel 13221: }
13222: }
1.448 albertel 13223: close($config);
1.1 albertel 13224: }
1.11 www 13225: # ------------------------------------------------------------ Read permissions
13226: {
1.1172.2.96 raeburn 13227: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13228:
13229: while (my $configline=<$config>) {
1.448 albertel 13230: chomp($configline);
13231: if ($configline) {
13232: my ($role,$perm)=split(/ /,$configline);
13233: if ($perm ne '') { $pr{$role}=$perm; }
13234: }
1.11 www 13235: }
1.448 albertel 13236: close($config);
1.11 www 13237: }
13238:
13239: # -------------------------------------------- Read plain texts for permissions
13240: {
1.1172.2.96 raeburn 13241: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13242:
13243: while (my $configline=<$config>) {
1.448 albertel 13244: chomp($configline);
13245: if ($configline) {
1.742 raeburn 13246: my ($short,@plain)=split(/:/,$configline);
13247: %{$prp{$short}} = ();
13248: if (@plain > 0) {
13249: $prp{$short}{'std'} = $plain[0];
13250: for (my $i=1; $i<@plain; $i++) {
13251: $prp{$short}{'alt'.$i} = $plain[$i];
13252: }
13253: }
1.448 albertel 13254: }
1.135 www 13255: }
1.448 albertel 13256: close($config);
1.135 www 13257: }
13258:
13259: # ---------------------------------------------------------- Read package table
13260: {
1.1172.2.96 raeburn 13261: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13262:
13263: while (my $configline=<$config>) {
1.483 albertel 13264: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13265: chomp($configline);
13266: my ($short,$plain)=split(/:/,$configline);
13267: my ($pack,$name)=split(/\&/,$short);
13268: if ($plain ne '') {
13269: $packagetab{$pack.'&'.$name.'&name'}=$name;
13270: $packagetab{$short}=$plain;
13271: }
1.11 www 13272: }
1.448 albertel 13273: close($config);
1.329 matthew 13274: }
13275:
1.1172.2.27 raeburn 13276: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 13277:
1.1172.2.27 raeburn 13278: &load_loncaparevs();
13279:
13280: # ------------------------------------------------------- Read serverhostID table
13281:
13282: &load_serverhomeIDs();
1.1074 raeburn 13283:
1.1172.2.27 raeburn 13284: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13285: {
13286: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13287: if (-e $file) {
13288: my $parser = HTML::LCParser->new($file);
13289: while (my $token = $parser->get_token()) {
13290: if ($token->[0] eq 'S') {
13291: my $item = $token->[1];
13292: my $name = $token->[2]{'name'};
13293: my $value = $token->[2]{'value'};
13294: if ($item ne '' && $name ne '' && $value ne '') {
13295: my $release = $parser->get_text();
13296: $release =~ s/(^\s*|\s*$ )//gx;
13297: $needsrelease{$item.':'.$name.':'.$value} = $release;
13298: }
13299: }
13300: }
13301: }
1.1073 raeburn 13302: }
13303:
1.1138 raeburn 13304: # ---------------------------------------------------------- Read managers table
13305: {
13306: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 13307: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 13308: while (my $configline=<$config>) {
13309: chomp($configline);
13310: next if ($configline =~ /^\#/);
13311: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13312: $managerstab{$configline} = 1;
13313: }
13314: }
13315: close($config);
13316: }
13317: }
13318: }
13319:
1.329 matthew 13320: # ------------- set up temporary directory
13321: {
1.1117 foxr 13322: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13323:
1.11 www 13324: }
13325:
1.794 albertel 13326: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13327: 'compress_threshold'=> 20_000,
13328: });
1.185 www 13329:
1.281 www 13330: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13331: $dumpcount=0;
1.958 www 13332: $locknum=0;
1.22 www 13333:
1.163 harris41 13334: &logtouch();
1.672 albertel 13335: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13336: $readit=1;
1.564 albertel 13337: {
13338: use integer;
13339: my $test=(2**32)+1;
1.568 albertel 13340: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13341: &logthis(" Detected 64bit platform ($_64bit)");
13342: }
1.195 www 13343: }
1.1 albertel 13344: }
1.179 www 13345:
1.1 albertel 13346: 1;
1.191 harris41 13347: __END__
13348:
1.243 albertel 13349: =pod
13350:
1.191 harris41 13351: =head1 NAME
13352:
1.243 albertel 13353: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13354:
13355: =head1 SYNOPSIS
13356:
1.243 albertel 13357: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13358:
13359: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13360:
1.243 albertel 13361: Common parameters:
13362:
13363: =over 4
13364:
13365: =item *
13366:
13367: $uname : an internal username (if $cname expecting a course Id specifically)
13368:
13369: =item *
13370:
13371: $udom : a domain (if $cdom expecting a course's domain specifically)
13372:
13373: =item *
13374:
13375: $symb : a resource instance identifier
13376:
13377: =item *
13378:
13379: $namespace : the name of a .db file that contains the data needed or
13380: being set.
13381:
13382: =back
13383:
1.394 bowersj2 13384: =head1 OVERVIEW
1.191 harris41 13385:
1.394 bowersj2 13386: lonnet provides subroutines which interact with the
13387: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13388: about classes, users, and resources.
1.243 albertel 13389:
13390: For many of these objects you can also use this to store data about
13391: them or modify them in various ways.
1.191 harris41 13392:
1.394 bowersj2 13393: =head2 Symbs
1.191 harris41 13394:
1.394 bowersj2 13395: To identify a specific instance of a resource, LON-CAPA uses symbols
13396: or "symbs"X<symb>. These identifiers are built from the URL of the
13397: map, the resource number of the resource in the map, and the URL of
13398: the resource itself. The latter is somewhat redundant, but might help
13399: if maps change.
13400:
13401: An example is
13402:
13403: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13404:
13405: The respective map entry is
13406:
13407: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13408: title="Problem 2">
13409: </resource>
13410:
13411: Symbs are used by the random number generator, as well as to store and
13412: restore data specific to a certain instance of for example a problem.
13413:
13414: =head2 Storing And Retrieving Data
13415:
13416: X<store()>X<cstore()>X<restore()>Three of the most important functions
13417: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13418: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13419: is is the non-critical message twin of cstore. These functions are for
13420: handlers to store a perl hash to a user's permanent data space in an
13421: easy manner, and to retrieve it again on another call. It is expected
13422: that a handler would use this once at the beginning to retrieve data,
13423: and then again once at the end to send only the new data back.
13424:
13425: The data is stored in the user's data directory on the user's
13426: homeserver under the ID of the course.
13427:
13428: The hash that is returned by restore will have all of the previous
13429: value for all of the elements of the hash.
13430:
13431: Example:
13432:
13433: #creating a hash
13434: my %hash;
13435: $hash{'foo'}='bar';
13436:
13437: #storing it
13438: &Apache::lonnet::cstore(\%hash);
13439:
13440: #changing a value
13441: $hash{'foo'}='notbar';
13442:
13443: #adding a new value
13444: $hash{'bar'}='foo';
13445: &Apache::lonnet::cstore(\%hash);
13446:
13447: #retrieving the hash
13448: my %history=&Apache::lonnet::restore();
13449:
13450: #print the hash
13451: foreach my $key (sort(keys(%history))) {
13452: print("\%history{$key} = $history{$key}");
13453: }
13454:
13455: Will print out:
1.191 harris41 13456:
1.394 bowersj2 13457: %history{1:foo} = bar
13458: %history{1:keys} = foo:timestamp
13459: %history{1:timestamp} = 990455579
13460: %history{2:bar} = foo
13461: %history{2:foo} = notbar
13462: %history{2:keys} = foo:bar:timestamp
13463: %history{2:timestamp} = 990455580
13464: %history{bar} = foo
13465: %history{foo} = notbar
13466: %history{timestamp} = 990455580
13467: %history{version} = 2
13468:
13469: Note that the special hash entries C<keys>, C<version> and
13470: C<timestamp> were added to the hash. C<version> will be equal to the
13471: total number of versions of the data that have been stored. The
13472: C<timestamp> attribute will be the UNIX time the hash was
13473: stored. C<keys> is available in every historical section to list which
13474: keys were added or changed at a specific historical revision of a
13475: hash.
13476:
13477: B<Warning>: do not store the hash that restore returns directly. This
13478: will cause a mess since it will restore the historical keys as if the
13479: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13480:
1.394 bowersj2 13481: Calling convention:
1.191 harris41 13482:
1.1172.2.27 raeburn 13483: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 13484: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13485:
1.394 bowersj2 13486: For more detailed information, see lonnet specific documentation.
1.191 harris41 13487:
1.394 bowersj2 13488: =head1 RETURN MESSAGES
1.191 harris41 13489:
1.394 bowersj2 13490: =over 4
1.191 harris41 13491:
1.394 bowersj2 13492: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13493:
1.394 bowersj2 13494: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13495: when the connection is brought back up
1.191 harris41 13496:
1.394 bowersj2 13497: =item * B<con_failed>: unable to contact remote host and unable to save message
13498: for later delivery
1.191 harris41 13499:
1.967 bisitz 13500: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13501:
1.394 bowersj2 13502: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13503: that was requested
1.191 harris41 13504:
1.243 albertel 13505: =back
1.191 harris41 13506:
1.243 albertel 13507: =head1 PUBLIC SUBROUTINES
1.191 harris41 13508:
1.243 albertel 13509: =head2 Session Environment Functions
1.191 harris41 13510:
1.243 albertel 13511: =over 4
1.191 harris41 13512:
1.394 bowersj2 13513: =item *
13514: X<appenv()>
1.949 raeburn 13515: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13516: the user envirnoment file, and will be restored for each access this
1.620 albertel 13517: user makes during this session, also modifies the %env for the current
1.949 raeburn 13518: process. Optional rolesarrayref - if defined contains a reference to an array
13519: of roles which are exempt from the restriction on modifying user.role entries
13520: in the user's environment.db and in %env.
1.191 harris41 13521:
13522: =item *
1.394 bowersj2 13523: X<delenv()>
1.987 raeburn 13524: B<delenv($delthis,$regexp)>: removes all items from the session
13525: environment file that begin with $delthis. If the
13526: optional second arg - $regexp - is true, $delthis is treated as a
13527: regular expression, otherwise \Q$delthis\E is used.
13528: The values are also deleted from the current processes %env.
1.191 harris41 13529:
1.795 albertel 13530: =item * get_env_multiple($name)
13531:
13532: gets $name from the %env hash, it seemlessly handles the cases where multiple
13533: values may be defined and end up as an array ref.
13534:
13535: returns an array of values
13536:
1.243 albertel 13537: =back
13538:
13539: =head2 User Information
1.191 harris41 13540:
1.243 albertel 13541: =over 4
1.191 harris41 13542:
13543: =item *
1.394 bowersj2 13544: X<queryauthenticate()>
13545: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13546: authentication scheme
13547:
13548: =item *
1.394 bowersj2 13549: X<authenticate()>
1.1073 raeburn 13550: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13551: authenticate user from domain's lib servers (first use the current
13552: one). C<$upass> should be the users password.
1.1073 raeburn 13553: $checkdefauth is optional (value is 1 if a check should be made to
13554: authenticate user using default authentication method, and allow
13555: account creation if username does not have account in the domain).
13556: $clientcancheckhost is optional (value is 1 if checking whether the
13557: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13558:
13559: =item *
1.394 bowersj2 13560: X<homeserver()>
13561: B<homeserver($uname,$udom)>: find the server which has
13562: the user's directory and files (there must be only one), this caches
13563: the answer, and also caches if there is a borken connection.
1.191 harris41 13564:
13565: =item *
1.394 bowersj2 13566: X<idget()>
13567: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13568: (IDs are a unique resource in a domain, there must be only 1 ID per
13569: username, and only 1 username per ID in a specific domain) (returns
13570: hash: id=>name,id=>name)
1.191 harris41 13571:
13572: =item *
1.394 bowersj2 13573: X<idrget()>
13574: B<idrget($udom,@unames)>: find the IDs behind a list of
13575: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13576:
13577: =item *
1.394 bowersj2 13578: X<idput()>
13579: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13580:
13581: =item *
1.394 bowersj2 13582: X<rolesinit()>
1.1169 droeschl 13583: B<rolesinit($udom,$username)>: get user privileges.
13584: returns user role, first access and timer interval hashes
1.243 albertel 13585:
13586: =item *
1.1171 droeschl 13587: X<privileged()>
13588: B<privileged($username,$domain)>: returns a true if user has a
13589: privileged and active role (i.e. su or dc), false otherwise.
13590:
13591: =item *
1.551 albertel 13592: X<getsection()>
13593: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13594: course $cname, return section name/number or '' for "not in course"
13595: and '-1' for "no section"
13596:
13597: =item *
1.394 bowersj2 13598: X<userenvironment()>
13599: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13600: passed in @what from the requested user's environment, returns a hash
13601:
1.858 raeburn 13602: =item *
13603: X<userlog_query()>
1.859 albertel 13604: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13605: activity.log file. %filters defines filters applied when parsing the
13606: log file. These can be start or end timestamps, or the type of action
13607: - log to look for Login or Logout events, check for Checkin or
13608: Checkout, role for role selection. The response is in the form
13609: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13610: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13611:
1.243 albertel 13612: =back
13613:
13614: =head2 User Roles
13615:
13616: =over 4
13617:
13618: =item *
13619:
1.1172.2.65 raeburn 13620: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13621: returns codes for allowed actions.
13622:
13623: The first argument is required, all others are optional.
13624:
13625: $priv is the privilege being checked.
13626: $uri contains additional information about what is being checked for access (e.g.,
13627: URL, course ID etc.).
13628: $symb is the unique resource instance identifier in a course; if needed,
13629: but not provided, it will be retrieved via a call to &symbread().
13630: $role is the role for which a priv is being checked (only used if priv is evb).
13631: $clientip is the user's IP address (only used when checking for access to portfolio
13632: files).
13633: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13634: prevents recursive calls to &allowed.
13635:
1.243 albertel 13636: F: full access
13637: U,I,K: authentication modes (cxx only)
13638: '': forbidden
13639: 1: user needs to choose course
13640: 2: browse allowed
1.766 albertel 13641: A: passphrase authentication needed
1.1172.2.65 raeburn 13642: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13643:
13644: =item *
13645:
1.1172.2.13 raeburn 13646: constructaccess($url,$setpriv) : check for access to construction space URL
13647:
13648: See if the owner domain and name in the URL match those in the
13649: expected environment. If so, return three element list
13650: ($ownername,$ownerdomain,$ownerhome).
13651:
13652: Otherwise return the null string.
13653:
13654: If second argument 'setpriv' is true, it assigns the privileges,
13655: and returns the same three element list, unless the owner has
13656: blocked "ad hoc" Domain Coordinator access to the Author Space,
13657: in which case the null string is returned.
13658:
13659: =item *
13660:
1.1172.2.84 raeburn 13661: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
13662: define a custom role rolename set privileges in format of lonTabs/roles.tab
13663: for system, domain, and course level. $uname and $udom are optional (current
13664: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 13665:
13666: =item *
13667:
1.988 raeburn 13668: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13669: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13670: $type is Course (default) or Community.
1.988 raeburn 13671: If $forcedefault evaluates to true, text returned will be default
13672: text for $type. Otherwise, if this is a course, the text returned
13673: will be a custom name for the role (if defined in the course's
13674: environment). If no custom name is defined the default is returned.
13675:
1.832 raeburn 13676: =item *
13677:
1.1172.2.23 raeburn 13678: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13679: All arguments are optional. Returns a hash of a roles, either for
13680: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13681: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13682: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13683: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13684: For each key, value is set to colon-separated start and end times for
13685: the role. If no username and domain are specified, will default to
1.934 raeburn 13686: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13687: of role statuses (active, future or previous), roles
13688: (e.g., cc,in, st etc.) and domains of the roles which can be used
13689: to restrict the list of roles reported. If no array ref is
13690: provided for types, will default to return only active roles.
1.834 albertel 13691:
1.1172.2.13 raeburn 13692: =item *
13693:
13694: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13695: user: $uname:$udom has a role in the course: $cdom_$cnum.
13696:
13697: Additional optional arguments are: $type (if role checking is to be restricted
13698: to certain user status types -- previous (expired roles), active (currently
13699: available roles) or future (roles available in the future), and
13700: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13701: have active Domain Coordinator role in course's domain or in additional
13702: domains (specified in 'Domains to check for privileged users' in course
13703: environment -- set via: Course Settings -> Classlists and staff listing).
13704:
13705: =item *
13706:
13707: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13708: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13709: $possdomains and $possroles are optional array refs -- to domains to check and
13710: roles to check. If $possdomains is not specified, a dump will be done of the
13711: users' roles.db to check for a dc or su role in any domain. This can be
13712: time consuming if &privileged is called repeatedly (e.g., when displaying a
13713: classlist), so in such cases, supplying a $possdomains array is preferred, as
13714: this then allows &privileged_by_domain() to be used, which caches the identity
13715: of privileged users, eliminating the need for repeated calls to &dump().
13716:
13717: =item *
13718:
13719: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13720: where the outer hash keys are domains specified in the $possdomains array ref,
13721: next inner hash keys are privileged roles specified in the $roles array ref,
13722: and the innermost hash contains key = value pairs for username:domain = end:start
13723: for active or future "privileged" users with that role in that domain. To avoid
13724: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13725: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13726:
1.243 albertel 13727: =back
13728:
13729: =head2 User Modification
13730:
13731: =over 4
13732:
13733: =item *
13734:
1.957 raeburn 13735: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13736: user for the level given by URL. Optional start and end dates (leave empty
13737: string or zero for "no date")
1.191 harris41 13738:
13739: =item *
13740:
1.243 albertel 13741: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13742: change a users, password, possible return values are: ok,
13743: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13744: refused
1.191 harris41 13745:
13746: =item *
13747:
1.243 albertel 13748: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13749:
13750: =item *
13751:
1.1058 raeburn 13752: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13753: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13754:
13755: will update user information (firstname,middlename,lastname,generation,
13756: permanentemail), and if forceid is true, student/employee ID also.
13757: A user's institutional affiliation(s) can also be updated.
13758: User information fields will not be overwritten with empty entries
13759: unless the field is included in the $candelete array reference.
13760: This array is included when a single user is modified via "Manage Users",
13761: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13762:
13763: =item *
13764:
1.286 matthew 13765: modifystudent
13766:
1.957 raeburn 13767: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13768: The course id is resolved based on the current user's environment.
13769: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13770: associated with a course.
13771:
1.297 matthew 13772: This call is essentially a wrapper for lonnet::modifyuser and
13773: lonnet::modify_student_enrollment
1.286 matthew 13774:
13775: Inputs:
13776:
13777: =over 4
13778:
1.957 raeburn 13779: =item B<$udom> Student's loncapa domain
1.286 matthew 13780:
1.957 raeburn 13781: =item B<$uname> Student's loncapa login name
1.286 matthew 13782:
1.964 bisitz 13783: =item B<$uid> Student/Employee ID
1.286 matthew 13784:
1.957 raeburn 13785: =item B<$umode> Student's authentication mode
1.286 matthew 13786:
1.957 raeburn 13787: =item B<$upass> Student's password
1.286 matthew 13788:
1.957 raeburn 13789: =item B<$first> Student's first name
1.286 matthew 13790:
1.957 raeburn 13791: =item B<$middle> Student's middle name
1.286 matthew 13792:
1.957 raeburn 13793: =item B<$last> Student's last name
1.286 matthew 13794:
1.957 raeburn 13795: =item B<$gene> Student's generation
1.286 matthew 13796:
1.957 raeburn 13797: =item B<$usec> Student's section in course
1.286 matthew 13798:
13799: =item B<$end> Unix time of the roles expiration
13800:
13801: =item B<$start> Unix time of the roles start date
13802:
13803: =item B<$forceid> If defined, allow $uid to be changed
13804:
13805: =item B<$desiredhome> server to use as home server for student
13806:
1.957 raeburn 13807: =item B<$email> Student's permanent e-mail address
13808:
13809: =item B<$type> Type of enrollment (auto or manual)
13810:
1.963 raeburn 13811: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13812:
13813: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13814:
1.963 raeburn 13815: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13816:
1.963 raeburn 13817: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13818:
1.1172.2.19 raeburn 13819: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13820:
13821: =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 13822:
1.286 matthew 13823: =back
1.297 matthew 13824:
13825: =item *
13826:
13827: modify_student_enrollment
13828:
1.1172.2.31 raeburn 13829: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13830: 'role.request.course' must be defined for this function to proceed.
13831:
13832: Inputs:
13833:
13834: =over 4
13835:
1.1172.2.31 raeburn 13836: =item $udom, student's domain
1.297 matthew 13837:
1.1172.2.31 raeburn 13838: =item $uname, student's name
1.297 matthew 13839:
1.1172.2.31 raeburn 13840: =item $uid, student's user id
1.297 matthew 13841:
1.1172.2.31 raeburn 13842: =item $first, student's first name
1.297 matthew 13843:
13844: =item $middle
13845:
13846: =item $last
13847:
13848: =item $gene
13849:
13850: =item $usec
13851:
13852: =item $end
13853:
13854: =item $start
13855:
1.957 raeburn 13856: =item $type
13857:
13858: =item $locktype
13859:
13860: =item $cid
13861:
13862: =item $selfenroll
13863:
13864: =item $context
13865:
1.1172.2.19 raeburn 13866: =item $credits, number of credits student will earn from this class
13867:
1.1172.2.76 raeburn 13868: =item $instsec, institutional course section code for student
13869:
1.297 matthew 13870: =back
13871:
1.191 harris41 13872:
13873: =item *
13874:
1.243 albertel 13875: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13876: custom role; give a custom role to a user for the level given by URL. Specify
13877: name and domain of role author, and role name
1.191 harris41 13878:
13879: =item *
13880:
1.243 albertel 13881: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13882:
13883: =item *
13884:
1.243 albertel 13885: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13886:
13887: =back
13888:
13889: =head2 Course Infomation
13890:
13891: =over 4
1.191 harris41 13892:
13893: =item *
13894:
1.1118 foxr 13895: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13896: specified course id, including all environment settings for the
13897: course, the description of the course will be in the hash under the
13898: key 'description'
1.191 harris41 13899:
1.1118 foxr 13900: $options is an optional parameter that if supplied is a hash reference that controls
13901: what how this function works. It has the following key/values:
13902:
13903: =over 4
13904:
13905: =item freshen_cache
13906:
13907: If defined, and the environment cache for the course is valid, it is
13908: returned in the returned hash.
13909:
13910: =item one_time
13911:
13912: If defined, the last cache time is set to _now_
13913:
13914: =item user
13915:
13916: If defined, the supplied username is used instead of the current user.
13917:
13918:
13919: =back
13920:
1.191 harris41 13921: =item *
13922:
1.624 albertel 13923: resdata($name,$domain,$type,@which) : request for current parameter
13924: setting for a specific $type, where $type is either 'course' or 'user',
13925: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13926: answers for 10 minutes.
1.243 albertel 13927:
1.877 foxr 13928: =item *
13929:
13930: get_courseresdata($courseid, $domain) : dump the entire course resource
13931: data base, returning a hash that is keyed by the resource name and has
13932: values that are the resource value. I believe that the timestamps and
13933: versions are also returned.
13934:
1.1172.2.31 raeburn 13935: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13936: supplemental content area. This routine caches the number of files for
13937: 10 minutes.
13938:
1.243 albertel 13939: =back
13940:
13941: =head2 Course Modification
13942:
13943: =over 4
1.191 harris41 13944:
13945: =item *
13946:
1.243 albertel 13947: writecoursepref($courseid,%prefs) : write preferences (environment
13948: database) for a course
1.191 harris41 13949:
13950: =item *
13951:
1.1011 raeburn 13952: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13953:
13954: =item *
13955:
1.1038 raeburn 13956: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13957:
1.1167 droeschl 13958: =item *
13959:
13960: is_course($courseid), is_course($cdom, $cnum)
13961:
13962: Accepts either a combined $courseid (in the form of domain_courseid) or the
13963: two component version $cdom, $cnum. It checks if the specified course exists.
13964:
13965: Returns:
13966: undef if the course doesn't exist, otherwise
13967: in scalar context the combined courseid.
13968: in list context the two components of the course identifier, domain and
13969: courseid.
13970:
1.243 albertel 13971: =back
13972:
13973: =head2 Resource Subroutines
13974:
13975: =over 4
1.191 harris41 13976:
13977: =item *
13978:
1.243 albertel 13979: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13980:
13981: =item *
13982:
1.243 albertel 13983: repcopy($filename) : subscribes to the requested file, and attempts to
13984: replicate from the owning library server, Might return
1.607 raeburn 13985: 'unavailable', 'not_found', 'forbidden', 'ok', or
13986: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13987: resource. Expects the local filesystem pathname
13988: (/home/httpd/html/res/....)
13989:
13990: =back
13991:
13992: =head2 Resource Information
13993:
13994: =over 4
1.191 harris41 13995:
13996: =item *
13997:
1.1172.2.28 raeburn 13998: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13999: and returns the value of a variety of different possible values,
14000: $varname should be a request string, and the other parameters can be
14001: used to specify who and what one is asking about. Ordinarily, $cid
14002: does not need to be specified, as it is retrived from
14003: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14004: within lonuserstate::loadmap() when initializing a course, before
14005: $env{'request.course.id'} has been set, so it needs to be provided
14006: in that one case.
1.243 albertel 14007:
14008: Possible values for $varname are environment.lastname (or other item
14009: from the envirnment hash), user.name (or someother aspect about the
14010: user), resource.0.maxtries (or some other part and parameter of a
14011: resource)
1.204 albertel 14012:
14013: =item *
14014:
1.243 albertel 14015: directcondval($number) : get current value of a condition; reads from a state
14016: string
1.204 albertel 14017:
14018: =item *
14019:
1.243 albertel 14020: condval($condidx) : value of condition index based on state
1.204 albertel 14021:
14022: =item *
14023:
1.243 albertel 14024: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14025: resource's metadata, $what should be either a specific key, or either
14026: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14027: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14028:
14029: this function automatically caches all requests
1.191 harris41 14030:
14031: =item *
14032:
1.243 albertel 14033: metadata_query($query,$custom,$customshow) : make a metadata query against the
14034: network of library servers; returns file handle of where SQL and regex results
14035: will be stored for query
1.191 harris41 14036:
14037: =item *
14038:
1.1172.2.66 raeburn 14039: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14040: return symbolic list entry (all arguments optional).
14041:
14042: Args: filename is the filename (including path) for the file for which a symb
14043: is required; donotrecurse, if true will prevent calls to allowed() being made
14044: to check access status if more than one resource was found in the bighash
14045: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14046: a randompick); ignorecachednull, if true will prevent a symb of '' being
14047: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14048: cause possible symbs to be checked to determine if they are subject to content
14049: blocking, if so they will not be included as possible symbs; possibles is a
14050: ref to a hash, which, as a side effect, will be populated with all possible
14051: symbs (content blocking not tested).
14052:
1.243 albertel 14053: returns the data handle
1.191 harris41 14054:
14055: =item *
14056:
1.1172.2.17 raeburn 14057: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 14058: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14059: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 14060: on failure, user must be in a course, as it assumes the existence of
14061: the course initial hash, and uses $env('request.course.id'}. The third
14062: arg is an optional reference to a scalar. If this arg is passed in the
14063: call to symbverify, it will be set to 1 if the symb has been set to be
14064: encrypted; otherwise it will be null.
1.243 albertel 14065:
1.191 harris41 14066: =item *
14067:
1.243 albertel 14068: symbclean($symb) : removes versions numbers from a symb, returns the
14069: cleaned symb
1.191 harris41 14070:
14071: =item *
14072:
1.243 albertel 14073: is_on_map($uri) : checks if the $uri is somewhere on the current
14074: course map, user must be in a course for it to work.
1.191 harris41 14075:
14076: =item *
14077:
1.243 albertel 14078: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14079:
14080: =item *
14081:
1.243 albertel 14082: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14083: a random seed, all arguments are optional, if they aren't sent it uses the
14084: environment to derive them. Note: if symb isn't sent and it can't get one
14085: from &symbread it will use the current time as its return value
1.191 harris41 14086:
14087: =item *
14088:
1.243 albertel 14089: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14090: unfakeable, receipt
1.191 harris41 14091:
14092: =item *
14093:
1.620 albertel 14094: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14095:
14096: =item *
14097:
1.243 albertel 14098: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14099:
14100: =item *
14101:
1.243 albertel 14102: 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 14103:
14104: =item *
14105:
1.243 albertel 14106: 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 14107:
14108: =item *
14109:
1.243 albertel 14110: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14111:
14112: =item *
14113:
1.243 albertel 14114: devalidate($symb) : devalidate temporary spreadsheet calculations,
14115: forcing spreadsheet to reevaluate the resource scores next time.
14116:
1.1172.2.13 raeburn 14117: =item *
14118:
14119: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14120: when viewing in course context.
14121:
14122: input: six args -- filename (decluttered), course number, course domain,
14123: url, symb (if registered) and group (if this is a
14124: group item -- e.g., bulletin board, group page etc.).
14125:
14126: output: array of five scalars --
14127: $cfile -- url for file editing if editable on current server
14128: $home -- homeserver of resource (i.e., for author if published,
14129: or course if uploaded.).
14130: $switchserver -- 1 if server switch will be needed.
14131: $forceedit -- 1 if icon/link should be to go to edit mode
14132: $forceview -- 1 if icon/link should be to go to view mode
14133:
14134: =item *
14135:
14136: is_course_upload($file,$cnum,$cdom)
14137:
14138: Used in course context to determine if current file was uploaded to
14139: the course (i.e., would be found in /userfiles/docs on the course's
14140: homeserver.
14141:
14142: input: 3 args -- filename (decluttered), course number and course domain.
14143: output: boolean -- 1 if file was uploaded.
14144:
1.243 albertel 14145: =back
14146:
14147: =head2 Storing/Retreiving Data
14148:
14149: =over 4
1.191 harris41 14150:
14151: =item *
14152:
1.1172.2.64 raeburn 14153: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14154: permanently for this url; hashref needs to be given and should be a \%hashname;
14155: the remaining args aren't required and if they aren't passed or are '' they will
14156: be derived from the env (with the exception of $laststore, which is an
14157: optional arg used when a user's submission is stored in grading).
14158: $laststore is $version=$timestamp, where $version is the most recent version
14159: number retrieved for the corresponding $symb in the $namespace db file, and
14160: $timestamp is the timestamp for that transaction (UNIX time).
14161: $laststore is currently only passed when cstore() is called by
14162: structuretags::finalize_storage().
1.191 harris41 14163:
14164: =item *
14165:
1.1172.2.64 raeburn 14166: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14167: but uses critical subroutine
1.191 harris41 14168:
14169: =item *
14170:
1.243 albertel 14171: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14172: all args are optional
1.191 harris41 14173:
14174: =item *
14175:
1.717 albertel 14176: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14177: dumps the complete (or key matching regexp) namespace into a hash
14178: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14179: normally &store()ed into
14180:
14181: $range should be either an integer '100' (give me the first 100
14182: matching records)
14183: or be two integers sperated by a - with no spaces
14184: '30-50' (give me the 30th through the 50th matching
14185: records)
14186:
14187:
14188: =item *
14189:
1.1172.2.59 raeburn 14190: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14191: replaces a &store() version of data with a replacement set of data
14192: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 14193: reference. If $tolog is true, the transaction is logged in the courselog
14194: with an action=PUTSTORE.
1.717 albertel 14195:
14196: =item *
14197:
1.243 albertel 14198: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14199: works very similar to store/cstore, but all data is stored in a
14200: temporary location and can be reset using tmpreset, $storehash should
14201: be a hash reference, returns nothing on success
1.191 harris41 14202:
14203: =item *
14204:
1.243 albertel 14205: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14206: similar to restore, but all data is stored in a temporary location and
14207: can be reset using tmpreset. Returns a hash of values on success,
14208: error string otherwise.
1.191 harris41 14209:
14210: =item *
14211:
1.243 albertel 14212: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14213: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14214:
14215: =item *
14216:
1.243 albertel 14217: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14218: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14219:
14220: =item *
14221:
1.243 albertel 14222: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14223: namesp ($udom and $uname are optional)
1.191 harris41 14224:
14225: =item *
14226:
1.702 albertel 14227: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14228: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14229: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14230:
1.702 albertel 14231: $range should be either an integer '100' (give me the first 100
14232: matching records)
14233: or be two integers sperated by a - with no spaces
14234: '30-50' (give me the 30th through the 50th matching
14235: records)
1.449 matthew 14236: =item *
14237:
14238: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14239: $store can be a scalar, an array reference, or if the amount to be
14240: incremented is > 1, a hash reference.
14241:
14242: ($udom and $uname are optional)
1.191 harris41 14243:
14244: =item *
14245:
1.243 albertel 14246: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14247: ($udom and $uname are optional)
1.191 harris41 14248:
14249: =item *
14250:
1.243 albertel 14251: cput($namespace,$storehash,$udom,$uname) : critical put
14252: ($udom and $uname are optional)
1.191 harris41 14253:
14254: =item *
14255:
1.748 albertel 14256: newput($namespace,$storehash,$udom,$uname) :
14257:
14258: Attempts to store the items in the $storehash, but only if they don't
14259: currently exist, if this succeeds you can be certain that you have
14260: successfully created a new key value pair in the $namespace db.
14261:
14262:
14263: Args:
14264: $namespace: name of database to store values to
14265: $storehash: hashref to store to the db
14266: $udom: (optional) domain of user containing the db
14267: $uname: (optional) name of user caontaining the db
14268:
14269: Returns:
14270: 'ok' -> succeeded in storing all keys of $storehash
14271: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14272: least <key> already existed in the db (other
14273: requested keys may also already exist)
1.967 bisitz 14274: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14275: 'con_lost' -> unable to contact request server
14276: 'refused' -> action was not allowed by remote machine
14277:
14278:
14279: =item *
14280:
1.243 albertel 14281: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14282: reference filled in from namesp (encrypts the return communication)
14283: ($udom and $uname are optional)
1.191 harris41 14284:
14285: =item *
14286:
1.243 albertel 14287: log($udom,$name,$home,$message) : write to permanent log for user; use
14288: critical subroutine
14289:
1.806 raeburn 14290: =item *
14291:
1.860 raeburn 14292: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14293: array reference filled in from namespace found in domain level on either
14294: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14295:
14296: =item *
14297:
1.860 raeburn 14298: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14299: domain level either on specified domain server ($uhome) or primary domain
14300: server ($udom and $uhome are optional)
1.806 raeburn 14301:
1.943 raeburn 14302: =item *
14303:
1.1172.2.35 raeburn 14304: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14305: for: authentication, language, quotas, timezone, date locale, and portal URL in
14306: the target domain.
14307:
14308: May also include additional key => value pairs for the following groups:
14309:
14310: =over
14311:
14312: =item
14313: disk quotas (MB allocated by default to portfolios and authoring spaces).
14314:
14315: =over
14316:
14317: =item defaultquota, authorquota
14318:
14319: =back
14320:
14321: =item
14322: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14323: portfolio for users).
14324:
14325: =over
14326:
14327: =item
14328: aboutme, blog, webdav, portfolio
14329:
14330: =back
14331:
14332: =item
14333: requestcourses: ability to request courses, and how requests are processed.
14334:
14335: =over
14336:
14337: =item
1.1172.2.37 raeburn 14338: official, unofficial, community, textbook
1.1172.2.35 raeburn 14339:
14340: =back
14341:
14342: =item
14343: inststatus: types of institutional affiliation, and order in which they are displayed.
14344:
14345: =over
14346:
14347: =item
1.1172.2.44 raeburn 14348: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 14349:
14350: =back
14351:
14352: =item
14353: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14354: for course's uploaded content.
14355:
14356: =over
14357:
14358: =item
1.1172.2.68 raeburn 14359: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
14360: communityquota, textbookquota
1.1172.2.35 raeburn 14361:
14362: =back
14363:
14364: =item
14365: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14366: on your servers.
14367:
14368: =over
14369:
14370: =item
14371: remotesessions, hostedsessions
14372:
14373: =back
14374:
14375: =back
14376:
14377: In cases where a domain coordinator has never used the "Set Domain Configuration"
14378: utility to create a configuration.db file on a domain's primary library server
14379: only the following domain defaults: auth_def, auth_arg_def, lang_def
14380: -- corresponding values are authentication type (internal, krb4, krb5,
14381: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14382: will be available. Values are retrieved from cache (if current), unless the
14383: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14384: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14385:
14386: Typical usage:
1.943 raeburn 14387:
1.1172.2.35 raeburn 14388: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14389:
1.243 albertel 14390: =back
14391:
14392: =head2 Network Status Functions
14393:
14394: =over 4
1.191 harris41 14395:
14396: =item *
14397:
1.1137 raeburn 14398: dirlist() : return directory list based on URI (first arg).
14399:
14400: Inputs: 1 required, 5 optional.
14401:
14402: =over
14403:
14404: =item
14405: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14406:
14407: =item
14408: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14409:
14410: =item
14411: $username - username of user/course to be listed. Extracted from $uri if absent.
14412:
14413: =item
14414: $getpropath - boolean: 1 if prepend path using &propath().
14415:
14416: =item
14417: $getuserdir - boolean: 1 if prepend path for "userfiles".
14418:
14419: =item
14420: $alternateRoot - path to prepend in place of path from $uri.
14421:
14422: =back
14423:
14424: Returns: Array of up to two items.
14425:
14426: =over
14427:
14428: a reference to an array of files/subdirectories
14429:
14430: =over
14431:
14432: Each element in the array of files/subdirectories is a & separated list of
14433: item name and the result of running stat on the item. If dirlist was requested
14434: for a file instead of a directory, the item name will be ''. For a directory
14435: listing, if the item is a metadata file, the element will end &N&M
14436: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14437: default copyright set (1).
14438:
14439: =back
14440:
14441: a scalar containing error condition (if encountered).
14442:
14443: =over
14444:
14445: =item
14446: no_host (no homeserver identified for $username:$domain).
14447:
14448: =item
14449: no_such_host (server contacted for listing not identified as valid host).
14450:
14451: =item
14452: con_lost (connection to remote server failed).
14453:
14454: =item
14455: refused (invalid $username:$domain received on lond side).
14456:
14457: =item
14458: no_such_dir (directory at specified path on lond side does not exist).
14459:
14460: =item
14461: empty (directory at specified path on lond side is empty).
14462:
14463: =over
14464:
14465: This is currently not encountered because the &ls3, &ls2,
14466: &ls (_handler) routines on the lond side do not filter out
14467: . and .. from a directory listing.
14468:
14469: =back
14470:
14471: =back
14472:
14473: =back
1.191 harris41 14474:
14475: =item *
14476:
1.243 albertel 14477: spareserver() : find server with least workload from spare.tab
14478:
1.986 foxr 14479:
14480: =item *
14481:
14482: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14483: if there is no corresponding loncapa host.
14484:
1.243 albertel 14485: =back
14486:
1.986 foxr 14487:
1.243 albertel 14488: =head2 Apache Request
14489:
14490: =over 4
1.191 harris41 14491:
14492: =item *
14493:
1.243 albertel 14494: ssi($url,%hash) : server side include, does a complete request cycle on url to
14495: localhost, posts hash
14496:
14497: =back
14498:
14499: =head2 Data to String to Data
14500:
14501: =over 4
1.191 harris41 14502:
14503: =item *
14504:
1.243 albertel 14505: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14506: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14507:
14508: =item *
14509:
1.243 albertel 14510: hashref2str($hashref) : convert a hashref into a string complete with
14511: escaping and '=' and '&' separators, supports elements that are
14512: arrayrefs and hashrefs
1.191 harris41 14513:
14514: =item *
14515:
1.243 albertel 14516: arrayref2str($arrayref) : convert an arrayref into a string complete
14517: with escaping and '&' separators, supports elements that are arrayrefs
14518: and hashrefs
1.191 harris41 14519:
14520: =item *
14521:
1.243 albertel 14522: str2hash($string) : convert string to hash using unescaping and
14523: splitting on '=' and '&', supports elements that are arrayrefs and
14524: hashrefs
1.191 harris41 14525:
14526: =item *
14527:
1.243 albertel 14528: str2array($string) : convert string to hash using unescaping and
14529: splitting on '&', supports elements that are arrayrefs and hashrefs
14530:
14531: =back
14532:
14533: =head2 Logging Routines
14534:
14535:
14536: These routines allow one to make log messages in the lonnet.log and
14537: lonnet.perm logfiles.
1.191 harris41 14538:
1.1119 foxr 14539: =over 4
14540:
1.191 harris41 14541: =item *
14542:
1.243 albertel 14543: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14544:
14545: =item *
14546:
1.243 albertel 14547: logthis() : append message to the normal lonnet.log file, it gets
14548: preiodically rolled over and deleted.
1.191 harris41 14549:
14550: =item *
14551:
1.243 albertel 14552: logperm() : append a permanent message to lonnet.perm.log, this log
14553: file never gets deleted by any automated portion of the system, only
14554: messages of critical importance should go in here.
14555:
1.1119 foxr 14556:
1.243 albertel 14557: =back
14558:
14559: =head2 General File Helper Routines
14560:
14561: =over 4
1.191 harris41 14562:
14563: =item *
14564:
1.481 raeburn 14565: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14566: (a) files in /uploaded
14567: (i) If a local copy of the file exists -
14568: compares modification date of local copy with last-modified date for
14569: definitive version stored on home server for course. If local copy is
14570: stale, requests a new version from the home server and stores it.
14571: If the original has been removed from the home server, then local copy
14572: is unlinked.
14573: (ii) If local copy does not exist -
14574: requests the file from the home server and stores it.
14575:
14576: If $caller is 'uploadrep':
14577: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14578: for request for files originally uploaded via DOCS.
14579: - returns 'ok' if fresh local copy now available, -1 otherwise.
14580:
14581: Otherwise:
14582: This indicates a call from the content generation phase of the request.
14583: - returns the entire contents of the file or -1.
14584:
14585: (b) files in /res
14586: - returns the entire contents of a file or -1;
14587: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14588:
1.712 albertel 14589:
14590: =item *
14591:
14592: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14593: reference
14594:
14595: returns either a stat() list of data about the file or an empty list
14596: if the file doesn't exist or couldn't find out about it (connection
14597: problems or user unknown)
14598:
1.191 harris41 14599: =item *
14600:
1.243 albertel 14601: filelocation($dir,$file) : returns file system location of a file
14602: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14603: directory that relative $file lookups are to looked in ($dir of /a/dir
14604: and a file of ../bob will become /a/bob)
1.191 harris41 14605:
14606: =item *
14607:
14608: hreflocation($dir,$file) : returns file system location or a URL; same as
14609: filelocation except for hrefs
14610:
14611: =item *
14612:
1.1172.2.49 raeburn 14613: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14614: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14615:
1.243 albertel 14616: =back
14617:
1.608 albertel 14618: =head2 Usererfile file routines (/uploaded*)
14619:
14620: =over 4
14621:
14622: =item *
14623:
14624: userfileupload(): main rotine for putting a file in a user or course's
14625: filespace, arguments are,
14626:
1.620 albertel 14627: formname - required - this is the name of the element in $env where the
1.608 albertel 14628: filename, and the contents of the file to create/modifed exist
1.620 albertel 14629: the filename is in $env{'form.'.$formname.'.filename'} and the
14630: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14631: context - if coursedoc, store the file in the course of the active role
14632: of the current user;
14633: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14634: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14635: subdir - required - subdirectory to put the file in under ../userfiles/
14636: if undefined, it will be placed in "unknown"
14637:
14638: (This routine calls clean_filename() to remove any dangerous
14639: characters from the filename, and then calls finuserfileupload() to
14640: complete the transaction)
14641:
14642: returns either the url of the uploaded file (/uploaded/....) if successful
14643: and /adm/notfound.html if unsuccessful
14644:
14645: =item *
14646:
14647: clean_filename(): routine for cleaing a filename up for storage in
14648: userfile space, argument is:
14649:
14650: filename - proposed filename
14651:
14652: returns: the new clean filename
14653:
14654: =item *
14655:
1.1090 raeburn 14656: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14657: userspace, probably shouldn't be called directly
14658:
14659: docuname: username or courseid of destination for the file
14660: docudom: domain of user/course of destination for the file
14661: formname: same as for userfileupload()
1.1090 raeburn 14662: fname: filename (including subdirectories) for the file
14663: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14664: allfiles: reference to hash used to store objects found by parser
14665: codebase: reference to hash used for codebases of java objects found by parser
14666: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14667: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14668: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14669: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14670: context: if 'overwrite', will move the uploaded file from its temporary location to
14671: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14672: mimetype: reference to scalar to accommodate mime type determined
14673: from File::MMagic if $parser = parse.
1.608 albertel 14674:
14675: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14676: and /adm/notfound.html if unsuccessful (or an error message if context
14677: was 'overwrite').
14678:
1.608 albertel 14679:
14680: =item *
14681:
14682: renameuserfile(): renames an existing userfile to a new name
14683:
14684: Args:
14685: docuname: username or courseid of destination for the file
14686: docudom: domain of user/course of destination for the file
14687: old: current file name (including any subdirs under userfiles)
14688: new: desired file name (including any subdirs under userfiles)
14689:
14690: =item *
14691:
14692: mkdiruserfile(): creates a directory is a userfiles dir
14693:
14694: Args:
14695: docuname: username or courseid of destination for the file
14696: docudom: domain of user/course of destination for the file
14697: dir: dir to create (including any subdirs under userfiles)
14698:
14699: =item *
14700:
14701: removeuserfile(): removes a file that exists in userfiles
14702:
14703: Args:
14704: docuname: username or courseid of destination for the file
14705: docudom: domain of user/course of destination for the file
14706: fname: filname to delete (including any subdirs under userfiles)
14707:
14708: =item *
14709:
14710: removeuploadedurl(): convience function for removeuserfile()
14711:
14712: Args:
14713: url: a full /uploaded/... url to delete
14714:
1.747 albertel 14715: =item *
14716:
14717: get_portfile_permissions():
14718: Args:
14719: domain: domain of user or course contain the portfolio files
14720: user: name of user or num of course contain the portfolio files
14721: Returns:
14722: hashref of a dump of the proper file_permissions.db
14723:
14724:
14725: =item *
14726:
14727: get_access_controls():
14728:
14729: Args:
14730: current_permissions: the hash ref returned from get_portfile_permissions()
14731: group: (optional) the group you want the files associated with
14732: file: (optional) the file you want access info on
14733:
14734: Returns:
1.749 raeburn 14735: a hash (keys are file names) of hashes containing
14736: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14737: values are XML containing access control settings (see below)
1.747 albertel 14738:
14739: Internal notes:
14740:
1.749 raeburn 14741: access controls are stored in file_permissions.db as key=value pairs.
14742: key -> path to file/file_name\0uniqueID:scope_end_start
14743: where scope -> public,guest,course,group,domains or users.
14744: end -> UNIX time for end of access (0 -> no end date)
14745: start -> UNIX time for start of access
14746:
14747: value -> XML description of access control
14748: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14749: <start></start>
14750: <end></end>
14751:
14752: <password></password> for scope type = guest
14753:
14754: <domain></domain> for scope type = course or group
14755: <number></number>
14756: <roles id="">
14757: <role></role>
14758: <access></access>
14759: <section></section>
14760: <group></group>
14761: </roles>
14762:
14763: <dom></dom> for scope type = domains
14764:
14765: <users> for scope type = users
14766: <user>
14767: <uname></uname>
14768: <udom></udom>
14769: </user>
14770: </users>
14771: </scope>
14772:
14773: Access data is also aggregated for each file in an additional key=value pair:
14774: key -> path to file/file_name\0accesscontrol
14775: value -> reference to hash
14776: hash contains key = value pairs
14777: where key = uniqueID:scope_end_start
14778: value = UNIX time record was last updated
14779:
14780: Used to improve speed of look-ups of access controls for each file.
14781:
14782: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14783:
1.1172.2.13 raeburn 14784: =item *
14785:
1.749 raeburn 14786: modify_access_controls():
14787:
14788: Modifies access controls for a portfolio file
14789: Args
14790: 1. file name
14791: 2. reference to hash of required changes,
14792: 3. domain
14793: 4. username
14794: where domain,username are the domain of the portfolio owner
14795: (either a user or a course)
14796:
14797: Returns:
14798: 1. result of additions or updates ('ok' or 'error', with error message).
14799: 2. result of deletions ('ok' or 'error', with error message).
14800: 3. reference to hash of any new or updated access controls.
14801: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14802: key = integer (inbound ID)
1.1172.2.13 raeburn 14803: value = uniqueID
14804:
14805: =item *
14806:
14807: get_timebased_id():
14808:
14809: Attempts to get a unique timestamp-based suffix for use with items added to a
14810: course via the Course Editor (e.g., folders, composite pages,
14811: group bulletin boards).
14812:
14813: Args: (first three required; six others optional)
14814:
14815: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14816: docssequence, or name of group
14817:
14818: 2. keyid (alphanumeric): name of temporary locking key in hash,
14819: e.g., num, boardids
14820:
14821: 3. namespace: name of gdbm file used to store suffixes already assigned;
14822: file will be named nohist_namespace.db
14823:
14824: 4. cdom: domain of course; default is current course domain from %env
14825:
14826: 5. cnum: course number; default is current course number from %env
14827:
14828: 6. idtype: set to concat if an additional digit is to be appended to the
14829: unix timestamp to form the suffix, if the plain timestamp is already
14830: in use. Default is to not do this, but simply increment the unix
14831: timestamp by 1 until a unique key is obtained.
14832:
14833: 7. who: holder of locking key; defaults to user:domain for user.
14834:
14835: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14836: retrying); default is 3.
14837:
14838: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14839:
14840: Returns:
14841:
14842: 1. suffix obtained (numeric)
14843:
14844: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14845:
14846: 3. error: contains (localized) error message if an error occurred.
14847:
1.747 albertel 14848:
1.608 albertel 14849: =back
14850:
1.243 albertel 14851: =head2 HTTP Helper Routines
14852:
14853: =over 4
14854:
1.191 harris41 14855: =item *
14856:
14857: escape() : unpack non-word characters into CGI-compatible hex codes
14858:
14859: =item *
14860:
14861: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14862:
1.243 albertel 14863: =back
14864:
14865: =head1 PRIVATE SUBROUTINES
14866:
14867: =head2 Underlying communication routines (Shouldn't call)
14868:
14869: =over 4
14870:
14871: =item *
14872:
14873: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14874:
14875: =item *
14876:
14877: reply() : uses subreply to send a message to remote machine, logs all failures
14878:
14879: =item *
14880:
14881: critical() : passes a critical message to another server; if cannot
14882: get through then place message in connection buffer directory and
14883: returns con_delayed, if incapable of saving message, returns
14884: con_failed
14885:
14886: =item *
14887:
14888: reconlonc() : tries to reconnect lonc client processes.
14889:
14890: =back
14891:
14892: =head2 Resource Access Logging
14893:
14894: =over 4
14895:
14896: =item *
14897:
14898: flushcourselogs() : flush (save) buffer logs and access logs
14899:
14900: =item *
14901:
14902: courselog($what) : save message for course in hash
14903:
14904: =item *
14905:
14906: courseacclog($what) : save message for course using &courselog(). Perform
14907: special processing for specific resource types (problems, exams, quizzes, etc).
14908:
1.191 harris41 14909: =item *
14910:
14911: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14912: as a PerlChildExitHandler
1.243 albertel 14913:
14914: =back
14915:
14916: =head2 Other
14917:
14918: =over 4
14919:
14920: =item *
14921:
14922: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14923:
14924: =back
14925:
14926: =cut
1.877 foxr 14927:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>